# Streams

Some checks gather data from many places, and the first parts are ready long before the last. A stream
sends each part as soon as it is in, over server-sent events, so your app can show progress instead of a
spinner. The final result is exactly what the tool's own endpoint returns.

## Start a stream

Send `POST /v1/streams` with the tool's id and the same input its endpoint takes:

```sh
curl -X POST "$API_BASE/v1/streams" \
  -H "Authorization: Bearer $DNSSUPER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tool": "dns-lookup", "input": {"domain": "example.com", "types": "A,MX"}}'
```

Input, credits and limits are checked first, so a bad domain or a low balance comes back here as a normal
JSON error. Otherwise the answer is 202 with a `stream_url`.

## Read the events

Open `stream_url` with any server-sent events client; a browser's `EventSource` works. It needs no API key:
the stream's ID is the access, so treat the URL like a password and don't log it. Each event carries a
JSON object in `data`:

| Event | Data |
| --- | --- |
| `started` | `tool`, `target` and `request_id`. |
| `section` | `section` and its `data`, for example each DNS record type as soon as it is in. |
| `result` | The last event on success: the tool endpoint's full result, plus `replayed`. |
| `error` | The last event on failure: the error body, for example `source_unavailable`. |

Comments (`: keepalive`) keep a quiet connection open. A stream expires 10 minutes after its last event.

## Resume after a drop

Reconnect with the `Last-Event-ID` header set to the last event you got, and the stream carries on from
there. If events stall altogether, `GET /v1/streams/{stream_id}/result` returns everything published so far
as JSON, and waits up to `wait` seconds for the last event. It never charges and never runs the check
again.

## What it costs

A stream costs the same as calling the tool's endpoint. The price is held before the first section is sent
and charged once, when the result is complete, whether or not anyone is still listening. A check that ends
in an `error` event costs nothing. Retrying with the same `X-Request-Id` within 24 hours gives you a stream
holding only the stored result, marked `replayed`, with no new charge.

When too many streams are open at once on our side, reading one can answer 503 `busy` with a
`Retry-After` header; wait that long and try again. The check itself keeps running.
