Live queries
The JS client does this for you. This page is the HTTP underneath. Part of the client API.
A live query is a GraphQL query that the server runs again whenever data it reads changes, and pushes to you when the result is different.
Opening a stream#
POST /live with the same JSON body as POST /graphql. The answer is a
Server-Sent Events stream (text/event-stream) that stays open:
- Lang
- Text
POST /live Content-Type: application/json Authorization: Bearer <access token> {"query": "query ($board: UUID!) { threads(first: 10, filter: {boardId: {eq: $board}}) { items { title } } }", "variables": {"board": "4c1d..."}}
Authorizationis optional. Without it the stream is anonymous, and sees what anonymous callers may view: in the demo forum, its threads, which are public, and their authors, which its$usersrule shows to everyone. With the shared-lists schema an anonymous stream sees nothing: lists need a member, and users are closed.- With it, the stream runs as the signed-in user. A bearer that names no
live session is a
401(token-expiredorinvalid-token, as onPOST /graphql), never an anonymous stream: refresh, then open it again. - A stream belongs to the sign-in whose access token opened it, not to that access token: it stays open across refreshes, and ends when the sign-in does (sign-out, a reused refresh token, its 30 days).
- The query and its variables travel in the body, so they never appear in a URL or an access log, and have no URL length limit.
EventSource can only send a GET, so it can't open a live query. Read the
stream with fetch instead (this is what the client does):
- Lang
- JavaScript
async function subscribe(query, variables, onResult, token) { const headers = {'content-type': 'application/json', accept: 'text/event-stream'}; if (token) headers.authorization = 'Bearer ' + token; const res = await fetch(API + '/live', {method: 'POST', headers, body: JSON.stringify({query, variables})}); if (!res.ok) throw new Error(JSON.stringify(await res.json())); // see Limits and errors const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); let buf = ''; for (;;) { const {value, done} = await reader.read(); if (done) return; // the server closed it: open it again buf += value; let i; while ((i = buf.indexOf('\n\n')) >= 0) { // one event per blank line const frame = buf.slice(0, i); buf = buf.slice(i + 2); const event = /^event: (.*)$/m.exec(frame)?.[1]; const data = frame.split('\n').filter((l) => l.startsWith('data: ')).map((l) => l.slice(6)).join('\n'); if (event === 'result') onResult(JSON.parse(data)); } } }
A real client also reconnects with backoff when the stream ends or goes
quiet (no heartbeat for 45 seconds), and refreshes the access token on a
401.
Each stream holds an HTTP connection open. Serve october over HTTP/2 when you run it yourself (a reverse proxy such as nginx or Caddy in front of it): over HTTP/1.1 a browser opens at most 6 connections to one origin, shared by all its tabs, so six live queries leave no connection for queries, writes or other streams, and the page seems to hang. The hosted service serves HTTP/2.
Events#
Each push is an event: result whose data is JSON:
- Lang
- Text
event: result data: {"data":{"list":{"title":"Weekend","items":{"items":[]}}},"errors":null,"basisT":1026,"mine":false,"cost":{"requested":153,"actual":4,"budget":20000,"remaining":19996}} event: result data: {"data":{"list":{"title":"Weekend","items":{"items":[{"text":"Firewood","done":null}]}}},"errors":null,"basisT":1028,"mine":false,"cost":{...}} event: result data: {"data":{"list":{"title":"Weekend","items":{"items":[{"text":"Firewood","done":null},{"text":"Matches","done":null}]}}},"errors":null,"basisT":1030,"mine":true,"cost":{...}}
This stream was Ada's, watching her list. Bo added "Firewood" (mine: false); then Ada added "Matches" (mine: true).
| Field | Meaning |
|---|---|
data, errors |
the query's result, as from POST /graphql |
basisT |
the database version the result was computed at; it only grows |
mine |
true when every change in this push was made by the subscriber; false for others' changes, for anonymous subscribers, and for the first result |
cost |
this run's cost (the work it did, see Query cost) |
A signed-in subscriber also gets event: basis with data: {"basisT": 1032} when one of its own writes reached the stream without changing its
result (it doesn't read what changed, or the change doesn't show). Every
mutation answers the basis it committed at as extensions.basisT, so a
client can wait until its streams show basisT at or past it before it
reads its own write: the client does that in mutate.
- The first event comes at once with the current result.
- A new event comes only when
dataorerrorschange. A write that doesn't change your result (Ada editing the list'sownerNote, which the query doesn't select) sends nothing. - Use
mineto skip echoes of the user's own writes, or to highlight other people's changes. - A blank line is sent every 15 seconds to keep the connection open.
- Every re-run counts against the subscriber's bucket, like a new
query: the estimate first, then back down to its actual cost (the
push's
costsays both). Subscribing counts for the first result. A query that is light to run once can still empty the bucket when the data it reads changes often: each change it wakes up for is a run. A re-run the bucket can't cover is postponed, not lost: it runs, with every change folded in, once the bucket has refilled.
Limits and errors#
Mutations can't be live (/live is for queries). The checks, in order:
| Status | Cause |
|---|---|
| 401 | the bearer names no live session: token-expired (refresh, then open it again) or invalid-token (sign in again), as on POST /graphql |
| 400 | no query, bad variables, a parse error, a mutation, or over the depth or cost limit. Body: {"errors":[...],"extensions":{"cost":...}}; october's own messages have code BAD_REQUEST. |
| 429 | {"type":"too-many-subscriptions",...,"extensions":{"cost":...}}: too many open streams for this user, counting all their tabs and devices. Retrying doesn't help until one closes. |
| 429 | RATE_LIMITED, with a Retry-After header in seconds |
Every one of these bodies but the 401 carries extensions.cost as POST /graphql
does: {requested, budget, remaining} (no actual: nothing ran), plus limit and max when a limit
refused the query. A refusal takes nothing from the bucket, so remaining is what your
bucket holds now: the signed-in user's, or, without a bearer, your
address's. requested is 0 when the query never parsed.
- Lang
- JSON
{"errors": [{"message": "Cannot query field `nope' on type `Query'.", "locations": [{"line": 1, "column": 3}]}], "extensions": {"cost": {"requested": 0, "budget": 20000, "remaining": 19789}}}
A 400 (or any other 4xx but 401 and 429) is about the request
itself: sending it again gets the same answer.
The server closes a stream when the user signs out, when the client is too slow to read, and when a new schema is pushed to the tenant (on the next request after the push). Open it again when it ends.