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C,EAAA;AACA,EAAA;AACD;AAEA;AACC,EAAA;AACD;AAEA;AACK,EAAA;AACH,IAAA;AACD,EAAA;AACA,EAAA;AACD;AD/aO;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/kora/kora/packages/store/dist/chunk-QKCC6JSA.cjs","sourcesContent":[null,"/**\n * Multi-tab SQLite storage coordination via `navigator.locks` and `BroadcastChannel`.\n *\n * One tab holds the exclusive `kora-leader-${dbName}` lock and owns the SQLite\n * worker. Other tabs send worker RPC over a named broadcast channel. In browsers\n * the leader's WORKER answers that channel itself ({@link startWorkerRpcRelay}),\n * so a hung leader main thread never blocks other tabs, and it pushes heartbeats\n * (also from inside long statements) that followers use to detect a hung or\n * frozen leader (NEW-STORE-9).\n */\n\nimport {\n\tgatedLeaderIdentityLockPrefix,\n\tgatedLeaderLockName,\n\tleaderLockName,\n\tstorageChannelName,\n} from '../adapters/opfs-names'\nimport type {\n\tWorkerBridge,\n\tWorkerRequest,\n\tWorkerResponse,\n\tWorkerSendOptions,\n} from '../adapters/sqlite-wasm-channel'\nimport {\n\tBridgeTerminatedError,\n\tLeaderUnresponsiveError,\n\tNoLeaderError,\n\tRequestAbortedError,\n\tWorkerTimeoutError,\n} from '../errors'\n\nconst RPC_REQUEST = 'kora-worker-request'\nconst RPC_RESPONSE = 'kora-worker-response'\nconst CLIENT_LEAVE = 'kora-client-leave'\nconst LEADER_PING = 'kora-leader-ping'\nconst LEADER_PONG = 'kora-leader-pong'\nconst LEADER_HEARTBEAT = 'kora-leader-heartbeat'\n/**\n * A follower asks the leader TAB (its main thread, which owns the IndexedDB snapshot\n * scheduler) for a strict snapshot. Deliberately not an {@link RPC_REQUEST}: the leader's\n * worker relay forwards those to SQLite, and a snapshot is not a database statement. The\n * answer travels as an ordinary {@link RPC_RESPONSE}, so the follower's pending-request,\n * heartbeat and watchdog machinery applies unchanged.\n */\nconst SNAPSHOT_BARRIER_REQUEST = 'kora-snapshot-barrier-request'\n\n/** Default interval between leader heartbeats and follower watchdog ticks. */\nexport const DEFAULT_HEARTBEAT_MS = 1000\n/** Missed heartbeat intervals after which a follower gives up on a leader it heard. */\nconst MISSED_BEATS_UNRESPONSIVE = 3\n/** Silent intervals after which a follower that never heard a leader gives up. */\nconst MISSED_BEATS_ABSENT = 2\n/** Default idle budget for a client that owns an open transaction span. */\nconst DEFAULT_TRANSACTION_IDLE_TIMEOUT_MS = 10_000\n/** Completed follower responses remembered for de-duplicating retried requests. */\nconst DEDUP_CAPACITY = 512\n/**\n * Response code of a relay that refused a request bound to another relay's epoch:\n * the request belongs to a transaction whose BEGIN a previous leader worker\n * answered, so running it here would autocommit part of that transaction.\n */\nconst LEADER_CHANGED = 'LEADER_CHANGED'\n/** Span binding for a BEGIN answered by a relay that reports no epoch (older build). */\nconst LEGACY_RELAY_EPOCH = 'legacy-relay'\n/** Code of {@link BridgeTerminatedError}, carried in responses across the channel. */\nconst BRIDGE_TERMINATED = 'BRIDGE_TERMINATED'\n\ninterface RpcRequestMessage {\n\ttype: typeof RPC_REQUEST\n\trequestId: string\n\tclientId: string\n\trequest: WorkerRequest\n\t/**\n\t * Epoch of the relay that answered this request's transaction BEGIN. A relay\n\t * with another epoch (a different leader worker) refuses the request unrun.\n\t */\n\tepoch?: string\n}\n\ninterface RpcResponseMessage {\n\ttype: typeof RPC_RESPONSE\n\trequestId: string\n\tresponse: WorkerResponse\n\t/** Epoch of the answering relay (one per leader worker). */\n\tepoch?: string\n}\n\ninterface ClientLeaveMessage {\n\ttype: typeof CLIENT_LEAVE\n\tclientId: string\n}\n\ninterface HeartbeatMessage {\n\ttype: typeof LEADER_HEARTBEAT\n\tepoch: string\n\tsource: 'main' | 'worker'\n\t/**\n\t * The leader tab's version gate identity (`{ build, format, openSeq, tabId }`). A\n\t * heartbeat without one comes from a leader running a pre-gate build.\n\t */\n\tidentity?: unknown\n}\n\ninterface SnapshotBarrierRequestMessage {\n\ttype: typeof SNAPSHOT_BARRIER_REQUEST\n\trequestId: string\n}\n\ntype ChannelMessage =\n\t| SnapshotBarrierRequestMessage\n\t| RpcRequestMessage\n\t| RpcResponseMessage\n\t| ClientLeaveMessage\n\t| HeartbeatMessage\n\t| { type: typeof LEADER_PING }\n\t| { type: typeof LEADER_PONG }\n\ninterface ReclaimingWorkerBridge extends WorkerBridge {\n\treclaimClient(clientId: string, reason: string): void\n}\n\nexport type TabStorageRole = 'leader' | 'follower'\n\nexport interface AcquireTabStorageOptions {\n\t/**\n\t * Invoked when a follower is promoted to leader because the previous leader\n\t * released the lock (its tab closed, crashed, or suspended itself on freeze).\n\t * The adapter uses this to rebuild its bridge as a leader. Never fires for a\n\t * tab that started as leader.\n\t */\n\tonPromote?: () => void\n\t/**\n\t * Hold the gated-leader marker while this tab holds the leader lock (taken right after\n\t * the grant, released with the leader lock), so other tabs' version gates can tell this\n\t * leader from one running a pre-gate build.\n\t */\n\tmarkGatedLeader?: boolean\n\t/**\n\t * The leader's version gate identity, read when the leader lock is granted: the marker is\n\t * also held under a name carrying it ({@link gatedLeaderIdentityLockPrefix}).\n\t */\n\tgatedLeaderIdentity?: () => unknown\n}\n\n/**\n * Take the gated-leader marker of `dbName`; the returned function releases it. A no-op\n * function when the marker is not wanted.\n */\nfunction holdGatedLeaderMarker(\n\tdbName: string,\n\toptions: AcquireTabStorageOptions | undefined,\n): () => void {\n\tif (!options?.markGatedLeader) return () => {}\n\tlet release: () => void = () => {}\n\tconst held = new Promise<void>((resolve) => {\n\t\trelease = resolve\n\t})\n\tvoid navigator.locks\n\t\t.request(gatedLeaderLockName(dbName), { mode: 'exclusive' }, () => held)\n\t\t.catch(() => undefined)\n\tconst identity = options.gatedLeaderIdentity?.()\n\tif (identity !== undefined && identity !== null) {\n\t\tvoid navigator.locks\n\t\t\t.request(\n\t\t\t\t`${gatedLeaderIdentityLockPrefix(dbName)}${JSON.stringify(identity)}`,\n\t\t\t\t{ mode: 'exclusive' },\n\t\t\t\t() => held,\n\t\t\t)\n\t\t\t.catch(() => undefined)\n\t}\n\treturn release\n}\n\nexport interface TabStorageSession {\n\trole: TabStorageRole\n\tchannelName: string\n\t/** Leader only: release the navigator lock when closing the database. */\n\treleaseLock?: () => Promise<void>\n\t/**\n\t * Follower only: cancels the queued lock request (or, once promoted, releases\n\t * the lock this tab won). Present so callers can tear the session down.\n\t */\n\tcancelPromotionWatch?: () => void\n}\n\n/**\n * Returns whether multi-tab coordination APIs exist in this runtime.\n */\nexport function isMultiTabStorageSupported(): boolean {\n\treturn (\n\t\ttypeof globalThis !== 'undefined' &&\n\t\ttypeof BroadcastChannel !== 'undefined' &&\n\t\ttypeof navigator !== 'undefined' &&\n\t\ttypeof navigator.locks?.request === 'function'\n\t)\n}\n\n/**\n * Resolve leader vs follower for a database name.\n * Without lock APIs, every instance is treated as leader (single-tab / Node).\n *\n * A follower additionally queues a blocking request for the same lock. When the\n * current leader releases it (its tab closed, crashed, or suspended on freeze),\n * the browser grants the lock to this follower and\n * {@link AcquireTabStorageOptions.onPromote} fires so the adapter can rebuild\n * itself as the new leader. Kora never uses the Web Locks `steal` option: a\n * frozen leader's worker would still hold the OPFS file handles.\n */\nexport async function acquireTabStorageSession(\n\tdbName: string,\n\toptions?: AcquireTabStorageOptions,\n): Promise<TabStorageSession> {\n\tconst channelName = storageChannelName(dbName)\n\tconst lockName = leaderLockName(dbName)\n\n\tif (!isMultiTabStorageSupported()) {\n\t\treturn { role: 'leader', channelName }\n\t}\n\n\treturn new Promise<TabStorageSession>((resolve, reject) => {\n\t\tlet releaseHeld: (() => void) | undefined\n\n\t\tconst request = navigator.locks.request(\n\t\t\tlockName,\n\t\t\t{ mode: 'exclusive', ifAvailable: true },\n\t\t\t(lock) => {\n\t\t\t\tif (lock === null) {\n\t\t\t\t\tresolve(startFollowerSession(dbName, channelName, lockName, options))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tconst releaseMarker = holdGatedLeaderMarker(dbName, options)\n\t\t\t\tresolve({\n\t\t\t\t\trole: 'leader',\n\t\t\t\t\tchannelName,\n\t\t\t\t\t// Resolves once the lock manager released the lock, so a caller that releases\n\t\t\t\t\t// its version gate tab lock next does so after the leader lock.\n\t\t\t\t\treleaseLock: async () => {\n\t\t\t\t\t\treleaseHeld?.()\n\t\t\t\t\t\treleaseMarker()\n\t\t\t\t\t\tawait request.catch(() => undefined)\n\t\t\t\t\t},\n\t\t\t\t})\n\n\t\t\t\treturn new Promise<void>((release) => {\n\t\t\t\t\treleaseHeld = release\n\t\t\t\t})\n\t\t\t},\n\t\t)\n\t\t// The request can reject before its callback runs (a detached document's\n\t\t// SecurityError, for instance): fail the open instead of leaving it pending forever.\n\t\t// After the callback resolved the session this is a no-op.\n\t\trequest.catch(reject)\n\t})\n}\n\n/**\n * Builds a follower session and starts watching for promotion. The follower holds\n * a queued lock request; when it is finally granted (old leader gone), it becomes\n * the leader for the rest of its lifetime and notifies via `onPromote`.\n */\nfunction startFollowerSession(\n\tdbName: string,\n\tchannelName: string,\n\tlockName: string,\n\toptions?: AcquireTabStorageOptions,\n): TabStorageSession {\n\tlet promoted = false\n\tlet releasePromotedLock: (() => void) | undefined\n\tlet releaseMarker: () => void = () => {}\n\tconst abort = new AbortController()\n\n\tvoid navigator.locks\n\t\t.request(lockName, { mode: 'exclusive', signal: abort.signal }, () => {\n\t\t\t// Reaching here means the previous leader released the lock and this tab\n\t\t\t// won it. Hold it (never-resolving promise) so this tab is now the leader.\n\t\t\tpromoted = true\n\t\t\treleaseMarker = holdGatedLeaderMarker(dbName, options)\n\t\t\toptions?.onPromote?.()\n\t\t\treturn new Promise<void>((release) => {\n\t\t\t\treleasePromotedLock = release\n\t\t\t})\n\t\t})\n\t\t.catch(() => {\n\t\t\t// AbortError when the tab closes before promotion. Nothing to do.\n\t\t})\n\n\treturn {\n\t\trole: 'follower',\n\t\tchannelName,\n\t\tcancelPromotionWatch: () => {\n\t\t\tif (promoted) {\n\t\t\t\treleasePromotedLock?.()\n\t\t\t\treleaseMarker()\n\t\t\t} else {\n\t\t\t\tabort.abort()\n\t\t\t}\n\t\t},\n\t}\n}\n\n/**\n * Answers follower RPC with a bounded response cache keyed by request id, so a\n * follower that retries a request it lost track of (leader looked unresponsive,\n * caller aborted) gets the original response instead of a second application.\n */\nfunction createRequestDeduper(): {\n\trun(requestId: string, start: () => Promise<WorkerResponse>): Promise<WorkerResponse> | null\n} {\n\tconst inflight = new Map<string, Promise<WorkerResponse>>()\n\tconst completed = new Map<string, WorkerResponse>()\n\treturn {\n\t\trun(requestId, start) {\n\t\t\tconst done = completed.get(requestId)\n\t\t\tif (done) return Promise.resolve(done)\n\t\t\t// Already running: the original response is broadcast when it lands.\n\t\t\tif (inflight.has(requestId)) return null\n\t\t\tconst promise = start().then((response) => {\n\t\t\t\tinflight.delete(requestId)\n\t\t\t\tcompleted.set(requestId, response)\n\t\t\t\tif (completed.size > DEDUP_CAPACITY) {\n\t\t\t\t\tconst oldest = completed.keys().next().value\n\t\t\t\t\tif (oldest !== undefined) completed.delete(oldest)\n\t\t\t\t}\n\t\t\t\treturn response\n\t\t\t})\n\t\t\tinflight.set(requestId, promise)\n\t\t\treturn promise\n\t\t},\n\t}\n}\n\n/** Options for the leader-side relays. */\nexport interface LeaderRelayOptions {\n\t/** Heartbeat interval; 0 disables heartbeats. */\n\theartbeatMs?: number\n\t/** The leader tab's version gate identity, carried by every heartbeat. */\n\tidentity?: unknown\n}\n\n/** Handle returned by {@link startWorkerRpcRelay}. */\nexport interface WorkerRpcRelay {\n\t/** Push a heartbeat now (called from inside long statements). */\n\tbeat(): void\n\tstop(): void\n}\n\nfunction serveChannel(\n\tchannel: BroadcastChannel,\n\tbridge: WorkerBridge,\n\tsource: 'main' | 'worker',\n\theartbeatMs: number,\n\tidentity?: unknown,\n): WorkerRpcRelay {\n\tconst epoch = createClientId()\n\tconst dedup = createRequestDeduper()\n\t// Requests still running when the relay stops settle afterwards: posting their answer\n\t// (or a heartbeat from a long statement) on the closed channel would throw.\n\tlet stopped = false\n\tconst beat = (): void => {\n\t\tif (stopped) return\n\t\tconst message: HeartbeatMessage = {\n\t\t\ttype: LEADER_HEARTBEAT,\n\t\t\tepoch,\n\t\t\tsource,\n\t\t\t...(identity !== undefined ? { identity } : {}),\n\t\t}\n\t\tchannel.postMessage(message)\n\t}\n\tconst respond = (requestId: string, response: WorkerResponse): void => {\n\t\tif (stopped) return\n\t\tconst msg: RpcResponseMessage = { type: RPC_RESPONSE, requestId, response, epoch }\n\t\tchannel.postMessage(msg)\n\t}\n\n\tconst onMessage = (event: MessageEvent<ChannelMessage>): void => {\n\t\tconst data = event.data\n\t\t// Answer liveness probes immediately, without touching the database.\n\t\tif (data?.type === LEADER_PING) {\n\t\t\tchannel.postMessage({ type: LEADER_PONG })\n\t\t\treturn\n\t\t}\n\t\tif (data?.type === CLIENT_LEAVE) {\n\t\t\tif (hasReclaimClient(bridge)) {\n\t\t\t\tbridge.reclaimClient(data.clientId, 'client-left')\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (data?.type !== RPC_REQUEST) {\n\t\t\treturn\n\t\t}\n\t\tif (data.epoch !== undefined && data.epoch !== epoch) {\n\t\t\t// The transaction this request belongs to began on another leader worker,\n\t\t\t// which rolled it back (or is gone). Running the request here would apply\n\t\t\t// it outside that transaction, so refuse it unrun.\n\t\t\t//\n\t\t\t// Assumes at most one relay is live per channel at a time. The leader lock\n\t\t\t// guarantees it: a leader terminates its worker (which stops the relay)\n\t\t\t// before it releases the lock, and the next leader starts its relay only\n\t\t\t// after it holds the lock. With two live relays, this refusal could reach\n\t\t\t// the follower before the matching relay's real answer, and a committed\n\t\t\t// transaction would be reported as a retriable failure.\n\t\t\trespond(data.requestId, {\n\t\t\t\tid: data.request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'The storage leader changed during the transaction; the request was not run.',\n\t\t\t\tcode: LEADER_CHANGED,\n\t\t\t})\n\t\t\treturn\n\t\t}\n\t\tif (\n\t\t\tdata.request.type === 'close' ||\n\t\t\tdata.request.type === 'destroy' ||\n\t\t\tdata.request.type === 'serve'\n\t\t) {\n\t\t\t// Only the owning tab may close or remove the database; a follower\n\t\t\t// leaving just stops sending requests.\n\t\t\trespond(data.requestId, { id: data.request.id, type: 'success' })\n\t\t\treturn\n\t\t}\n\n\t\tconst pending = dedup.run(data.requestId, () =>\n\t\t\tbridge.send(data.request, data.clientId).catch(\n\t\t\t\t(error: unknown): WorkerResponse => ({\n\t\t\t\t\tid: data.request.id,\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\tmessage: error instanceof Error ? error.message : 'Worker RPC failed',\n\t\t\t\t\tcode: errorCode(error) ?? 'LEADER_RPC_ERROR',\n\t\t\t\t}),\n\t\t\t),\n\t\t)\n\t\tvoid pending?.then((response) => respond(data.requestId, response))\n\t}\n\n\tchannel.addEventListener('message', onMessage)\n\tconst interval = heartbeatMs > 0 ? setInterval(beat, heartbeatMs) : undefined\n\tif (heartbeatMs > 0) beat()\n\treturn {\n\t\tbeat,\n\t\tstop: () => {\n\t\t\tstopped = true\n\t\t\tif (interval !== undefined) clearInterval(interval)\n\t\t\tchannel.removeEventListener('message', onMessage)\n\t\t\tchannel.close()\n\t\t},\n\t}\n}\n\n/**\n * Leader main thread: forward follower RPC to the worker bridge. Used where the\n * worker cannot host the relay itself (Node tests, custom bridges). Heartbeats\n * are off by default here; pass `heartbeatMs` to enable them.\n */\nexport function startLeaderRpcRelay(\n\tchannelName: string,\n\tbridge: WorkerBridge,\n\toptions: LeaderRelayOptions = {},\n): () => void {\n\treturn serveChannel(\n\t\tnew BroadcastChannel(channelName),\n\t\tbridge,\n\t\t'main',\n\t\toptions.heartbeatMs ?? 0,\n\t\toptions.identity,\n\t).stop\n}\n\n/**\n * Leader WORKER: answer follower RPC, pings and heartbeats from inside the\n * dedicated SQLite worker, through the worker's transaction serializer. The\n * leader tab's main thread is not on this path, so a hung or busy main thread\n * does not stall other tabs (NEW-STORE-9).\n */\nexport function startWorkerRpcRelay(\n\tchannelName: string,\n\tbridge: WorkerBridge,\n\toptions: LeaderRelayOptions = {},\n): WorkerRpcRelay {\n\treturn serveChannel(\n\t\tnew BroadcastChannel(channelName),\n\t\tbridge,\n\t\t'worker',\n\t\toptions.heartbeatMs ?? DEFAULT_HEARTBEAT_MS,\n\t\toptions.identity,\n\t)\n}\n\n/**\n * What a follower needs to route its durability barrier to the leader tab: implemented\n * by {@link FollowerBroadcastBridge}.\n */\nexport interface SnapshotBarrierClient {\n\trequestSnapshotBarrier(options?: WorkerSendOptions): Promise<WorkerResponse>\n}\n\n/** Whether `bridge` can route a durability barrier to the leader tab. */\nexport function isSnapshotBarrierClient(bridge: unknown): bridge is SnapshotBarrierClient {\n\treturn (\n\t\ttypeof bridge === 'object' &&\n\t\tbridge !== null &&\n\t\ttypeof (bridge as Partial<SnapshotBarrierClient>).requestSnapshotBarrier === 'function'\n\t)\n}\n\n/**\n * Leader TAB (main thread): answer followers' snapshot-barrier requests with `run`, which\n * saves a strict snapshot taken after the request arrived (the leader's persistence\n * scheduler, so every barrier waiting there shares it). Answers `success` once `run`\n * resolved and an error response, carrying the failure's `code` and message, when it threw.\n * A request id already running is answered by that run. Returns the function that stops\n * serving.\n */\nexport function serveSnapshotBarriers(channelName: string, run: () => Promise<void>): () => void {\n\tconst channel = new BroadcastChannel(channelName)\n\tconst epoch = createClientId()\n\tconst running = new Set<string>()\n\t// A barrier still running when serving stops settles afterwards: never post on the\n\t// closed channel (it throws); the follower falls back on its own.\n\tlet stopped = false\n\tconst onMessage = (event: MessageEvent<ChannelMessage>): void => {\n\t\tconst data = event.data\n\t\tif (data?.type !== SNAPSHOT_BARRIER_REQUEST || running.has(data.requestId)) return\n\t\trunning.add(data.requestId)\n\t\tconst respond = (response: WorkerResponse): void => {\n\t\t\trunning.delete(data.requestId)\n\t\t\tif (stopped) return\n\t\t\tconst msg: RpcResponseMessage = {\n\t\t\t\ttype: RPC_RESPONSE,\n\t\t\t\trequestId: data.requestId,\n\t\t\t\tresponse,\n\t\t\t\tepoch,\n\t\t\t}\n\t\t\tchannel.postMessage(msg)\n\t\t}\n\t\trun().then(\n\t\t\t() => respond({ id: 0, type: 'success' }),\n\t\t\t(error: unknown) =>\n\t\t\t\trespond({\n\t\t\t\t\tid: 0,\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\tmessage: error instanceof Error ? error.message : 'Snapshot barrier failed',\n\t\t\t\t\tcode: errorCode(error) ?? 'SNAPSHOT_BARRIER_FAILED',\n\t\t\t\t\tcontext: errorContext(error),\n\t\t\t\t}),\n\t\t)\n\t}\n\tchannel.addEventListener('message', onMessage)\n\treturn () => {\n\t\tstopped = true\n\t\tchannel.removeEventListener('message', onMessage)\n\t\tchannel.close()\n\t}\n}\n\n/** The structured-cloneable part of an error's context a follower needs to classify it. */\nfunction errorContext(error: unknown): Record<string, unknown> | undefined {\n\tif (!(error instanceof Error)) return undefined\n\tconst context = (error as { context?: Record<string, unknown> }).context\n\tconst detail = context?.code\n\tconst quota =\n\t\tcontext?.quotaExceeded === true ||\n\t\terror.name === 'QuotaExceededError' ||\n\t\t/quota/i.test(error.message)\n\treturn {\n\t\t...(typeof detail === 'string' ? { detail } : {}),\n\t\t...(quota ? { quotaExceeded: true } : {}),\n\t}\n}\n\ninterface PendingFollowerRequest {\n\ttype: string\n\t/**\n\t * Snapshot-barrier requests only: epoch of the leader relay whose heartbeat was last\n\t * heard when the request was sent. A heartbeat of another epoch means the leader that\n\t * received the request is gone and the successor never saw it.\n\t */\n\trelayEpoch?: string\n\tresolve: (r: WorkerResponse, epoch?: string) => void\n\treject: (e: Error) => void\n}\n\n/**\n * Follower tab: proxy {@link WorkerBridge} over BroadcastChannel to the leader.\n *\n * A single watchdog runs while requests are pending. Any message from the leader\n * (heartbeat, pong, response) is a sign of life; when the leader goes quiet the\n * watchdog pings it, and after {@link MISSED_BEATS_UNRESPONSIVE} silent intervals\n * it fails every pending request with a typed, retriable\n * {@link LeaderUnresponsiveError} (or {@link NoLeaderError} if no leader was\n * heard at all) instead of waiting out the full RPC timeout.\n */\nexport class FollowerBroadcastBridge implements WorkerBridge {\n\tprivate readonly channel: BroadcastChannel\n\tprivate readonly clientId = createClientId()\n\tprivate readonly onPageHide = (): void => {\n\t\tthis.leaveLeader()\n\t}\n\tprivate readonly pending = new Map<string, PendingFollowerRequest>()\n\tprivate readonly timeoutMs: number\n\tprivate readonly heartbeatMs: number\n\tprivate terminated = false\n\tprivate lastHeardAt = 0\n\tprivate heardSinceWatch = false\n\t/** Epoch of the leader relay whose heartbeat was heard last. */\n\tprivate lastRelayEpoch: string | undefined\n\tprivate watchdog: ReturnType<typeof setInterval> | undefined\n\t/**\n\t * Epoch of the leader relay that answered the open transaction's BEGIN. Every\n\t * later request of the span carries it, so a different leader worker refuses\n\t * the request instead of autocommitting it outside the transaction.\n\t */\n\tprivate spanEpoch: string | undefined\n\n\t/**\n\t * @param channelName - Storage channel of the database\n\t * @param timeoutMs - Hard ceiling per request (default 30s)\n\t * @param heartbeatMs - Expected leader heartbeat interval, also the watchdog tick\n\t */\n\tconstructor(channelName: string, timeoutMs = 30000, heartbeatMs = DEFAULT_HEARTBEAT_MS) {\n\t\tthis.timeoutMs = timeoutMs\n\t\tthis.heartbeatMs = Math.max(10, Math.min(heartbeatMs, timeoutMs))\n\t\tthis.channel = new BroadcastChannel(channelName)\n\t\tif (typeof addEventListener === 'function') {\n\t\t\taddEventListener('pagehide', this.onPageHide)\n\t\t}\n\t\tthis.channel.addEventListener('message', (event: MessageEvent<ChannelMessage>) => {\n\t\t\tconst data = event.data\n\t\t\tif (\n\t\t\t\tdata?.type === LEADER_HEARTBEAT ||\n\t\t\t\tdata?.type === LEADER_PONG ||\n\t\t\t\tdata?.type === RPC_RESPONSE\n\t\t\t) {\n\t\t\t\tthis.markHeard()\n\t\t\t}\n\t\t\tif (data?.type === LEADER_HEARTBEAT) {\n\t\t\t\tthis.noteRelayEpoch(data.epoch)\n\t\t\t}\n\t\t\tif (data?.type !== RPC_RESPONSE) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconst entry = this.pending.get(data.requestId)\n\t\t\tif (entry) {\n\t\t\t\tthis.pending.delete(data.requestId)\n\t\t\t\tentry.resolve(data.response, data.epoch)\n\t\t\t}\n\t\t})\n\t}\n\n\t/**\n\t * A heartbeat names its relay's epoch (one per leader worker). A pending snapshot barrier\n\t * was sent to the leader of the epoch heard then; once another epoch beats, that leader\n\t * is gone and its successor never received the request, so the barrier fails fast\n\t * (retriable) instead of waiting out the RPC timeout.\n\t */\n\tprivate noteRelayEpoch(epoch: string): void {\n\t\tthis.lastRelayEpoch = epoch\n\t\tfor (const [, entry] of [...this.pending]) {\n\t\t\tif (entry.type !== 'snapshot-barrier') continue\n\t\t\tif (entry.relayEpoch === undefined) {\n\t\t\t\tentry.relayEpoch = epoch\n\t\t\t} else if (entry.relayEpoch !== epoch) {\n\t\t\t\tentry.reject(new BridgeTerminatedError('snapshot-barrier', 'the storage leader changed'))\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Readiness handshake: resolves `true` as soon as a live leader answers a ping,\n\t * or `false` if none answers within the budget. The adapter calls this before\n\t * its first RPC so a follower created before a leader relay is live retries the\n\t * handshake instead of firing into the void.\n\t */\n\tasync waitForLeader(timeoutMs = 3000, attempts = 3): Promise<boolean> {\n\t\tconst perAttempt = Math.max(50, Math.floor(timeoutMs / Math.max(1, attempts)))\n\t\tfor (let attempt = 0; attempt < attempts; attempt += 1) {\n\t\t\tif (this.terminated) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif (await this.pingLeader(perAttempt)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t/** Sends one liveness ping and resolves whether a leader answered in time. */\n\tprivate pingLeader(timeoutMs: number): Promise<boolean> {\n\t\tif (this.terminated) {\n\t\t\treturn Promise.resolve(false)\n\t\t}\n\t\treturn new Promise<boolean>((resolve) => {\n\t\t\tconst onPong = (event: MessageEvent<{ type: string }>): void => {\n\t\t\t\tif (event.data?.type === LEADER_PONG) {\n\t\t\t\t\tcleanup()\n\t\t\t\t\tresolve(true)\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst cleanup = (): void => {\n\t\t\t\tclearTimeout(timer)\n\t\t\t\tthis.channel.removeEventListener('message', onPong)\n\t\t\t}\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup()\n\t\t\t\tresolve(false)\n\t\t\t}, timeoutMs)\n\t\t\tthis.channel.addEventListener('message', onPong)\n\t\t\tthis.channel.postMessage({ type: LEADER_PING })\n\t\t})\n\t}\n\n\tasync send(\n\t\trequest: WorkerRequest,\n\t\t_clientId?: string,\n\t\toptions: WorkerSendOptions = {},\n\t): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn {\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'Follower bridge terminated',\n\t\t\t\tcode: 'BRIDGE_TERMINATED',\n\t\t\t}\n\t\t}\n\n\t\tconst requestId = request.requestId ?? createClientId()\n\t\tconst signal = options.signal\n\t\tif (signal?.aborted) {\n\t\t\tthrow new RequestAbortedError(request.type, requestId)\n\t\t}\n\t\t// Bind the request to the worker that answered the span's BEGIN. A BEGIN\n\t\t// starts a new span; a successful COMMIT or a ROLLBACK ends it. A relay\n\t\t// from an older build sends no epoch; the span is then bound to \"a legacy\n\t\t// relay\", which every relay that checks epochs refuses.\n\t\tconst epoch = request.type === 'begin' || request.type === 'open' ? undefined : this.spanEpoch\n\t\tif (request.type === 'begin' || request.type === 'rollback') {\n\t\t\tthis.spanEpoch = undefined\n\t\t}\n\t\tconst msg: RpcRequestMessage = {\n\t\t\ttype: RPC_REQUEST,\n\t\t\trequestId,\n\t\t\tclientId: this.clientId,\n\t\t\trequest: { ...request, requestId },\n\t\t\t...(epoch !== undefined ? { epoch } : {}),\n\t\t}\n\t\tconst timeoutMs = options.timeoutMs ?? this.timeoutMs\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tsettle(() => reject(new RequestAbortedError(request.type, requestId)))\n\t\t\t}\n\t\t\tconst settle = (fn: () => void): void => {\n\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\tthis.stopWatchdogIfIdle()\n\t\t\t\tfn()\n\t\t\t}\n\t\t\tif (Number.isFinite(timeoutMs)) {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tsettle(() => reject(new WorkerTimeoutError(`follower-rpc:${request.type}`, timeoutMs)))\n\t\t\t\t}, timeoutMs)\n\t\t\t}\n\t\t\tsignal?.addEventListener('abort', onAbort, { once: true })\n\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\ttype: request.type,\n\t\t\t\tresolve: (response, answeredBy) =>\n\t\t\t\t\tsettle(() => {\n\t\t\t\t\t\tif (response.type === 'error' && response.code === LEADER_CHANGED) {\n\t\t\t\t\t\t\treject(\n\t\t\t\t\t\t\t\tnew BridgeTerminatedError(\n\t\t\t\t\t\t\t\t\trequest.type,\n\t\t\t\t\t\t\t\t\t'storage leader changed during transaction',\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (response.type === 'error' && response.code === BRIDGE_TERMINATED) {\n\t\t\t\t\t\t\t// The leader's worker stopped serving (its state became unknown);\n\t\t\t\t\t\t\t// the request did not run there.\n\t\t\t\t\t\t\treject(new BridgeTerminatedError(request.type, response.message))\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (request.type === 'begin' && response.type === 'success') {\n\t\t\t\t\t\t\tthis.spanEpoch = answeredBy ?? LEGACY_RELAY_EPOCH\n\t\t\t\t\t\t} else if (request.type === 'commit' && response.type === 'success') {\n\t\t\t\t\t\t\t// A failed COMMIT keeps the binding for the ROLLBACK that follows.\n\t\t\t\t\t\t\tthis.spanEpoch = undefined\n\t\t\t\t\t\t}\n\t\t\t\t\t\tresolve(response)\n\t\t\t\t\t}),\n\t\t\t\treject: (error) => settle(() => reject(error)),\n\t\t\t})\n\t\t\tthis.startWatchdog()\n\t\t\tthis.channel.postMessage(msg)\n\t\t})\n\t}\n\n\t/**\n\t * Ask the leader tab for one strict snapshot that holds every write committed before\n\t * this call (one RPC, instead of exporting the whole database over the channel). The\n\t * leader answers after its persistence scheduler saved a snapshot taken after the\n\t * request arrived, sharing it with every other barrier waiting there.\n\t *\n\t * Resolves with the leader's answer (`error` when its snapshot failed: the caller treats\n\t * the writes as not durable). Rejects with {@link LeaderUnresponsiveError} or\n\t * {@link NoLeaderError} when the leader goes silent first (killed, frozen, hung),\n\t * {@link BridgeTerminatedError} when this tab was promoted or left meanwhile, and\n\t * {@link WorkerTimeoutError} past the timeout. It never resolves without the leader's\n\t * word, so a caller can fall back safely.\n\t */\n\trequestSnapshotBarrier(options: WorkerSendOptions = {}): Promise<WorkerResponse> {\n\t\tif (this.terminated) {\n\t\t\treturn Promise.reject(\n\t\t\t\tnew BridgeTerminatedError('snapshot-barrier', 'follower bridge terminated'),\n\t\t\t)\n\t\t}\n\t\tconst requestId = createClientId()\n\t\tconst signal = options.signal\n\t\tif (signal?.aborted) {\n\t\t\treturn Promise.reject(new RequestAbortedError('snapshot-barrier', requestId))\n\t\t}\n\t\tconst timeoutMs = options.timeoutMs ?? this.timeoutMs\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tlet timer: ReturnType<typeof setTimeout> | undefined\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tsettle(() => reject(new RequestAbortedError('snapshot-barrier', requestId)))\n\t\t\t}\n\t\t\tconst settle = (fn: () => void): void => {\n\t\t\t\tif (timer !== undefined) clearTimeout(timer)\n\t\t\t\tsignal?.removeEventListener('abort', onAbort)\n\t\t\t\tthis.pending.delete(requestId)\n\t\t\t\tthis.stopWatchdogIfIdle()\n\t\t\t\tfn()\n\t\t\t}\n\t\t\tif (Number.isFinite(timeoutMs)) {\n\t\t\t\ttimer = setTimeout(() => {\n\t\t\t\t\tsettle(() => reject(new WorkerTimeoutError('follower-rpc:snapshot-barrier', timeoutMs)))\n\t\t\t\t}, timeoutMs)\n\t\t\t}\n\t\t\tsignal?.addEventListener('abort', onAbort, { once: true })\n\t\t\tthis.pending.set(requestId, {\n\t\t\t\ttype: 'snapshot-barrier',\n\t\t\t\t...(this.lastRelayEpoch !== undefined ? { relayEpoch: this.lastRelayEpoch } : {}),\n\t\t\t\tresolve: (response) => settle(() => resolve(response)),\n\t\t\t\treject: (error) => settle(() => reject(error)),\n\t\t\t})\n\t\t\tthis.startWatchdog()\n\t\t\tconst message: SnapshotBarrierRequestMessage = { type: SNAPSHOT_BARRIER_REQUEST, requestId }\n\t\t\tthis.channel.postMessage(message)\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.leaveLeader()\n\t\tif (typeof removeEventListener === 'function') {\n\t\t\tremoveEventListener('pagehide', this.onPageHide)\n\t\t}\n\t\tthis.channel.close()\n\t\tfor (const [, entry] of [...this.pending]) {\n\t\t\tentry.reject(new BridgeTerminatedError(entry.type, 'follower bridge terminated'))\n\t\t}\n\t\tthis.pending.clear()\n\t\tthis.stopWatchdog()\n\t}\n\n\tprivate markHeard(): void {\n\t\tthis.lastHeardAt = Date.now()\n\t\tthis.heardSinceWatch = true\n\t}\n\n\tprivate startWatchdog(): void {\n\t\tif (this.watchdog !== undefined) return\n\t\t// A recent beat means a leader is known to exist; otherwise the silence\n\t\t// clock starts now.\n\t\tconst now = Date.now()\n\t\tthis.heardSinceWatch = now - this.lastHeardAt < this.heartbeatMs * 2\n\t\tif (!this.heardSinceWatch) {\n\t\t\tthis.lastHeardAt = now\n\t\t\t// Ask for a sign of life at once. Waiting a full interval first let a tick\n\t\t\t// that fired a millisecond \"early\" (interval timers and Date.now are not\n\t\t\t// aligned) skip its ping, so the next tick declared a live leader absent\n\t\t\t// without ever having asked it (LMS-7).\n\t\t\tthis.channel.postMessage({ type: LEADER_PING })\n\t\t}\n\t\tthis.watchdog = setInterval(() => this.checkLiveness(), this.heartbeatMs)\n\t}\n\n\tprivate stopWatchdogIfIdle(): void {\n\t\tif (this.pending.size === 0) this.stopWatchdog()\n\t}\n\n\tprivate stopWatchdog(): void {\n\t\tif (this.watchdog !== undefined) {\n\t\t\tclearInterval(this.watchdog)\n\t\t\tthis.watchdog = undefined\n\t\t}\n\t}\n\n\tprivate checkLiveness(): void {\n\t\tif (this.pending.size === 0) {\n\t\t\tthis.stopWatchdog()\n\t\t\treturn\n\t\t}\n\t\tconst silentMs = Date.now() - this.lastHeardAt\n\t\tconst heard = this.heardSinceWatch\n\t\tconst limit = this.heartbeatMs * (heard ? MISSED_BEATS_UNRESPONSIVE : MISSED_BEATS_ABSENT)\n\t\tif (silentMs >= limit) {\n\t\t\tfor (const [requestId, entry] of [...this.pending]) {\n\t\t\t\tentry.reject(\n\t\t\t\t\theard\n\t\t\t\t\t\t? new LeaderUnresponsiveError(`follower-rpc:${entry.type}`, silentMs, requestId)\n\t\t\t\t\t\t: new NoLeaderError(`follower-rpc:${entry.type}`),\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\t// Pull a sign of life from leaders that do not push heartbeats: on every tick\n\t\t// that heard nothing for at least half an interval, so timer jitter can never\n\t\t// skip the probe before the limit above is reached.\n\t\tif (silentMs * 2 >= this.heartbeatMs) {\n\t\t\tthis.channel.postMessage({ type: LEADER_PING })\n\t\t}\n\t}\n\n\tprivate leaveLeader(): void {\n\t\ttry {\n\t\t\tconst message: ClientLeaveMessage = {\n\t\t\t\ttype: CLIENT_LEAVE,\n\t\t\t\tclientId: this.clientId,\n\t\t\t}\n\t\t\tthis.channel.postMessage(message)\n\t\t} catch {\n\t\t\t// Best effort: the serializer's idle rollback is the guaranteed backstop.\n\t\t}\n\t}\n}\n\n/** Options for {@link TransactionSerializingWorkerBridge}. */\nexport interface TransactionSerializingOptions {\n\t/**\n\t * Called once when the serializer stops serving because the worker's\n\t * transaction state is unknown (a ROLLBACK of a span, its own or the owner's,\n\t * failed with anything but \"no transaction is active\").\n\t * The owner must replace the worker; this one never runs another request.\n\t */\n\tonBroken?: (reason: string) => void\n}\n\ninterface QueuedWorkerRequest {\n\tclientId: string\n\trequest: WorkerRequest\n\tresolve: (response: WorkerResponse) => void\n\treject: (error: Error) => void\n}\n\n/**\n * Serializes one SQLite worker across the leader tab and all follower tabs.\n *\n * SQLite transactions are represented as multiple worker messages\n * (`begin`, one or more reads/writes, then `commit`/`rollback`). Per-tab mutexes\n * cannot protect that span because follower messages converge at the leader.\n * This bridge promotes the worker boundary into the serialization point, so no\n * other client can interleave while a client owns an active transaction.\n */\nexport class TransactionSerializingWorkerBridge implements WorkerBridge {\n\tprivate readonly inner: WorkerBridge\n\tprivate readonly leaderClientId = createClientId()\n\tprivate readonly transactionIdleTimeoutMs: number\n\tprivate queue: QueuedWorkerRequest[] = []\n\tprivate activeTransactionClient: string | null = null\n\tprivate abortedClients = new Set<string>()\n\tprivate transactionIdleTimer: ReturnType<typeof setTimeout> | null = null\n\tprivate reclaiming = false\n\tprivate processing = false\n\tprivate terminated = false\n\t/** Set when the worker's transaction state became unknown; see {@link markBroken}. */\n\tprivate brokenReason: string | null = null\n\tprivate readonly onBroken: ((reason: string) => void) | undefined\n\n\tconstructor(\n\t\tinner: WorkerBridge,\n\t\ttransactionIdleTimeoutMs = DEFAULT_TRANSACTION_IDLE_TIMEOUT_MS,\n\t\toptions: TransactionSerializingOptions = {},\n\t) {\n\t\tthis.inner = inner\n\t\tthis.transactionIdleTimeoutMs = transactionIdleTimeoutMs\n\t\tthis.onBroken = options.onBroken\n\t}\n\n\tsend(request: WorkerRequest, clientId = this.leaderClientId): Promise<WorkerResponse> {\n\t\tif (this.brokenReason !== null) {\n\t\t\treturn Promise.reject(new BridgeTerminatedError(request.type, this.brokenReason))\n\t\t}\n\t\tif (this.terminated) {\n\t\t\treturn Promise.resolve({\n\t\t\t\tid: request.id,\n\t\t\t\ttype: 'error',\n\t\t\t\tmessage: 'Worker has been terminated',\n\t\t\t\tcode: 'WORKER_TERMINATED',\n\t\t\t})\n\t\t}\n\t\tif (this.abortedClients.has(clientId)) {\n\t\t\tif (request.type === 'begin') {\n\t\t\t\tthis.abortedClients.delete(clientId)\n\t\t\t} else if (request.type === 'rollback') {\n\t\t\t\t// The owner acknowledging the abort. The queue already rolled the span\n\t\t\t\t// back; running this ROLLBACK now could end another client's span.\n\t\t\t\tthis.abortedClients.delete(clientId)\n\t\t\t\treturn Promise.resolve({ id: request.id, type: 'success' })\n\t\t\t} else {\n\t\t\t\treturn Promise.resolve({\n\t\t\t\t\tid: request.id,\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\tmessage: 'Previous transaction was aborted because the client stopped sending requests.',\n\t\t\t\t\tcode: 'TRANSACTION_ABORTED',\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\treturn new Promise<WorkerResponse>((resolve, reject) => {\n\t\t\tthis.queue.push({ clientId, request, resolve, reject })\n\t\t\tvoid this.processQueue()\n\t\t})\n\t}\n\n\tterminate(): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.clearTransactionIdleTimer()\n\t\tthis.inner.terminate()\n\t\tconst pending = this.queue.splice(0)\n\t\tfor (const entry of pending) {\n\t\t\tentry.reject(new BridgeTerminatedError(entry.request.type, 'worker terminated'))\n\t\t}\n\t}\n\n\treclaimClient(clientId: string, reason: string): void {\n\t\tif (this.terminated) {\n\t\t\treturn\n\t\t}\n\t\tvoid this.reclaimClientNow(clientId, reason)\n\t}\n\n\tprivate async processQueue(): Promise<void> {\n\t\tif (this.processing || this.reclaiming) {\n\t\t\treturn\n\t\t}\n\t\tthis.processing = true\n\t\ttry {\n\t\t\twhile (!this.terminated && !this.reclaiming) {\n\t\t\t\tconst index = this.nextRunnableIndex()\n\t\t\t\tif (index === -1) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst [entry] = this.queue.splice(index, 1)\n\t\t\t\tif (!entry) {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tconst inSpan = this.activeTransactionClient === entry.clientId\n\t\t\t\t// The owner is not idle while its own request runs.\n\t\t\t\tif (inSpan) this.clearTransactionIdleTimer()\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await this.inner.send(entry.request)\n\t\t\t\t\tthis.recordTransactionState(entry, response)\n\t\t\t\t\tentry.resolve(response)\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// The worker's state is unknown (its BEGIN or a statement of the span may\n\t\t\t\t\t// have run). Roll the span back here, before any other client's request\n\t\t\t\t\t// runs, and refuse the owner's further span requests.\n\t\t\t\t\tif (inSpan || entry.request.type === 'begin') {\n\t\t\t\t\t\tawait this.abortSpan(entry.clientId, 'request-failed')\n\t\t\t\t\t}\n\t\t\t\t\tentry.reject(error instanceof Error ? error : new Error(String(error)))\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.processing = false\n\t\t\tif (!this.terminated && !this.reclaiming && this.nextRunnableIndex() !== -1) {\n\t\t\t\tvoid this.processQueue()\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate nextRunnableIndex(): number {\n\t\tif (this.queue.length === 0) {\n\t\t\treturn -1\n\t\t}\n\t\tif (this.activeTransactionClient === null) {\n\t\t\treturn 0\n\t\t}\n\t\treturn this.queue.findIndex((entry) => entry.clientId === this.activeTransactionClient)\n\t}\n\n\t/**\n\t * Tracks which client owns the open SQLite transaction. The span stays held\n\t * until its owner's COMMIT succeeds or its ROLLBACK is answered: an error on a\n\t * statement inside the span (or on COMMIT, e.g. a deferred constraint) leaves\n\t * SQLite's transaction open, so releasing the span then would let another\n\t * client's request run inside it, be acknowledged, and be erased by the\n\t * owner's rollback. A silent owner is reclaimed (rolled back) by the idle timer.\n\t */\n\tprivate recordTransactionState(entry: QueuedWorkerRequest, response: WorkerResponse): void {\n\t\tconst owner = this.activeTransactionClient === entry.clientId\n\t\tif (entry.request.type === 'begin' && !owner) {\n\t\t\tif (response.type === 'success') {\n\t\t\t\tthis.activeTransactionClient = entry.clientId\n\t\t\t\tthis.armTransactionIdleTimer(entry.clientId)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif (!owner) {\n\t\t\treturn\n\t\t}\n\t\tif (entry.request.type === 'rollback') {\n\t\t\tconst failure = unconfirmedRollback(response)\n\t\t\tif (failure !== null) {\n\t\t\t\t// The owner's ROLLBACK failed for another reason (e.g. disk I/O error):\n\t\t\t\t// SQLite may still hold the transaction open, so serving another client\n\t\t\t\t// could run its request inside it. Same rule as the queue's own rollback.\n\t\t\t\tthis.markBroken(`owner rollback failed: ${failure}`)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// Confirmed, or \"no transaction is active\" (SQLite already rolled it back):\n\t\t\t// the span is over.\n\t\t\tthis.activeTransactionClient = null\n\t\t\tthis.clearTransactionIdleTimer()\n\t\t\treturn\n\t\t}\n\t\tif (entry.request.type === 'commit' && response.type === 'success') {\n\t\t\tthis.activeTransactionClient = null\n\t\t\tthis.clearTransactionIdleTimer()\n\t\t\treturn\n\t\t}\n\t\tthis.armTransactionIdleTimer(entry.clientId)\n\t}\n\n\t/**\n\t * Rolls back `clientId`'s span from the queue itself and refuses the client's\n\t * further span requests, before any other client's request runs.\n\t */\n\tprivate async abortSpan(clientId: string, reason: string): Promise<void> {\n\t\tthis.clearTransactionIdleTimer()\n\t\tif (this.activeTransactionClient === clientId) {\n\t\t\tthis.activeTransactionClient = null\n\t\t}\n\t\tthis.abortedClients.add(clientId)\n\t\tthis.rejectQueuedClientRequests(clientId, reason)\n\t\tawait this.rollbackOrBreak(reason)\n\t}\n\n\t/**\n\t * The queue's own ROLLBACK of a span it took back. If it fails (throws, or\n\t * answers with anything but \"no transaction is active\"), the transaction may\n\t * still be open in the worker: serving another client then would run its\n\t * request inside that transaction, acknowledge it, and lose it with the\n\t * eventual rollback. So the serializer stops serving instead.\n\t */\n\tprivate async rollbackOrBreak(reason: string): Promise<void> {\n\t\tlet failure: string | null = null\n\t\ttry {\n\t\t\tconst response = await this.inner.send({ id: 0, type: 'rollback' })\n\t\t\tfailure = unconfirmedRollback(response)\n\t\t} catch (error) {\n\t\t\tfailure = error instanceof Error ? error.message : String(error)\n\t\t}\n\t\tif (failure !== null) {\n\t\t\tthis.markBroken(`rollback after ${reason} failed: ${failure}`)\n\t\t}\n\t}\n\n\t/**\n\t * Stops serving for good: queued requests fail with a retriable\n\t * {@link BridgeTerminatedError} without running, later sends fail the same way,\n\t * the inner bridge is terminated, and `onBroken` lets the owner replace the\n\t * worker (terminating a worker discards its uncommitted transaction).\n\t */\n\tprivate markBroken(reason: string): void {\n\t\tif (this.brokenReason !== null || this.terminated) return\n\t\tthis.brokenReason = `storage worker state unknown (${reason})`\n\t\tthis.clearTransactionIdleTimer()\n\t\tthis.activeTransactionClient = null\n\t\tfor (const entry of this.queue.splice(0)) {\n\t\t\tentry.reject(new BridgeTerminatedError(entry.request.type, this.brokenReason))\n\t\t}\n\t\tthis.terminated = true\n\t\tthis.inner.terminate()\n\t\ttry {\n\t\t\tthis.onBroken?.(this.brokenReason)\n\t\t} catch (error) {\n\t\t\tconsole.error('[kora] onBroken handler failed:', error)\n\t\t}\n\t}\n\n\tprivate armTransactionIdleTimer(clientId: string): void {\n\t\tthis.clearTransactionIdleTimer()\n\t\tthis.transactionIdleTimer = setTimeout(() => {\n\t\t\tvoid this.reclaimClientNow(clientId, 'transaction-idle-timeout')\n\t\t}, this.transactionIdleTimeoutMs)\n\t}\n\n\tprivate clearTransactionIdleTimer(): void {\n\t\tif (this.transactionIdleTimer) {\n\t\t\tclearTimeout(this.transactionIdleTimer)\n\t\t\tthis.transactionIdleTimer = null\n\t\t}\n\t}\n\n\tprivate async reclaimClientNow(clientId: string, reason: string): Promise<void> {\n\t\tif (this.reclaiming || this.activeTransactionClient !== clientId) {\n\t\t\treturn\n\t\t}\n\t\tthis.reclaiming = true\n\t\tthis.clearTransactionIdleTimer()\n\t\tthis.activeTransactionClient = null\n\t\tthis.abortedClients.add(clientId)\n\t\tthis.rejectQueuedClientRequests(clientId, reason)\n\n\t\ttry {\n\t\t\tawait this.rollbackOrBreak(reason)\n\t\t} finally {\n\t\t\tthis.reclaiming = false\n\t\t\tif (!this.terminated && this.nextRunnableIndex() !== -1) {\n\t\t\t\tvoid this.processQueue()\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate rejectQueuedClientRequests(clientId: string, reason: string): void {\n\t\tconst keep: QueuedWorkerRequest[] = []\n\t\tfor (const entry of this.queue) {\n\t\t\tif (entry.clientId === clientId) {\n\t\t\t\tentry.resolve({\n\t\t\t\t\tid: entry.request.id,\n\t\t\t\t\ttype: 'error',\n\t\t\t\t\tmessage: `Transaction client was reclaimed: ${reason}`,\n\t\t\t\t\tcode: 'TRANSACTION_ABORTED',\n\t\t\t\t})\n\t\t\t} else {\n\t\t\t\tkeep.push(entry)\n\t\t\t}\n\t\t}\n\t\tthis.queue = keep\n\t}\n}\n\n/**\n * Why a ROLLBACK response does not confirm that no transaction is open, or null\n * when it does: success, or \"no transaction is active\" (SQLite had already\n * rolled the transaction back, e.g. after SQLITE_FULL or an interrupt).\n */\nfunction unconfirmedRollback(response: WorkerResponse): string | null {\n\tif (response.type !== 'error') return null\n\treturn /no transaction is active/i.test(response.message) ? null : response.message\n}\n\nfunction errorCode(error: unknown): string | undefined {\n\tconst code = (error as { code?: unknown } | null)?.code\n\treturn typeof code === 'string' ? code : undefined\n}\n\nfunction hasReclaimClient(bridge: WorkerBridge): bridge is ReclaimingWorkerBridge {\n\treturn typeof (bridge as Partial<ReclaimingWorkerBridge>).reclaimClient === 'function'\n}\n\nfunction createClientId(): string {\n\tif (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n\t\treturn crypto.randomUUID()\n\t}\n\treturn `${Date.now()}-${Math.random().toString(36).slice(2)}`\n}\n"]}