Skip to content

Commit 81fb098

Browse files
committed
Fixed API output data and replaced exactfit algorithm
1 parent be6928a commit 81fb098

9 files changed

Lines changed: 240 additions & 206 deletions

File tree

CHANGELOG.md

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,31 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

88
### ROADMAP
9-
- Switch to Flex Net Sim v0.8.2.
10-
- Enhance previous algorithms.
11-
- Add algorithm BestFit.
129
- Switch to new domain.
1310

1411
## [2.0.0] - 2025-03-03
1512

1613
### Added
17-
- New `/run_simulation_stream` endpoint for streaming simulation results in real-time
18-
- Refactored backend code to reduce duplication and improve maintainability
19-
- Added unit tests for the streaming endpoint
20-
- Modified `simulator.hpp` to flush stdout after each line for better streaming support (see `src/README.md`)
21-
- Improved help endpoint with more concise documentation
22-
- Enabled CORS only for `/run_simulation_stream` endpoint to allow controlled API access
14+
- New `/run_simulation_stream` endpoint for streaming simulation results in real-time:
15+
- Streaming responses include event types and structured JSON data.
16+
- Refactored backend code to reduce duplication and improve maintainability.
17+
- Added unit tests for the streaming endpoint.
18+
- Modified `simulator.hpp` to flush `stdout` after each line for better streaming support (see `src/README.md`).
19+
- Improved the `\help` endpoint with more concise documentation.
20+
- Enabled CORS only for the `/run_simulation_stream` endpoint to allow controlled API access.
2321

2422
### Changed
23+
- Switched to Flex Net Sim v0.8.2.
2524
- Standardized API response format for better consistency:
26-
- Success responses now use `status: "success"` with data in a `data` field
27-
- Error responses now use `status: "error"` with a `message` and detailed `error` fields
28-
- Streaming responses include event types and structured JSON data
29-
- Reorganized test suite into separate files for better maintainability
30-
- Improved parameter validation with descriptive error messages
31-
- Changed error response code from 500 to 400 for invalid parameters
32-
- Moved parameter validation from C++ to the API layer for better user experience
25+
- Success responses now use `status: "success"` with data in a `data` field.
26+
- Error responses now use `status: "error"` with a `message` and detailed `error` fields.
27+
- Reorganized the test suite into separate files for better maintainability.
28+
- Improved parameter validation with descriptive error messages.
29+
- Changed the error response code from `500` to `400` for invalid parameters.
30+
- Moved parameter validation from C++ to the API layer for a better user experience.
31+
- Replaced the `ExactFit` algorithm with `BestFit`.
32+
- Enhanced algorithms
33+
3334

3435
## [1.1.1] - 2025-03-01
3536

@@ -65,7 +66,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6566
- This API hopefully serves as playground to all new users of Flex Net Sim C++ simulation library.
6667
- The current version utilizes Flex Net Sim v0.8.1.
6768
- `/run_simulation` endpoint for simulation includes parameters such as:
68-
- `algorithm`: FirstFit, ExactFit.
69+
- `algorithm`: FirstFit, BestFit.
6970
- `networkType`: Only 1 (EON) available for now.
7071
- `goalConnections`: 1 to 10,000,000.
7172
- `confidence`: significance level (alpha) greater than zero.

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Flex Net Sim Backend API
22

