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 becomestruewhen the first state arrives and staystrueacross later disconnects.exists(): whether the document exists, as the server confirmed it:undefineduntil it is ready, thentrueorfalse.
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
| Name | Type | Description |
|---|---|---|
primitive * | Primitive | The document's schema. |
url * | string | The server's session endpoint: wss://…/v1/sessions. |
database * | string | The database's id: 32 lowercase hexadecimal characters. |
collection * | string | The collection's id: 32 lowercase hexadecimal characters. |
document * | string | The 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. |
initialValue | Value | An 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. |
schemaFingerprint | string | Identifies the schema this client was built with. See Schema versions. |
schemaVersion | number | The collection's schema version this client was built for. See Schema versions. |
scope | readonly Path[] | Holds only the parts of the document at these paths. See Partial sync. |
onStateChange | (snapshot) => void | Called whenever the document's value changes. |
onConnectionChange | (connected: boolean) => void | Called when the session opens or closes. |
onReady | () => void | Called when the document's state arrives. |
onExistenceChange | (exists: boolean) => void | Called when it is first known whether the document exists, and when it is created or deleted. |
onRejection | (transactionId, reason, code?, engineCode?) => void | Called once for every local edit that will never apply, or whose fate is unknown. |
onSyncError | (error: MimicClientError) => void | Called when local edits stop reaching the server, or syncing stops. |
onSchemaMismatch | (mismatch: SchemaMismatch) => void | Called when this client's schema differs from the document's. |
onReplaced | (reason: string) => void | Called when the server sent the document's state in place of the history the client held. |
createSocket | (url: string) => SessionSocket | Creates the WebSocket. Defaults to the global WebSocket. |
clock | SessionClock | The 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 onA 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, orsetScope(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 afterwardsCall dispose() when your application is done with a document, for example
when the user navigates away from it.
Next
- Reading and writing
- Zustand bindings, if you render with React