> ## 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.

# d1-worker Isolate Profile

> Comprehensive engineering specification for the Hoox D1 SQLite Database Proxy Worker, covering SQL query interfaces, batch operations, and dashboard statistics aggregation.

The **`d1-worker`** is the data routing hub of the Hoox trading platform. Deployed as an isolated, private micro-worker, it acts as a centralized SQL execution proxy. By encapsulating database interactions behind secure Service Bindings, it allows other lightweight compute workers to execute parameterized queries, trigger transactional batch operations, and retrieve structured dashboard telemetry without direct database driver overhead.

***

## ⚡ 1. Declared Wrangler Configurations & Bindings

The `d1-worker` binds directly to the production SQLite database (`trade-data-db`) and does not expose any public endpoints:

```jsonc theme={null}
{
  "name": "d1-worker",
  "account_id": "debc6545e63bea36be059cbc82d80ec8",
  "main": "src/index.ts",
  "alias": {
    "@jango-blockchained/hoox-shared/errors": "../../packages/shared/src/errors.ts",
    "@jango-blockchained/hoox-shared/middleware": "../../packages/shared/src/middleware/index.ts",
    "@jango-blockchained/hoox-shared/router": "../../packages/shared/src/router.ts",
    "@jango-blockchained/hoox-shared/types": "../../packages/shared/src/types.ts",
    "@jango-blockchained/hoox-shared/analytics": "../../packages/shared/src/analytics.ts",
    "@jango-blockchained/hoox-shared/health": "../../packages/shared/src/health.ts",
    "@jango-blockchained/hoox-shared/types/router": "../../packages/shared/src/types/router.ts",
  },
  "compatibility_date": "2026-04-17",
  "compatibility_flags": ["nodejs_compat"],
  "placement": {
    "mode": "smart",
  },
  "observability": {
    "enabled": true,
    "head_sampling_rate": 1,
  },
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "trade-data-db",
      "database_id": "a682f084-594e-4bd8-be2d-40ea5f8cf42e",
    },
  ],
  "vars": {
    "INTERNAL_KEY_BINDING": "__SECRET__",
  },
  "kv_namespaces": [
    {
      "binding": "CONFIG_KV",
      "id": "c5917667a21745e390ff969f32b1847d",
    },
  ],
  "services": [
    {
      "binding": "ANALYTICS_SERVICE",
      "service": "analytics-worker",
    },
  ],
}
```

***

## 🔌 2. 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).

Every endpoint is secured via `requireInternalAuth` and expects the `X-Internal-Auth-Key` header.

### A. Execute Single SQL Query

* **Endpoint**: `/query`
* **Method**: `POST`
* **JSON Payload**:
  ```json theme={null}
  {
    "query": "SELECT created_at, symbol, action, price FROM trades WHERE symbol = ? ORDER BY created_at DESC LIMIT ?",
    "params": ["BTCUSDT", 5]
  }
  ```
* **SELECT Success Response (200 OK)**:
  ```json theme={null}
  {
    "success": true,
    "results": [
      {
        "created_at": 1779261050000,
        "symbol": "BTCUSDT",
        "action": "LONG",
        "price": 68425.5
      }
    ]
  }
  ```
* **Write Success Response (200 OK)** (INSERT/UPDATE/DELETE/REPLACE):
  ```json theme={null}
  {
    "success": true,
    "lastRowId": 123,
    "changes": 1
  }
  ```

***

### B. Execute Transactional Batch Operations

Allows running multiple statements atomically in a single network trip, reducing latency.

* **Endpoint**: `/batch`
* **Method**: `POST`
* **JSON Payload**:
  ```json theme={null}
  {
    "statements": [
      {
        "query": "INSERT INTO trades (id, symbol, price) VALUES (?, ?, ?)",
        "params": ["trade-1", "BTCUSDT", 68000]
      },
      {
        "query": "UPDATE positions SET size = size + ? WHERE symbol = ?",
        "params": [0.005, "BTCUSDT"]
      }
    ]
  }
  ```
* **Success Response (200 OK)**:
  ```json theme={null}
  {
    "success": true,
    "results": [
      { "success": true, "meta": { "last_row_id": 1, "changes": 1 } },
      { "success": true, "meta": { "changes": 1 } }
    ]
  }
  ```

***

### C. Dashboard Telemetry Statistics

Calculates aggregated win ratios, active positions size, and time-series P\&L.

* **Endpoint**: `/api/dashboard/stats`
* **Method**: `GET`
* **Success Response (200 OK)**:
  ```json theme={null}
  {
    "success": true,
    "stats": {
      "totalTrades": 1048,
      "winRate": 64.2,
      "totalPnlUSDT": 18340.5,
      "activePositionsCount": 2,
      "dailyTradesCount": 14
    }
  }
  ```

***

## 🛡️ 3. Security & SQL Injection Protection

To protect financial transaction ledgers and portfolios against SQL injection attacks, `d1-worker` enforces strict development rules:

* **Parameterized Bindings**: All inputs must utilize parameterized placeholders (`?` or `?1`) mapped to `env.DB.prepare().bind()`. **Never** concatenate raw request strings directly into SQL statements.
* **Access Isolation**: The database does not exist publicly. By binding D1 solely to this worker and accessing it via V8 Service Bindings, you prevent external crawlers or bots from querying database nodes directly.

***

<Tip>
  If you are extending schemas or adding tables, generate migration scripts
  locally using Drizzle: `hoox db migrate --remote`. This keeps edge schema
  histories atomic and securely tracked.
</Tip>

### 🔗 Next Steps

* **[System Storage Architecture](../architecture/storage)** — Review SQLite properties and R2 bucketing pipelines.
* **[Database Operations Manual](../../enduser/guides/database-ops)** — Learn commands to run query ledgers and restore backups.
