Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Your own Durable Object

Host a document in any Durable Object with attachRoom, load it from and save it to your own storage (R2, KV, D1), and edit it on the server.

DocumentRoom is a ready-made Durable Object. When you already have one, or want your own storage and server logic, attach the document to it instead:

import { DurableObject } from 'cloudflare:workers';
import { attachRoom, closedSocket, routeDocumentSocket } from 'edytor/cloudflare';

export class Notes extends DurableObject<Env> {
  document = attachRoom(this, {
    onLoad: () => loadFromMyStore(this.ctx.id.name!), // { update, replicas }
    onSave: ({ update, replicas }) => saveToMyStore(this.ctx.id.name!, { update, replicas })
  });
}

export default {
  fetch(request, env) {
    const match = /^\/rooms\/([^/]+)$/.exec(new URL(request.url).pathname);
    if (!match) return new Response('not found', { status: 404 });
    let documentId: string; // the provider percent-encodes the room id
    try {
      documentId = decodeURIComponent(match[1]);
    } catch {
      return closedSocket(4400, 'invalid document id');
    }
    return routeDocumentSocket(request, env.NOTES, documentId, authorize);
  }
} satisfies ExportedHandler<Env>;

That is the whole server. routeDocumentSocket works with any namespace whose objects host a document, and authorization is unchanged.

What attachRoom(this, options) does

  • Storage. The document lives in the object’s SQLite storage, in tables named edytor_rows, edytor_replicas and edytor_meta (with edytor_epochs, edytor_editors and edytor_restore for the history and the purge, edytor_history for a history in the room, and edytor_moves and edytor_late for moves; Room internals says what each holds), beside your own tables. Every edit is stored there before it is acknowledged, whatever your hooks do. tablePrefix changes the prefix.
  • Sockets. The document’s sockets carry the tag edytor (SOCKET_TAG). Other sockets of the object are yours.
  • Handlers. Each handler your class does not define is installed on the object: fetch, webSocketMessage, webSocketClose, webSocketError, and alarm, which runs the room’s alarm tasks: onSave, the history, the purge, the forwarding of moves’ late edits and the sockets’ credential expiry. It is always installed.
  • Return value. An AttachedDocument with the same handlers, plus the methods transact, read, compact, compressed, metrics, lastUpdated, dropWaitingDeletes, reset, records, owns(ws), the history’s listHistory, readHistory, restoreHistory, undoRestore and historyWritten, purge (the purge task, now), reseed (a re-seed, now) and the getter epoch, closeUser and setAccess (revoking access), and the moves’ exportBlocks, importBlocks, commitMove, abortMove, lateEdits, ackLateEdits and applyLateEdits, the comments’ listComments and comment, and the fields facade, doc, failure, refusals, refusalCounts, presence and origin (see the room).
  • RPC. Durable Object RPC reaches only your class’s own methods, not the returned document’s. Forward the ones you call from a Worker or an admin route, for example dropWaitingDeletes() { return this.document.dropWaitingDeletes(); }.

Call it once, in a field or the constructor.

Alongside your own handlers

A class that defines a handler keeps it and delegates to the document. The document’s socket handlers return false for sockets that are not its own:

export class Workspace extends DurableObject<Env> {
  document = attachRoom(this, { onSave: (saved) => this.persist(saved) });

  async fetch(request: Request) {
    if (new URL(request.url).pathname.startsWith('/events')) return this.openEventStream(request);
    return this.document.fetch(request); // the document's upgrade
  }

  webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
    if (this.document.webSocketMessage(ws, message)) return;
    // …your own sockets
  }

  async alarm() {
    await this.document.alarm(); // runs onSave, the history's slots, the purge
    // …your own scheduled work
  }
}

A Durable Object has one alarm, which the document shares among its tasks: onSave (saveAfter ms after an unsaved edit), the history’s half-day slots and its retention, the re-seed, the purge’s daily tick, the forwarding of moves’ late edits and the sockets’ credential expiry (Room internals has when each is due). It stores each task’s due time and sets the alarm to the earliest, which replaces a time you set earlier. A task already due keeps its time, so frequent edits or wakes never push onSave back. If your class also uses alarms, re-arm your own schedule from alarm(), and call document.alarm() from it.

Options

