Transactions from a backend

Changing documents from a backend service - editing through the schema, submitting commands, outcomes and retries, and presence leases.

A backend changes a document the same way a browser does: by submitting a transaction. The difference is that it submits over the HTTP API instead of a session. This page covers how, on a collection handle of the engine SDK:

const boards = sdk.database(databaseId).collection(collectionId, { primitive: BoardDocument });

Clients that have the document open receive a backend's committed transaction like any other.

Editing through the schema

update reads the document, runs your function on the same typed proxy a client transaction has, and writes what it did as one transaction:

import * as Option from "effect/Option";

const outcome = await boards.update("roadmap", (root) => {
  root.children.first()?.data.name.set("Roadmap 2027");
});

if (Option.isNone(outcome)) {
  // The function changed nothing: nothing was written.
} else if (outcome.value.result.kind === "rejected") {
  console.log(outcome.value.result.code, outcome.value.result.message);
}

The write is exact: it commits only if the document is still at the revision update read. When someone else wrote in between, it is rejected revision_mismatch; read again and repeat. Pass { exact: false } to have it applied to whatever the document holds then instead (see below). A document that is not live fails with not_found.

Submitting commands

transaction sends a batch of commands for one document. Build the commands from the document's current value with Primitive.commands:

import * as Option from "effect/Option";
import { Primitive } from "@voidhash/mimic-core";

const current = await boards.get("roadmap");
const value = Option.getOrThrow(current.value);

const commands = Primitive.commands(BoardDocument, value, (root) => {
  root.children.first()?.data.name.set("Roadmap 2027");
});

const outcome = await boards.transaction("roadmap", commands, {
  base: { incarnation: current.incarnation, revision: current.revision, schema: current.schema },
});
NameTypeDefaultDescription
base{ incarnation, revision, schema }—The document position and schema version the commands were built on. Read from the document when omitted.
exactbooleantrueWhether the transaction commits only on the document at its base revision.
idTransactionId—The transaction's id, a version-7 UUID. Minted by the SDK when omitted.

Exact and rebase

  • Exact (the SDK's default): the server rejects the transaction with revision_mismatch unless its base revision is the document's current one. Use it when the change depends on what you read. On revision_mismatch, read the document again, rebuild the commands, and submit a new transaction.
  • Rebase (exact: false): the server applies the commands to the current document whatever happened since the base, skipping commands whose target is gone, as it does for browser clients. Use it for changes that are valid regardless of concurrent edits, such as appending an item.

Either way, the server refuses a transaction made on another schema version than the document's (schema_mismatch): a document migrated since you read it needs reading again.

Outcomes

A write's answer is its outcome, { id, result, token }. A rejection is an outcome, not an error:

result.kindMeaning
committedIt committed; incarnation and revision are the document's after it
unchangedIt was evaluated, but every command was skipped or changed nothing
rejectedIt was not applied; code and message say why

token is the commit token of a committed write, an opaque string that identifies the change. Common rejection codes:

codeWhyWhat to do
revision_mismatchAn exact write whose base is no longer the headRead again, rebuild, submit a new write
incarnation_mismatchThe document was deleted (and maybe created again) since the baseRead again
schema_mismatchThe document is at another schema versionRead again, with a schema of that version
validation_failedThe result would violate the collection's schemaDo not retry the same commands
migration_blockedA migration of the collection is being applied, and the result fails itChange the edit
already_existsA create of a document that existsRead it instead

Retries

Every write carries a transaction id, and the server evaluates an id at most once: sent again, the same request is answered with the outcome it recorded the first time. So a write is safe to send again whenever its answer was lost, and the SDK does so: a write answered without a verdict (no answer, unavailable, resource_exhausted or internal) is sent again, as the same request, up to maxAttempts times with backoff.

If your own code retries a write whose outcome it did not learn, for example after a process restart, send it again with the same id, and the same commands and base. Mint the id yourself so you can keep it: await sdk.run(sdk.client.mint) returns a fresh one. outcome(document, id) reads the recorded outcome of an id, if any, without sending anything.

The server answers ids from its record for its retry horizon (30 days by default). The SDK mints ids on its server's clock; a clock more than an hour ahead of the database's is refused transaction_id_ahead, which the SDK retries a few times and then reports.

Deleting and creating

delete(document) ends the document's live incarnation, and create/createFrom start a new one; see Collections and documents. Both return an outcome and are retried like any write.

Presence leases

A backend that works on a document for a while, such as an agent editing alongside users, can appear among the document's participants without a session, with a presence lease:

// Show the agent to the document's participants for 30 seconds.
await boards.lease("roadmap", "assistant", payload, { ttlMs: 30_000 });

// Renew it before it runs out, as often as needed.
await boards.lease("roadmap", "assistant", payload, { ttlMs: 30_000 });

// Leave.
await boards.clearLease("roadmap", "assistant");

A lease is named by your backend (assistant here), and lasts ttlMs, 1 to 300 seconds, from each renewal, so a crashed service does not leave a ghost participant. It needs write on the document. Sessions see it as any other participant's presence. payload is the presence value in its JSON form: coreValueToJson(Presence.encode(data)), with coreValueToJson from @voidhash/mimic-contracts/core, for clients that declared a presence schema.

A lease belongs to whoever set it: the key, or the subject of the document token, that set it. Another holder's lease of the same name is another lease. A lease leaves when the document moves to another server process; renewing it brings it back.

Edits on a user's behalf

To make a backend's edits stand apart, write them with a document token minted for a subject that names the agent (see Issuing document tokens):

const { capability } = await sdk.database(databaseId).mintCapability({
  collection: collectionId,
  document: "roadmap",
  permission: "write",
  sub: `agent:${userId}:${runId}`,
});

const agent = new EngineSDK({ url, credential: capability });
await agent
  .database(databaseId)
  .collection(collectionId, { primitive: BoardDocument })
  .update("roadmap", (root) => root.children.first()?.data.name.set("Renamed by the agent"));

Clients see such edits with actor.sub set to the subject, and a user's undo history can adopt the subject to make the agent's edits undoable by the user who started it. A lease set with that token carries the subject too.

Next