# Frontend Technical Specification

## 1. Technology Stack
Pure vanilla web stack (`HTML5`, `CSS3`, `vanilla ES6 JavaScript`). Zero build tools, no npm modules, no external runtime dependencies.

---

## 2. Backend Endpoints
The frontend acts as an execution and results visualization client for the following backend routes:

- **Validation & Fuzzing:**
  - `POST /api/apitests` (JSON)
  - `POST /api/apitests/file` (Multipart form-data)
- **Concurrency & Load:**
  - `POST /api/concurrencetest` (JSON)
  - `POST /api/concurrencetest/file` (Multipart form-data)
- **Sequence Simulation:**
  - `POST /api/sequencetest` (JSON)
  - `POST /api/sequencetest/file` (Multipart form-data)
- **Live Stream (SSE):**
  - `GET /api/sequencetest/events/:jobid` (Server-Sent Events)

---

## 3. Input Handling
- **Target Endpoint Selector:** User specifies or selects which backend endpoint to call.
- **JSON Editor:** A code/text editor where the user pastes, types, or uploads their raw JSON payload. The frontend does not validate or parse internal test parameters; it sends the payload as-is to the selected endpoint.
- **File Upload:** Optional file picker for endpoints accepting multipart uploads (`/file` routes).
- **Run Trigger:** Action button to dispatch the request to the backend.

---

## 4. Real-Time SSE Streaming (Sequence Tests)
For sequence simulation requests:
1. Generate a unique `jobid`.
2. Connect an `EventSource` to `GET /api/sequencetest/events/:jobid`.
3. Pass `jobid` with the execution request.
4. Listen for incoming `checkpoint` events and display them live as they stream in.
5. Close the connection when the sequence finishes or is canceled.

---

## 5. Results & Telemetry Processing
All backend endpoints return a unified response schema:

```json
{
  "message": "string",
  "metrics": {
    "latency": {
      "count": 0,
      "average": 0,
      "averageMs": 0,
      "min": 0,
      "max": 0,
      "p50": 0,
      "p75": 0,
      "p90": 0,
      "p95": 0,
      "p99": 0
    },
    "summary": {},
    "dataprocessed": {
      "sent": 0,
      "received": 0
    },
    "cycles": []
  },
  "data": {}
}
```

### 5.1. Common Metrics (All Engines)
- **Latency Percentiles:** `p50`, `p75`, `p90`, `p95`, `p99`, `min`, `max`, and `average`.
- **Data Volume:** Total bytes sent and received (`dataprocessed.sent`, `dataprocessed.received`).
- **Diagnostics & Raw Data:** Inspect failed requests, status codes, and server output contained in `data`.

### 5.2. Concurrency Engine Output Differentiation (`metrics.cycles`)
Unlike the validation and sequence engines, the concurrency engine produces progressive phase-by-phase execution data stored in `metrics.cycles` (normalized from `requestcycle`).

Each cycle item contains:
```json
{
  "requestcyclenum": 1,
  "batchsize": 50,
  "currentConcurrency": 50,
  "totalrequestssent": 50,
  "successfulrequests": 49,
  "totalrequestfailed": 1
}
```
- `requestcyclenum` (number): 1-indexed sequential cycle number.
- `batchsize` (number): Requests allocated to this cycle batch.
- `currentConcurrency` (number): Effective concurrency level for this cycle (reflects incremental ramp-up).
- `totalrequestssent` (number): Number of requests dispatched during this specific cycle.
- `successfulrequests` (number): Successful completions during this cycle.
- `totalrequestfailed` (number): Failures/timeouts encountered during this cycle.

> **Note on Frontend Handling:**  
> The frontend must check if `metrics.cycles` is present and non-empty:
> - If `metrics.cycles` has items (Concurrency Test), render the cycle progression breakdown (e.g. tracking success vs failure rates as concurrency ramps up across cycles).
> - If `metrics.cycles` is empty or null (Validation or Sequence Test), hide the cycle breakdown and display standard latency and diagnostics panels.

---

## 6. Response Abstraction (Success vs Failure)

### 6.1. Success (HTTP 200)
Returned when test execution finishes (even if individual target requests failed).
- **Structure:** Always contains `message`, `metrics` (`latency`, `summary`, `dataprocessed`, `cycles`), and `data` (including `diagnostics` for failed target requests).
- **Target Errors:** Failed target requests are counted in `metrics.summary.totalRequestsFailed` and detailed in `data.diagnostics`.

### 6.2. Failure (HTTP 4xx / 5xx)
Returned on invalid parameters, missing body, or failed sequence conditions.
- **Structure:**
  ```json
  {
    "message": "Error description string"
  }
  ```
- **Unified Key:** All backend error responses consistently surface the failure reason in top-level `message`.
- **Note:** `metrics` is omitted on pre-execution validation errors.

---

## 7. History & Comparison
- **Run History:** Persist recent test runs and their result metrics in `localStorage`.
- **Run Comparison:** Enable selecting two historical runs to calculate performance deltas ($\Delta$ latency percentiles, $\Delta$ errors, $\Delta$ throughput).

---

## 8. Build & Deployment
- Vite compiles the Svelte 5 application into static files (`dist/`).
- The Express backend serves these static files via `express.static()`.