Option Default Description
onLoad Returns the document for a room that stores nothing yet. See Load.
onSave Receives { value, update, replicas } after edits. See Save.
saveAfter 2000 ms between the first unsaved edit and onSave.
compactAfter 500 Stored updates before the rows are replaced by one snapshot of the live document.
maxRowBytes 1,995,904 Largest stored row. Can only be lowered.
maxFrameBytes 32 MiB Largest frame sent whole; larger ones are chunked. Can only be lowered.
maxDocumentBytes 2 MiB The document quota.
maxUpdatesPerSecond 50 Sync messages per second and socket (quota).
maxInboundFrameBytes 4 MiB Largest frame a socket may send, reassembled (quota).
maxPresenceBytes 16 KiB Largest presence state a socket may publish (presence).
maxPresencePerSecond 50 Presence messages per second and socket (presence).
maxBufferedBytes twice maxInboundFrameBytes The chunk sequences in flight on every socket together (catch-up).
tablePrefix 'edytor_' Prefix of the room’s tables.
semantics defaultSemantics The block roles server edits obey. See Block roles on the server.
validate Asked after each client frame that changed blocks; false makes the room undo it. See Validate edits.
log console.log of JSON Receives the room’s log entries; false logs nothing.
locks { key, subtree, bypass }: per-block locks, checked before validate.
rooms () => namespace: the rooms blocks move to; the room then forwards late edits itself.
history { store, retentionDays, timeZone, maxValueBytes }: keep two versions a day in a store (roomHistory(), kvHistory(namespace), r2History(bucket) or your own HistoryStore). See History and purge.
purgeAfterDays the retention, else 30 Days after which deleted content is purged; false never purges.
reseed on { at, idleMs, gain, force, graceDays } (ReseedOptions): when the room re-seeds a document that grew; false never does.
now Date.now The room’s clock (its slots, epochs and alarm read it), for tests.

DocumentRoom reads the same settings from vars (EDYTOR_SAVE_AFTER, EDYTOR_COMPACT_AFTER, …; see the room) and uses the unprefixed tables rows, replicas and meta. It takes semantics from its semantics() method, history from its history() method (the EDYTOR_HISTORY binding or variable by default) and reseed from its reseeding() method (false when EDYTOR_RESEED is off), each read at first use, so they may return a field of your subclass; now() is its clock.

Load

onLoad() runs when the object starts and stores nothing yet, before any socket is served. It may be async. Return:

Return Effect
{ update, replicas } What an earlier onSave received: the v14 state and who owns which client id. Restores both (and the document’s epoch, which it holds).
Uint8Array A bare v14 update. Restores the content but not the owners: each client id that holds content is unowned until a signed-in writer dials with it as its replica (logged as an orphan entry).
JSONDoc Seeded as the document, with its data (the document’s properties). Seeding is deterministic, so a client that seeds the same value converges with it.
undefined / null An empty room; the first client seeds it.

Nothing is stored until onLoad settles, and the result is stored in one transaction, so the room is never left half-loaded:

  • Nothing returned is provisional: onLoad is asked again at every start until something is stored. A KV read that is not yet visible is retried at the next start.
  • A throw refuses sockets with 1011 (their providers retry), and the next dial or start asks onLoad again.
  • A refused payload (another generation or schema, undecodable bytes, any other shape) sets failure and refuses every socket with 1008 (refused: container). The object keeps answering.

Once anything is stored, the object restores from its own storage and does not ask again.

A saved copy can be older than the room’s last edits (it is written saveAfter ms after them). Clients that reconnect after such a restore deliver what the room lacks, including other users’ edits they received: nobody is disconnected for it, and nobody takes over another user’s client id. See restoring from an older snapshot.

Save

onSave({ value, update, replicas }) runs saveAfter ms after the first edit it has not saved (a stored waiting delete counts), on the object’s alarm, so it does not keep the object from hibernating. If it throws, the save stays due and runs again a minute later (the alarm call throws too, so the platform logs it). If the alarm fires while the room cannot read its rows (a storage fault), it reads them again first; if that fails too, the save stays due and the alarm is set again, backing off up to 5 minutes, so onSave runs once the room recovers. The same alarm runs the history and the purge.

Field Content
update The full CRDT state. Store it to load the document back.
replicas Who owns each client id ({ replica, user }[]), read with update. Store it beside update and return both from onLoad, so returning clients can write again after a restore. See replicas.
value The document as JSON (data, when it has properties, and children), for search, previews or exports.

Storage recipes

The room’s name is this.ctx.id.name: rooms are opened with getByName(documentId), and Cloudflare keeps the name for the object’s lifetime, including when an alarm wakes it.

import { DurableObject } from 'cloudflare:workers';
import { attachRoom, type ReplicaOwner } from 'edytor/cloudflare';

