UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

401 lines (400 loc) • 12.5 kB
import { i as createSqliteWorkerOperationAdmission } from "./sqlite-worker-operation-admission-9E_X-oRy.mjs"; import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as createSqliteWorkerWriteAdmission } from "./sqlite-worker-store-D51tD0Vp.mjs"; import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs"; import { n as invalidateChannelIngressHealth, r as resolveChannelIngressStateEnv } from "./ingress-queue-health-cache-Du0xxr3k.mjs"; import { a as corruptClaimRecord, i as completedRecord, l as selectChannelIngressClaim, n as baseRecord, o as decodeClaimColumns, r as claimedRecord, s as failedRecord } from "./ingress-queue.codec-CVNfRH4k.mjs"; //#region src/channels/message/ingress-queue.ts var ChannelIngressClaimPolicyConflict = class extends Error { constructor(e) { super("Channel ingress lane policy changed before claim commit"); this.settled = e; } }; function normalizePart(e, t) { return e?.trim() || t; } function idFrom(e) { const t = normalizePart(typeof e === "string" ? e : e.id, ""); if (!t) throw new Error("Channel ingress event id cannot be empty"); return t; } function requiredRecord(e) { const t = baseRecord(e); if (!t) throw new Error(`Corrupt payload_json in channel ingress event ${e.queue_name}/${e.event_id}`); return t; } /** Account discovery never creates or migrates a missing database. */ async function listChannelIngressQueueAccountIdsReadOnly(e) { const t = await executeExistingOpenClawStateRead({ env: resolveChannelIngressStateEnv(e.stateDir) }, { type: "channelIngress.accounts", input: { channelId: normalizePart(e.channelId, "unknown") } }); if (!t) return []; return t.result; } /** Durable ingress decisions commit in the shared-state worker; channels retain payload policy. */ function createChannelIngressQueue(e, t) { t?.(); const n = normalizePart(e.channelId, "unknown"); const r = normalizePart(e.accountId, "default"); const i = JSON.stringify([n, r]); const a = { channelId: n, accountId: r, queueName: i }; const o = resolveChannelIngressStateEnv(e.stateDir); const s = e.access === "read-only"; const c = e.now; const l = c ?? Date.now; const assertQueueCurrent = (e) => { e.admission.assertCurrent(); t?.(); }; const capture = () => { t?.(); return captureOpenClawStateWorkerContext({ env: o }); }; const execute = async (e, t, n = capture(), r, i, a) => { const assertActive = () => { assertQueueCurrent(n); a?.(); r?.throwIfAborted(); }; const o = e === "channelIngress.claim" || e === "channelIngress.claimNext" || e === "channelIngress.enqueueAndClaim" ? c : void 0; const s = await runOpenClawStateWorkerOperation(n, (n) => n.execute({ type: e, input: t }, { signal: r }), { assertCurrent: assertActive, createAdmission: o || i ? (e) => { const t = o ? new Float64Array(new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT)) : void 0; let r = "transaction"; return { nativeLocations: [n.admission.databasePath], admission: createSqliteWorkerOperationAdmission((n, a) => { if (n.stage !== r) throw new Error("Channel ingress claim authority requested out of order"); assertActive(); if (r === "transaction" && o && t) t[0] = o(); const s = i?.() ?? true; assertActive(); if (!s) throw new ChannelIngressClaimPolicyConflict(e.settled); if (!a()) throw new Error("Channel ingress claim authority expired"); r = r === "transaction" ? "commit" : "settled"; }, t) }; } : createSqliteWorkerWriteAdmission(assertActive, [n.admission.databasePath]) }).finally(() => { if (e !== "channelIngress.list" && e !== "channelIngress.claimSnapshot" && e !== "channelIngress.staleClaims") invalidateChannelIngressHealth(n); }); if (e === "channelIngress.list" || e === "channelIngress.claimSnapshot" || e === "channelIngress.staleClaims") assertQueueCurrent(n); return s; }; const readRows = async (e) => { const n = capture(); const r = await runOpenClawStateWorkerOperation(n, (t) => t.execute({ type: "channelIngress.list", input: { ...e, queueName: i, readOnly: s } }), { existingOnly: s, assertCurrent: t }); assertQueueCurrent(n); return r ?? []; }; const mutation = (e, t) => ({ queueName: i, id: idFrom(e), token: typeof e === "string" ? null : e.claim?.token ?? null, now: t }); const recoverStaleClaims = async (e) => { const t = capture(); const n = e?.shouldRecover; const r = e?.shouldRecoverCorrupt; const a = e?.now ?? l(); const o = a - Math.max(0, Math.floor(e?.staleMs ?? 0)); const s = await execute("channelIngress.staleClaims", { queueName: i, cutoff: o }, t); let c = 0; for (const e of s) { assertQueueCurrent(t); const i = decodeClaimColumns(e); const s = i === null ? null : claimedRecord(e); if (s) { if (n) { const e = await n(s); assertQueueCurrent(t); if (!e) continue; } } else if (i !== null) { if (r) { const n = await r(corruptClaimRecord(e, i)); assertQueueCurrent(t); if (!n) continue; } else if (n) continue; } assertQueueCurrent(t); if (await execute("channelIngress.recover", { row: e, cutoff: o, now: a }, t)) c++; } return c; }; const claimNext = async (e) => { const t = capture(); const n = e?.deriveLaneKey; const r = e?.reconcileStoredLaneKey; const a = normalizePart(e?.ownerId, `${process.pid}`); if (e?.staleMs !== void 0) await recoverStaleClaims({ staleMs: e.staleMs }); const o = e?.candidateIds === void 0 ? void 0 : [...e.candidateIds].map((e) => e.trim()).filter(Boolean); if (o?.length === 0) return null; const s = { queueName: i, candidateIds: o, blockedLaneKeys: [...e?.blockedLaneKeys ?? []].map((e) => e.trim()).filter(Boolean), deriveLaneKey: Boolean(n), orderBy: e?.orderBy, scanLimit: e?.scanLimit }; const resolveLane = (e) => { if (e.status === "claimed" && e.lane_key && !r) return e.lane_key; const t = baseRecord(e); if (!t) return e.lane_key ?? void 0; const i = t.laneKey; if (i === void 0) return n?.(t); if (!n || !r) return i; const a = n(t); return a && a !== i && r(t, i, a) ? a : i; }; while (true) { const e = await execute("channelIngress.claimSnapshot", s, t); const r = []; const i = selectChannelIngressClaim(e, s, n ? (e) => { const t = resolveLane(e); r.push({ row: e, laneKey: t }); return t; } : resolveLane); try { const o = await execute("channelIngress.claimNext", { request: s, snapshot: e, selection: i, ownerId: a, customClock: c ? true : void 0 }, t, void 0, n ? () => r.every(({ row: e, laneKey: t }) => resolveLane(e) === t) : void 0); if (o.kind === "conflict") continue; return o.row ? claimedRecord(o.row) : null; } catch (e) { if (e instanceof ChannelIngressClaimPolicyConflict && (await e.settled).kind === "completed") continue; throw e; } } }; const enqueueResult = (e) => { const t = e.row; if (e.accepted) return { kind: "accepted", duplicate: false, record: requiredRecord(t) }; if (t.status === "completed") return { kind: "completed", duplicate: true, record: completedRecord(t) }; if (t.status === "failed") return { kind: "failed", duplicate: true, record: failedRecord(t) }; if (t.status === "claimed") { const e = claimedRecord(t); if (!e) throw new Error(`Corrupt claimed channel ingress event ${i}/${t.event_id}`); return { kind: "claimed", duplicate: true, record: e }; } return { kind: "pending", duplicate: true, record: requiredRecord(t) }; }; const serializeEvent = (e) => ({ id: idFrom(e.id), payloadJson: JSON.stringify(e.payload), metadataJson: e.metadata === void 0 ? null : JSON.stringify(e.metadata), receivedAt: e.receivedAt ?? l(), laneKey: e.laneKey }); const enqueueBatch = async (e, t) => { t?.(); if (e.length === 0) return []; return (await execute("channelIngress.enqueue", { ...a, events: e.map(serializeEvent), now: l() }, capture(), void 0, void 0, t)).map(enqueueResult); }; const enqueue = async (e, t, n, r) => { const [i] = await enqueueBatch([{ id: e, payload: t, ...n }], r); return i; }; return { enqueue, enqueueBatch, enqueueBatchAuthorized: (e, t) => { if (typeof t.assertCurrent !== "function") return Promise.reject(/* @__PURE__ */ new TypeError("Authorized ingress requires a current-owner assertion")); return enqueueBatch(e, t.assertCurrent); }, async enqueueAndClaim(e, t, n) { const [r] = await execute("channelIngress.enqueueAndClaim", { ...a, events: [serializeEvent({ id: e, payload: t, ...n })], now: l(), idleClaimOwnerId: n.ownerId, customClock: c ? true : void 0 }); const i = enqueueResult(r); return { result: i, freshClaim: i.kind === "accepted" && r.freshClaim ? { ...i.record, claim: r.freshClaim } : void 0 }; }, enqueueAuthorized: (e, t, n) => { if (typeof n.assertCurrent !== "function") return Promise.reject(/* @__PURE__ */ new TypeError("Authorized ingress requires a current-owner assertion")); const { assertCurrent: r, ...i } = n; return enqueue(e, t, i, r); }, async listPending(e) { return (await readRows({ status: "pending", ...e })).map((e) => requiredRecord(e)); }, async listClaims() { return (await readRows({ status: "claimed" })).map((e) => claimedRecord(e)).filter((e) => e !== null); }, async listUnsettled(e) { const t = await readRows({ status: "unsettled", ...e }); const n = []; const r = []; for (const e of t) if (e.status === "claimed") { const t = claimedRecord(e); if (t) r.push(t); } else { const t = baseRecord(e); if (t) n.push(t); } return { pending: n, claims: r }; }, async listFailed(e) { return (await readRows({ status: "failed", ...e })).map((e) => failedRecord(e)); }, claimNext, async claim(e, t) { const n = await execute("channelIngress.claim", { queueName: i, id: idFrom(e), ownerId: normalizePart(t?.ownerId, `${process.pid}`), laneKey: t?.laneKey, customClock: c ? true : void 0 }); return n ? claimedRecord(n) : null; }, refreshClaim: async (e, t) => await execute("channelIngress.refresh", mutation(e, t?.refreshedAt ?? l())), complete: async (e, t) => await execute("channelIngress.complete", { ...a, ...mutation(e, t?.completedAt ?? l()), metadataJson: t?.metadata === void 0 ? null : JSON.stringify(t.metadata) }), release: async (e, t) => await execute("channelIngress.release", { ...mutation(e, t?.releasedAt ?? l()), recordAttempt: t?.recordAttempt, lastError: t?.lastError }), fail: async (e, t) => await execute("channelIngress.fail", { ...mutation(e, t.failedAt ?? l()), reason: t.reason, message: t.message }), async resubmit(e, t) { const n = await execute("channelIngress.resubmit", { queueName: i, id: idFrom(e), now: t?.resubmittedAt ?? l() }); switch (n.kind) { case "not-found": case "active": return n; case "completed": return { kind: n.kind, record: completedRecord(n.row) }; case "unrecoverable": return { kind: n.kind, record: failedRecord(n.row) }; case "resubmitted": return { kind: n.kind, record: requiredRecord(n.row), previous: failedRecord(n.previous) }; } return n; }, delete: async (e) => await execute("channelIngress.delete", mutation(e, l())), recoverStaleClaims, purge: async (e) => await execute("channelIngress.purge", { queueName: i }, capture(), e?.signal), async prune(e) { t?.(); if (!e || e.pendingTtlMs === void 0 && e.completedTtlMs === void 0 && e.failedTtlMs === void 0 && e.pendingMaxEntries === void 0 && e.completedMaxEntries === void 0 && e.failedMaxEntries === void 0) return 0; return execute("channelIngress.prune", { queueName: i, options: { ...e, protectIds: e.protectIds === void 0 ? void 0 : [...e.protectIds] }, now: e.now ?? l() }); } }; } //#endregion export { listChannelIngressQueueAccountIdsReadOnly as n, createChannelIngressQueue as t };