# HTTP Network Client & Request Staggering

This document explains the mobile app's network client module, request queue throttle logic, and retry policies.

---

## 1. Custom HTTP Wrapper (`Http` class)

All network calls in the app route through the custom `Http` wrapper defined in [http.dart](file:///var/www/html/Smartbulls_app/lib/api/http.dart). This wrapper coordinates security signatures, session tokens, and connection health checking.

---

## 2. Request Queue Staggering (Throttling)

To prevent the client app from sending bursts of concurrent API calls that spike server load, the network client utilizes a static FIFO queue `RequestQueue`:

```mermaid
sequenceDiagram
    participant API1 as API Request 1
    participant API2 as API Request 2
    participant Queue as RequestQueue FIFO
    participant Server as Node.js Server
    
    API1->>Queue: throttle()
    API2->>Queue: throttle()
    Queue->>Server: Execute Request 1
    Note over Queue: Delayed by 100ms
    Queue->>Server: Execute Request 2
```

* **Stagger interval:** 100ms delay between consecutive requests.
* **Benefit:** Smoothes client traffic spikes and ensures that network requests are processed orderly.

---

## 3. Automatic Retry Loop & Backoff

On public servers, intermittent connectivity issues or busy states (HTTP `502 Bad Gateway`, `503 Service Unavailable`, `504 Gateway Timeout`) can fail requests. The network client runs a robust **Retry Loop**:

```mermaid
flowchart TD
    Request[Start Request] --> Execute[Execute request via RequestQueue]
    Execute --> Success{Is Status OK or 2xx?}
    Success -->|Yes| Return[Return Response]
    Success -->|No| CheckRetry{Is Code 502/503/504 & Attempt < 3?}
    CheckRetry -->|Yes| Backoff[Exponential Delay: 2s * attempt] --> Execute
    CheckRetry -->|No| Fail[Throw Timeout/Socket/API failure]
```

* **Attempts Limit:** Max 3 retry attempts.
* **Exponential Backoff:** Delays re-sending by `2 * attempt` seconds.
* **User Feedback:** Displays temporary snackbar: `"Server is busy, retrying... (Attempt X)"`.

---

## 4. Security Signatures & Host Configs

The HTTP client injects Staging/Live signature headers configured in [rest_api.dart](file:///var/www/html/Smartbulls_app/lib/api/rest_api.dart):

```dart
static const headerSignature = 'xStag3!n9_S1gN@tur3_KeY2025'; // Signature verified by Caddy/Proxy
static const host = 'https://app.edistry.com'; // Base endpoint host
static const nodeapiHost = '${host}:3000/api'; // Direct API gateway
```
* Custom headers inject client platform (`Platform.isAndroid ? 'Android' : 'iOS'`), current app version, and the active signature key to satisfy API firewall filtering constraints.