export class Notes extends DurableObject<Env> {
  document = attachRoom(this, {
    onLoad: async () => {
      const [object, owners] = await Promise.all([
        this.env.DOCS.get(`${this.ctx.id.name}.bin`),
        this.env.DOCS.get(`${this.ctx.id.name}.replicas.json`)
      ]);
      if (!object) return undefined;
      const update = new Uint8Array(await object.arrayBuffer());
      return owners ? { update, replicas: await owners.json<ReplicaOwner[]>() } : update;
    },
    onSave: async ({ value, update, replicas }) => {
      await this.env.DOCS.put(`${this.ctx.id.name}.bin`, update);
      await this.env.DOCS.put(`${this.ctx.id.name}.replicas.json`, JSON.stringify(replicas));
      await this.env.DOCS.put(`${this.ctx.id.name}.json`, JSON.stringify(value)); // optional
    }
  });
}

R2 has no practical size limit: the best fit for documents. ReplicaOwner is exported by edytor/cloudflare; a copy saved before replicas existed still loads as a bare update.

import { DurableObject } from 'cloudflare:workers';
import { attachRoom, type ReplicaOwner } from 'edytor/cloudflare';

export class Notes extends DurableObject<Env> {
  document = attachRoom(this, {
    onLoad: async () => {
      const name = this.ctx.id.name!;
      const bytes = await this.env.DOCS_KV.get(name, 'arrayBuffer');
      const replicas = await this.env.DOCS_KV.get<ReplicaOwner[]>(`${name}:replicas`, 'json');
      if (!bytes) return undefined;
      return replicas ? { update: new Uint8Array(bytes), replicas } : new Uint8Array(bytes);
    },
    onSave: async ({ update, replicas }) => {
      await this.env.DOCS_KV.put(this.ctx.id.name!, update);
      await this.env.DOCS_KV.put(`${this.ctx.id.name}:replicas`, JSON.stringify(replicas));
    }
  });
}

A KV value holds at most 25 MiB, and other locations may read an old value for a short while. onLoad only runs for a room that stores nothing, and a missing value is asked again at the next start, so that rarely matters here.

import { DurableObject } from 'cloudflare:workers';
import { attachRoom } from 'edytor/cloudflare';

export class Notes extends DurableObject<Env> {
  document = attachRoom(this, {
    onLoad: async () => {
      const row = await this.env.DB.prepare('SELECT state, replicas FROM documents WHERE id = ?')
        .bind(this.ctx.id.name)
        .first<{ state: ArrayBuffer; replicas: string }>();
      return row ? { update: new Uint8Array(row.state), replicas: JSON.parse(row.replicas) } : undefined;
    },
    onSave: async ({ value, update, replicas }) => {
      await this.env.DB.prepare(
        'INSERT OR REPLACE INTO documents (id, state, replicas, json) VALUES (?, ?, ?, ?)'
      )
        .bind(this.ctx.id.name, update, JSON.stringify(replicas), JSON.stringify(value))
        .run();
    }
  });
}

A D1 row holds at most 2 MB; use R2 for larger documents.

Edit on the server

transact(fn) runs fn with the document’s operations (DocumentOperations, also the room’s facade) in one transaction, stores the edit and broadcasts it to every connected socket, like a client’s edit. It returns what fn returns. fn runs synchronously: writes after an await in it are not part of the transaction. A transact called inside fn joins the outer one.

Throws and storage faults.

  • It is one transaction, not a rollback, like every client-side transact: if fn throws, the writes it made before the throw are kept, stored and broadcast, and the error is rethrown. Validate before writing, or build one plan with facade.prepare.* and apply it: a refused plan writes nothing.
  • If storing the edit fails, the storage error is thrown instead and nothing is kept: the room rebuilds the document from its rows, which replaces doc and facade, and subscriptions made on the old ones (facade.onChange, doc.on) end. Read facade from the room each time rather than keeping it.
  • Write through transact. A write straight through facade is stored and broadcast too, but when its append fails nothing is thrown and that write is dropped when the room next serves or reads the document, or when you next read facade or doc while the room is idle (not inside a transaction, a client’s frame or their change events), so a later write through a freshly read facade or doc is stored. A later write through a facade or doc you kept from before the failure is dropped with it.

