Sync / foldkit-sync

Advanced: the replica

Sync.mount is the normal path. Underneath, a Replica works on the shared slice alone, and an application that is not a Foldkit runtime (a worker, a server-side actor, a test) uses it directly.

ts
const worker = Effect.gen(function* () {
  const storage = yield* Sync.indexedDb('todos/worker')
  const replica = yield* TodoSync.openReplica(storage)

  yield* replica.submit(Message.CreatedTodo({ id: 't1', title: 'Milk' }))
  const optimistic = yield* replica.shared // includes the pending edit

  yield* replica.synchronize // one exchange
  return optimistic
}).pipe(Effect.scoped, Effect.provide(Sync.transport.socket({ url: 'wss://example.com/sync' })))

submit(message) takes a durable Message: on a replica from Sync.forApplication(App).make, a local one does not compile, and an annotated export names the subset (Sync<Message, Shared, Durable>). It checks again that the Message is durable, replays it against the current optimistic state, gives it a stable operation id, saves it to the outbox, publishes the new optimistic value, and wakes the loop. It sends nothing. A Message replay refuses never enters the outbox.

synchronize takes one snapshot of the cursor and outbox, performs one exchange, validates the answer, and reconciles it with the replica's current state, so an edit submitted while the request was in flight survives.

The rest of the surface: committed (the base alone), pending, cursor, status, statusChanges, changes (status and shared from one snapshot), snapshot (the same plus nextLocalSequence), start, dismiss (forgets a status.refused operation), and close. pending and a rejection's operation are WrittenOperations: as written, with messageVersion.

The exchange

One request, one answer. A custom server implements this; a custom transport carries it.

Request fields:

  • cursor: last committed sequence the replica holds.
  • pending: pending operations as written (messageVersion past 1).
  • epoch?: the server history epoch, once heard.

Answer fields:

  • operations: contiguous operations committed after cursor.
  • acknowledged: ids the server accepted without repeating them.
  • rejected: ids the server refused.
  • refusals?: [{ opId, refusal }] encoded SyncRefusal reasons for rejected ids.
  • reasons?: [{ opId, reason }] deprecated strings (at most 500 chars each).
  • checkpoint?: { cursor, model } when older history was compacted.
  • more?: true when another page follows.
  • epoch?: the server's current history epoch.

An acknowledged operation leaves the outbox once its committed copy has arrived or the last page has been read. A rejected one leaves at once.

A custom server that reads operations through the codec, or appends them to a Durable journal itself, must do what journalExchange does with a newer messageVersion than its own (codec.messageVersion): fail the whole exchange before appending anything. Durable alone sees such an entry as an InvalidOperationError, and rejecting it by id loses the edit. It reads each sent entry with codec.writtenFrom before appending it, too: that is where a server-only Message, a replica id under server/ or one past 128 characters is refused. Stored history is read with journalContract().operation.decode, which takes the server's own Messages; a journal decoding its rows with codec.normalizeOperation would refuse them. The replica validates every field; see when things go wrong.

Transports

Transport is an Effect service with one operation. Sync ships:

  • Sync.transport.socket({ url, … }): a reconnecting WebSocket client. It queues exchanges while connecting, retries on a jittered backoff capped at maxRetryDelay (5 s), keeps request ids stable across resends, and after maxRetries (5) consecutive failed connections fails queued work and fails new exchanges fast until a socket is healthy again. maxQueue (64) bounds the queue. Instead of a url, pass makeSocket: () => SocketLike to connect over something else; it is called again on each reconnect. Beside Transport it provides TransportSocket, the connection it keeps, for another protocol to share; a layer without a socket has no TransportSocket in its type.
  • Sync.transport.serve(socket, { exchange, changes? }): the server side of one accepted socket. With changes, a subscription to the document's commits, it sends a notice after each; the client's loop exchanges on every notice, so a tab that is only reading still sees others' edits without polling.
  • Sync.transport.portSocket(port, { signal? }): a socket over a MessagePort, for a server in a worker or in the page. A port tells neither end when the other goes, so its onClose fires on close() or when signal aborts: a host aborts it when the pane it serves is gone, and serve stops. A client opens one per connection: Sync.transport.socket({ makeSocket: () => Sync.transport.portSocket(open()) }).
  • Sync.transport.loopback(handler), fromPromise(client), toPromise(shape), and nativeSocket for the platform WebSocket.

