Creating a client

Opening a document from the browser with a client document, and closing it again.

@voidhash/mimic/sync is the browser client. It opens one document over a WebSocket at the server's /v1/sessions endpoint, keeps a local copy of it, and syncs edits in both directions. This page shows how to create a client for a document and what its options are.

A client document

A client document is the document as your code sees it. It holds the local copy, applies your edits optimistically, queues them for the server, keeps the session open, and tells you when anything changes.

import { createSyncClientDocument } from "@voidhash/mimic/sync";
import { BoardDocument } from "./shared";

const document = createSyncClientDocument({
  primitive: BoardDocument,
  url: "wss://db.example.com/v1/sessions",
  database: databaseId,
  collection: collectionId,
  document: documentId,
  credential: () => fetchDocumentToken(documentId),
});

await document.connect();

url is the server's session endpoint: its address with the ws or wss scheme, at /v1/sessions (on the hosted service, the database's websocketUrl). database and collection are the ids the server knows them by, and document is your document's id. fetchDocumentToken is your own function that asks your backend for a document token.

There is one client document per open document. To open several documents, create a client document for each; each has a session of its own.

The credential function

credential is a function, not a string. The client calls it every time it opens a session, and when it renews one before the token expires. It may return the credential or a promise of it.

A document token can be used again until it expires, so the function may return the same one as long as it is valid, and fetch a new one only when it is about to expire:

let current: { token: string; expires: number } | undefined;

const credential = async () => {
  // `expires` is in seconds since the Unix epoch.
  if (current === undefined || current.expires * 1000 - Date.now() < 60_000) {
    current = await fetchDocumentAccess(documentId); // { token, expires }
  }
  return current.token;
};

A function that throws or returns undefined is not fatal: the client tries again with backoff. When the server refuses two credentials in a row, the client stops and reports a terminal sync error; see Connection states and errors.

Connecting and readiness

document.connect() starts the session and keeps it open from then on, reconnecting as needed. It resolves at once; the document becomes ready when the server has sent it.

Three things describe where the document is:

  • isConnected(): a session is open.
  • isReady(): the document's state has arrived. It becomes true when the first state arrives and stays true across later disconnects.
  • exists(): whether the document exists, as the server confirmed it: undefined until it is ready, then true or false.

Until the document is ready, getSnapshot() returns undefined and writes throw. Wait for onReady, or check isReady(), before you render or edit.

const unsubscribe = document.subscribe({
  onReady: () => render(document.getSnapshot()),
  onStateChange: (snapshot) => render(snapshot),
  onConnectionChange: (connected) => showConnection(connected),
});

A document that does not exist yet

A session can open on a document that does not exist. It becomes ready with exists() false, and reads as undefined. Create it with create, which takes the document's encoded value, or pass initialValue to have the client create it once it finds the document missing:

const document = createSyncClientDocument({
  primitive: BoardDocument,
  url,
  database: databaseId,
  collection: collectionId,
  document: documentId,
  credential,
  initialValue: BoardDocument.encode([{ type: "board", name: "Untitled", children: [] }]),
});

When two clients create the same document at once, one wins; the other's creation is rejected conflict (already_exists), and it receives the winner's document. onExistenceChange reports each change of exists().

Options

NameTypeDescription
primitive *PrimitiveThe document's schema.
url *stringThe server's session endpoint: wss://…/v1/sessions.
database *stringThe database's id: 32 lowercase hexadecimal characters.
collection *stringThe collection's id: 32 lowercase hexadecimal characters.
document *stringThe document's id: 1 to 128 characters of letters, digits and - . _ ~ : @.
credential *() => string | undefined | Promise<string | undefined>Returns a document token or a database key. Called for every open and renewal.
presence{ primitive, initial? }Enables presence with the given schema and an optional first value.
initialValueValueAn encoded document value the client creates the document with when it does not exist.
persistence{ documentKey, store?, legacy?, onError? }Keeps pending edits across page reloads. See Pending edits.
schemaFingerprintstringIdentifies the schema this client was built with. See Schema versions.
schemaVersionnumberThe collection's schema version this client was built for. See Schema versions.
scopereadonly Path[]Holds only the parts of the document at these paths. See Partial sync.
onStateChange(snapshot) => voidCalled whenever the document's value changes.
onConnectionChange(connected: boolean) => voidCalled when the session opens or closes.
onReady() => voidCalled when the document's state arrives.
onExistenceChange(exists: boolean) => voidCalled when it is first known whether the document exists, and when it is created or deleted.
onRejection(transactionId, reason, code?, engineCode?) => voidCalled once for every local edit that will never apply, or whose fate is unknown.
onSyncError(error: MimicClientError) => voidCalled when local edits stop reaching the server, or syncing stops.
onSchemaMismatch(mismatch: SchemaMismatch) => voidCalled when this client's schema differs from the document's.
onReplaced(reason: string) => voidCalled when the server sent the document's state in place of the history the client held.
createSocket(url: string) => SessionSocketCreates the WebSocket. Defaults to the global WebSocket.
clockSessionClockThe clock and timers the client uses. Defaults to the host's.

The callbacks are described in Connection states and errors, Pending edits and Schema versions.

Partial sync

A document can be large while a view needs only part of it: one page of a design file, one column of a board. scope makes the client hold only the subtrees at the paths you give, at most 16 unless the gateway allows more, and receive only the changes that touch them:

const document = createSyncClientDocument({
  primitive: BoardDocument,
  url,
  database: databaseId,
  collection: collectionId,
  document: documentId,
  credential,
  scope: [[{ kind: "node", id: columnId }]],
});

const column = document.getScopedValue([{ kind: "node", id: columnId }]);
await document.setScope(null); // hold the whole document from now on

A path is a list of steps from the root: a field of an object, an item of an array, or a node of a tree, by id. A path keeps naming the same element when others are inserted, moved or deleted around it. On a scoped document:

  • getScopedValue(path) reads the value at one of the scope's paths, or within one, in its encoded form; the snapshot methods are not meaningful.
  • Edits may only change what the scope holds. The server checks every edit against the whole document and the collection's schema, as for any client; the client checks only what it holds.
  • setScope(paths) changes the scope, or setScope(null) takes the whole document, and resolves once the server has sent the new scope's state. A scope that would not cover an edit still pending is refused.

A scope selects what the client receives; it is not a permission. The document token still grants the whole document.

Closing

document.disconnect(); // closes the session; connect() opens it again
document.dispose(); // closes it for good; the document must not be used afterwards

Call dispose() when your application is done with a document, for example when the user navigates away from it.

Next