Writing from a change subscriber. A facade.onChange subscriber or a doc.on('afterAllTransactions') listener may read the room.

  • A transact there, whether the change is a client’s or comes from the room’s own transact, or inside a facade.transact or doc.transact you opened, throws without writing: the engine would apply its write only after the change being handled, too late for the room to store it before transact returns. Only a transact called inside fn itself joins.
  • After a write straight through facade (outside transact and a client’s frame), a doc.on('afterAllTransactions') listener runs once that write is done: a transact there is a change of its own and is stored.
  • Defer it with queueMicrotask(() => this.transact(...)): it then runs once the change is handled, and throws the storage error if storing fails.
  • When the append of the change a subscriber sees failed, a read there does not hide it: a client’s change is dropped and its sender’s socket closed (1011, so the client resends it) once the subscriber returns, and the room’s own transact throws the storage error.

Expose transact through your own RPC methods:

import { DurableObject } from 'cloudflare:workers';
import { attachRoom } from 'edytor/cloudflare';
import { toBlockSpec } from 'edytor/crdt/edytor';

interface Env {
  NOTES: DurableObjectNamespace<Notes>; // as `wrangler types` writes it
}

export class Notes extends DurableObject<Env> {
  document = attachRoom(this);

  appendNote(text: string) {
    return this.document.transact((doc) =>
      doc.insertBlocks({ parent: null, index: doc.childrenIds(null).length }, [toBlockSpec({ type: 'paragraph', content: [{ text }] })])
    );
  }
}

// A route your deploy pipeline calls; a queue consumer or a cron trigger calls it the same way.
export default {
  async fetch(request, env) {
    const documentId = new URL(request.url).pathname.slice(1);
    await env.NOTES.getByName(documentId).appendNote('Deployed v2');
    return new Response('noted');
  }
} satisfies ExportedHandler<Env>;

read() returns the document as JSON. A room with no document yet is seeded with one empty block before transact runs.

Block roles on the server

The server has no plugins, so it takes the block roles it checks from semantics: which kinds are void, islands or islands of lines (lines, the code block), which are layouts (layout, the columns plugin’s columns), which render no content, and each container’s default child. The default, defaultSemantics from edytor/crdt/edytor, holds the kinds of the bundled rich-text, code, image, media (embed, bookmark, file, video, audio) and columns plugins (the media and columns plugins are opt-in in a view, but their rows are here). Server edits obey them as a view does: merging into a divider, splitting an image or moving a code line out of its code block is refused.

If your clients’ plugins add void or island kinds, pass the same rules, from the same kind table your plugin spreads (see Block roles):

import { DurableObject } from 'cloudflare:workers';
import { attachRoom } from 'edytor/cloudflare';
import { defaultSemantics, mergeSemantics, semanticsOf } from 'edytor/crdt/edytor';

// The kinds your plugins add, shared with the client (a `kinds.ts` both import).
const widgetKinds = { widget: { void: true, rendersContent: false } };

export class Notes extends DurableObject<Env> {
  document = attachRoom(this, {
    semantics: mergeSemantics(defaultSemantics, semanticsOf(widgetKinds))
  });
}

In a DocumentRoom subclass, override protected semantics() and return the config. semantics: {} checks no roles.

To catch a missing rule while you develop, the room compares its roles with each client’s: in development builds a client’s document advertises a digest of its roles in its presence, and the room logs { "edytor": "semantics", "user", "kinds" } naming the kinds (mark:<name> for a mark, @defaultType for the default type) it reads otherwise, once per digest. A kind the client does not know is not reported (a view without that plugin). Nothing is refused; production builds advertise nothing.

Validate edits

The room applies a client’s frame, stores it and relays it, then asks validate whether to keep it: accept, then compensate. Return false (or throw) to deny it, and the room writes the frame’s inverse as its own edit, stores it and sends it to every socket, the sender’s included, so every replica converges. The sender stays connected, its frame stays acknowledged, and the denial is logged as a denied entry ({ user, touched }) in refusals.

validate receives one frame:

Field Content
user, replica The sender’s verified user and client id.
touched The ids of the blocks the frame changed: shown or hidden (with their subtrees), given another parent or moved among their siblings (a block a sibling’s move shifts is not touched), retyped, given other data or other text.
dataChanged The frame changed the document’s own data.
before(id) A block as it was before the frame ({ id, type, data, content, parent }), null if it did not show.
after(id) The block as it is now, null if it does not show.
facade The live document, to read (write from a deferred transact, never from validate).

The inverse is the undo of exactly that frame, with the history’s rules: text it typed is deleted, text it deleted comes back (except where another writer’s delete still holds it), blocks it deleted show again, a block it created is withdrawn (it stays only if it holds someone else’s content), a move returns the block where it was, and data and types return to the values it replaced. Edits other clients made in between are kept. The frame that created the document (its first seed, which no history records) has its blocks deleted instead.

