Remote / foldkit-remote-server

Live data

A live subscription is one stream per Entity, from that Entity's live Source. There are three ways to produce one:

  • write a live Source directly, below;
  • over Drizzle, foldkit-remote-drizzle's pollLive, a live Source that re-reads the subscribed rows and lists from inside the subscriber's own request, which is what Workers need;
  • in a long-lived process, a liveHub that re-reads what each write changed.

Write a live Source directly

ts
// `projectEvents` is your own stream of `LiveChange`s.
const ProjectLive = RemoteServer.live(Project, {
  subscribe: ({ requirements, queries, after, principal }) =>
    projectEvents({
      requirements,
      queries,
      after,
      principal,
    }),
})

after is the client's resume cursor. Events at or before it are duplicates, and the stream's cursors count on from it: its first event is after + 1, or the client takes the skipped cursors for a gap and restarts the stream. The stream carries Remote LiveChanges: entity patches/deletes and connection insert/remove/invalidate events.

queries are the lists of this Entity the subscriber reads live (liveQuery(Data, …)), each a LiveQuery the handler has already admitted and resolved: identity (the connection as the client keys it, for the connection events), select (what the read draws of each row), and edges, the registered query run as the subscriber with the page's window. The handler refuses, with RemoteLiveRefused and before any live Source is asked, a list of a query it does not register, an input that does not decode, one with no select or no first, one whose select is of another Entity than its query lists (a QuerySource names that Entity: RemoteServer.query reads it from the descriptor's connection), and one whose first, added to the ids of its Entity the subscription names, passes maxIdsPerEntity. A subscription watches at most 32 lists (MAX_LIVE_QUERIES), refused at decode.

If an Entity has no live Source, it contributes no stream. That is not an error: the client planner can fall back to refetching it.

A live Source that reads rows to send them must read them as a read would, or it sends what the read handlers withhold. RemoteServer.readAs is that read: only the asked fields the Source declares and its authorize allows, each record through its filter, and no other field.

ts
const asReader = RemoteServer.readAs(ProjectSource, {
  ids: ['p1'],
  fields: ['name', 'privateNotes'],
  principal: { isAdmin: false },
})
// An Effect that succeeds with Option.some([{ id: 'p1', values: { name: 'Apollo' } }]),
// or Option.none() when the principal may read none of the fields asked.

RemoteServer.allowedFields(ProjectSource, principal, fields) says which of fields that read would read, without reading: a Source reading several rows together, each asked for fields of its own, reads them in one read and still tells nothing of a row whose fields the principal may read none of.

A live Source that sends only what it reads through one Source names it as reads, so a startup check can trust it as far as it trusts that Source: GuardServer.validate accepts a live Source over a guarded Entity only when it reads the guarded Source it checked. foldkit-remote-drizzle's pollLive reads through readAs and sets reads.

Let a liveHub re-read changed fields

A hub fans what changed out to live subscribers. Give it to the handlers, and every mutation's answer is published to it: each patch as a change of the fields it carries, each deletion as a deletion. A mutation Source names nothing twice.

ts
// Building a hub is an Effect.
const program = Effect.gen(function* () {
  const entitySources = [ProjectSource]
  const hub = yield* RemoteServer.liveHub(entitySources)

  const handlers = RemoteServer.handlers(Server, principal, {
    live: hub,
  })

  // Only for a write that is not a mutation: a database trigger consumer, a job.
  yield* hub.changed(Project.ref('p1'), ['name'])
  yield* hub.deleted(Project.ref('p1'))
  return handlers
})

A mutation's publish runs after its Source returned, so after a write that commits as it goes. A failed publish is reported as a PublishFailed diagnostic and the mutation still answers: its write has happened, and a failed answer would be retried.

The hub remembers each subscriber's requirements and principal. changed:

  1. intersects the changed fields with what each subscriber selected;
  2. re-reads only that intersection through the Entity Source;
  3. applies that subscriber's authorization again;
  4. emits the resulting patch with a continuing cursor, or a deletion where the re-read no longer finds the row: deleted, or moved out of that subscriber's sight.

deleted asks each subscriber again too, for every field it selects: a row deleted for one writer may only be hidden from them, so a subscriber that still reads it is sent what it now sees, and only one it is gone for a deletion. One subscriber's failed read does not keep the others from theirs; the call fails once they are sent.

Subscribers that selected none of the changed fields do no work, and subscribers with one principal share one re-read. One principal means the same value, unless the hub is given a key: then two requests whose principals have one key, each with a principal object of its own, share it, read as the first of them. A key must therefore name everything the Sources decide by, the reader itself included when a Source answers a viewer-relative member (a Derived.exists, whose value is each reader's own; foldkit-guard's Policy.keyOf names every field of the principal). A key by role, as here, fits Sources that answer only by role:

ts
const keyed = Effect.gen(function* () {
  return yield* RemoteServer.liveHub([ProjectSource], {
    key: (user: Principal) => (user.isAdmin ? 'admin' : 'member'),
  })
})

Fields every principal reads alike

A re-read per principal is how the hub stays exact when who is asking decides what a row shows. Where nothing does, a Source can say so, and the hub sends a written value as it is:

ts
// Everyone reads a project's name alike; only an admin reads its private notes.
const SharedProjectSource = RemoteServer.entity<Principal>(Project, {
  authorize: ProjectSource.authorize,
  read: ProjectSource.read,
  shared: ['name'],
})
  • shared names fields every principal reads alike, of every row: no rule about who is asking hides the row or the field, or changes its value. The server trusts it, so declare it only where that holds; a field the Source does not serve is refused when the Source is made.
  • hub.changed(ref, fields, values) takes the row's stored values. A shared field among them goes to each subscriber that selected it with no read; the rest are re-read as above. A field a subscriber pages with a window is always re-read.
  • The handlers pass a declared write's answer (RemoteServer.write), which is the row as stored. A handler's answer is its own claim, so its fields are re-read.
  • foldkit-remote-drizzle's source and RemoteServer.memory take it too, and foldkit-guard's GuardServer.validate refuses a shared field a Read rule could tell readers apart by. source refuses a Derived.exists as shared: it is each reader's own.

A hub is an in-memory fan-out, so whatever calls changed must be able to wake the subscriber's fiber. In a worker it cannot: one request cannot wake another's stream, so a hub fed from a second request delivers nothing and tears the first stream down: the open response belongs to the request that opened it, and the Workers runtime cancels it when another request wakes it. On Workers, poll the shared store from inside the subscriber's own request instead, as pollLive does. A hub is right for a long-lived server process that owns both sides.

A hand-written live Source and a hub number their events independently. Use one or the other for a given subscription path rather than mixing cursor domains.