Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
263 changes: 143 additions & 120 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,120 +1,143 @@
# Fibonacci Restful Service (a Rubicon Coding Question)

Fibonacci restful service is designed to be high-scaliablity service to quickly calculate Fibonacci.

### Fibonacci Algorithm
Matrix exponentiation (fast)
The algorithm is based on this innocent-looking identity (which can be proven by mathematical induction):
```
[1 1]n [F(n+1) F(n) ]
[1 0] =[F(n) F(n−1)].
```
It is important to use exponentiation by squaring with this algorithm, because otherwise it degenerates into the dynamic programming algorithm. This algorithm takes O(1) space and O(logn) operations. (Note: This is counted in terms of the number of bigint arithmetic operations, not primitive fixed-width operations.)

So, that gives me a idea that the calculation could be sperated into smaller jobs to finish together.
##### Related codes:
* [FibonacciCoreCalucaltion](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/fibonacci/FibonacciCoreCalucaltion.java)

### Infrastructure Design
```
+-------------------------------------------------------+
Request | |
| |
+-------------> |
| HAProxy (Load Balance) |
+-----------+--------------------------------+----------+
| Compression |
| |
+----------v----------+ +--------------v---------+
| | | |
| | | |
| | | +---------------------+
| spring container 1|... | spring container N | |
| | | | |
+-+-------------+-----+ +---------------+--------+ |
| | | |
+-------------------------------------------------------------------------+ +------------v---------------+
| | | | | | |
| +------v-----+ +-----v-----+ +------v---+ Heart Beat +------------------+ |
| | | | | | <-----------------> Worker Queue | |
| | | | | | <-----------------> | |
| | JVM1(Docker)| JVM2 (Docker) | JVM-N | | | +------------------+ |
| | | | | | | start new one +------------------+ |
| | | | | | | <-----+--+---+ AutoScaling | |
| +-^---------^+ +-----------+ +---^------+ | | | | |
| | | | | | +------------------+ |
| | | Worker Pool | | | Worker Monitor |
+----------+---------+----------------------------------------------------+ +----------------------------+
Map & Reduce |
+ | |
| | |
+------v-+ +v--------+ +---------+ +----v----+
| + | | | | | |
| Job1 (Thread) | JobN (Thread) | Job | | Job |
| | | | | | | |
+--------+ +---------+ +---------+ +---------+


```
##### Notice
* Load balance is not designed yet for this test. I would continously upgrade and improve project codes on that.
* Each request comes from the load balance mechnisum and go through ***Spring container***.
* The restful services will check the number first and then once the validation is passed, then it will trigger a JVM (or docker). See [code](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/rest/FibonacciCalculationResource.java).
* According to the max threadhold defined in the [properties](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/resources/application.properties), JVM will start the counts of calculation jobs. The result of each jobs will be persisted to temp files. After all jobs are done, spring container will collect these in order and then output as ***compressed*** stream. The temp files will be ***deleted*** async. See [Job Thread](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/fibonacci/FibonacciPartThread.java) and [Process](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/process/ProcessRunner.java). JVM will have a max maxheapsize (512m) for each run. So it prevent more JVM causing spring main process down.
* Properties is defined in [HERE](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/resources/application.properties). You can easily adjust JVM max heap size, task timeout (currently define 10 min), and report heart-beating.
```
# JVM parameters
jvm.parameters.maxheapsize=-Xmx512m

# default timeout (10 * 60 * 1000) in millisecond for executing a specific task
task.execution.timeout.default=900000

# the interval in millisecond for reporting the progress of the task
task.execution.progress.report.interval=10000
```
* When the request has a big and time-consuming task, then it will ***enqueue*** worker to worker queue and the status is ***BUSY*** meaning it is running. Suppose while the working is running and another big task comes in, then enqueue worker into queue. The queue could know if it is suitable to extend to run in another machine. If yes, then queue will record this machine id and automatically starts another container to run JVM. If no, so mark its status as ***ENQUEUE*** meaning it is waiting for previous big task done. When the first task is done, then status is marked as ***COMPLETE***.If the task has problem and not finish, then the status is marked as ***ABORTED***. It is in second version I would post. The diagram above is what I am thinking to do.

### How to Run

You need install maven 3 before running:

```sh
$ mvn spring-boot:run
```
Then you can GET http://localhost:9000/v1/rest/fibonacci/:id

### Restful service Document
----
Returns string to represent the fibonacci result.

* **URL**

http://localhost:9000/v1/rest/fibonacci/:id

* **Method:**

`GET`

* **URL Params**

**Required:**

`id=[integer]`

* **Header Params**

None.

If you specify following parameter, then the content will be ***gzip*** through transportation layer.