validate is synchronous and runs only when set; the room then keeps an index of every block’s state, updated at each commit, and a history of the frame being validated, released after each frame so it keeps no deleted content alive. Your own server edits (transact) are never validated. For example, only the users your app lists as a block’s editors may change it:

import { DocumentRoom, type FrameValidation } from 'edytor/cloudflare';

/** A block whose `data.editors` lists users may be changed by them alone. */
export class EditorsRoom extends DocumentRoom<Env> {
  protected override validate({ user, touched, before, after }: FrameValidation) {
    const allows = (id: string, read: typeof before) => {
      const editors = read(id)?.data.editors;
      return !Array.isArray(editors) || editors.includes(user);
    };
    return touched.every((id) => allows(id, before) && allows(id, after));
  }
}

Per-block locks

Locks are built in: lockedBlocks is a validate hook that keeps a locked block its owner’s. A block is locked when its data names a user under key (default lockedBy); another user typing into it, retyping, moving, deleting, unlocking it, or locking a block for someone else, sees the edit undone. A block inserted before a locked one is not a change of it.

Option Default
key 'lockedBy' The data key naming the owner.
subtree false A lock also holds every block shown under the locked one (its children, theirs, …): typing into a child, adding one, moving a block in or out are the owner’s alone. The nearest locked ancestor decides.
bypass (user) => boolean: users who edit locked blocks anyway (an admin).

With DocumentRoom, set the EDYTOR_LOCKS variable to the key ("EDYTOR_LOCKS": "lockedBy"), or override locks():

import { DocumentRoom, type LockOptions } from 'edytor/cloudflare';

export class LockedRoom extends DocumentRoom<Env> {
  protected override locks(): LockOptions {
    return { key: 'lockedBy', subtree: true, bypass: (user) => user.startsWith('admin:') };
  }
}

With attachRoom, pass locks: { key: 'lockedBy' }. Locks are checked before your own validate, and both must accept a frame. To lock a block, a client writes its own user into the block’s data (edytor.patchData(id, [{ path: ['lockedBy'], value: userId }]), or the document’s patchData); to unlock it, the owner removes the key. A view does not know about locks: an edit to a locked block shows locally, then the room’s inverse removes it. Read the key in your kind’s rendering to show the lock and make the block read-only for others (contenteditable on its content, or a readonly view).

The room also enforces one rule itself: a block’s per-writer marks (del.<n> for a delete, wd.<n> for an undone creation) are written and deleted only by client n. A frame writing another client’s mark has that client’s new content stripped, as content under another user’s client id is, and a delete of another user’s mark is dropped (unless its block goes with it), both logged as a mark entry; the rest of the frame applies.

Subclassing DocumentRoom

The ready-made room exposes the same hooks as methods:

import { DocumentRoom, type ReplicaOwner, type SavedDocument } from 'edytor/cloudflare';

export class Room extends DocumentRoom<Env> {
  protected override async onLoad() {
    const name = this.ctx.id.name;
    const [object, owners] = await Promise.all([
      this.env.DOCS.get(`${name}.bin`),
      this.env.DOCS.get(`${name}.replicas.json`)
    ]);
    if (!object) return undefined;
    const update = new Uint8Array(await object.arrayBuffer());
    return owners ? { update, replicas: await owners.json<ReplicaOwner[]>() } : update;
  }

  protected override async onSave({ update, replicas }: SavedDocument) {
    await this.env.DOCS.put(`${this.ctx.id.name}.bin`, update);
    await this.env.DOCS.put(`${this.ctx.id.name}.replicas.json`, JSON.stringify(replicas));
  }
}

Bind and migrate the subclass by its own class name ("class_name": "Room", "new_sqlite_classes": ["Room"]). If it defines alarm(), call await super.alarm() from it. Override protected validate(frame) to validate edits, protected locks() for per-block locks, protected rooms() to name the rooms blocks move to, protected history() to keep a history, protected reseeding() for when the room re-seeds (false: never), and protected onComment(change) for comment notifications. transact, read, compact, metrics, closeUser, setAccess, compressed, lastUpdated, dropWaitingDeletes, reset, listHistory, readHistory, restoreHistory, undoRestore, historyWritten, purge, reseed, exportBlocks, importBlocks, commitMove, abortMove, lateEdits, ackLateEdits, applyLateEdits, listComments and comment are methods of the room itself, so RPC reaches them without forwarding.

Was this page helpful?