Live updates
A resource with .live() keeps the pages people have open on its records current: when a record changes, every open list, record page, count and chart of the resource reads it again within a second or two, without a reload. The changes are captured by the same database triggers as events, so writes from psql, other services and cron SQL show up too, not only those through the API.
import { f, resource } from '@protobase/schema'
// A team's tasks: a list or task page someone has open shows a colleague's change within a second or two.
/** tasks */export const tasks = resource('tasks') .table('tasks') .fields({ id: f.integer().readOnly().filterable().sortable(), title: f.text(), status: f.enum(['todo', 'doing', 'done']).default('todo').filterable(), }) .primaryKey((r) => r.id) .live()What a page hears
Section titled “What a page hears”The server tells each open app which records changed, by resource and key, never their values. The app then reads again what it shows of that resource through the regular API, as its user, so the same tenant, row filters and field rules apply as to any other read. A page only hears of the live resources its user may list or read, in their tenant.
Changes that come close together are read once: a page gathers them for 300 milliseconds. A form with unsaved changes keeps the record it was opened with, so its Save still finds a conflict when someone else changed the record; the record is read again once the form is saved or left.
It is live data, not multiplayer editing: two people editing the same record still see a conflict on Save, as without .live().
The stream
Section titled “The stream”An app with the relay serves no stream: its pages hear the same over the relay. GET /api/live answers a text/event-stream to anyone who may read a live resource, a visitor of the anonymous role too. Each event’s data is JSON with a cursor:
type |
|
|---|---|
current |
Nothing new up to cursor. Sent first, and every 25 seconds. |
changes |
changes: [{ resource, key, operation }] in commit order, operation being create, update, delete or undelete. |
resync |
Changes went by that are no longer kept: read everything shown again. |
refresh |
The caller’s access changed, through live.refresh: read everything shown again. The stream then ends, so the page connects again with ?after=<cursor> and hears what its access allows now. |
Connecting again with ?after=<cursor> catches up on what was missed while disconnected. client.live({ onChanges, onResync }) of @protobase/client follows the stream and connects again by itself, as the app does. However many callers of one client follow it, they share one stream, so a page with many live views holds one connection, which matters under HTTP/1.1, where a browser opens at most six to a host.
Live tokens
Section titled “Live tokens”A list or record read of a live resource gives a live token on request: GET /api/v1/<resource>, GET /api/v1/<resource>/<key>, the list under a record and :search take RFC 7240 Prefer: live, or ?live=1 where a page cannot set headers. The answer then has Preference-Applied: live and the token in Protobase-Live. Without the request the server resolves and encrypts nothing. These reads answer Vary: Prefer, so a cache keeps the two answers apart, and the API’s CORS allows Prefer and exposes Protobase-Live and Preference-Applied.
The token is a JWE (dir, A256GCM), so its holder can neither read nor change it. It holds:
| Claim | |
|---|---|
subs |
One subscription, { resource, where }. resource is the table read, as schema.table outside the public schema; a table or schema whose name holds a dot gets no token, since the change stream never takes one. where is what the read keeps to, as a condition on the row’s columns alone: the soft delete, the tenant, the access row filter, the parents the caller must read, the caller’s own filter, and a record read’s key. Left out when nothing is kept out. |
fields |
The fields the read returned. |
snapshot |
The read’s pg_current_snapshot(). The whole read runs in one REPEATABLE READ snapshot, so the token tells exactly which transactions the rows include. |
sub, sid |
The signed-in person and their sign-in session, which the token is bound to. |
anonymous |
true for a visitor’s token, which is bound to no session. |
iat, exp |
When it was issued and when it expires. |
A signed-in person’s token expires when their session ends, after an hour at most. A visitor’s token lasts an hour, longer than any cache time of the API, which lets none. An API key, an outside app acting for a person and a caller without a session of the app get no token. The token is sealed with a key derived from the relay’s ticket key, so an app without a relay gives none.
When a session ends, by a sign-out, a revoke, a ban or a delete in SQL, its tokens stop getting changes committed after it. The trigger on the sessions table that closes the session’s relay sockets also writes a row (sid, exp) to changes.revocations, in the transaction that deletes the session. exp is the latest expiry a token of the session can have: an hour after the session ends, or the session’s own expiry if that comes first. The same statement deletes the rows past their exp. The relay’s changes service creates changes.revocations with its own migration and reads it; Protobase writes no migration for it. A read gives no token while the table is missing, since no sign-out would end the token. The trigger finds the table in the catalog, so a role that may not insert into it makes the sign-out fail rather than leaving the token live. exp because locking the session row when a token is issued is not implemented.
Conditions that read other rows are evaluated when the token is issued: a parent the caller must read, a related() term and a lookup field become the list of keys they match at that moment, such as {"in": ["project_id", [4, 9]]}. A record that starts to match one of them later is not in the token, and a role or membership change does not change a token already issued; refresh the person’s pages instead.
A condition is JSON of one operator: {"eq": [column, value]}, neq, lt, lte, gt and gte for the filter’s comparisons, {"in": [column, [values]]}, {"is_null": column}, and and, or and not. A value is a string, a number or a boolean, written so the change stream compares it with the column as Postgres does: an integer or decimal as a number, a uuid in lower case, a related key as the type of the key it points at, and an integer too long for a JSON number as its text, for equality only.
The server gives no token, and no Preference-Applied, when it cannot write the read as conditions on the row alone. similar, regex, a text pattern, a JSON field term, now(), a date or timestamp, an order on text or booleans, a relation to a key of several parts, or a number written in a form the change stream reads differently, because matching those in the change stream as Postgres does is not implemented.
Refreshing access
Section titled “Refreshing access”live.refresh({ user }), on the context of an API function, also one served for supabase-js, and of a function a webhook subscription calls, tells the open pages of the user with that id to read everything they show again, which gives them new tokens for their access as it is now. Call it once a change of their roles or memberships has committed. It writes a notice in its own transaction, so a page that reconnects with ?after= still gets it; with the relay, it publishes refresh to the user on the relay’s people channel, and the page also reads again each time its socket connects again. In an app without a live resource or calls it does nothing.
Over the relay
Section titled “Over the relay”In an app with the relay, each page follows its live resources on the relay’s one socket, with the socket its other relay features use. client.relay.live({ resources, polled?, onChanges, onResync }) of @protobase/client does the same from code, sharing one socket however many callers follow it. For each resource it reads a token of every record the caller may read, GET /api/v1/<resource>?limit=1 with Prefer: live, and joins the relay’s live query live:<resource> with it. It then hears the changes as onChanges does above, and reads the resource again once, since what the page read came before the token.
- Each change carries a cursor. When the token expires, or the socket connects again, it joins with a fresh token after the last cursor, so nothing in between is missed.
- When the relay’s changes service no longer has every change since the cursor, the live query starts again from a new read, and the resource is read again.
- The relay’s
peoplechannel carriesrefresh, which reads everything again with new tokens, andrings, for the calls that ring the person.
A resource the relay cannot keep live is read again every 30 seconds instead, and whenever the window gets the focus again, as every query is. That happens when the read gives no token, when the relay has no changes service or lost it, and while the socket is down. Polling stops at the resource’s next change. A token read that got no answer is tried again at each poll, until the join succeeds. A resource live from others, given in polled, is always polled this way. .live({ reads })) cannot update at once over the relay because live queries of the resources it reads are not implemented.protobase dev cannot take live updates over its relay, and poll instead, because running a change stream for that relay is not implemented.
Resources backed by a view
Section titled “Resources backed by a view”A resource backed by a database view, such as a chat thread that merges messages and replies, updates live when the tables it reads change. A view takes no trigger, so name the resources it reads with .live({ reads }): a change in any of them refreshes the view’s open lists, record pages and related lists, and a change in another table does not. protobase migration cannot refuse a trigger on a resource backed by a view before Postgres refuses it as the file applies because reading which tables are views without a database is not implemented.
import { f, resource } from '@protobase/schema'
// A chat thread over a view merging messages and replies: an open thread shows a new message or reply within a second or two.
/** thread */export const thread = resource('thread') .table('thread') .fields({ id: f.text().filterable(), body: f.text(), sent_at: f.timestamp().sortable(), }) .primaryKey((r) => r.id) .live({ reads: ['messages', 'replies'] })Each resource it names is captured like a live one, needs no .live() of its own and still needs a resource of its own; protobase dev and protobase serve do not start when a name is not a resource, or is another resource backed by a view: name the tables that view reads instead. The stream sends the view a change with an empty key, { resource, key: '', operation: 'update' }, once for writes that come close together: any of its records may have changed, so the page reads what it shows of the view again. A reader hears of it in the tenant of the record that changed, or in every tenant when that resource has no tenant.
Polling, then a socket
Section titled “Polling, then a socket”pollThenSocket({ poll, onError, socket, onMessage, pollMs?, switchAfterMs?, socketFirst? }) of @protobase/client, in the browser and on Node, keeps up with anything that changes, until the function it returns is called. It calls poll at once and again pollMs (5 seconds) after each call ends, also after one that rejected, whose error goes to onError, and after switchAfterMs (30 seconds) opens the WebSocket socket() returns, such as () => new WebSocket(url). Once the socket is open, polling stops: poll runs once more, for what changed before the socket opened, and onMessage gets each message’s data. When the socket closes, or never opens, it polls again at once and opens a new socket switchAfterMs later. Polling goes on while a socket connects, so nothing waits on it. A short visit thus never opens a socket; socketFirst: true opens one at once instead, for a process that stays, and polls only while it is down.
Who is on a record’s page and what they send each other, which no change of a record says, goes over the record’s channel.
The table
Section titled “The table”protobase migration adds the table changes.notices to the changes schema of the event capture (renamed with events: { schema }), and the capture triggers of each live resource and of each resource a live view reads; apply it with the project’s other migrations. protobase dev and protobase serve do not start while the record of migrations lacks the table or a trigger.
A notice is a resource, a record key, the record’s tenant and the operation, written by the changes.dispatch job in the transaction that removes the change from the outbox; a live resource therefore needs the jobs schema and the app’s workers. Notices are kept for 10 minutes. Each serving process with at least one page open reads the table once a second, however many pages it serves, so live updates work with several serving processes, with PROTOBASE_JOBS=false and through a pooler in transaction mode.