> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hoox.sh/llms.txt
> Use this file to discover all available pages before exploring further.

# analytics-worker Isolate Profile

> Comprehensive engineering specification for the Hoox Analytics Observability Worker, covering Analytics Engine datasets, latency metrics, and dashboard API queries.

The **`analytics-worker`** is the observability engine of the Hoox trading platform. Deployed as a private internal microservice, it aggregates time-series metrics, database query latencies, execution performance ratios, and API status codes across all V8 isolates. By translating incoming events and writing them to **Cloudflare Analytics Engine**, it provides the backend telemetry used to draw live charts in the Next.js Dashboard.

***

## ⚡ 1. Declared Wrangler Configurations & Bindings

The `analytics-worker` binds directly to Cloudflare’s **Analytics Engine** dataset and does not expose any public endpoints:

```jsonc theme={null}
{
  "name": "analytics-worker",
  "main": "src/index.ts",
  "compatibility_date": "2026-04-17",
  "compatibility_flags": ["nodejs_compat"],
  "account_id": "debc6545e63bea36be059cbc82d80ec8",
  "analytics_engine_datasets": [
    {
      "binding": "ANALYTICS_ENGINE",
      "dataset": "hoox-analytics",
    },
  ],
  "placement": { "mode": "smart" },
  "observability": { "enabled": true, "head_sampling_rate": 1 },
}
```

> No `CLOUDFLARE_API_TOKEN` or `CLOUDFLARE_ACCOUNT_ID` are in `secrets` — these are set as `vars` in `wrangler.jsonc` and used for the Cloudflare SQL API query path.

***

## 🔑 2. Environmental Variables & Encrypted Secrets

* **`CLOUDFLARE_API_TOKEN`** (var): A secure token with `Account.Analytics` read permissions, allowing the worker to query stored datasets via the Cloudflare SQL API.
* **`CLOUDFLARE_ACCOUNT_ID`** (var): Your Cloudflare Account ID used in SQL API requests.

***

## 🔌 3. Internal REST API Specification

> **Note:** For the canonical endpoint directory with full request/response examples across all workers, see [`/docs/devops/api/endpoints`](../api/endpoints).

All endpoints are reachable via Cloudflare Service Bindings only (no public URL). Each endpoint validates its payload with a Zod schema using `.strict()` to reject unknown fields.

### A. Track Trade Event

* **Endpoint**: `POST /track/trade`
* **Payload**:
  ```json theme={null}
  {
    "payload": {
      "exchange": "binance",
      "symbol": "BTCUSDT",
      "action": "LONG",
      "quantity": 0.5
    },
    "result": { "success": true },
    "latencyMs": 1200
  }
  ```
* **Response**: `{ "success": true }`

### B. Track API Call Event

Invoked by other workers (like `hoox` or `trade-worker`) immediately upon completing an action.

* **Endpoint**: `POST /track/api-call`
* **Payload**:
  ```json theme={null}
  {
    "worker": "trade-worker",
    "endpoint": "/api/v3/order",
    "latencyMs": 250,
    "success": true
  }
  ```

#### Under-the-Hood Analytics Engine Write

The worker formats and writes a time-series data point to the `hoox-analytics` dataset:

```typescript theme={null}
env.ANALYTICS_ENGINE.writeDataPoint({
  blobs: ["api-call", "trade-worker", "success", "/api/v3/order", ""],
  doubles: [250, 0, 0],
  indexes: ["550e8400-e29b-41d4-a716-446655440000"],
});
```

* **Response (200)** : `{ "success": true }`

### C. Track Worker Performance

* **Endpoint**: `POST /track/worker-perf`
* **Payload**:
  ```json theme={null}
  {
    "data": {
      "worker": "trade-worker",
      "requests": 100,
      "errors": 0,
      "duration": 25000
    }
  }
  ```

### D. Track Signal

* **Endpoint**: `POST /track/signal`
* **Payload**:
  ```json theme={null}
  {
    "data": {
      "source": "agent-worker",
      "type": "BUY",
      "symbol": "ETHUSDT",
      "confidence": 0.85
    }
  }
  ```

### E. Track Notification

* **Endpoint**: `POST /track/notification`
* **Payload**:
  ```json theme={null}
  {
    "data": { "type": "trade_executed", "target": "telegram", "success": true }
  }
  ```

### F. Health

* **Endpoint**: `GET /health`
* **Response**: `{ "status": "ok", "worker": "analytics-worker" }`

***

### Query Methods (Exported Functions)

The analytics worker exports query functions that are called via Service Bindings (not HTTP). Each builds a SQL query and executes it against the Cloudflare Analytics Engine SQL API:

| Function                                   | Parameters        | Purpose                       |
| ------------------------------------------ | ----------------- | ----------------------------- |
| `getTradeMetrics(timeRange)`               | ISO date range    | Trade counts by exchange      |
| `getTradesByExchange(exchange, limit)`     | Exchange name     | Recent trades for an exchange |
| `getTradeSuccessRate(timeRange?)`          | Optional ISO date | Overall trade success rate    |
| `getWorkerPerformance(worker, timeRange?)` | Worker name       | Request counts and latency    |
| `getApiCallStats(exchange?)`               | Optional exchange | API call statistics           |
| `getSignalOutcomes(timeRange?)`            | Optional ISO date | Signal analysis by source     |

All SQL queries are built via `sanitizeQueryInputs()` which validates parameters using allowlists and regex to prevent SQL injection.

***

## 📈 4. Dashboard Visual Integrations

The metrics written to `hoox-analytics` are queried by the dashboard to render:

1. **System Health Indicators**: Real-time error spikes trigger warning banners in under 2 seconds.
2. **Isolate Latency Charts**: Visual line graphs showing V8 processing speeds vs exchange API transit speeds.
3. **Volume Load Heatmaps**: Visualizes peak trading hours and signal traffic volumes globally.

***

<Tip>
  Testing analytics locally? Local Wrangler dev automatically intercepts
  `writeDataPoint` calls and logs the parsed Blobs and Doubles straight to your
  terminal standard output, ensuring easy debugging!
</Tip>

### 🔗 Next Steps

* **[System Observability Guides](../deployment/monitoring)** — Deepen your understanding of time-series logging and metrics.
* **[trade-worker Profile](trade-worker)** — Review how execution latency details are generated and offloaded.
