import { BasicIndex, IR, createCollection, createLiveQueryCollection, createTransaction, eq, whenSyncAccepted, } from '@tanstack/db' import { BrowserCollectionCoordinator } from '../src/browser-coordinator' import { createBrowserWASQLitePersistence } from '../src/browser-persistence' import { persistedCollectionOptions } from '../../db-sqlite-persistence-core/src/persisted' import { followerReacquisitionError } from '../../db-sqlite-persistence-core/tests/follower-rotation-oracle' import type { LoadSubsetOptions, SyncConfig } from '@tanstack/db' import type { BrowserWASQLiteDatabase } from '../src/browser-persistence' import type { FollowerErrorRepresentation, FollowerPublicApplication, FollowerPublication, FollowerSourceRevision, ReacquisitionObservation, VersionedRow, } from '../../db-sqlite-persistence-core/tests/follower-rotation-oracle' import type { HydrationPersistenceAdapter, TxCommitted, } from '../../db-sqlite-persistence-core/src/persisted' function revisionToken(metadata: unknown): string | undefined { if (typeof metadata !== `object` || metadata === null) return undefined const token = (metadata as { followerRevision?: unknown }).followerRevision return typeof token === `string` ? token : undefined } function deferred() { let resolve!: () => void let reject!: (error: unknown) => void const promise = new Promise((done, fail) => { resolve = done reject = fail }) return { promise, resolve, reject } } // This receiving driver controls only source replies and rotation return. Real // SQLite creates the new generation; another normal Collection claims its head // and elects before the follower binds it. Every notice is emitted by the real // Browser coordinator after the owner's actual durable source commit. export function createFollowerRotationTab(options: { database: BrowserWASQLiteDatabase dbName: string version: number holdReplies?: boolean holdRotation?: boolean }) { const execute = options.database.execute.bind(options.database) let ownerCommitGate: ReturnType | undefined let ownerCommitHeld = false let durableReadStarted = false options.database.execute = (sql, bindings) => { const gate = ownerCommitGate if (sql !== `COMMIT` || !gate || ownerCommitHeld) return execute(sql, bindings) ownerCommitHeld = true return gate.promise.then(() => { ownerCommitGate = undefined ownerCommitHeld = false return execute(sql, bindings) }) } const coordinator = new BrowserCollectionCoordinator({ dbName: options.dbName, }) const persistence = createBrowserWASQLitePersistence({ database: options.database, coordinator, }) const resolved = persistence.resolvePersistenceForCollection!({ collectionId: `rotated-follower`, mode: `sync-present`, }) const adapter = resolved.adapter const reads: Array<{ storageId: string revisions: Array }> = [] const recordRead = (selected: HydrationPersistenceAdapter) => async (...args: Parameters) => { const rows = await selected.loadSubset(...args) reads.push({ storageId: args[0].kind === `managed` ? args[0].storageCollectionId : args[0].collectionId, revisions: rows.map((row) => revisionToken(row.metadata)), }) return rows } const read = adapter.loadSubset.bind(adapter) adapter.loadSubset = recordRead({ ...adapter, loadSubset: read }) const hydrationScope = adapter.runInHydrationScope?.bind(adapter) if (hydrationScope) adapter.runInHydrationScope = (task) => hydrationScope((scoped) => task({ ...scoped, loadSubset: recordRead(scoped) }), ) let persistedScanGate: ReturnType | undefined let persistedScanHeld = false const scanRows = adapter.scanRows?.bind(adapter) if (scanRows) adapter.scanRows = async (...args) => { const rows = await scanRows(...args) if (persistedScanGate) { persistedScanHeld = true await persistedScanGate.promise } return rows } const rotation = deferred() let rotationReached = false let sourceRestartGate: ReturnType | undefined let sourceRestartEntered = false let rotatedId: string | undefined let freshIndexGate: ReturnType | undefined let freshIndexReached = false const ensureIndex = adapter.ensureIndex.bind(adapter) adapter.ensureIndex = async (target, ...args) => { if ( target.kind === `managed` && target.storageCollectionId === rotatedId && freshIndexGate ) { freshIndexReached = true await freshIndexGate.promise } return ensureIndex(target, ...args) } const rotate = adapter.rotateCacheGeneration!.bind(adapter) adapter.rotateCacheGeneration = async (...args) => { const claim = await rotate(...args) rotatedId = claim.storageCollectionId rotationReached = true if (options.holdRotation) await rotation.promise return claim } let storageId: string | undefined let claimId: string | undefined const setAdapter = coordinator.setAdapterForCollection.bind(coordinator) coordinator.setAdapterForCollection = (id, selected, claim) => { if (claim) { storageId = id claimId = claim } setAdapter(id, selected, claim) } // Record the error the real coordinator delivers, then forward it unchanged. // Remote Browser RPC serializes text and reconstructs a plain Error; an error // name that a custom local coordinator preserves is not a native premise. const remoteRejections: Array<{ group: string | undefined name: string | undefined message: string | undefined }> = [] const remoteFulfillments: Array = [] const remoteDeliveries: Array<{ storageId: string group: string | undefined outcome: `fulfilled` | `rejected` }> = [] // Native RPC receipt and delivery of its result to the persisted wrapper are // separate receiving facts. A legal host delay can separate those boundaries. const remoteRequests: Array<{ storageId: string group: string | undefined }> = [] const remoteReceipts: Array<{ storageId: string group: string | undefined outcome: `fulfilled` | `rejected` }> = [] const remoteResultGates = new Map>() const ensure = coordinator.requestEnsureRemoteSubset.bind(coordinator) coordinator.requestEnsureRemoteSubset = async (id, subset) => { const where = subset.where as IR.Func | undefined const group = (where?.args[1] as IR.Value | undefined)?.value as string | undefined remoteRequests.push({ storageId: id, group }) let failure: { error: unknown } | undefined try { await ensure(id, subset) } catch (error) { failure = { error } } remoteReceipts.push({ storageId: id, group, outcome: failure ? `rejected` : `fulfilled`, }) if (group) await remoteResultGates.get(group)?.promise remoteDeliveries.push({ storageId: id, group, outcome: failure ? `rejected` : `fulfilled`, }) if (failure) { const { error } = failure remoteRejections.push({ group, name: error instanceof Error ? error.name : undefined, message: error instanceof Error ? error.message : undefined, }) throw error } remoteFulfillments.push(group) } const gates = { a: deferred(), b: deferred() } const loaded: Array = [] const notices: Array = [] const noticeReceipts: Array<{ storageId: string txId: string revisions: Array rowVersion: number deletedKeys: Array changedKeys: Array }> = [] const sourceRevisions: Array = [] const applications: Array = [] const publications: Array = [] const publicRevisions: Record = {} let transaction: FollowerPublicApplication | undefined let publishing: FollowerPublicApplication | undefined let newLoad: ReacquisitionObservation[`newLoad`] = `pending` let newLoadError: string | undefined const rejectNewLoad = (error: unknown) => { newLoadError = error instanceof Error ? error.message : String(error) newLoad = `rejected` } let rowAtNewLoadSettlement: number | undefined const releaseApplication = deferred() let applicationHold: Promise | undefined let params: Parameters[`sync`]>[0] | undefined const requireSource = () => { if (!params) throw new Error(`The source sync callback has not started`) return params } const configured = persistedCollectionOptions({ id: `rotated-follower`, syncMode: `on-demand`, getKey: (row) => row.id, persistence: resolved, sync: { sync: (controls) => { params = controls controls.markReady() return { restartAfterScopedRecovery: (cacheRotated) => sourceRestartGate ? cacheRotated.then(() => { sourceRestartEntered = true return sourceRestartGate?.promise }) : cacheRotated, loadSubset: async (subset) => { const where = subset.where as IR.Func const group = (where.args[1] as IR.Value).value as `a` | `b` | `c` // A finite source prefix turns a baseline refetch loop into a row // comparison instead of starving the host event loop. if (delivered.has(group)) return await commit(group, options.version) loaded.push(group) if (options.holdReplies && group !== `c`) await gates[group].promise }, } }, }, }) // The observer decorates the receiving Collection boundary, not the provider. // Metadata carries opaque source-authored revision identity through cloned // SQLite/native messages. Only the original receipt's applied settlement // certifies visibility; recording a metadata write does not certify it. // A synchronous receipt attributes its subscriber callbacks directly // to the commit. An optimistic transaction can defer application across // several accepted commits; that lane checks their actual receipts. const sync = configured.sync.sync configured.sync.sync = (controls) => sync({ ...controls, begin: (beginOptions) => { controls.begin(beginOptions) transaction = { id: applications.length, storageId, keys: [], revisions: {}, outcome: `pending`, } }, write: (message) => { controls.write(message) const key = `key` in message ? message.key : message.value.id transaction?.keys.push(key) }, truncate: (truncateOptions) => { controls.truncate(truncateOptions) if (transaction) transaction.truncate = true }, commit: (signal) => { if (!transaction) throw new Error(`Instrument: commit without observed begin`) const application = transaction transaction = undefined for (const key of application.keys) application.revisions[key] = revisionToken( controls.metadata?.row.get(key), ) applications.push(application) publishing = application let receipt try { receipt = controls.commit(signal) } finally { publishing = undefined } application.receiptKind = receipt === true ? `true` : `promise` const applied = () => { application.outcome = `visible` updatePublicRevisions(application) application.observation = observe() capture(`applied`, application) } if (receipt === true) applied() else void receipt.then(applied, () => { application.outcome = `rejected` }) return receipt }, }) const collection = createCollection(configured) function observe(): ReacquisitionObservation { return { rows: { a: collection.get(`a-row`)?.v, b: collection.get(`b-row`)?.v, c: collection.get(`c-row`)?.v, }, newLoad, status: collection.status === `crashed` ? `crashed` : collection.health.error ? `stopped` : collection.health.failureReason ? `retrying` : `healthy`, } } function updatePublicRevisions(application: FollowerPublicApplication) { if (application.truncate) for (const key of Object.keys(publicRevisions)) delete publicRevisions[key] Object.assign(publicRevisions, application.revisions) } const subscriberRows = new Map() function capture( kind: FollowerPublication[`kind`], application?: FollowerPublicApplication, ) { publications.push({ kind, applicationId: application?.id, storageId, observation: observe(), subscriberRows: { a: subscriberRows.get(`a-row`), b: subscriberRows.get(`b-row`), c: subscriberRows.get(`c-row`), }, revisions: { ...publicRevisions }, deliveries: remoteDeliveries.map((delivery) => ({ ...delivery })), }) } const changes = collection.subscribeChanges( (batch) => { for (const change of batch) { if (change.type === `delete`) subscriberRows.delete(change.key) else subscriberRows.set(change.key, change.value.v) } if (publishing) updatePublicRevisions(publishing) capture(`change`, publishing) }, { includeInitialState: false, deferAcquisition: true }, ) const health = collection.on(`health:change`, () => capture(`health`)) const delivered = new Set() async function deleteRow(group: `a` | `b`) { const source = requireSource() source.begin() source.write({ type: `delete`, key: `${group}-row` }) source.metadata!.row.delete(`${group}-row`) delivered.delete(group) await whenSyncAccepted(source.commit()) } async function commit(group: `a` | `b` | `c`, version: number) { const source = requireSource() const token = crypto.randomUUID() const revision = { token, storageId, group, version } sourceRevisions.push(revision) source.begin() source.write({ type: delivered.has(group) ? `update` : `insert`, value: { id: `${group}-row`, group, v: version }, }) source.metadata!.row.set(`${group}-row`, { followerRevision: token }) delivered.add(group) await whenSyncAccepted(source.commit()) return revision } const subscribe = coordinator.subscribe.bind(coordinator) let heldCrossingNotices: Array<() => void> | undefined let heldGapNotices: Array<() => void> | undefined let journalReplyGate: ReturnType | undefined const pulledJournal: Array<{ count?: number; rowVersion: number }> = [] const pullSince = coordinator.pullSince.bind(coordinator) coordinator.pullSince = async (...args) => { const response = await pullSince(...args) if (response.ok && !response.requiresFullReload) pulledJournal.push({ count: response.deltas?.length, rowVersion: response.latestRowVersion, }) if (journalReplyGate) await journalReplyGate.promise return response } coordinator.subscribe = (id, callback) => subscribe(id, (message) => { if ((message.payload as { type?: string }).type === `tx:committed`) { notices.push(id) const notice = message.payload as TxCommitted noticeReceipts.push({ storageId: id, txId: notice.txId, rowVersion: notice.latestRowVersion, deletedKeys: notice.requiresFullReload ? [] : notice.deletedKeys, changedKeys: notice.requiresFullReload ? [] : notice.changedRows.map(({ key }) => key), revisions: notice.requiresFullReload ? [] : (notice.rowMetadataMutations ?? []).map((mutation) => mutation.type === `set` ? revisionToken(mutation.value) : undefined, ), }) if (heldGapNotices) { heldGapNotices.push(() => callback(message)) return } if ( heldCrossingNotices && !notice.requiresFullReload && notice.changedRows.some(({ key }) => key === `c-row`) ) { heldCrossingNotices.push(() => callback(message)) return } } callback(message) }) const demand = ( group: `a` | `b` | `c`, ): LoadSubsetOptions & { where: IR.Func } => ({ where: new IR.Func(`eq`, [new IR.PropRef([`group`]), new IR.Value(group)]), }) const demands = { a: demand(`a`), b: demand(`b`), c: demand(`c`) } const aborts = { a: new AbortController(), b: new AbortController() } demands.a.signal = aborts.a.signal demands.b.signal = aborts.b.signal let publicDemands: ReturnType | undefined let cleanupCompiledDemand: (() => Promise) | undefined const load = (group: `a` | `b` | `c`): Promise => { if (!publicDemands) return Promise.resolve(collection._sync.loadSubset(demands[group])).then( () => undefined, ) const result = deferred() const callback = { delivered: false } publicDemands.requestSnapshot({ where: demands[group].where, signal: demands[group].signal, onLoadSubsetResult: (value) => { callback.delivered = true void Promise.resolve(value).then(result.resolve, result.reject) }, }) if (!callback.delivered) throw new Error( `Public subscription reported no load result for ${group}`, ) return result.promise } let originalLoad: | { outcome: `pending` } | { outcome: `fulfilled`; row: number | undefined } | { outcome: `rejected`; message: string } | undefined return { start: () => collection.startSyncImmediate(), subscribeToDemands: () => { publicDemands = collection.subscribeChanges(() => {}, { includeInitialState: false, }) }, load, beginOriginalLoad: () => { originalLoad = { outcome: `pending` } void load(`a`).then( () => { originalLoad = { outcome: `fulfilled`, row: collection.base.get(`a-row`)?.v, } }, (error: unknown) => { originalLoad = { outcome: `rejected`, message: error instanceof Error ? error.message : String(error), } }, ) }, holdFreshIndex: () => { freshIndexGate = deferred() collection.createIndex((row) => row.group, { indexType: BasicIndex }) }, releaseFreshIndex: () => freshIndexGate?.resolve(), holdPersistedScan: () => { persistedScanGate = deferred() }, releasePersistedScan: () => persistedScanGate?.resolve(), scanPersistedRows: async () => { const scan = params?.metadata?.persistence?.scanPersistedRows if (!scan) throw new Error(`Persisted scan requires a managed Collection`) await scan() }, beginNewLoad: (compiled = false) => { if (compiled) { const live = createLiveQueryCollection((query) => query .from({ row: collection }) .where(({ row }) => eq(row.group, `c`)) .select(({ row }) => ({ id: row.id, v: row.v })), ) cleanupCompiledDemand = () => live.cleanup() void live.preload().then(() => { rowAtNewLoadSettlement = live.toArray.find( ({ id }) => id === `c-row`, )?.v newLoad = `fulfilled` }, rejectNewLoad) return } void load(`c`).then(() => { rowAtNewLoadSettlement = collection.base.get(`c-row`)?.v newLoad = `fulfilled` }, rejectNewLoad) }, holdApplication: () => { const transaction = createTransaction({ mutationFn: () => releaseApplication.promise, }) transaction.mutate(() => collection.insert({ id: `optimistic-gate`, group: `local`, v: 0 }), ) applicationHold = transaction.when(`settled`) void applicationHold.catch(() => undefined) }, holdCrossingNotice: () => { heldCrossingNotices = [] }, releaseCrossingNotice: () => { const notices = heldCrossingNotices heldCrossingNotices = undefined for (const deliver of notices ?? []) deliver() }, holdGapNotices: () => { heldGapNotices = [] }, deliverLastGapNotice: () => { const deliver = heldGapNotices?.at(-1) heldGapNotices = undefined if (!deliver) throw new Error(`Missing final notice after journal gap`) deliver() }, deliverFirstGapNotice: () => { const deliver = heldGapNotices?.shift() if (!deliver) throw new Error(`Missing first notice after journal gap`) deliver() }, holdJournalReply: () => { journalReplyGate = deferred() }, releaseJournalReply: () => { journalReplyGate?.resolve() journalReplyGate = undefined }, releaseApplication: async () => { releaseApplication.resolve() await applicationHold }, retire: (group: `a` | `b`, kind: `release` | `abort`) => { if (kind === `abort`) aborts[group].abort() else if (publicDemands) publicDemands.releaseSnapshot(demands[group].where) else collection._sync.unloadSubset(demands[group]) }, rotate: () => requireSource().metadata!.persistence!.startScopedRecovery!(), holdOwnerCommit: () => { ownerCommitGate = deferred() }, releaseOwnerCommit: () => ownerCommitGate?.resolve(), releaseRotation: () => rotation.resolve(), holdSourceRestart: () => { sourceRestartGate = deferred() }, releaseSourceRestart: () => sourceRestartGate?.resolve(), holdRemoteResult: (group: `a` | `b` | `c`) => { remoteResultGates.set(group, deferred()) }, releaseRemoteResult: (group: `a` | `b` | `c`) => remoteResultGates.get(group)?.resolve(), release: (group: `a` | `b`) => gates[group].resolve(), reject: ( group: `a` | `b`, representation: FollowerErrorRepresentation, message?: string, ) => gates[group].reject( message === undefined ? followerReacquisitionError(representation) : new Error(message), ), commit, deleteRow, state: () => ({ storageId, ownerCommitHeld, durableReadStarted, sourceStarted: params !== undefined, failureMessages: collection.health.failureReason?.errors.map(({ message }) => message) ?? [], statusError: collection.health.error?.message, rowAtNewLoadSettlement, newLoad, newLoadError, rotatedId, rotationReached, persistedScanHeld, heldGapNoticeCount: heldGapNotices?.length ?? 0, pulledJournal: [...pulledJournal], sourceRestartEntered, freshIndexReached, originalLoad, loaded: [...loaded], notices: [...notices], remoteRequests: [...remoteRequests], remoteReceipts: [...remoteReceipts], remoteRejections: [...remoteRejections], remoteFulfillments: [...remoteFulfillments], remoteDeliveries: remoteDeliveries.map((delivery) => ({ ...delivery })), sourceRevisions: sourceRevisions.map((revision) => ({ ...revision })), reads: reads.map((record) => ({ ...record, revisions: [...record.revisions], })), noticeReceipts: noticeReceipts.map((record) => ({ ...record, revisions: [...record.revisions], })), applications: applications.map((application) => ({ ...application, keys: [...application.keys], revisions: { ...application.revisions }, })), publications: [...publications], leader: storageId ? coordinator.isLeader(storageId) : false, }), observe, durable: async () => { if (!storageId || !claimId) throw new Error(`Missing claim`) durableReadStarted = true return adapter.loadSubset( { kind: `managed`, storageCollectionId: storageId, claimId }, {}, ) }, cleanup: async () => { changes.unsubscribe() publicDemands?.unsubscribe() health() rotation.resolve() sourceRestartGate?.resolve() freshIndexGate?.resolve() persistedScanGate?.resolve() ownerCommitGate?.resolve() journalReplyGate?.resolve() releaseApplication.resolve() for (const gate of remoteResultGates.values()) gate.resolve() gates.a.resolve() gates.b.resolve() // These resources have independent owners. A failed Collection teardown // must not leave its coordinator or SQLite handle open, and a later // finalizer must not replace the first failure. const failures: Array = [] try { await applicationHold } catch (error) { failures.push(error) } try { await cleanupCompiledDemand?.() } catch (error) { failures.push(error) } try { await collection.cleanup() } catch (error) { failures.push(error) } try { coordinator.dispose() } catch (error) { failures.push(error) } try { await options.database.close?.() } catch (error) { failures.push(error) } if (failures.length === 1) throw failures[0] if (failures.length > 1) throw new AggregateError(failures, `Follower tab cleanup failed`) }, } }