UNPKG

@tldraw/sync-core

Version:

tldraw infinite canvas SDK (multiplayer sync).

5 lines • 65.5 kB
{ "version": 3, "sources": ["../../src/lib/TLSyncRoom.ts"], "sourcesContent": ["import { Atom, atom, transaction } from '@tldraw/state'\nimport {\n\tIdOf,\n\tMigrationFailureReason,\n\tRecordType,\n\tSerializedSchema,\n\tStoreSchema,\n\tUnknownRecord,\n} from '@tldraw/store'\nimport { DocumentRecordType, PageRecordType, TLDOCUMENT_ID } from '@tldraw/tlschema'\nimport {\n\tIndexKey,\n\tResult,\n\tassert,\n\tassertExists,\n\texhaustiveSwitchError,\n\tgetOwnProperty,\n\thasOwnProperty,\n\tisEqual,\n\tisNativeStructuredClone,\n\tobjectMapEntries,\n\tobjectMapKeys,\n\tstructuredClone,\n} from '@tldraw/utils'\nimport { createNanoEvents } from 'nanoevents'\nimport {\n\tRoomSession,\n\tRoomSessionState,\n\tSESSION_IDLE_TIMEOUT,\n\tSESSION_REMOVAL_WAIT_TIME,\n\tSESSION_START_WAIT_TIME,\n} from './RoomSession'\nimport { TLSyncLog } from './TLSocketRoom'\nimport { TLSyncErrorCloseEventCode, TLSyncErrorCloseEventReason } from './TLSyncClient'\nimport {\n\tNetworkDiff,\n\tObjectDiff,\n\tRecordOp,\n\tRecordOpType,\n\tValueOpType,\n\tapplyObjectDiff,\n\tdiffRecord,\n} from './diff'\nimport { interval } from './interval'\nimport {\n\tTLIncompatibilityReason,\n\tTLSocketClientSentEvent,\n\tTLSocketServerSentDataEvent,\n\tTLSocketServerSentEvent,\n\tgetTlsyncProtocolVersion,\n} from './protocol'\n\n/** @internal */\nexport interface TLRoomSocket<R extends UnknownRecord> {\n\tisOpen: boolean\n\tsendMessage(msg: TLSocketServerSentEvent<R>): void\n\tclose(code?: number, reason?: string): void\n}\n\n// the max number of tombstones to keep in the store\nexport const MAX_TOMBSTONES = 3000\n// the number of tombstones to delete when the max is reached\nexport const TOMBSTONE_PRUNE_BUFFER_SIZE = 300\n// the minimum time between data-related messages to the clients\nexport const DATA_MESSAGE_DEBOUNCE_INTERVAL = 1000 / 60\n\nconst timeSince = (time: number) => Date.now() - time\n\n/** @internal */\nexport class DocumentState<R extends UnknownRecord> {\n\t_atom: Atom<{ state: R; lastChangedClock: number }>\n\n\tstatic createWithoutValidating<R extends UnknownRecord>(\n\t\tstate: R,\n\t\tlastChangedClock: number,\n\t\trecordType: RecordType<R, any>\n\t): DocumentState<R> {\n\t\treturn new DocumentState(state, lastChangedClock, recordType)\n\t}\n\n\tstatic createAndValidate<R extends UnknownRecord>(\n\t\tstate: R,\n\t\tlastChangedClock: number,\n\t\trecordType: RecordType<R, any>\n\t): Result<DocumentState<R>, Error> {\n\t\ttry {\n\t\t\trecordType.validate(state)\n\t\t} catch (error: any) {\n\t\t\treturn Result.err(error)\n\t\t}\n\t\treturn Result.ok(new DocumentState(state, lastChangedClock, recordType))\n\t}\n\n\tprivate constructor(\n\t\tstate: R,\n\t\tlastChangedClock: number,\n\t\tprivate readonly recordType: RecordType<R, any>\n\t) {\n\t\tthis._atom = atom('document:' + state.id, { state, lastChangedClock })\n\t}\n\t// eslint-disable-next-line no-restricted-syntax\n\tget state() {\n\t\treturn this._atom.get().state\n\t}\n\t// eslint-disable-next-line no-restricted-syntax\n\tget lastChangedClock() {\n\t\treturn this._atom.get().lastChangedClock\n\t}\n\treplaceState(state: R, clock: number): Result<ObjectDiff | null, Error> {\n\t\tconst diff = diffRecord(this.state, state)\n\t\tif (!diff) return Result.ok(null)\n\t\ttry {\n\t\t\tthis.recordType.validate(state)\n\t\t} catch (error: any) {\n\t\t\treturn Result.err(error)\n\t\t}\n\t\tthis._atom.set({ state, lastChangedClock: clock })\n\t\treturn Result.ok(diff)\n\t}\n\tmergeDiff(diff: ObjectDiff, clock: number): Result<ObjectDiff | null, Error> {\n\t\tconst newState = applyObjectDiff(this.state, diff)\n\t\treturn this.replaceState(newState, clock)\n\t}\n}\n\n/** @public */\nexport interface RoomSnapshot {\n\tclock: number\n\tdocuments: Array<{ state: UnknownRecord; lastChangedClock: number }>\n\ttombstones?: Record<string, number>\n\tschema?: SerializedSchema\n}\n\n/**\n * A room is a workspace for a group of clients. It allows clients to collaborate on documents\n * within that workspace.\n *\n * @internal\n */\nexport class TLSyncRoom<R extends UnknownRecord, SessionMeta> {\n\t// A table of connected clients\n\treadonly sessions = new Map<string, RoomSession<R, SessionMeta>>()\n\n\t// eslint-disable-next-line local/prefer-class-methods\n\tpruneSessions = () => {\n\t\tfor (const client of this.sessions.values()) {\n\t\t\tswitch (client.state) {\n\t\t\t\tcase RoomSessionState.Connected: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.lastInteractionTime) > SESSION_IDLE_TIMEOUT\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\tthis.cancelSession(client.sessionId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingConnectMessage: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.sessionStartTime) > SESSION_START_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut || !client.socket.isOpen) {\n\t\t\t\t\t\t// remove immediately\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcase RoomSessionState.AwaitingRemoval: {\n\t\t\t\t\tconst hasTimedOut = timeSince(client.cancellationTime) > SESSION_REMOVAL_WAIT_TIME\n\t\t\t\t\tif (hasTimedOut) {\n\t\t\t\t\t\tthis.removeSession(client.sessionId)\n\t\t\t\t\t}\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tdefault: {\n\t\t\t\t\texhaustiveSwitchError(client)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate disposables: Array<() => void> = [interval(this.pruneSessions, 2000)]\n\n\tprivate _isClosed = false\n\n\tclose() {\n\t\tthis.disposables.forEach((d) => d())\n\t\tthis.sessions.forEach((session) => {\n\t\t\tsession.socket.close()\n\t\t})\n\t\tthis._isClosed = true\n\t}\n\n\tisClosed() {\n\t\treturn this._isClosed\n\t}\n\n\treadonly events = createNanoEvents<{\n\t\troom_became_empty(): void\n\t\tsession_removed(args: { sessionId: string; meta: SessionMeta }): void\n\t}>()\n\n\t// Values associated with each uid (must be serializable).\n\t/** @internal */\n\tstate = atom<{\n\t\tdocuments: Record<string, DocumentState<R>>\n\t\ttombstones: Record<string, number>\n\t}>('room state', {\n\t\tdocuments: {},\n\t\ttombstones: {},\n\t})\n\n\t// this clock should start higher than the client, to make sure that clients who sync with their\n\t// initial lastServerClock value get the full state\n\t// in this case clients will start with 0, and the server will start with 1\n\tclock = 1\n\tdocumentClock = 1\n\ttombstoneHistoryStartsAtClock = this.clock\n\t// map from record id to clock upon deletion\n\n\treadonly serializedSchema: SerializedSchema\n\n\treadonly documentTypes: Set<string>\n\treadonly presenceType: RecordType<R, any> | null\n\tprivate log?: TLSyncLog\n\tpublic readonly schema: StoreSchema<R, any>\n\tprivate onDataChange?(): void\n\tprivate onPresenceChange?(): void\n\n\tconstructor(opts: {\n\t\tlog?: TLSyncLog\n\t\tschema: StoreSchema<R, any>\n\t\tsnapshot?: RoomSnapshot\n\t\tonDataChange?(): void\n\t\tonPresenceChange?(): void\n\t}) {\n\t\tthis.schema = opts.schema\n\t\tlet snapshot = opts.snapshot\n\t\tthis.log = opts.log\n\t\tthis.onDataChange = opts.onDataChange\n\t\tthis.onPresenceChange = opts.onPresenceChange\n\n\t\tassert(\n\t\t\tisNativeStructuredClone,\n\t\t\t'TLSyncRoom is supposed to run either on Cloudflare Workers' +\n\t\t\t\t'or on a 18+ version of Node.js, which both support the native structuredClone API'\n\t\t)\n\n\t\t// do a json serialization cycle to make sure the schema has no 'undefined' values\n\t\tthis.serializedSchema = JSON.parse(JSON.stringify(this.schema.serialize()))\n\n\t\tthis.documentTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types)\n\t\t\t\t.filter((t) => t.scope === 'document')\n\t\t\t\t.map((t) => t.typeName)\n\t\t)\n\n\t\tconst presenceTypes = new Set(\n\t\t\tObject.values<RecordType<R, any>>(this.schema.types).filter((t) => t.scope === 'presence')\n\t\t)\n\n\t\tif (presenceTypes.size > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`TLSyncRoom: exactly zero or one presence type is expected, but found ${presenceTypes.size}`\n\t\t\t)\n\t\t}\n\n\t\tthis.presenceType = presenceTypes.values().next()?.value ?? null\n\n\t\tif (!snapshot) {\n\t\t\tsnapshot = {\n\t\t\t\tclock: 0,\n\t\t\t\tdocuments: [\n\t\t\t\t\t{\n\t\t\t\t\t\tstate: DocumentRecordType.create({ id: TLDOCUMENT_ID }),\n\t\t\t\t\t\tlastChangedClock: 0,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tstate: PageRecordType.create({ name: 'Page 1', index: 'a1' as IndexKey }),\n\t\t\t\t\t\tlastChangedClock: 0,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}\n\t\t}\n\n\t\tthis.clock = snapshot.clock\n\t\tlet didIncrementClock = false\n\t\tconst ensureClockDidIncrement = (_reason: string) => {\n\t\t\tif (!didIncrementClock) {\n\t\t\t\tdidIncrementClock = true\n\t\t\t\tthis.clock++\n\t\t\t}\n\t\t}\n\n\t\tconst tombstones = { ...snapshot.tombstones }\n\t\tconst filteredDocuments = []\n\t\tfor (const doc of snapshot.documents) {\n\t\t\tif (this.documentTypes.has(doc.state.typeName)) {\n\t\t\t\tfilteredDocuments.push(doc)\n\t\t\t} else {\n\t\t\t\tensureClockDidIncrement('doc type was not doc type')\n\t\t\t\ttombstones[doc.state.id] = this.clock\n\t\t\t}\n\t\t}\n\n\t\tconst documents: Record<string, DocumentState<R>> = Object.fromEntries(\n\t\t\tfilteredDocuments.map((r) => [\n\t\t\t\tr.state.id,\n\t\t\t\tDocumentState.createWithoutValidating<R>(\n\t\t\t\t\tr.state as R,\n\t\t\t\t\tr.lastChangedClock,\n\t\t\t\t\tassertExists(getOwnProperty(this.schema.types, r.state.typeName))\n\t\t\t\t),\n\t\t\t])\n\t\t)\n\n\t\tconst migrationResult = this.schema.migrateStoreSnapshot({\n\t\t\tstore: Object.fromEntries(\n\t\t\t\tobjectMapEntries(documents).map(([id, { state }]) => [id, state as R])\n\t\t\t) as Record<IdOf<R>, R>,\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\tschema: snapshot.schema ?? this.schema.serializeEarliestVersion(),\n\t\t})\n\n\t\tif (migrationResult.type === 'error') {\n\t\t\t// TODO: Fault tolerance\n\t\t\tthrow new Error('Failed to migrate: ' + migrationResult.reason)\n\t\t}\n\n\t\tfor (const [id, r] of objectMapEntries(migrationResult.value)) {\n\t\t\tconst existing = documents[id]\n\t\t\tif (!existing) {\n\t\t\t\t// record was added during migration\n\t\t\t\tensureClockDidIncrement('record was added during migration')\n\t\t\t\tdocuments[id] = DocumentState.createWithoutValidating(\n\t\t\t\t\tr,\n\t\t\t\t\tthis.clock,\n\t\t\t\t\tassertExists(getOwnProperty(this.schema.types, r.typeName)) as any\n\t\t\t\t)\n\t\t\t} else if (!isEqual(existing.state, r)) {\n\t\t\t\t// record was maybe updated during migration\n\t\t\t\tensureClockDidIncrement('record was maybe updated during migration')\n\t\t\t\texisting.replaceState(r, this.clock)\n\t\t\t}\n\t\t}\n\n\t\tfor (const id of objectMapKeys(documents)) {\n\t\t\tif (!migrationResult.value[id as keyof typeof migrationResult.value]) {\n\t\t\t\t// record was removed during migration\n\t\t\t\tensureClockDidIncrement('record was removed during migration')\n\t\t\t\ttombstones[id] = this.clock\n\t\t\t\tdelete documents[id]\n\t\t\t}\n\t\t}\n\n\t\tthis.state.set({ documents, tombstones })\n\n\t\tthis.pruneTombstones()\n\t\tthis.documentClock = this.clock\n\t\tif (didIncrementClock) {\n\t\t\topts.onDataChange?.()\n\t\t}\n\t}\n\n\t// eslint-disable-next-line local/prefer-class-methods\n\tprivate pruneTombstones = () => {\n\t\t// avoid blocking any pending responses\n\t\tthis.state.update(({ tombstones, documents }) => {\n\t\t\tconst entries = Object.entries(this.state.get().tombstones)\n\t\t\tif (entries.length > MAX_TOMBSTONES) {\n\t\t\t\t// sort entries in ascending order by clock\n\t\t\t\tentries.sort((a, b) => a[1] - b[1])\n\t\t\t\t// trim off the first bunch\n\t\t\t\tconst excessQuantity = entries.length - MAX_TOMBSTONES\n\t\t\t\ttombstones = Object.fromEntries(entries.slice(excessQuantity + TOMBSTONE_PRUNE_BUFFER_SIZE))\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdocuments,\n\t\t\t\ttombstones,\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate getDocument(id: string) {\n\t\treturn this.state.get().documents[id]\n\t}\n\n\tprivate addDocument(id: string, state: R, clock: number): Result<void, Error> {\n\t\tlet { documents, tombstones } = this.state.get()\n\t\tif (hasOwnProperty(tombstones, id)) {\n\t\t\ttombstones = { ...tombstones }\n\t\t\tdelete tombstones[id]\n\t\t}\n\t\tconst createResult = DocumentState.createAndValidate(\n\t\t\tstate,\n\t\t\tclock,\n\t\t\tassertExists(getOwnProperty(this.schema.types, state.typeName))\n\t\t)\n\t\tif (!createResult.ok) return createResult\n\t\tdocuments = { ...documents, [id]: createResult.value }\n\t\tthis.state.set({ documents, tombstones })\n\t\treturn Result.ok(undefined)\n\t}\n\n\tprivate removeDocument(id: string, clock: number) {\n\t\tthis.state.update(({ documents, tombstones }) => {\n\t\t\tdocuments = { ...documents }\n\t\t\tdelete documents[id]\n\t\t\ttombstones = { ...tombstones, [id]: clock }\n\t\t\treturn { documents, tombstones }\n\t\t})\n\t}\n\n\tgetSnapshot(): RoomSnapshot {\n\t\tconst { documents, tombstones } = this.state.get()\n\t\treturn {\n\t\t\tclock: this.clock,\n\t\t\ttombstones,\n\t\t\tschema: this.serializedSchema,\n\t\t\tdocuments: Object.values(documents)\n\t\t\t\t.filter((d) => this.documentTypes.has(d.state.typeName))\n\t\t\t\t.map((doc) => ({\n\t\t\t\t\tstate: doc.state,\n\t\t\t\t\tlastChangedClock: doc.lastChangedClock,\n\t\t\t\t})),\n\t\t}\n\t}\n\n\t/**\n\t * Send a message to a particular client. Debounces data events\n\t *\n\t * @param sessionId - The id of the session to send the message to.\n\t * @param message - The message to send.\n\t */\n\tprivate sendMessage(\n\t\tsessionId: string,\n\t\tmessage: TLSocketServerSentEvent<R> | TLSocketServerSentDataEvent<R>\n\t) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to send message to unknown session', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.state !== RoomSessionState.Connected) {\n\t\t\tthis.log?.warn?.('Tried to send message to disconnected client', message.type)\n\t\t\treturn\n\t\t}\n\t\tif (session.socket.isOpen) {\n\t\t\tif (message.type !== 'patch' && message.type !== 'push_result') {\n\t\t\t\t// this is not a data message\n\t\t\t\tif (message.type !== 'pong') {\n\t\t\t\t\t// non-data messages like \"connect\" might still need to be ordered correctly with\n\t\t\t\t\t// respect to data messages, so it's better to flush just in case\n\t\t\t\t\tthis._flushDataMessages(sessionId)\n\t\t\t\t}\n\t\t\t\tsession.socket.sendMessage(message)\n\t\t\t} else {\n\t\t\t\tif (session.debounceTimer === null) {\n\t\t\t\t\t// this is the first message since the last flush, don't delay it\n\t\t\t\t\tsession.socket.sendMessage({ type: 'data', data: [message] })\n\n\t\t\t\t\tsession.debounceTimer = setTimeout(\n\t\t\t\t\t\t() => this._flushDataMessages(sessionId),\n\t\t\t\t\t\tDATA_MESSAGE_DEBOUNCE_INTERVAL\n\t\t\t\t\t)\n\t\t\t\t} else {\n\t\t\t\t\tsession.outstandingDataMessages.push(message)\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tthis.cancelSession(session.sessionId)\n\t\t}\n\t}\n\n\t// needs to accept sessionId and not a session because the session might be dead by the time\n\t// the timer fires\n\t_flushDataMessages(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\n\t\tif (!session || session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\n\t\tsession.debounceTimer = null\n\n\t\tif (session.outstandingDataMessages.length > 0) {\n\t\t\tsession.socket.sendMessage({ type: 'data', data: session.outstandingDataMessages })\n\t\t\tsession.outstandingDataMessages.length = 0\n\t\t}\n\t}\n\n\t/** @internal */\n\tprivate removeSession(sessionId: string, fatalReason?: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Tried to remove unknown session')\n\t\t\treturn\n\t\t}\n\n\t\tthis.sessions.delete(sessionId)\n\n\t\tconst presence = this.getDocument(session.presenceId ?? '')\n\n\t\ttry {\n\t\t\tif (fatalReason) {\n\t\t\t\tsession.socket.close(TLSyncErrorCloseEventCode, fatalReason)\n\t\t\t} else {\n\t\t\t\tsession.socket.close()\n\t\t\t}\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\n\t\tif (presence) {\n\t\t\tthis.state.update(({ tombstones, documents }) => {\n\t\t\t\tdocuments = { ...documents }\n\t\t\t\tdelete documents[session.presenceId!]\n\t\t\t\treturn { documents, tombstones }\n\t\t\t})\n\n\t\t\tthis.broadcastPatch({\n\t\t\t\tdiff: { [session.presenceId!]: [RecordOpType.Remove] },\n\t\t\t\tsourceSessionId: sessionId,\n\t\t\t})\n\t\t}\n\n\t\tthis.events.emit('session_removed', { sessionId, meta: session.meta })\n\t\tif (this.sessions.size === 0) {\n\t\t\tthis.events.emit('room_became_empty')\n\t\t}\n\t}\n\n\tprivate cancelSession(sessionId: string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\treturn\n\t\t}\n\n\t\tif (session.state === RoomSessionState.AwaitingRemoval) {\n\t\t\tthis.log?.warn?.('Tried to cancel session that is already awaiting removal')\n\t\t\treturn\n\t\t}\n\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingRemoval,\n\t\t\tsessionId,\n\t\t\tpresenceId: session.presenceId,\n\t\t\tsocket: session.socket,\n\t\t\tcancellationTime: Date.now(),\n\t\t\tmeta: session.meta,\n\t\t\tisReadonly: session.isReadonly,\n\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t})\n\n\t\ttry {\n\t\t\tsession.socket.close()\n\t\t} catch {\n\t\t\t// noop, calling .close() multiple times is fine\n\t\t}\n\t}\n\n\t/**\n\t * Broadcast a message to all connected clients except the one with the sessionId provided.\n\t *\n\t * @param message - The message to broadcast.\n\t */\n\tbroadcastPatch(message: { diff: NetworkDiff<R>; sourceSessionId?: string }) {\n\t\tconst { diff, sourceSessionId } = message\n\t\tthis.sessions.forEach((session) => {\n\t\t\tif (session.state !== RoomSessionState.Connected) return\n\t\t\tif (sourceSessionId === session.sessionId) return\n\t\t\tif (!session.socket.isOpen) {\n\t\t\t\tthis.cancelSession(session.sessionId)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tconst res = this.migrateDiffForSession(session.serializedSchema, diff)\n\n\t\t\tif (!res.ok) {\n\t\t\t\t// disconnect client and send incompatibility error\n\t\t\t\tthis.rejectSession(\n\t\t\t\t\tsession.sessionId,\n\t\t\t\t\tres.error === MigrationFailureReason.TargetVersionTooNew\n\t\t\t\t\t\t? TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t\t\t: TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthis.sendMessage(session.sessionId, {\n\t\t\t\ttype: 'patch',\n\t\t\t\tdiff: res.value,\n\t\t\t\tserverClock: this.clock,\n\t\t\t})\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * When a client connects to the room, add them to the list of clients and then merge the history\n\t * down into the snapshots.\n\t *\n\t * @internal\n\t */\n\thandleNewSession(opts: {\n\t\tsessionId: string\n\t\tsocket: TLRoomSocket<R>\n\t\tmeta: SessionMeta\n\t\tisReadonly: boolean\n\t}) {\n\t\tconst { sessionId, socket, meta, isReadonly } = opts\n\t\tconst existing = this.sessions.get(sessionId)\n\t\tthis.sessions.set(sessionId, {\n\t\t\tstate: RoomSessionState.AwaitingConnectMessage,\n\t\t\tsessionId,\n\t\t\tsocket,\n\t\t\tpresenceId: existing?.presenceId ?? this.presenceType?.createId() ?? null,\n\t\t\tsessionStartTime: Date.now(),\n\t\t\tmeta,\n\t\t\tisReadonly: isReadonly ?? false,\n\t\t\t// this gets set later during handleConnectMessage\n\t\t\trequiresLegacyRejection: false,\n\t\t})\n\t\treturn this\n\t}\n\n\t/**\n\t * When we send a diff to a client, if that client is on a lower version than us, we need to make\n\t * the diff compatible with their version. At the moment this means migrating each affected record\n\t * to the client's version and sending the whole record again. We can optimize this later by\n\t * keeping the previous versions of records around long enough to recalculate these diffs for\n\t * older client versions.\n\t */\n\tprivate migrateDiffForSession(\n\t\tserializedSchema: SerializedSchema,\n\t\tdiff: NetworkDiff<R>\n\t): Result<NetworkDiff<R>, MigrationFailureReason> {\n\t\t// TODO: optimize this by recalculating patches using the previous versions of records\n\n\t\t// when the client connects we check whether the schema is identical and make sure\n\t\t// to use the same object reference so that === works on this line\n\t\tif (serializedSchema === this.serializedSchema) {\n\t\t\treturn Result.ok(diff)\n\t\t}\n\n\t\tconst result: NetworkDiff<R> = {}\n\t\tfor (const [id, op] of Object.entries(diff)) {\n\t\t\tif (op[0] === RecordOpType.Remove) {\n\t\t\t\tresult[id] = op\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst migrationResult = this.schema.migratePersistedRecord(\n\t\t\t\tthis.getDocument(id).state,\n\t\t\t\tserializedSchema,\n\t\t\t\t'down'\n\t\t\t)\n\n\t\t\tif (migrationResult.type === 'error') {\n\t\t\t\treturn Result.err(migrationResult.reason)\n\t\t\t}\n\n\t\t\tresult[id] = [RecordOpType.Put, migrationResult.value]\n\t\t}\n\n\t\treturn Result.ok(result)\n\t}\n\n\t/**\n\t * When the server receives a message from the clients Currently, supports connect and patches.\n\t * Invalid messages types throws an error. Currently, doesn't validate data.\n\t *\n\t * @param sessionId - The session that sent the message\n\t * @param message - The message that was sent\n\t */\n\tasync handleMessage(sessionId: string, message: TLSocketClientSentEvent<R>) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) {\n\t\t\tthis.log?.warn?.('Received message from unknown session')\n\t\t\treturn\n\t\t}\n\t\tswitch (message.type) {\n\t\t\tcase 'connect': {\n\t\t\t\treturn this.handleConnectRequest(session, message)\n\t\t\t}\n\t\t\tcase 'push': {\n\t\t\t\treturn this.handlePushRequest(session, message)\n\t\t\t}\n\t\t\tcase 'ping': {\n\t\t\t\tif (session.state === RoomSessionState.Connected) {\n\t\t\t\t\tsession.lastInteractionTime = Date.now()\n\t\t\t\t}\n\t\t\t\treturn this.sendMessage(session.sessionId, { type: 'pong' })\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\texhaustiveSwitchError(message)\n\t\t\t}\n\t\t}\n\t}\n\n\t/** If the client is out of date, or we are out of date, we need to let them know */\n\trejectSession(sessionId: string, fatalReason?: TLSyncErrorCloseEventReason | string) {\n\t\tconst session = this.sessions.get(sessionId)\n\t\tif (!session) return\n\t\tif (!fatalReason) {\n\t\t\tthis.removeSession(sessionId)\n\t\t\treturn\n\t\t}\n\t\tif (session.requiresLegacyRejection) {\n\t\t\ttry {\n\t\t\t\tif (session.socket.isOpen) {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\tlet legacyReason: TLIncompatibilityReason\n\t\t\t\t\tswitch (fatalReason) {\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.CLIENT_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ClientTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.SERVER_TOO_OLD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.ServerTooOld\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tcase TLSyncErrorCloseEventReason.INVALID_RECORD:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidRecord\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-deprecated\n\t\t\t\t\t\t\tlegacyReason = TLIncompatibilityReason.InvalidOperation\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tsession.socket.sendMessage({\n\t\t\t\t\t\ttype: 'incompatibility_error',\n\t\t\t\t\t\treason: legacyReason,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// noop\n\t\t\t} finally {\n\t\t\t\tthis.removeSession(sessionId)\n\t\t\t}\n\t\t} else {\n\t\t\tthis.removeSession(sessionId, fatalReason)\n\t\t}\n\t}\n\n\tprivate handleConnectRequest(\n\t\tsession: RoomSession<R, SessionMeta>,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'connect' }>\n\t) {\n\t\t// if the protocol versions don't match, disconnect the client\n\t\t// we will eventually want to try to make our protocol backwards compatible to some degree\n\t\t// and have a MIN_PROTOCOL_VERSION constant that the TLSyncRoom implements support for\n\t\tlet theirProtocolVersion = message.protocolVersion\n\t\t// 5 is the same as 6\n\t\tif (theirProtocolVersion === 5) {\n\t\t\ttheirProtocolVersion = 6\n\t\t}\n\t\t// 6 is almost the same as 7\n\t\tsession.requiresLegacyRejection = theirProtocolVersion === 6\n\t\tif (theirProtocolVersion === 6) {\n\t\t\ttheirProtocolVersion++\n\t\t}\n\t\tif (theirProtocolVersion == null || theirProtocolVersion < getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t} else if (theirProtocolVersion > getTlsyncProtocolVersion()) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.SERVER_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\t// If the client's store is at a different version to ours, it could cause corruption.\n\t\t// We should disconnect the client and ask them to refresh.\n\t\tif (message.schema == null) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\t\tconst migrations = this.schema.getMigrationsSince(message.schema)\n\t\t// if the client's store is at a different version to ours, we can't support them\n\t\tif (!migrations.ok || migrations.value.some((m) => m.scope === 'store' || !m.down)) {\n\t\t\tthis.rejectSession(session.sessionId, TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\treturn\n\t\t}\n\n\t\tconst sessionSchema = isEqual(message.schema, this.serializedSchema)\n\t\t\t? this.serializedSchema\n\t\t\t: message.schema\n\n\t\tconst connect = (msg: TLSocketServerSentEvent<R>) => {\n\t\t\tthis.sessions.set(session.sessionId, {\n\t\t\t\tstate: RoomSessionState.Connected,\n\t\t\t\tsessionId: session.sessionId,\n\t\t\t\tpresenceId: session.presenceId,\n\t\t\t\tsocket: session.socket,\n\t\t\t\tserializedSchema: sessionSchema,\n\t\t\t\tlastInteractionTime: Date.now(),\n\t\t\t\tdebounceTimer: null,\n\t\t\t\toutstandingDataMessages: [],\n\t\t\t\tmeta: session.meta,\n\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\trequiresLegacyRejection: session.requiresLegacyRejection,\n\t\t\t})\n\t\t\tthis.sendMessage(session.sessionId, msg)\n\t\t}\n\n\t\ttransaction((rollback) => {\n\t\t\tif (\n\t\t\t\t// if the client requests changes since a time before we have tombstone history, send them the full state\n\t\t\t\tmessage.lastServerClock < this.tombstoneHistoryStartsAtClock ||\n\t\t\t\t// similarly, if they ask for a time we haven't reached yet, send them the full state\n\t\t\t\t// this will only happen if the DB is reset (or there is no db) and the server restarts\n\t\t\t\t// or if the server exits/crashes with unpersisted changes\n\t\t\t\tmessage.lastServerClock > this.clock\n\t\t\t) {\n\t\t\t\tconst diff: NetworkDiff<R> = {}\n\t\t\t\tfor (const [id, doc] of Object.entries(this.state.get().documents)) {\n\t\t\t\t\tif (id !== session.presenceId) {\n\t\t\t\t\t\tdiff[id] = [RecordOpType.Put, doc.state]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst migrated = this.migrateDiffForSession(sessionSchema, diff)\n\t\t\t\tif (!migrated.ok) {\n\t\t\t\t\trollback()\n\t\t\t\t\tthis.rejectSession(\n\t\t\t\t\t\tsession.sessionId,\n\t\t\t\t\t\tmigrated.error === MigrationFailureReason.TargetVersionTooNew\n\t\t\t\t\t\t\t? TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t\t\t\t: TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t\t\t\t\t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconnect({\n\t\t\t\t\ttype: 'connect',\n\t\t\t\t\tconnectRequestId: message.connectRequestId,\n\t\t\t\t\thydrationType: 'wipe_all',\n\t\t\t\t\tprotocolVersion: getTlsyncProtocolVersion(),\n\t\t\t\t\tschema: this.schema.serialize(),\n\t\t\t\t\tserverClock: this.clock,\n\t\t\t\t\tdiff: migrated.value,\n\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\t// calculate the changes since the time the client last saw\n\t\t\t\tconst diff: NetworkDiff<R> = {}\n\t\t\t\tconst updatedDocs = Object.values(this.state.get().documents).filter(\n\t\t\t\t\t(doc) => doc.lastChangedClock > message.lastServerClock\n\t\t\t\t)\n\t\t\t\tconst presenceDocs = this.presenceType\n\t\t\t\t\t? Object.values(this.state.get().documents).filter(\n\t\t\t\t\t\t\t(doc) =>\n\t\t\t\t\t\t\t\tthis.presenceType!.typeName === doc.state.typeName &&\n\t\t\t\t\t\t\t\tdoc.state.id !== session.presenceId\n\t\t\t\t\t\t)\n\t\t\t\t\t: []\n\t\t\t\tconst deletedDocsIds = Object.entries(this.state.get().tombstones)\n\t\t\t\t\t.filter(([_id, deletedAtClock]) => deletedAtClock > message.lastServerClock)\n\t\t\t\t\t.map(([id]) => id)\n\n\t\t\t\tfor (const doc of updatedDocs) {\n\t\t\t\t\tdiff[doc.state.id] = [RecordOpType.Put, doc.state]\n\t\t\t\t}\n\t\t\t\tfor (const doc of presenceDocs) {\n\t\t\t\t\tdiff[doc.state.id] = [RecordOpType.Put, doc.state]\n\t\t\t\t}\n\n\t\t\t\tfor (const docId of deletedDocsIds) {\n\t\t\t\t\tdiff[docId] = [RecordOpType.Remove]\n\t\t\t\t}\n\t\t\t\tconst migrated = this.migrateDiffForSession(sessionSchema, diff)\n\t\t\t\tif (!migrated.ok) {\n\t\t\t\t\trollback()\n\t\t\t\t\tthis.rejectSession(\n\t\t\t\t\t\tsession.sessionId,\n\t\t\t\t\t\tmigrated.error === MigrationFailureReason.TargetVersionTooNew\n\t\t\t\t\t\t\t? TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t\t\t\t: TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t\t\t\t\t)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconnect({\n\t\t\t\t\ttype: 'connect',\n\t\t\t\t\tconnectRequestId: message.connectRequestId,\n\t\t\t\t\thydrationType: 'wipe_presence',\n\t\t\t\t\tschema: this.schema.serialize(),\n\t\t\t\t\tprotocolVersion: getTlsyncProtocolVersion(),\n\t\t\t\t\tserverClock: this.clock,\n\t\t\t\t\tdiff: migrated.value,\n\t\t\t\t\tisReadonly: session.isReadonly,\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\n\tprivate handlePushRequest(\n\t\tsession: RoomSession<R, SessionMeta> | null,\n\t\tmessage: Extract<TLSocketClientSentEvent<R>, { type: 'push' }>\n\t) {\n\t\t// We must be connected to handle push requests\n\t\tif (session && session.state !== RoomSessionState.Connected) {\n\t\t\treturn\n\t\t}\n\n\t\t// update the last interaction time\n\t\tif (session) {\n\t\t\tsession.lastInteractionTime = Date.now()\n\t\t}\n\n\t\t// increment the clock for this push\n\t\tthis.clock++\n\n\t\tconst initialDocumentClock = this.documentClock\n\t\tlet didPresenceChange = false\n\t\ttransaction((rollback) => {\n\t\t\t// collect actual ops that resulted from the push\n\t\t\t// these will be broadcast to other users\n\t\t\tinterface ActualChanges {\n\t\t\t\tdiff: NetworkDiff<R> | null\n\t\t\t}\n\t\t\tconst docChanges: ActualChanges = { diff: null }\n\t\t\tconst presenceChanges: ActualChanges = { diff: null }\n\n\t\t\tconst propagateOp = (changes: ActualChanges, id: string, op: RecordOp<R>) => {\n\t\t\t\tif (!changes.diff) changes.diff = {}\n\t\t\t\tchanges.diff[id] = op\n\t\t\t}\n\n\t\t\tconst fail = (\n\t\t\t\treason: TLSyncErrorCloseEventReason,\n\t\t\t\tunderlyingError?: Error\n\t\t\t): Result<void, void> => {\n\t\t\t\trollback()\n\t\t\t\tif (session) {\n\t\t\t\t\tthis.rejectSession(session.sessionId, reason)\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error('failed to apply changes: ' + reason, underlyingError)\n\t\t\t\t}\n\t\t\t\tif (typeof process !== 'undefined' && process.env.NODE_ENV !== 'test') {\n\t\t\t\t\tthis.log?.error?.('failed to apply push', reason, message, underlyingError)\n\t\t\t\t}\n\t\t\t\treturn Result.err(undefined)\n\t\t\t}\n\n\t\t\tconst addDocument = (changes: ActualChanges, id: string, _state: R): Result<void, void> => {\n\t\t\t\tconst res = session\n\t\t\t\t\t? this.schema.migratePersistedRecord(_state, session.serializedSchema, 'up')\n\t\t\t\t\t: { type: 'success' as const, value: _state }\n\t\t\t\tif (res.type === 'error') {\n\t\t\t\t\treturn fail(\n\t\t\t\t\t\tres.reason === MigrationFailureReason.TargetVersionTooOld // target version is our version\n\t\t\t\t\t\t\t? TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t\t\t\t: TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst { value: state } = res\n\n\t\t\t\t// Get the existing document, if any\n\t\t\t\tconst doc = this.getDocument(id)\n\n\t\t\t\tif (doc) {\n\t\t\t\t\t// If there's an existing document, replace it with the new state\n\t\t\t\t\t// but propagate a diff rather than the entire value\n\t\t\t\t\tconst diff = doc.replaceState(state, this.clock)\n\t\t\t\t\tif (!diff.ok) {\n\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.INVALID_RECORD)\n\t\t\t\t\t}\n\t\t\t\t\tif (diff.value) {\n\t\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff.value])\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// Otherwise, if we don't already have a document with this id\n\t\t\t\t\t// create the document and propagate the put op\n\t\t\t\t\tconst result = this.addDocument(id, state, this.clock)\n\t\t\t\t\tif (!result.ok) {\n\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.INVALID_RECORD)\n\t\t\t\t\t}\n\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Put, state])\n\t\t\t\t}\n\n\t\t\t\treturn Result.ok(undefined)\n\t\t\t}\n\n\t\t\tconst patchDocument = (\n\t\t\t\tchanges: ActualChanges,\n\t\t\t\tid: string,\n\t\t\t\tpatch: ObjectDiff\n\t\t\t): Result<void, void> => {\n\t\t\t\t// if it was already deleted, there's no need to apply the patch\n\t\t\t\tconst doc = this.getDocument(id)\n\t\t\t\tif (!doc) return Result.ok(undefined)\n\t\t\t\t// If the client's version of the record is older than ours,\n\t\t\t\t// we apply the patch to the downgraded version of the record\n\t\t\t\tconst downgraded = session\n\t\t\t\t\t? this.schema.migratePersistedRecord(doc.state, session.serializedSchema, 'down')\n\t\t\t\t\t: { type: 'success' as const, value: doc.state }\n\t\t\t\tif (downgraded.type === 'error') {\n\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t}\n\n\t\t\t\tif (downgraded.value === doc.state) {\n\t\t\t\t\t// If the versions are compatible, apply the patch and propagate the patch op\n\t\t\t\t\tconst diff = doc.mergeDiff(patch, this.clock)\n\t\t\t\t\tif (!diff.ok) {\n\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.INVALID_RECORD)\n\t\t\t\t\t}\n\t\t\t\t\tif (diff.value) {\n\t\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff.value])\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// need to apply the patch to the downgraded version and then upgrade it\n\n\t\t\t\t\t// apply the patch to the downgraded version\n\t\t\t\t\tconst patched = applyObjectDiff(downgraded.value, patch)\n\t\t\t\t\t// then upgrade the patched version and use that as the new state\n\t\t\t\t\tconst upgraded = session\n\t\t\t\t\t\t? this.schema.migratePersistedRecord(patched, session.serializedSchema, 'up')\n\t\t\t\t\t\t: { type: 'success' as const, value: patched }\n\t\t\t\t\t// If the client's version is too old, we'll hit an error\n\t\t\t\t\tif (upgraded.type === 'error') {\n\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.CLIENT_TOO_OLD)\n\t\t\t\t\t}\n\t\t\t\t\t// replace the state with the upgraded version and propagate the patch op\n\t\t\t\t\tconst diff = doc.replaceState(upgraded.value, this.clock)\n\t\t\t\t\tif (!diff.ok) {\n\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.INVALID_RECORD)\n\t\t\t\t\t}\n\t\t\t\t\tif (diff.value) {\n\t\t\t\t\t\tpropagateOp(changes, id, [RecordOpType.Patch, diff.value])\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn Result.ok(undefined)\n\t\t\t}\n\n\t\t\tconst { clientClock } = message\n\n\t\t\tif (this.presenceType && session?.presenceId && 'presence' in message && message.presence) {\n\t\t\t\tif (!session) throw new Error('session is required for presence pushes')\n\t\t\t\t// The push request was for the presence scope.\n\t\t\t\tconst id = session.presenceId\n\t\t\t\tconst [type, val] = message.presence\n\t\t\t\tconst { typeName } = this.presenceType\n\t\t\t\tswitch (type) {\n\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t// Try to put the document. If it fails, stop here.\n\t\t\t\t\t\tconst res = addDocument(presenceChanges, id, { ...val, id, typeName })\n\t\t\t\t\t\t// if res.ok is false here then we already called `fail` and we should stop immediately\n\t\t\t\t\t\tif (!res.ok) return\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t// Try to patch the document. If it fails, stop here.\n\t\t\t\t\t\tconst res = patchDocument(presenceChanges, id, {\n\t\t\t\t\t\t\t...val,\n\t\t\t\t\t\t\tid: [ValueOpType.Put, id],\n\t\t\t\t\t\t\ttypeName: [ValueOpType.Put, typeName],\n\t\t\t\t\t\t})\n\t\t\t\t\t\t// if res.ok is false here then we already called `fail` and we should stop immediately\n\t\t\t\t\t\tif (!res.ok) return\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (message.diff && !session?.isReadonly) {\n\t\t\t\t// The push request was for the document scope.\n\t\t\t\tfor (const [id, op] of Object.entries(message.diff!)) {\n\t\t\t\t\tswitch (op[0]) {\n\t\t\t\t\t\tcase RecordOpType.Put: {\n\t\t\t\t\t\t\t// Try to add the document.\n\t\t\t\t\t\t\t// If we're putting a record with a type that we don't recognize, fail\n\t\t\t\t\t\t\tif (!this.documentTypes.has(op[1].typeName)) {\n\t\t\t\t\t\t\t\treturn fail(TLSyncErrorCloseEventReason.INVALID_RECORD)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst res = addDocument(docChanges, id, op[1])\n\t\t\t\t\t\t\t// if res.ok is false here then we already called `fail` and we should stop immediately\n\t\t\t\t\t\t\tif (!res.ok) return\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase RecordOpType.Patch: {\n\t\t\t\t\t\t\t// Try to patch the document. If it fails, stop here.\n\t\t\t\t\t\t\tconst res = patchDocument(docChanges, id, op[1])\n\t\t\t\t\t\t\t// if res.ok is false here then we already called `fail` and we should stop immediately\n\t\t\t\t\t\t\tif (!res.ok) return\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase RecordOpType.Remove: {\n\t\t\t\t\t\t\tconst doc = this.getDocument(id)\n\t\t\t\t\t\t\tif (!doc) {\n\t\t\t\t\t\t\t\t// If the doc was already deleted, don't do anything, no need to propagate a delete op\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// Delete the document and propagate the delete op\n\t\t\t\t\t\t\tthis.removeDocument(id, this.clock)\n\t\t\t\t\t\t\t// Schedule a pruneTombstones call to happen on the next call stack\n\t\t\t\t\t\t\tsetTimeout(this.pruneTombstones, 0)\n\t\t\t\t\t\t\tpropagateOp(docChanges, id, op)\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Let the client know what action to take based on the results of the push\n\t\t\tif (\n\t\t\t\t// if there was only a presence push, the client doesn't need to do anything aside from\n\t\t\t\t// shift the push request.\n\t\t\t\t!message.diff ||\n\t\t\t\tisEqual(docChanges.diff, message.diff)\n\t\t\t) {\n\t\t\t\t// COMMIT\n\t\t\t\t// Applying the client's changes had the exact same effect on the server as\n\t\t\t\t// they had on the client, so the client should keep the diff\n\t\t\t\tif (session) {\n\t\t\t\t\tthis.sendMessage(session.sessionId, {\n\t\t\t\t\t\ttype: 'push_result',\n\t\t\t\t\t\tserverClock: this.clock,\n\t\t\t\t\t\tclientClock,\n\t\t\t\t\t\taction: 'commit',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else if (!docChanges.diff) {\n\t\t\t\t// DISCARD\n\t\t\t\t// Applying the client's changes had no effect, so the client should drop the diff\n\t\t\t\tif (session) {\n\t\t\t\t\tthis.sendMessage(session.sessionId, {\n\t\t\t\t\t\ttype: 'push_result',\n\t\t\t\t\t\tserverClock: this.clock,\n\t\t\t\t\t\tclientClock,\n\t\t\t\t\t\taction: 'discard',\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// REBASE\n\t\t\t\t// Applying the client's changes had a different non-empty effect on the server,\n\t\t\t\t// so the client should rebase with our gold-standard / authoritative diff.\n\t\t\t\t// First we need to migrate the diff to the client's version\n\t\t\t\tif (session) {\n\t\t\t\t\tconst migrateResult = this.migrateDiffForSession(\n\t\t\t\t\t\tsession.serializedSchema,\n\t\t\t\t\t\tdocChanges.diff\n\t\t\t\t\t)\n\t\t\t\t\tif (!migrateResult.ok) {\n\t\t\t\t\t\treturn fail(\n\t\t\t\t\t\t\tmigrateResult.error === MigrationFailureReason.TargetVersionTooNew\n\t\t\t\t\t\t\t\t? TLSyncErrorCloseEventReason.SERVER_TOO_OLD\n\t\t\t\t\t\t\t\t: TLSyncErrorCloseEventReason.CLIENT_TOO_OLD\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\t// If the migration worked, send the rebased diff to the client\n\t\t\t\t\tthis.sendMessage(session.sessionId, {\n\t\t\t\t\t\ttype: 'push_result',\n\t\t\t\t\t\tserverClock: this.clock,\n\t\t\t\t\t\tclientClock,\n\t\t\t\t\t\taction: { rebaseWithDiff: migrateResult.value },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If there are merged changes, broadcast them to all other clients\n\t\t\tif (docChanges.diff || presenceChanges.diff) {\n\t\t\t\tthis.broadcastPatch({\n\t\t\t\t\tsourceSessionId: session?.sessionId,\n\t\t\t\t\tdiff: {\n\t\t\t\t\t\t...docChanges.diff,\n\t\t\t\t\t\t...presenceChanges.diff,\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (docChanges.diff) {\n\t\t\t\tthis.documentClock = this.clock\n\t\t\t}\n\t\t\tif (presenceChanges.diff) {\n\t\t\t\tdidPresenceChange = true\n\t\t\t}\n\n\t\t\treturn\n\t\t})\n\n\t\t// if it threw the changes will have been rolled back and the document clock will not have been incremented\n\t\tif (this.documentClock !== initialDocumentClock) {\n\t\t\tthis.onDataChange?.()\n\t\t}\n\n\t\tif (didPresenceChange) {\n\t\t\tthis.onPresenceChange?.()\n\t\t}\n\t}\n\n\t/**\n\t * Handle the event when a client disconnects.\n\t *\n\t * @param sessionId - The session that disconnected.\n\t */\n\thandleClose(sessionId: string) {\n\t\tthis.cancelSession(sessionId)\n\t}\n\n\t/**\n\t * Allow applying changes to the store in a transactional way.\n\t * @param updater - A function that will be called with a store object that can be used to make changes.\n\t * @returns A promise that resolves when the transaction is complete.\n\t */\n\tasync updateStore(updater: (store: RoomStoreMethods<R>) => void | Promise<void>) {\n\t\tif (this._isClosed) {\n\t\t\tthrow new Error('Cannot update store on a closed room')\n\t\t}\n\t\tconst context = new StoreUpdateContext<R>(\n\t\t\tObject.fromEntries(this.getSnapshot().documents.map((d) => [d.state.id, d.state]))\n\t\t)\n\t\ttry {\n\t\t\tawait updater(context)\n\t\t} finally {\n\t\t\tcontext.close()\n\t\t}\n\n\t\tconst diff = context.toDiff()\n\t\tif (Object.keys(diff).length === 0) {\n\t\t\treturn\n\t\t}\n\n\t\tthis.handlePushRequest(null, { type: 'push', diff, clientClock: 0 })\n\t}\n}\n\n/**\n * @public\n */\nexport interface RoomStoreMethods<R extends UnknownRecord = UnknownRecord> {\n\tput(record: R): void\n\tdelete(recordOrId: R | string): void\n\tget(id: string): R | null\n\tgetAll(): R[]\n}\n\nclass StoreUpdateContext<R extends UnknownRecord> implements RoomStoreMethods<R> {\n\tconstructor(private readonly snapshot: Record<string, UnknownRecord>) {}\n\tprivate readonly updates = {\n\t\tputs: {} as Record<string, UnknownRecord>,\n\t\tdeletes: new Set<string>(),\n\t}\n\tput(record: R): void {\n\t\tif (this._isClosed) throw new Error('StoreUpdateContext is closed')\n\t\tif (record.id in this.snapshot && isEqual(this.snapshot[record.id], record)) {\n\t\t\tdelete this.updates.puts[record.id]\n\t\t} else {\n\t\t\tthis.updates.puts[record.id] = structuredClone(record)\n\t\t}\n\t\tthis.updates.deletes.delete(record.id)\n\t}\n\tdelete(recordOrId: R | string): void {\n\t\tif (this._isClosed) throw new Error('StoreUpdateContext is closed')\n\t\tconst id = typeof recordOrId === 'string' ? recordOrId : recordOrId.id\n\t\tdelete this.updates.puts[id]\n\t\tif (this.snapshot[id]) {\n\t\t\tthis.updates.deletes.add(id)\n\t\t}\n\t}\n\tget(id: string): R | null {\n\t\tif (this._isClosed) throw new Error('StoreUpdateContext is closed')\n\t\tif (hasOwnProperty(this.updates.puts, id)) {\n\t\t\treturn structuredClone(this.updates.puts[id]) as R\n\t\t}\n\t\tif (this.updates.deletes.has(id)) {\n\t\t\treturn null\n\t\t}\n\t\treturn structuredClone(this.snapshot[id] ?? null) as R\n\t}\n\n\tgetAll(): R[] {\n\t\tif (this._isClosed) throw new Error('StoreUpdateContext is closed')\n\t\tconst result = Object.values(this.updates.puts)\n\t\tfor (const [id, record] of Object.entries(this.snapshot)) {\n\t\t\tif (!this.updates.deletes.has(id) && !hasOwnProperty(this.updates.puts, id)) {\n\t\t\t\tresult.push(record)\n\t\t\t}\n\t\t}\n\t\treturn structuredClone(result) as R[]\n\t}\n\n\ttoDiff(): NetworkDiff<any> {\n\t\tconst diff: NetworkDiff<R> = {}\n\t\tfor (const [id, record] of Object.entries(this.updates.puts)) {\n\t\t\tdiff[id] = [RecordOpType.Put, record as R]\n\t\t}\n\t\tfor (const id of this.updates.deletes) {\n\t\t\tdiff[id] = [RecordOpType.Remove]\n\t\t}\n\t\treturn diff\n\t}\n\n\tprivate _isClosed = false\n\tclose() {\n\t\tthis._isClosed = true\n\t}\n}\n"], "mappings": "AAAA,SAAe,MAAM,mBAAmB;AACxC;AAAA,EAEC;A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