3-
[![Static Badge](https://img.shields.io/badge/version-1.1.0-blue)](https://github.com/MirkoZETA/FlexNetSim-API)
3+
[![Static Badge](https://img.shields.io/badge/version-2.0.0-blue)](https://github.com/MirkoZETA/FlexNetSim-API)
44
![Static Badge](https://img.shields.io/badge/language-python-blue)
55
[![Static Badge](https://img.shields.io/badge/licese-MIT-green)](https://github.com/MirkoZETA/FlexNetSim-API/blob/master/LICENSE)
66
[![Static Badge](https://github.com/MirkoZETA/FlexNetSim-API/actions/workflows/fns-api-workflow.yml/badge.svg)](https://github.com/MirkoZETA/FlexNetSim-API/actions/workflows/fns-api-workflow.yml)
@@ -40,7 +40,7 @@ Runs a network simulation with the provided parameters and returns complete resu
4040

4141
| Parameter | Type | Description | Allowed Values & Constraints | Default |
4242
|---------------|---------|----------------------------|-------------------------------------------------|-----------|
43-
| `algorithm` | `string` | RSA algorithm | `FirstFit`, `ExactFit` | `FirstFit` |
43+
| `algorithm` | `string` | RSA algorithm | `FirstFit`, `BestFit` | `FirstFit` |
4444
| `networkType` | `integer` | Network type | Only `1` (EON) supported | `1` |
4545
| `goalConnections` | `integer` | Target connection requests | Must be > 0 and < 10,000,000 | `100000` |
4646
| `confidence` | `float` | Confidence level | Must be > 0 and < 1.0 | `0.05` |
@@ -134,7 +134,7 @@ The endpoint returns a stream of Server-Sent Events with the following event typ
134134
2. **Data Events** (multiple events, one per line of output):
135135
```
136136
event: data
137-
data: {"status": "running", "data": "Line of simulation output"}
137+
data: {"status": "running", "message": "Line of simulation output"}
138138
```
139139

140140
3. **End Event**:

backend.py

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
from flask import Flask, request, Response, stream_with_context
55
from flask_cors import CORS
66
from utils.helpers import *
7+
import time
8+
import json
79

810
# --- Flask Application Setup ---
911
app = Flask(__name__)
@@ -76,65 +78,69 @@ def run_simulation():
7678
def run_simulation_stream():
7779
"""
7880
Executes a network simulation with the provided parameters and streams the output.
79-
81+
8082
Accepts a JSON request with simulation parameters and runs the C++ executable
8183
with those parameters. Returns a streaming response with simulation results
8284
as they become available.
83-
85+
8486
Returns:
8587
Streaming response: Line-by-line simulation data
8688
"""
8789
# Validate prerequisites
8890
is_valid, error_response = validate_simulation_prerequisites()
8991
if not is_valid:
9092
return error_response
91-
93+
9294
try:
9395
data = request.get_json()
94-
96+
9597
# Parse and validate parameters
9698
is_valid, result = parse_simulation_parameters(data)
9799
if not is_valid:
98100
return result
99-
101+
100102
# Build command
101103
command = build_simulation_command(result)
102104
logger.debug(f"Running streaming simulation with command: {' '.join(command)}")
103105

104106
# Create streaming function
105107
def generate():
106108
# Send initial event
107-
yield f"event: start\ndata: {{\n \"status\": \"started\",\n \"message\": \"Simulation started\"\n}}\n\n"
108-
109+
yield f"event: start\n"
110+
yield f"data: {json.dumps({'status': 'started', 'message': 'Simulation started', 'timestamp': time.time()})}\n\n"
111+
109112
# Execute simulation with streaming output
110113
process = subprocess.Popen(
111-
command,
112-
stdout=subprocess.PIPE,
113-
stderr=subprocess.PIPE,
114+
command,
115+
stdout=subprocess.PIPE,
116+
stderr=subprocess.PIPE,
114117
text=True,
115118
bufsize=1 # Line buffered
116119
)
117-
120+
118121
# Stream stdout
119122
for line in iter(process.stdout.readline, ""):
120123
if line:
121-
yield f"event: data\ndata: {{\n \"status\": \"running\",\n \"data\": \"{line.strip()}\"\n}}\n\n"
122-
124+
yield f"event: data\n"
125+
yield f"data: {json.dumps({'status': 'running', 'message': line.strip(), 'timestamp': time.time()})}\n\n"
126+
123127
# Check for errors at the end
124128
process.stdout.close()
125129
return_code = process.wait()
126-
130+
127131
if return_code != 0:
128-
error = process.stderr.read()
129-
yield f"event: error\ndata: {{\n \"status\": \"error\",\n \"message\": \"Simulation execution failed\",\n \"error\": \"{error.strip()}\"\n}}\n\n"
130-
logger.error(f"Streaming simulation failed. Return code: {return_code}, Error: {error.strip()}")
132+
error = process.stderr.read().strip()
133+
yield f"event: error\n"
134+
yield f"data: {json.dumps({'status': 'error', 'message': 'Simulation execution failed', 'error': error, 'timestamp': time.time()})}\n\n"
135+
logger.error(f"Streaming simulation failed. Return code: {return_code}, Error: {error}")
131136

132137
# Close the stream resources
133138
process.stderr.close()
134-
139+
135140
# Send completion event
136-
yield f"event: end\ndata: {{\n \"status\": \"completed\",\n \"message\": \"Simulation completed\"\n}}\n\n"
137-
141+
yield f"event: end\n"
142+
yield f"data: {json.dumps({'status': 'completed', 'message': 'Simulation completed', 'timestamp': time.time()})}\n\n"
143+
138144
return Response(
139145
stream_with_context(generate()),
140146
mimetype="text/event-stream",
@@ -150,8 +156,9 @@ def generate():
150156
logger.exception("Unexpected error during streaming simulation:")
151157
return jsonify({
152158
"status": "error",
153-
"message": "An unexpected error occurred",
154-
"error": str(e)
159+
"message": "An unexpected error occurred",
160+
"error": str(e),
161+
"timestamp": time.time()
155162
}), 500
156163

157164
@app.route("/help", methods=["GET"])
@@ -174,7 +181,7 @@ def simulation_help():
174181
- /run_simulation_stream (POST): Streams results in real-time using Server-Sent Events
175182
176183
COMMON PARAMETERS (JSON body, all optional):
177-
algorithm: "FirstFit" or "ExactFit" (default: "FirstFit")
184+
algorithm: "FirstFit" or "BestFit" (default: "FirstFit")
178185
networkType: 1 for EON (default: 1)
179186
goalConnections: 1-10000000 (default: 100000)
180187
confidence: 0-1 (default: 0.05)
@@ -206,7 +213,7 @@ def simulation_help():
206213
data: {"status": "started", "message": "Simulation started"}
207214
208215
event: data
209-
data: {"status": "running", "data": "Line of output"}
216+
data: {"status": "running", "message": "Line of output"}
210217
211218
event: end
212219
data: {"status": "completed", "message": "Simulation completed"}

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ flask
22
gunicorn
33
pytest
44
pytest-cov
5-
flask-testing
5+
flask-testing
6+
flask-cors

0 commit comments

Comments
 (0)