A refusal is data in the answer; only a wire failure is a TransportError.

When a served exchange throws. What the handler given to Sync.transport.serve throws is the server's own, and its replica reads none of it: the error frame is { id, error: 'Exchange failed', incident }, and what was thrown is reported as an ExchangeDefect under that incident, to serve's diagnostics reporter when given, else the default. The replica fails the exchange with a TransportError carrying the incident, shows Exchange failed in status.lastError, keeps its outbox whole and asks again on its backoff, as for any wire failure. This is the failure of an exchange as a whole; an operation the journal refuses is still a per-operation rejected, which the replica drops. Words meant for the replica are thrown as a new ExchangeRefused({ message }), sent as written with no incident: the journal's own are This connection may not open the document, a cursor ahead of the server's, and a pending entry that names no operation; a replica newer than the server (UnsupportedMessageVersionError) is told so the same way. A stored operation no build reads (UnreadableHistoryError) is both: reported under an incident, and answered with the journal's one sentence for it. A replica older than this change reads the frame as before: error is still a string, and incident a field it ignores.

When the host cannot say who is asking. A caller the resolver refuses reads the refusal's reason, or Unauthenticated: a 401 at the upgrade, a 4401 close on an open socket. A resolver that breaks answers a 500 Internal error with an incident, or closes with 1011; the cause is a HostDefect. The socket transport reads neither a refused upgrade's body nor a close's code: to the replica each is a connection that closed, so it reconnects on its backoff, shows transport closed in status.lastError once the retries are spent, and keeps its outbox until a socket opens. Nothing here signs anyone out.

Presence

"Who is viewing this" and "where is their caret" should vanish when the peer does, not replay next week. Sync.presence.make({ id, ttl, decodeValue, channel?, throttle? }) is a TTL'd peer registry outside the log: values are decoded before they enter it, a peer that stops refreshing is pruned, and throttle sends at most one value per interval, the latest. Sync.presence.socketChannel(socket), given the TransportSocket the socket transport provides, shares the sync socket across reconnects; Sync.presence.hub and .serve are the server side. .serve stamps each frame with the connection's peerId, so a peer cannot speak as another, and with opens (the exchange's own) joins only a connection that may open the document, relaying nothing to or from one refused. It asks again with each frame the connection sends, and one no longer let open the document leaves. examples/pages shows remote carets.

Last-writer-wins fields (experimental)

Server order decides concurrent edits. When one field should instead keep the newest logical write even from a device that reconnects late, Sync.lww.register(schema) gives it a stamped schema and a pure merge; Sync.lww.openClock allocates stamps from a persisted counter, before dispatch and never in update. It is a per-field rule, not a CRDT mode: sets, counters, and text stay outside.

ts
const Title = Sync.lww.register(Schema.String)
const Shared = Schema.Struct({ title: Title.schema })
// in update: title: Title.merge(model.title, message.title)

Without a Foldkit application

Sync.define({ documentId, message, shared, empty, durable, replay }) is the protocol primitive forApplication compiles to, for a client with no application to derive from. It takes migrations (a Sync.migrations history) in place of message, and reads the Message from it. Its replay is unguarded; the author owns its agreement with whatever applies the Message elsewhere.

Joining an assembly

TodoSync.wiring() adds the contract to a foldkit-bundle assembly so Module.validate can report two owners of one field. It routes nothing and runs nothing; Sync owns its runtime through mount.