# Live stream (WebSocket)

`GET /api/v1/customer/stream` is a WebSocket (RFC 6455) that pushes every newly released signal your package may see:
the same scope as `GET /api/v1/customer/signals`. A signal usually arrives within about a second of its release.
Opening a stream counts as one request against your quota; pushed signals cost nothing.

<Figure name="stream-sequence" caption="Connect (with a ticket from a browser), receive ready and signals, answer pings, and resume with lastEventId after a disconnect." />

## Connect

Use `wss://` on your RiskPilot host (`ws://` only for a local `http://` server). You need `signals:read` (any
session, the live key, or a named key with that scope). The sandbox key cannot stream.

### From a server or a mobile app

Send the credential on the upgrade request:

<CodeTabs>

```js title="Node (ws package)"
// npm install ws  (Node's built-in WebSocket cannot set headers)
import WebSocket from "ws";

const url = `${process.env.RISKPILOT_URL.replace(/^http/, "ws")}/api/v1/customer/stream`;
const ws = new WebSocket(url, "riskpilot.v1", { headers: { Authorization: `Bearer ${process.env.RISKPILOT_KEY}` } });

ws.on("message", (data) => {
  const msg = JSON.parse(String(data));
  if (msg.type === "signal") console.log(msg.id, msg.signal.ticker, msg.signal.className, msg.signal.headline);
});
ws.on("close", (code, reason) => console.log("closed", code, String(reason)));
```

```python title="Python (websockets)"
import asyncio, json, os
import websockets  # pip install "websockets>=14" (older versions call it extra_headers)

async def main():
    url = os.environ["RISKPILOT_URL"].replace("http", "ws", 1) + "/api/v1/customer/stream"
    headers = {"Authorization": f"Bearer {os.environ['RISKPILOT_KEY']}"}
    async with websockets.connect(url, additional_headers=headers, subprotocols=["riskpilot.v1"]) as ws:
        async for raw in ws:
            msg = json.loads(raw)
            if msg["type"] == "signal":
                s = msg["signal"]
                print(msg["id"], s["ticker"], s["className"], s["headline"])

asyncio.run(main())
```

</CodeTabs>

React Native's `WebSocket` accepts headers too: `new WebSocket(url, ["riskpilot.v1"], { headers: { Authorization } })`.
The subprotocol `riskpilot.v1` is optional.

### From a browser

Browsers cannot set headers on a WebSocket, and a key must never be in a web page. Instead, get a one-time
**ticket** and open the stream with it. In your own web app, let your backend ask for the ticket with its key and
hand only the ticket to the page; an app that holds a signed-in session can ask for it directly:

```js
const res = await fetch("/api/v1/customer/stream/ticket", {
  method: "POST",
  headers: { Authorization: `Bearer ${session}` },
});
const { ticket, expiresAt, path } = await res.json(); // 201; path = "/api/v1/customer/stream?ticket=…"
const ws = new WebSocket(`${location.origin.replace(/^http/, "ws")}${path}`, "riskpilot.v1");
```

A ticket works once, within 60 seconds, and is bound to the credential that asked for it. `POST /stream/ticket` is
not metered; opening the stream is.

## Messages

The server sends JSON text frames. Each has a `type`:

| Type | When | Fields |
| --- | --- | --- |
| `ready` | first, once per connection | `lastEventId` (the newest event now), `heartbeatMs`, `packageId`, `classes`, `historyWindowDays`, `quota` |
| `signal` | each newly released signal in your scope | `id` (event id), `signal` (the same object as in the REST list) |
| `heartbeat` | every `heartbeatMs` (25 s) | `at` |
| `replayed` | after a resume, once the missed signals were sent | `count`, `lastEventId` |
| `reset` | after a resume, when the gap cannot be replayed | `reason` (`too_many_missed`, `expired`), `lastEventId` |
| `pong` | answer to your `{ "type": "ping" }` | `at` |
| `error` | just before the server closes | `code`, `message` |

```json
{ "type": "signal", "id": "9121", "signal": { "filingId": "0001437749-26-031545", "className": "ACTION", "score": 87, … } }
```

Event ids are increasing integers sent as strings. Two signals released a moment apart may arrive in either order.

The only message a client may send is `{ "type": "ping" }` (at most 20 messages per 10 seconds, 4 KiB each); you do
not need it, the server's heartbeat keeps the connection alive.

## Heartbeat

Every 25 seconds the server sends a WebSocket **ping frame** and a `heartbeat` message. Your WebSocket library answers
the ping on its own; a client that has not answered the previous ping is disconnected (4408). Browsers cannot see ping
frames, so watch the `heartbeat` messages: if nothing arrives for about 70 seconds, treat the connection as dead and
reconnect.

At each heartbeat the server also checks your credential again: a revoked key or ended session closes the stream
with 4401, a suspended account with 4403, a lapsed payment with 4402.

## Resume after a disconnect

Keep the newest event id you have seen: the `id` of each `signal`, or the `lastEventId` of `ready`, `replayed` or
`reset`. Reconnect with it:

```
GET /api/v1/customer/stream?lastEventId=9121
```

(or send it as a `Last-Event-ID` header). After `ready`, the server replays the signals you missed, in your current
scope, then sends `replayed`. If more than 200 were missed, or the id is older than the 72 hours of retained events,
you get `reset` instead: fetch what you missed over REST (`GET /customer/signals?sort=newest`, until a signal you
have), then carry on from the `reset`'s `lastEventId`.

```js
let lastEventId = null;
let delay = 1000;

function connect() {
  const query = lastEventId ? `?lastEventId=${lastEventId}` : "";
  const ws = new WebSocket(`${streamUrl}${query}`, "riskpilot.v1", { headers });
  ws.on("open", () => { delay = 1000; });
  ws.on("message", (data) => {
    const msg = JSON.parse(String(data));
    if (msg.type === "signal") { handle(msg.signal); lastEventId = msg.id; }
    else if (msg.type === "ready" && !lastEventId) lastEventId = msg.lastEventId;
    else if (msg.type === "replayed") lastEventId = msg.lastEventId;
    else if (msg.type === "reset") { void refetchOverRest(); lastEventId = msg.lastEventId; }
  });
  ws.on("close", (code) => {
    if ([4401, 4402, 4403].includes(code)) return; // fix the credential or the account first
    setTimeout(connect, delay + Math.random() * 1000);
    delay = Math.min(delay * 2, 60_000);
  });
}
connect();
```

Signals are idempotent by `filingId`: if your handler might see one twice (a replay after a reconnect), key your
writes on it.

## Close codes and refusals

| Close code | Meaning | Reconnect? |
| --- | --- | --- |
| 1001 | The server is restarting | Yes, with `lastEventId` |
| 1008 | Too many client messages | Yes, and send fewer |
| 4401 | The credential stopped working (revoked, rotated, session ended) | Only with a new credential |
| 4402 | Payment needed | After billing is fixed |
| 4403 | The account is suspended, or the key lost access | No |
| 4408 | No answer to the ping | Yes |
| 4409 | Not reading fast enough (1 MiB queued) | Yes, with `lastEventId` |

A refused handshake answers with an HTTP status and the usual JSON error: 400 (bad request or `lastEventId`), 401,
402, 403 (`paused`, `sandbox_read_only`, `key_scope`), 429 (requests per minute, `stream_limit` above 5 open streams
per account, or a quota code; with `Retry-After`), 503 (`stream_off`, `stream_busy`).
