UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

770 lines (769 loc) • 30.4 kB
import { y as toErrorObject } from "./paths-0xDagtub.mjs"; import { p as isRecord } from "./utils-BclMknzT.mjs"; import { W as resolveGlobalSingleton } from "./path-guards-quCEQx1i.mjs"; import { a as wrapSqliteWorkerError, t as SqliteWorkerError } from "./sqlite-worker-error-Q7g0aE9t.mjs"; import { v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs"; import { r as sqlPublicationAnchor } from "./sql-connection-VmV9pnJI.mjs"; import { n as assertExistingDatabaseIdentity } from "./sqlite-worker-identity-CiWdPbPl.mjs"; import { Ct as stageSqliteTransactionState, at as installSqliteDatabaseAdmissions, ct as readSqliteDatabaseAdmissions, h as prepareSqliteDatabaseAdmissionAsync, it as captureSqliteDatabaseAdmissions, m as prepareSqliteDatabaseAdmission, mt as currentSqliteOperationTiming, ot as withSqliteDatabaseAdmissionExchange, st as createSqliteDatabaseAdmissionCursor, w as retainSqliteDatabaseAdmissionLocation } from "./sqlite-database-admission-DMm34jqt.mjs"; import { r as recordWorkerMessage } from "./worker-message-metrics-DnNsI1Wf.mjs"; import { r as StateDatabaseAdmissionPendingError } from "./gateway-state-owner-errors-ccLhqQIq.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; import { isPromise } from "node:util/types"; import { MessageChannel, MessagePort, receiveMessageOnPort } from "node:worker_threads"; import { serialize } from "node:v8"; //#region src/infra/sqlite-worker-contract.ts const processMonotonicClock = process.hrtime; /** Monotonic nanoseconds for deadlines measured within the calling thread. */ function readSqliteWorkerMonotonicNs() { return processMonotonicClock.bigint(); } const SQLITE_WORKER_MAX_MESSAGE_BYTES = 33554432; /** Only the factory's admission before agent open may certify this refusal. */ const SqliteWorkerOpenRefusedError = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerOpenRefusedError"), () => class OpenRefusedError extends Error { constructor(e) { super("SQLite worker admission was refused before agent open", { cause: e }); this.originalError = e; this.name = "SqliteWorkerOpenRefusedError"; } }); const SqliteWorkerAdmissionTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerAdmissionTimeoutError"), () => class AdmissionTimeoutError extends Error { constructor() { super("SQLite host admission timed out; retry after transaction rollback"); this.code = "admission-timeout"; this.name = "SqliteWorkerAdmissionTimeoutError"; } }); //#endregion //#region src/infra/sqlite-worker-database-admission-relay.ts const REQUESTED$2 = 0; const GRANTED$2 = 1; const ABANDONED = 2; const ADMISSION_PEER_SAFETY_TIMEOUT_MS = 6e5; const SQLITE_COLD_ADMISSION_PENDING = 4; var SqliteDatabaseAdmissionTimeoutError = class extends SqliteWorkerError { constructor() { super("SQLite admission facts exchange timed out; the host did not reply", "unavailable"); } }; const admissionWait = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseAdmissionWait"), () => new AsyncLocalStorage()); /** Callers own the deadline; worker transports carry its remaining absolute budget. */ function withSqliteDatabaseAdmissionWait(e, t) { const n = { wait: e, parent: admissionWait.getStore(), active: true }; const close = () => { n.active = false; }; let r = false; try { const e = admissionWait.run(n, t); if (isPromise(e)) { r = true; e.then(close, close); } return e; } finally { if (!r) close(); } } function readSqliteDatabaseAdmissionDeadline() { let e; for (let t = admissionWait.getStore(); t; t = t.parent) { if (!t.active) continue; const n = t.wait.deadlineAtMs; if (n !== void 0) e = Math.min(e ?? Infinity, n); } return e; } function assertSqliteDatabaseAdmissionWaitActive() { try { for (let e = admissionWait.getStore(); e; e = e.parent) if (e.active) e.wait.assertActive?.(); } catch (e) { throw wrapSqliteWorkerError("SQLite admission facts exchange cancelled by its caller", "unavailable", e); } } const admissionUpstream = resolveGlobalSingleton(Symbol.for("openclaw.sqliteDatabaseAdmissionUpstream"), () => ({})); function getSqliteDatabaseAdmissionUpstream() { return admissionUpstream.connection; } /** Format facts use this private channel independently of transaction authority. */ function exchangeSqliteDatabaseAdmissions(e, t, n, r) { return exchangeDatabaseAdmissions(e, t, n, r); } function exchangeDatabaseAdmissions(e, t, n, r) { const { port1: i, port2: a } = new MessageChannel(); const o = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); const s = currentSqliteOperationTiming(); const c = Date.now(); const l = readSqliteDatabaseAdmissionDeadline(); const u = l === void 0 ? ADMISSION_PEER_SAFETY_TIMEOUT_MS : Math.max(0, l - Date.now()); const d = readSqliteWorkerMonotonicNs() + BigInt(Math.ceil(u)) * 1000000n; const remaining = () => { assertSqliteDatabaseAdmissionWaitActive(); const e = Number(d - readSqliteWorkerMonotonicNs()) / 1e6; if (e <= 0) throw new SqliteDatabaseAdmissionTimeoutError(); return e; }; try { remaining(); e.postMessage({ kind: "sqlite-database-admissions", admissions: t, location: n, create: r, deadlineAtMs: l, port: a, decision: o.buffer }, [a]); while (Atomics.load(o, 0) === REQUESTED$2) { const e = remaining(); Atomics.wait(o, 0, REQUESTED$2, admissionWait.getStore() ? Math.min(100, e) : e); } remaining(); const s = Atomics.load(o, 0); if (s === 4 && n && r === true) throw new StateDatabaseAdmissionPendingError(n, `OpenClaw state at ${n} is undergoing schema admission; retry when it finishes.`); if (s !== GRANTED$2) throw new SqliteWorkerError("SQLite admission facts exchange failed", "unavailable"); const c = readSqliteDatabaseAdmissions(receiveMessageOnPort(i)?.message); if (!c) throw new SqliteWorkerError("SQLite admission facts reply is unavailable", "unavailable"); return c; } finally { Atomics.compareExchange(o, 0, REQUESTED$2, ABANDONED); if (s) s.databaseAdmissionWaitMs += Date.now() - c; i.close(); a.close(); } } //#endregion //#region src/infra/sqlite-worker-operation-settlement.ts function isNativeCommitReceipt(e) { return isRecord(e) && e.version === 1 && typeof e.sequence === "number" && Number.isSafeInteger(e.sequence) && e.sequence >= 1 && Object.hasOwn(e, "facts"); } const nativeCommitReceipts = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerNativeCommitReceipts"), () => /* @__PURE__ */ new WeakMap()); function resolveSqliteWorkerFinishSettlement(e, t, n) { return e ?? (n === "not-entered" && !t ? { kind: "completed" } : void 0); } function captureSqliteWorkerCommitReceipt(e) { const t = serialize(e); const n = t.byteLength; if (n > 33554432) return { kind: "oversized", serialized: t }; return { kind: "inline", facts: structuredClone(e), payloadBytes: n }; } function deferSqliteWorkerNativeCommitReceipt(e, t, n, r) { if (n.kind === "oversized") throw new SqliteWorkerError("SQLite worker commit receipt exceeds the transport limit", "overloaded"); const { facts: i, payloadBytes: a } = n; const o = sqlPublicationAnchor(t); const s = e.pendingReceipts ??= /* @__PURE__ */ new Map(); const pending = (e) => { const t = (s.get(o) ?? 0) + e; if (t === 0) s.delete(o); else s.set(o, t); }; if (!stageSqliteTransactionState(o, { stage: () => pending(1), rollback: () => pending(-1), commit() { pending(-1); const t = { version: 1, sequence: (nativeCommitReceipts.get(e)?.receipt.sequence ?? 0) + 1, facts: i }; const n = { receipt: t, payloadBytes: a, delivered: false }; nativeCommitReceipts.set(e, n); e.committed = { facts: i }; if (r === "commit") { e.port.postMessage({ kind: "native-commit", committed: t, payloadBytes: a }, []); n.delivered = true; } } })) throw new Error("SQLite worker receipt requires a transaction publication owner"); } const currentSqliteWorkerOperationAdmission = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerOperationAdmission"), () => new AsyncLocalStorage()); /** Record facts only after the real transaction commits, before native settlement is announced. */ function deferSqliteWorkerCommitReceipt(e, t, n = "commit") { const r = currentSqliteWorkerOperationAdmission.getStore(); if (!r?.active) throw new SqliteWorkerError("SQLite receipt requires its retained admission", "unavailable"); deferSqliteWorkerNativeCommitReceipt(r.owner, e, captureSqliteWorkerCommitReceipt(t), n); } /** Reuse the capture that selected an inline transport; publication still belongs to COMMIT. */ function deferCapturedSqliteWorkerCommitReceipt(e, t, n = "commit") { const r = currentSqliteWorkerOperationAdmission.getStore(); if (!r?.active) throw new SqliteWorkerError("SQLite receipt requires its retained admission", "unavailable"); deferSqliteWorkerNativeCommitReceipt(r.owner, e, t, n); } /** A typed fenced write cannot commit without its destination owner's settlement evidence. */ function assertSqliteWorkerCommitReceiptPending(e) { const t = currentSqliteWorkerOperationAdmission.getStore(); if (!t?.active || !t.owner.pendingReceipts?.get(sqlPublicationAnchor(e))) throw new SqliteWorkerError("SQLite source fence requires a destination commit receipt", "closed"); } //#endregion //#region src/state/openclaw-agent-execution-authority.ts const OPEN = 0; function readAgentDatabaseExecutionAuthority(e) { return Atomics.load(e.logical, 0) === OPEN && Atomics.load(e.native, 0) === OPEN && Atomics.load(e.logical, 0) === OPEN && Atomics.load(e.native, 0) === OPEN; } //#endregion //#region src/infra/sqlite-worker-request-custody.ts const ACTIVE = 1; const DISPATCHED = 2; const POST_ATTEMPTED = 4; const CANCELED = 8; const RETIRED = 16; function active(e) { return (e & ACTIVE) !== 0 && (e & 24) === 0; } /** Exact buffers retain generations; request IDs never identify authority. */ function readSqliteWorkerRequestCustody(e) { return Atomics.load(e.slot, 0) === 1 && active(Atomics.load(e.request, 0)); } var SqliteWorkerSlotCustody = class { constructor() { this.state = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); Atomics.store(this.state, 0, 1); } createRequest() { return new SqliteWorkerRequestCustody(this.state); } retire() { Atomics.store(this.state, 0, 0); } }; var SqliteWorkerRequestCustody = class { constructor(e) { this.descriptor = { slot: e, request: new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)) }; } activate() { if (Atomics.compareExchange(this.descriptor.request, 0, 0, ACTIVE) !== 0) throw new SqliteWorkerError("SQLite worker request custody was already used", "closed"); } assertCurrent() { if (!readSqliteWorkerRequestCustody(this.descriptor)) throw new SqliteWorkerError("SQLite worker job is no longer current", "closed"); } get dispatched() { return (Atomics.load(this.descriptor.request, 0) & DISPATCHED) !== 0; } get postAttempted() { return (Atomics.load(this.descriptor.request, 0) & POST_ATTEMPTED) !== 0; } accept() { this.assertCurrent(); Atomics.or(this.descriptor.request, 0, DISPATCHED); } post() { Atomics.or(this.descriptor.request, 0, POST_ATTEMPTED); } cancel() { if (!this.dispatched) Atomics.or(this.descriptor.request, 0, CANCELED); } retire() { Atomics.or(this.descriptor.request, 0, RETIRED); } }; //#endregion //#region src/infra/sqlite-writer-admission-client.ts const REQUESTED$1 = 0; const GRANTED$1 = 1; const TIMED_OUT$1 = 3; /** Cleanup borrows a physical database, independently of the actor's other clients. */ function assertSqliteWorkerDatabaseIdentity(e) { const t = e.databaseIdentity; if (!t) return; try { assertExistingDatabaseIdentity(t.databasePath, t.key, t.birthtime); } catch (t) { const n = new SqliteWorkerError("SQLite cleanup database no longer matches its borrowed native owner", "closed"); n.cause = t; e.refusal = n; throw n; } } function assertRequestCustody(e) { if (e.requestCustody && !readSqliteWorkerRequestCustody(e.requestCustody)) { const t = new SqliteWorkerError("SQLite worker request custody is revoked", "closed"); e.refusal = t; throw t; } if (e.executionAuthority && !readAgentDatabaseExecutionAuthority(e.executionAuthority)) { const t = new SqliteWorkerError("SQLite execution authority is revoked", "closed"); e.refusal = t; throw t; } assertSqliteWorkerDatabaseIdentity(e); } /** Ask the live host owner for a native stage; preparation precedes writer-lock acquisition. */ function requestSqliteWorkerOperationAdmission(e, t = []) { const n = currentSqliteWorkerOperationAdmission.getStore(); if (!n?.active) throw new SqliteWorkerError("SQLite operation requires its retained admission", "unavailable"); if (n.owner.sourceReservations) throw new SqliteWorkerError("SQLite source reservations prohibit host admission", "closed"); assertRequestCustody(n.owner); const r = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); const i = Date.now(); const a = e.deadlineMs === void 0 ? void 0 : readSqliteWorkerMonotonicNs() + BigInt(e.deadlineMs) * 1000000n; n.port.postMessage({ ...e, decision: r.buffer, ports: t.filter((e) => e instanceof MessagePort) }, t); while (Atomics.load(r, 0) === REQUESTED$1) { const e = a === void 0 ? void 0 : Number(a - readSqliteWorkerMonotonicNs()) / 1e6; if (e !== void 0 && e <= 0) Atomics.compareExchange(r, 0, REQUESTED$1, TIMED_OUT$1); else Atomics.wait(r, 0, REQUESTED$1, e); } const o = currentSqliteOperationTiming(); if (o) o.hostAdmissionWaitMs += Date.now() - i; const s = Atomics.load(r, 0); if (s === 4 && e.stage === "prepare" && isRecord(e.facts) && e.facts.kind === "schema-maintenance" && typeof e.facts.databasePath === "string") { const t = e.facts.databasePath; throw new StateDatabaseAdmissionPendingError(t, `OpenClaw state at ${t} is undergoing schema admission; retry when it finishes.`); } if (s !== GRANTED$1) { const e = s === TIMED_OUT$1 ? new SqliteWorkerAdmissionTimeoutError() : new SqliteWorkerError("SQLite transaction admission was refused", "closed"); n.owner.refusal = e; throw e; } assertRequestCustody(n.owner); delete n.owner.refusal; } //#endregion //#region src/infra/sqlite-worker-operation-scope.ts /** Install only the private port belonging to the broker's currently executing operation. */ function withSqliteWorkerOperationAdmission(e, t) { const n = { owner: e, port: e.port, active: true }; try { return runSqliteWorkerAdmissionScope(n, t); } finally { n.active = false; } } /** Async factories and cleanup retain the same grant until their accepted work settles. */ async function withSqliteWorkerOperationAdmissionAsync(e, t) { const n = { owner: e, port: e.port, active: true }; try { return await runSqliteWorkerAdmissionScope(n, t); } finally { n.active = false; } } function runSqliteWorkerAdmissionScope(e, t) { return withSqliteDatabaseAdmissionWait({ deadlineAtMs: e.owner.databaseAdmissionDeadlineAtMs }, () => currentSqliteWorkerOperationAdmission.run(e, () => withSqliteDatabaseAdmissionExchange((t, n, r) => { if (!e.active) { const e = getSqliteDatabaseAdmissionUpstream(); if (r || !e || e.closed) throw new SqliteWorkerError("SQLite facts require their retained admission", "unavailable"); return exchangeDatabaseAdmissions(e.port, t, n); } return exchangeSqliteDatabaseAdmissions(e.port, t, n, r); }, t))); } /** Schema work borrows live host authority through the same retained job port. */ function requestSqliteWorkerSchemaMaintenance(e) { if (!currentSqliteWorkerOperationAdmission.getStore()) return false; requestSqliteWorkerOperationAdmission({ stage: "prepare", facts: { kind: "schema-maintenance", databasePath: e } }); return true; } /** Require owner-prepared data carried by this operation's command envelope. */ function takeSqliteWorkerOperationAdmissionAttachment() { const e = currentSqliteWorkerOperationAdmission.getStore(); if (!e?.active) throw new SqliteWorkerError("SQLite operation requires its retained admission", "unavailable"); if (!e.owner.attachment) throw new SqliteWorkerError("SQLite operation attachment is unavailable", "unavailable"); return e.owner.attachment.value; } //#endregion //#region src/infra/sqlite-worker-operation-admission.ts const REQUESTED = 0; const GRANTED = 1; const REFUSED = 2; const TIMED_OUT = 3; const commitObserverBindings = /* @__PURE__ */ new WeakMap(); const executionAuthorities = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerExecutionAuthorities"), () => /* @__PURE__ */ new WeakMap()); const databaseAdmissionCursors = /* @__PURE__ */ new WeakMap(); function bindSqliteWorkerDatabaseAdmissionCursor(e, t, n) { databaseAdmissionCursors.set(e, { cursor: t, reset: n }); } function bindSqliteWorkerExecutionAuthority(e, t) { if (executionAuthorities.has(e)) throw new SqliteWorkerError("SQLite execution authority is already bound", "closed"); executionAuthorities.set(e, Object.freeze(t)); } function readSqliteWorkerExecutionAuthority(e) { return executionAuthorities.get(e); } /** Private publication binding leaves released SDK admission factories structurally unchanged. */ function observeSqliteWorkerCommittedFacts(e, t) { const n = commitObserverBindings.get(e); if (!n) throw new SqliteWorkerError("SQLite admission has no native receipt owner", "unavailable"); n(t); } /** The optional continuation runs under live host authority before releasing the native writer. */ const createSqliteWorkerOperationAdmission = (e, t, n) => createOperationAdmission(e, t, void 0, n); /** Task lifetime channels relay a broker's creation grant without acquiring database authority. */ function createSqliteDatabaseAdmissionRelay(e) { return createOperationAdmission(() => { throw new Error("Worker format facts do not grant database authority"); }, void 0, e); } function createOperationAdmission(e, t, n, r) { const { port1: i, port2: a } = new MessageChannel(); const o = AsyncLocalStorage.snapshot(); const s = /* @__PURE__ */ new Set(); let c = createSqliteDatabaseAdmissionCursor(); const l = []; let u = false; let d = false; let f; const p = []; let m = false; let h; let g; let _ = 0; let v; let y; const b = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)); const recordFailure = (e, t) => { if (!h || h.source === "domain" && t !== "domain") h = { error: e, source: t }; }; const refuse = (e, t, n) => { if (Atomics.compareExchange(e, 0, REQUESTED, REFUSED) === REQUESTED) { recordFailure(t, n); Atomics.notify(e, 0); } else if (Atomics.load(e, 0) === GRANTED) l.push(t); }; const invalidProtocol = (e, t = "outcome-unknown") => recordFailure(new SqliteWorkerError(`SQLite worker ${e} is invalid`, t), "protocol"); const installCommitted = (e) => { if (e.sequence <= _) return; _ = e.sequence; const t = { facts: e.facts }; g = t; m = true; try { o(() => { for (const e of p) e(t); }); } catch (e) { recordFailure(Object.assign(new SqliteWorkerError("SQLite committed facts publication failed", "outcome-unknown"), { cause: e }), "protocol"); } finally { m = false; } }; const receive = (t, i = false) => { const a = isRecord(t) ? t : void 0; recordWorkerMessage(a?.kind === "sqlite-database-admissions" ? "admission" : "authority", "from_worker", typeof a?.payloadBytes === "number" ? a.payloadBytes : void 0, x.requestClass); d = true; if (isRecord(t) && t.kind === "sqlite-database-admissions") { if (!(t.port instanceof MessagePort) || !(t.decision instanceof SharedArrayBuffer) || t.decision.byteLength !== Int32Array.BYTES_PER_ELEMENT || t.location !== void 0 && typeof t.location !== "string" || t.deadlineAtMs !== void 0 && (typeof t.deadlineAtMs !== "number" || !Number.isFinite(t.deadlineAtMs)) || t.create !== void 0 && typeof t.create !== "boolean" && t.create !== "admitted") { recordFailure(new SqliteWorkerError("SQLite admission facts request is invalid", "unavailable"), "protocol"); return; } const { location: e, port: r } = t; const a = new Int32Array(t.decision); s.add(a); const l = t.deadlineAtMs; const assertWaiting = () => { if (u) throw new SqliteWorkerError("SQLite worker admission is closed", "closed"); if (Atomics.load(a, 0) !== REQUESTED || l !== void 0 && Date.now() >= l) throw new SqliteWorkerError("SQLite admission requester stopped waiting", "unavailable"); }; (async () => { let u; let assertCreationCurrent; try { assertWaiting(); const s = t.create === "admitted" ? n : void 0; if (t.create === "admitted" && !s) throw new SqliteWorkerError("SQLite creation relay is not admitted", "closed"); const d = readSqliteDatabaseAdmissions(t.admissions); if (!d) throw new SqliteWorkerError("SQLite admission facts request is invalid", "unavailable"); installSqliteDatabaseAdmissions(d); let f = e; let p = false; if (e && t.create && !prepareSqliteDatabaseAdmission(e)) { f = resolveIdentityPathViaExistingAncestorSync(e); const n = f; const r = y; const i = r?.assertCreate?.bind(r); if (t.create === "admitted") p = true; else if (r && i) { if (r.coldOpenPath && resolveIdentityPathViaExistingAncestorSync(r.coldOpenPath) === n) u = r.coldOpenPath; assertCreationCurrent = () => o(() => { r.assertRequest?.(); r.assertAccess(); }); assertCreationCurrent(); o(() => i(n)); u = void 0; p = true; } } if (p) s?.(); const m = getSqliteDatabaseAdmissionUpstream(); if (m) { if (m.closed) throw new SqliteWorkerError("SQLite admission upstream is closed", "closed"); installSqliteDatabaseAdmissions(withSqliteDatabaseAdmissionWait({ deadlineAtMs: l, assertActive: assertWaiting }, () => exchangeDatabaseAdmissions(m.port, d, f, p ? "admitted" : void 0))); } else if (f) try { assertWaiting(); if (p) prepareSqliteDatabaseAdmission(f, { create: true }); const e = y?.databaseIdentity; const t = e && (f === e.databasePath || f === y?.databasePath) ? e : void 0; if (i) retainSqliteDatabaseAdmissionLocation(f, t); else await prepareSqliteDatabaseAdmissionAsync({ location: f, expectedIdentity: t, assertCurrent: assertWaiting }); } catch (e) { if (!isRecord(e) || e.code !== "ENOENT") throw e; } assertWaiting(); assertCreationCurrent?.(); if (p) s?.(); const h = e === void 0 && d.length === 0 ? void 0 : { location: e, admissions: d }; const g = databaseAdmissionCursors.get(x); const _ = captureSqliteDatabaseAdmissions(g?.cursor ?? c, h); r.postMessage(_, []); recordWorkerMessage("admission", "to_worker"); Atomics.compareExchange(a, 0, REQUESTED, GRANTED); } catch (e) { const t = databaseAdmissionCursors.get(x); if (t) t.cursor = t.reset(); else c = createSqliteDatabaseAdmissionCursor(); if (e instanceof StateDatabaseAdmissionPendingError && e.databasePath === u) Atomics.compareExchange(a, 0, REQUESTED, 4); else { recordFailure(e, "protocol"); Atomics.compareExchange(a, 0, REQUESTED, REFUSED); } } finally { s.delete(a); r.close(); Atomics.notify(a, 0); } })(); return; } if (isRecord(t) && t.kind === "native-commit") { const e = t.committed; if (!isNativeCommitReceipt(e)) { invalidProtocol("commit receipt"); return; } installCommitted(e); return; } if (isRecord(t) && t.kind === "native-settlement") { const e = t.settlement; if (!isRecord(e) || e.kind !== "completed" && e.kind !== "unknown" || e.committed !== void 0 && !isNativeCommitReceipt(e.committed)) { invalidProtocol("native settlement"); return; } if (e.committed !== void 0) installCommitted(e.committed); v = { kind: e.kind, ...g ? { committed: g } : {} }; return; } if (!isRecord(t) || !(t.decision instanceof SharedArrayBuffer) || t.decision.byteLength !== Int32Array.BYTES_PER_ELEMENT || t.stage !== "open" && t.stage !== "prepare" && t.stage !== "transaction" && t.stage !== "commit") { invalidProtocol("admission request", "unavailable"); return; } const l = new Int32Array(t.decision); const p = typeof t.deadlineMs === "number" && Number.isFinite(t.deadlineMs) ? readSqliteWorkerMonotonicNs() + BigInt(Math.max(0, Math.ceil(t.deadlineMs))) * 1000000n : void 0; const expired = () => { if (p !== void 0 && readSqliteWorkerMonotonicNs() >= p) { if (Atomics.compareExchange(l, 0, REQUESTED, TIMED_OUT) === REQUESTED) Atomics.notify(l, 0); } if (Atomics.load(l, 0) !== TIMED_OUT) return false; if (Array.isArray(t.ports)) { for (const e of t.ports) if (e instanceof MessagePort) e.close(); } return true; }; if (expired()) return; s.add(l); const m = { stage: t.stage, facts: t.facts }; try { o(() => f?.(m)); } catch (e) { refuse(l, e, "domain"); return; } if (u) { refuse(l, new SqliteWorkerError("SQLite worker admission is closed", "closed"), "authority"); return; } const grant = (e) => { if (u || expired() || Atomics.load(l, 0) !== REQUESTED) return false; try { o(() => y?.assertAccess()); } catch (e) { refuse(l, e, "authority"); return false; } if (u || expired() || Atomics.load(l, 0) !== REQUESTED) return false; e?.(); if (expired()) return false; const t = Atomics.compareExchange(l, 0, REQUESTED, GRANTED) === REQUESTED; if (t) Atomics.notify(l, 0); return t; }; let h = false; const finishDecision = () => { s.delete(l); if (Atomics.load(l, 0) === REQUESTED) refuse(l, new SqliteWorkerError("SQLite worker admission was not granted", "closed"), "domain"); }; let _ = "authority"; try { o(() => { y?.assertRequest?.(); }); if (m.stage === "prepare" && isRecord(m.facts) && m.facts.kind === "schema-maintenance") { const e = y; if (!e || typeof m.facts.databasePath !== "string" || resolveIdentityPathViaExistingAncestorSync(m.facts.databasePath) !== e.databasePath) throw new SqliteWorkerError("SQLite schema maintenance target differs from its admitted database", "closed"); o(() => { e.lease ??= e.acquireSchema(); e.assertAccess(); e.lease.assertCurrent(); grant(); }); } else { _ = "domain"; if (r) { h = true; (async () => { try { await o(r, m); if (!u && !expired() && Atomics.load(l, 0) === REQUESTED) o(e, m, grant); } catch (e) { refuse(l, e, "domain"); } finally { finishDecision(); } })(); return; } o(e, m, grant); } } catch (e) { if (e instanceof StateDatabaseAdmissionPendingError && y?.coldOpenPath === e.databasePath && !y.lease && m.stage === "prepare" && isRecord(m.facts) && m.facts.kind === "schema-maintenance" && typeof m.facts.databasePath === "string" && resolveIdentityPathViaExistingAncestorSync(m.facts.databasePath) === y.databasePath) { if (Atomics.compareExchange(l, 0, REQUESTED, 4) === REQUESTED) Atomics.notify(l, 0); } else refuse(l, e, _); } finally { if (!h) finishDecision(); } }; i.on("message", receive).unref(); const service = () => { if (m) return; for (let e = receiveMessageOnPort(i); e; e = receiveMessageOnPort(i)) receive(e.message, true); }; const x = { port: a, attachment: t === void 0 ? void 0 : { value: t }, observeRequests(e) { if (u || f) throw new SqliteWorkerError("SQLite request observation is already bound or closed", "closed"); f = e; }, bindDatabaseAuthority(e) { if (u || y) throw new SqliteWorkerError("SQLite database authority is already bound or closed", "closed"); y = { ...e }; }, get failure() { return h?.error; }, get failureSource() { return h?.source; }, get cleanupFailures() { return l; }, get committed() { service(); return g; }, get settlement() { return v; }, waitForSettlement(e) { while (true) { service(); if (h !== void 0) throw toErrorObject(h.error, "SQLite worker admission failed"); if (v?.kind === "completed") return v; const t = e - performance.now(); if (v?.kind === "unknown" || u || t <= 0) throw new SqliteWorkerError("SQLite worker native settlement is unknown", "outcome-unknown"); Atomics.wait(b, 0, 0, Math.min(5, t)); } }, service, finish(e) { u = true; service(); v = resolveSqliteWorkerFinishSettlement(v, g, e); if (s.size > 0) { for (const e of s) if (Atomics.load(e, 0) === REQUESTED) refuse(e, new SqliteWorkerError("SQLite worker admission is closed", "closed"), "authority"); } i.close(); a.close(); if (m) queueMicrotask(() => p.splice(0)); else p.length = 0; f = void 0; if (y?.lease) try { y.lease.release(); y.lease = void 0; } catch (e) { l.push(e); } if (!y?.lease) y = void 0; } }; commitObserverBindings.set(x, (e) => { if (u || d) throw new SqliteWorkerError("SQLite commit observation is closed or started", "closed"); p.push(e); }); return x; } //#endregion export { SqliteWorkerAdmissionTimeoutError as C, SQLITE_WORKER_MAX_MESSAGE_BYTES as S, deferSqliteWorkerCommitReceipt as _, observeSqliteWorkerCommittedFacts as a, readSqliteDatabaseAdmissionDeadline as b, takeSqliteWorkerOperationAdmissionAttachment as c, requestSqliteWorkerOperationAdmission as d, SqliteWorkerSlotCustody as f, deferCapturedSqliteWorkerCommitReceipt as g, currentSqliteWorkerOperationAdmission as h, createSqliteWorkerOperationAdmission as i, withSqliteWorkerOperationAdmission as l, assertSqliteWorkerCommitReceiptPending as m, bindSqliteWorkerExecutionAuthority as n, readSqliteWorkerExecutionAuthority as o, readSqliteWorkerRequestCustody as p, createSqliteDatabaseAdmissionRelay as r, requestSqliteWorkerSchemaMaintenance as s, bindSqliteWorkerDatabaseAdmissionCursor as t, withSqliteWorkerOperationAdmissionAsync as u, SqliteDatabaseAdmissionTimeoutError as v, withSqliteDatabaseAdmissionWait as x, assertSqliteDatabaseAdmissionWaitActive as y };