`Accept-Encoding = true`

* **Success Response:**

* **Code:** 200 <br />
**Content:** `0 1 1 2 3 5 ...`

* **Error Paramaters:**

* **Code:** 400 <br />
**Content:** `Invalid number - :id`
# Fibonacci Restful Service (a Rubicon Coding Question)

Fibonacci restful service is designed to be high-scaliablity service to quickly calculate Fibonacci.

### Fibonacci Algorithm
Matrix exponentiation (fast)
The algorithm is based on this innocent-looking identity (which can be proven by mathematical induction):
```
[1 1]n [F(n+1) F(n) ]
[1 0] =[F(n) F(n−1)].
```
It is important to use exponentiation by squaring with this algorithm, because otherwise it degenerates into the dynamic programming algorithm. This algorithm takes O(1) space and O(logn) operations. (Note: This is counted in terms of the number of bigint arithmetic operations, not primitive fixed-width operations.)

So, that gives me a idea that the calculation could be sperated into smaller jobs to finish together.
##### Related codes:
* [FibonacciCoreCalucaltion](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/fibonacci/FibonacciCoreCalucaltion.java)

### Infrastructure Design
```
+-------------------------------------------------------+
Request | |
| |
+-------------> |
| HAProxy (Load Balance) |
+-----------+--------------------------------+----------+
| Compression |
| |
+----------v----------+ +--------------v---------+
| | | |
| | | |
| | | +---------------------+
| spring container 1|... | spring container N | |
| | | | |
+-+-------------+-----+ +---------------+--------+ |
| | | |
+-------------------------------------------------------------------------+ +------------v---------------+
| | | | | | |
| +------v-----+ +-----v-----+ +------v---+ Heart Beat +------------------+ |
| | | | | | <-----------------> Worker Queue | |
| | | | | | <-----------------> | |
| | JVM1(Docker)| JVM2 (Docker) | JVM-N | | | +------------------+ |
| | | | | | | start new one +------------------+ |
| | | | | | | <-----+--+---+ AutoScaling | |
| +-^---------^+ +-----------+ +---^------+ | | | | |
| | | | | | +------------------+ |
| | | Worker Pool | | | Worker Monitor |
+----------+---------+----------------------------------------------------+ +----------------------------+
Map & Reduce |
+ | |
| | |
+------v-+ +v--------+ +---------+ +----v----+
| + | | | | | |
| Job1 (Thread) | JobN (Thread) | Job | | Job |
| | | | | | | |
+--------+ +---------+ +---------+ +---------+


```
##### Notice
* Load balance is not designed yet for this test. I would continously upgrade and improve project codes on that.
* Each request comes from the load balance mechnisum and go through ***Spring container***.
* The restful services will check the number first and then once the validation is passed, then it will trigger a JVM (or docker). See [code](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/rest/FibonacciCalculationResource.java).
* According to the max threadhold defined in the [properties](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/resources/application.properties), JVM will start the counts of calculation jobs. The result of each jobs will be persisted to temp files. After all jobs are done, spring container will collect these in order and then output as ***compressed*** stream. The temp files will be ***deleted*** async. See [Job Thread](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/fibonacci/FibonacciPartThread.java) and [Process](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/java/com/emc/test/process/ProcessRunner.java). JVM will have a max maxheapsize (512m) for each run. So it prevent more JVM causing spring main process down.
* Properties is defined in [HERE](https://github.com/jasonwang82/FibonacciRestful/blob/master/src/main/resources/application.properties). You can easily adjust JVM max heap size, task timeout (currently define 10 min), and report heart-beating.
```
# JVM parameters
jvm.parameters.maxheapsize=-Xmx512m

# default timeout (10 * 60 * 1000) in millisecond for executing a specific task
task.execution.timeout.default=900000

# the interval in millisecond for reporting the progress of the task
task.execution.progress.report.interval=10000
```
* When the request has a big and time-consuming task, then it will ***enqueue*** worker to worker queue and the status is ***BUSY*** meaning it is running. Suppose while the working is running and another big task comes in, then enqueue worker into queue. The queue could know if it is suitable to extend to run in another machine. If yes, then queue will record this machine id and automatically starts another container to run JVM. If no, so mark its status as ***ENQUEUE*** meaning it is waiting for previous big task done. When the first task is done, then status is marked as ***COMPLETE***.If the task has problem and not finish, then the status is marked as ***ABORTED***. It is in second version I would post. The diagram above is what I am thinking to do.

### How to Run

You need install maven 3 before running:

```sh
$ mvn spring-boot:run
```
Then you can GET http://localhost:9000/v1/rest/fibonacci/:id

### Restful service Document
----
Returns string to represent the fibonacci result.

* **URL**

http://localhost:9000/v1/rest/fibonacci/:id

* **Method:**

`GET`

* **URL Params**

**Required:**

`id=[integer]`

* **Header Params**

None.

If you specify following parameter, then the content will be ***gzip*** through transportation layer.

`Accept-Encoding = true`

* **Success Response:**

* **Code:** 200 <br />
**Content:** `0 1 1 2 3 5 ...`

* **Error Paramaters:**

* **Code:** 400 <br />
**Content:** `Invalid number - :id`

### Test Cases

The test suite for the FibonacciRestServiceApplication includes the following test cases:

1. **verifyFibonacci**: Verifies the Fibonacci calculation for input 7. Expects the output to be "0 1 1 2 3 5 8 ".
2. **verifyFibonacciForInput0**: Verifies the Fibonacci calculation for input 0. Expects the output to be "0 ".
3. **verifyFibonacciForInput1**: Verifies the Fibonacci calculation for input 1. Expects the output to be "0 1 ".
4. **verifyFibonacciForInput2**: Verifies the Fibonacci calculation for input 2. Expects the output to be "0 1 1 ".
5. **verifyFibonacciForInput10**: Verifies the Fibonacci calculation for input 10. Expects the output to be "0 1 1 2 3 5 8 13 21 34 ".
6. **verifyFibonacciForInput20**: Verifies the Fibonacci calculation for input 20. Expects the output to be "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 ".
7. **verifyFibonacciForNegativeInput**: Verifies the Fibonacci calculation for invalid negative input. Expects the output to be "Invalid number - -1".
8. **verifyFibonacciForNonNumericInput**: Verifies the Fibonacci calculation for invalid non-numeric input. Expects the output to be "Invalid number - a".

### Running the Tests

To run the tests, use the following command:

```sh
$ mvn test
```

The tests will be executed, and the results will be displayed in the console.
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
/**
* @author Jason.Wang
* This class contains test cases for the FibonacciRestServiceApplication.
* It uses the MockMvc framework to test the FibonacciCalculationResource class.
* The test cases verify the Fibonacci calculation for various inputs.
*
* Author: Jason.Wang
*/
package com.emc.test;

Expand Down Expand Up @@ -34,9 +38,12 @@ public void setup() {
this.restFibonacciMvc = MockMvcBuilders.standaloneSetup(cal).build();
}

/**
* Test case to verify the Fibonacci calculation for input 7.
* It expects the output to be "0 1 1 2 3 5 8 ".
*/
@Test
public void verifyFibonacci() throws Exception {

restFibonacciMvc.perform(get("/v1/rest/fibonacci/7"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 1 1 2 3 5 8 ".getBytes()));
Expand All @@ -50,4 +57,58 @@ public void verifyFibonacci() throws Exception {
.andExpect(content().bytes("Invalid number - a".getBytes()));
}
Comment on lines 57 to 58

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add test coverage for negative input values to ensure proper error handling [General, importance: 8]

Suggested change
.andExpect(content().bytes("Invalid number - a".getBytes()));
}
@Test
public void verifyFibonacciForNegativeInput() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/-1"))
.andExpect(status().is4xxClientError())
.andExpect(content().bytes("Invalid number - negative values not allowed".getBytes()));
}
@Test
public void verifyFibonacciForInput0() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/0"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 ".getBytes()));
}


/**
* Test case to verify the Fibonacci calculation for input 0.
* It expects the output to be "0 ".
*/
@Test
public void verifyFibonacciForInput0() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/0"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 ".getBytes()));
}

/**
* Test case to verify the Fibonacci calculation for input 1.
* It expects the output to be "0 1 ".
*/
@Test
public void verifyFibonacciForInput1() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/1"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 1 ".getBytes()));
}

/**
* Test case to verify the Fibonacci calculation for input 2.
* It expects the output to be "0 1 1 ".
*/
@Test
public void verifyFibonacciForInput2() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/2"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 1 1 ".getBytes()));
}

/**
* Test case to verify the Fibonacci calculation for input 10.
* It expects the output to be "0 1 1 2 3 5 8 13 21 34 ".
*/
@Test
public void verifyFibonacciForInput10() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/10"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 1 1 2 3 5 8 13 21 34 ".getBytes()));
}

/**
* Test case to verify the Fibonacci calculation for input 20.
* It expects the output to be "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 ".
*/
@Test
public void verifyFibonacciForInput20() throws Exception {
restFibonacciMvc.perform(get("/v1/rest/fibonacci/20"))
.andExpect(status().isOk())
.andExpect(content().bytes("0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 ".getBytes()));
}
}