// // Copyright 2024 DXOS.org // import { next as A, type Doc } from '@automerge/automerge'; import { stringifyAutomergeUrl, type DocHandleOptions, type DocumentId } from '@automerge/automerge-repo'; import { EventEmitter } from 'eventemitter3'; import { Trigger, TriggerState } from '@dxos/async'; import { invariant } from '@dxos/invariant'; import { type IDocHandle } from '../core-db'; export type ChangeEvent = { handle: DocHandleProxy; doc: A.Doc; patches: A.Patch[]; patchInfo: { before: A.Doc; after: A.Doc; source: 'change' }; }; export type ClientDocHandleEvents = { change: ChangeEvent; delete: { handle: DocHandleProxy }; }; /** * A client-side `IDocHandle` implementation. * Syncs with a Automerge Repo in shared worker. * Inspired by Automerge's `DocHandle`. */ export class DocHandleProxy extends EventEmitter> implements IDocHandle { private readonly _ready = new Trigger(); private _doc?: A.Doc = undefined; private _lastSentHeads: A.Heads = []; /** * Heads that are currently being synced. * If sync is successful, they will be moved to `_lastSentHeads`. */ private _currentlySendingHeads: A.Heads = []; constructor( private readonly _documentId: DocumentId, options: DocHandleOptions = {}, private readonly _callbacks?: { onDelete: () => void; }, ) { super(); if (options.isNew) { // T should really be constrained to extend `Record` (an automerge doc can't be // e.g. a primitive, an array, etc. - it must be an object). But adding that constraint creates // a bunch of other problems elsewhere so for now we'll just cast it here to make Automerge happy. this._doc = A.from(options.initialValue as Record) as T; this._doc = A.emptyChange(this._doc); this._ready.wake(); } else { this._doc = A.init(); } } get url() { return stringifyAutomergeUrl(this._documentId); } get documentId(): DocumentId { return this._documentId; } get state() { return this._ready.state === TriggerState.RESOLVED ? 'ready' : 'pending'; } doc(): A.Doc { if (!this._doc) { throw new Error('DocHandleProxy.doc called on deleted doc'); } return this._doc; } async whenReady(): Promise { await this._ready.wait(); } isReady(): boolean { return this._ready.state === TriggerState.RESOLVED; } change(fn: (doc: A.Doc) => void, opts?: A.ChangeOptions): void { invariant(this._doc, 'DocHandleProxy.change called on deleted doc'); const before = this._doc; const headsBefore = A.getHeads(this._doc); this._doc = opts ? A.change(this._doc, opts, fn) : A.change(this._doc, fn); this.emit('change', { handle: this, doc: this._doc, patches: A.diff(this._doc, headsBefore, A.getHeads(this._doc)), patchInfo: { before, after: this._doc, source: 'change' }, }); } changeAt(heads: A.Heads, fn: (doc: A.Doc) => void, opts?: A.ChangeOptions): A.Heads | undefined { invariant(this._doc, 'DocHandleProxy.changeAt called on deleted doc'); const before = this._doc; const headsBefore = A.getHeads(this._doc); const { newDoc, newHeads } = opts ? A.changeAt(this._doc, heads, opts, fn) : A.changeAt(this._doc, heads, fn); this._doc = newDoc; this.emit('change', { handle: this, doc: this._doc, patches: newHeads ? A.diff(this._doc, headsBefore, newHeads) : [], patchInfo: { before, after: this._doc, source: 'change' }, }); return newHeads ?? undefined; } update(updateCallback: (doc: A.Doc) => A.Doc): void { invariant(this._doc, 'DocHandleProxy.update called on deleted doc'); const before = this._doc; const headsBefore = A.getHeads(this._doc); const newDoc = updateCallback(this._doc); invariant(newDoc, 'DocHandleProxy.update returned undefined doc'); this._doc = newDoc; this.emit('change', { handle: this, doc: this._doc, patches: A.diff(this._doc, headsBefore, A.getHeads(this._doc)), patchInfo: { before, after: this._doc, source: 'change' }, }); } delete(): void { this._callbacks?.onDelete(); this.emit('delete', { handle: this }); this._doc = undefined; } /** * Get pending changes since last write. * @internal */ _getPendingChanges(): Uint8Array | undefined { invariant(this._doc, 'Doc is deleted, cannot get last write mutation'); if (A.equals(A.getHeads(this._doc), this._lastSentHeads)) { return; } const mutation = A.saveSince(this._doc, this._lastSentHeads); if (mutation.length === 0) { return; } this._currentlySendingHeads = A.getHeads(this._doc); return mutation; } /** * Confirm that the last write was successful. * @internal */ _confirmSync(): void { this._lastSentHeads = this._currentlySendingHeads; } /** * Update the doc with a foreign mutation from worker. * @internal */ _integrateHostUpdate(mutation: Uint8Array): void { invariant(this._doc, 'Doc is deleted, cannot write mutation'); const before = this._doc; const headsBefore = A.getHeads(this._doc); this._doc = A.loadIncremental(this._doc, mutation); if (A.equals(headsBefore, this._lastSentHeads)) { this._lastSentHeads = A.getHeads(this._doc); } this._ready.wake(); this.emit('change', { handle: this, doc: this._doc, patches: A.diff(this._doc, headsBefore, A.getHeads(this._doc)), patchInfo: { before, after: this._doc, source: 'change' }, }); } }