UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

348 lines (347 loc) • 14.5 kB
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, p as sqliteStringSet, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { c as parseFailedPayload, n as baseRecord, o as decodeClaimColumns, r as claimedRecord, t as FAILED_NULL_PAYLOAD_SENTINEL } from "./ingress-queue.codec-CVNfRH4k.mjs"; import { t as engineUnboundedRowLimit } from "./row-limit-DxcIDYaA.mjs"; import { randomUUID } from "node:crypto"; //#region src/channels/message/ingress-queue.kernel.ts const getQueue = (e) => getNodeSqliteKysely(e); const affectedRows = (e) => Number(e.numAffectedRows ?? 0n); const CLEARED_CLAIM_COLUMNS = { claim_token: null, claim_owner: null, claimed_at: null }; function executeMutation(e, t) { return affectedRows(executeSqliteQuerySync(e, t)) > 0; } const LIST_PENDING_BATCH_SIZE = 100; function normalizeLimit(e) { return e === "all" ? Number.MAX_SAFE_INTEGER : Math.max(1, Math.floor(e ?? 100)); } function selectQueueRows(e, t) { return getQueue(e).selectFrom("channel_ingress_events").selectAll().where("queue_name", "=", t); } function selectRow(e, t, n) { return executeSqliteQueryTakeFirstSync(e, selectQueueRows(e, t).where("event_id", "=", n)); } function readChannelIngressClaimSnapshotInDatabase(e, t) { const n = selectQueueRows(e, t.queueName); const r = t.candidateIds?.length ? executeSqliteQuerySync(e, n.where("status", "=", "claimed").where("event_id", "in", t.candidateIds).orderBy("event_id", "asc")).rows : []; if (t.candidateIds?.length === 0) return { pending: [], claimed: r }; let i = n.where("status", "=", "pending"); if (t.candidateIds) i = i.where("event_id", "in", t.candidateIds); const a = [.../* @__PURE__ */ new Set([...t.blockedLaneKeys, ...r.flatMap((e) => e.lane_key ? [e.lane_key] : [])])]; if (!t.deriveLaneKey && a.length) i = i.where((e) => e.or([e("lane_key", "is", null), e("lane_key", "not in", a)])); const o = t.orderBy === "id" ? i.orderBy("event_id", "asc") : i.orderBy("received_at", "asc").orderBy("event_id", "asc"); return { claimed: r, pending: executeSqliteQuerySync(e, o.limit(normalizeLimit(t.scanLimit) + 100)).rows }; } function tombstoneCorruptRow(e, t, n, r) { return executeSqliteQueryTakeFirstSync(e, getQueue(e).updateTable("channel_ingress_events").set((e) => ({ status: "failed", failed_at: n, failed_reason: r, last_error: null, ...r === "corrupt_payload" ? { payload_json: "null", metadata_json: null } : { payload_json: e.case().when("payload_json", "=", "null").then(FAILED_NULL_PAYLOAD_SENTINEL).else(e.ref("payload_json")).end() }, ...CLEARED_CLAIM_COLUMNS, updated_at: n })).where("queue_name", "=", t.queue_name).where("event_id", "=", t.event_id).returningAll()); } function enqueueChannelIngressInDatabase(e, t, n = Date.now) { const r = t.events.length === 1 ? t.idleClaimOwnerId : void 0; const i = r ? n() : void 0; const a = r !== void 0 && i !== void 0 && !executeSqliteQueryTakeFirstSync(e, getQueue(e).selectFrom("channel_ingress_events").select("event_id").where("queue_name", "=", t.queueName).where("status", "in", ["pending", "claimed"]).limit(1)) ? { token: randomUUID(), ownerId: r, claimedAt: i } : void 0; const o = /* @__PURE__ */ new Map(); for (const e of t.events) if (!o.has(e.id)) o.set(e.id, e); const s = [...o.values()]; const c = /* @__PURE__ */ new Map(); const l = /* @__PURE__ */ new Set(); for (let n = 0; n < s.length; n += 100) { const r = s.slice(n, n + 100); const i = executeSqliteQuerySync(e, getQueue(e).insertInto("channel_ingress_events").values(r.map((e) => ({ queue_name: t.queueName, event_id: e.id, channel_id: t.channelId, account_id: t.accountId, status: a ? "claimed" : "pending", claim_token: a?.token ?? null, claim_owner: a?.ownerId ?? null, claimed_at: a?.claimedAt ?? null, lane_key: e.laneKey ?? null, payload_json: e.payloadJson, metadata_json: e.metadataJson, received_at: e.receivedAt, updated_at: a?.claimedAt ?? t.now, attempts: 0 }))).onConflict((e) => e.columns(["queue_name", "event_id"]).doNothing()).returningAll()).rows; for (const e of i) { c.set(e.event_id, e); l.add(e.event_id); } const o = r.filter((e) => !c.has(e.id)).map((e) => e.id); if (o.length) for (const n of executeSqliteQuerySync(e, selectQueueRows(e, t.queueName).where("event_id", "in", o)).rows) { if (n.status === "claimed" && !claimedRecord(n)) throw new Error(`Corrupt claimed channel ingress event ${t.queueName}/${n.event_id}`); if (n.status === "pending" && !baseRecord(n)) { const r = tombstoneCorruptRow(e, n, t.now, "corrupt_payload"); if (r) c.set(n.event_id, r); } else c.set(n.event_id, n); } } return t.events.map((e) => { const n = c.get(e.id); if (!n) throw new Error(`Failed to read channel ingress event ${t.queueName}/${e.id}`); const r = l.delete(e.id); return { accepted: r, row: n, freshClaim: r ? a : void 0 }; }); } function claimChannelIngressInDatabase(e, t, n = Date.now) { const r = n(); const i = executeSqliteQueryTakeFirstSync(e, getQueue(e).updateTable("channel_ingress_events").set({ status: "claimed", claim_token: randomUUID(), claim_owner: t.ownerId, claimed_at: r, updated_at: r, ...t.laneKey ? { lane_key: t.laneKey } : {} }).where("queue_name", "=", t.queueName).where("event_id", "=", t.id).where("status", "=", "pending").returningAll()); if (!i) return null; if (!baseRecord(i)) { tombstoneCorruptRow(e, i, r, "corrupt_payload"); return null; } return i; } function claimNextChannelIngressInDatabase(e, t, n = Date.now) { const r = readChannelIngressClaimSnapshotInDatabase(e, t.request); if (JSON.stringify(r) !== JSON.stringify(t.snapshot)) return { kind: "conflict" }; const i = n(); const a = new Set(t.selection.corruptIds); for (const t of r.pending) if (a.has(t.event_id)) tombstoneCorruptRow(e, t, i, "corrupt_payload"); const o = t.selection.selected; return { kind: "claimed", row: o ? claimChannelIngressInDatabase(e, { queueName: t.request.queueName, ...o, ownerId: t.ownerId }, () => i) : null }; } function recoverChannelIngressClaimInDatabase(e, t) { const n = selectRow(e, t.row.queue_name, t.row.event_id); if (!n || JSON.stringify(n) !== JSON.stringify(t.row)) return false; const r = decodeClaimColumns(n); if (!r || !claimedRecord(n)) { tombstoneCorruptRow(e, n, t.now, r ? "corrupt_payload" : "corrupt_claim"); return true; } return executeMutation(e, getQueue(e).updateTable("channel_ingress_events").set({ status: "pending", ...CLEARED_CLAIM_COLUMNS, updated_at: t.now }).where("queue_name", "=", n.queue_name).where("event_id", "=", n.event_id).where("status", "=", "claimed").where("claim_token", "=", r.token).where("claimed_at", "<=", t.cutoff)); } function selectedMutation(e, t) { const n = getQueue(e).updateTable("channel_ingress_events").where("queue_name", "=", t.queueName).where("event_id", "=", t.id); return t.token === null ? n.where("status", "=", "pending") : n.where("status", "=", "claimed").where("claim_token", "=", t.token); } function refreshChannelIngressClaimInDatabase(e, t) { return executeMutation(e, selectedMutation(e, t).set({ claimed_at: t.now, updated_at: t.now })); } function completeChannelIngressInDatabase(e, t) { const n = executeSqliteQuerySync(e, selectedMutation(e, t).set({ status: "completed", completed_at: t.now, completed_metadata_json: t.metadataJson, payload_json: "null", metadata_json: null, ...CLEARED_CLAIM_COLUMNS, last_attempt_at: null, last_error: null, updated_at: t.now })); if (affectedRows(n) > 0) return true; if (t.token !== null) return false; return executeMutation(e, getQueue(e).insertInto("channel_ingress_events").values({ queue_name: t.queueName, event_id: t.id, channel_id: t.channelId, account_id: t.accountId, status: "completed", lane_key: null, payload_json: "null", metadata_json: null, received_at: t.now, updated_at: t.now, attempts: 0, completed_at: t.now, completed_metadata_json: t.metadataJson }).onConflict((e) => e.columns(["queue_name", "event_id"]).doNothing())); } function releaseChannelIngressInDatabase(e, t) { return executeMutation(e, selectedMutation(e, t).set((e) => ({ status: "pending", ...CLEARED_CLAIM_COLUMNS, ...t.recordAttempt === false ? {} : { attempts: e("attempts", "+", 1), last_attempt_at: t.now }, ...t.lastError === void 0 ? {} : { last_error: t.lastError }, updated_at: t.now }))); } function failChannelIngressInDatabase(e, t) { return executeMutation(e, selectedMutation(e, t).set((e) => ({ status: "failed", failed_at: t.now, failed_reason: t.reason, last_error: t.message ?? null, payload_json: e.case().when("payload_json", "=", "null").then(FAILED_NULL_PAYLOAD_SENTINEL).else(e.ref("payload_json")).end(), ...CLEARED_CLAIM_COLUMNS, updated_at: t.now }))); } function pruneChannelIngressInDatabase(e, t) { const n = getQueue(e); const r = (t.options.protectIds ?? []).map((e) => e.trim()).filter(Boolean); const i = r.filter((e) => e.isWellFormed()); let a = 0; const o = [ { status: "pending", column: "updated_at", ttl: t.options.pendingTtlMs, max: t.options.pendingMaxEntries }, { status: "completed", column: "completed_at", ttl: t.options.completedTtlMs, max: t.options.completedMaxEntries }, { status: "failed", column: "failed_at", ttl: t.options.failedTtlMs, max: t.options.failedMaxEntries } ]; for (const s of o) { if (s.ttl !== void 0) { let i = n.deleteFrom("channel_ingress_events").where("queue_name", "=", t.queueName).where("status", "=", s.status).where(s.column, "<", t.now - s.ttl); if (r.length) i = i.where("event_id", "not in", r); a += affectedRows(executeSqliteQuerySync(e, i)); } if (s.max === void 0) continue; const o = n.selectFrom("channel_ingress_events").select("event_id").where("queue_name", "=", t.queueName).where("status", "=", s.status).orderBy("updated_at", "desc").orderBy("event_id", "desc").limit(engineUnboundedRowLimit(e)).offset(Math.max(0, Math.floor(s.max))); let c = n.selectFrom(o.as("overflow")).select("event_id").limit(500); if (i.length) c = c.where("event_id", "not in", sqliteStringSet(i)); const l = n.deleteFrom("channel_ingress_events").where("queue_name", "=", t.queueName).where("status", "=", s.status).where("event_id", "in", c); while (true) { const t = affectedRows(executeSqliteQuerySync(e, l)); if (!t) break; a += t; } } return a; } function listStaleChannelIngressClaimsInDatabase(e, t) { return executeSqliteQuerySync(e, selectQueueRows(e, t.queueName).where("status", "=", "claimed").where((e) => e.or([ e("claimed_at", "<=", t.cutoff), e("claimed_at", "is", null), e("claim_token", "is", null), e("claim_owner", "is", null), e("claim_token", "=", ""), e("claim_owner", "=", "") ]))).rows; } function deleteChannelIngressInDatabase(e, t) { const n = getQueue(e).deleteFrom("channel_ingress_events").where("queue_name", "=", t.queueName).where("event_id", "=", t.id); return executeMutation(e, t.token === null ? n.where("status", "=", "pending") : n.where("status", "=", "claimed").where("claim_token", "=", t.token)); } function resubmitChannelIngressInDatabase(e, t) { const n = selectRow(e, t.queueName, t.id); if (!n) return { kind: "not-found" }; if (n.status === "completed") return { kind: "completed", row: n }; if (n.status !== "failed") return { kind: "active", status: n.status === "claimed" ? "claimed" : "pending" }; if (n.payload_json === "null" || !parseFailedPayload(n.payload_json).ok) return { kind: "unrecoverable", row: n }; const r = executeSqliteQueryTakeFirstSync(e, getQueue(e).updateTable("channel_ingress_events").set({ status: "pending", payload_json: n.payload_json === "OPENCLAW_CHANNEL_INGRESS_FAILED_NULL_V1" ? "null" : n.payload_json, received_at: t.now, updated_at: t.now, attempts: 0, last_attempt_at: null, last_error: null, failed_at: null, failed_reason: null, ...CLEARED_CLAIM_COLUMNS, completed_at: null, completed_metadata_json: null }).where("queue_name", "=", t.queueName).where("event_id", "=", t.id).where("status", "=", "failed").returningAll()); if (!r) throw new Error(`Failed to read resubmitted channel ingress event ${t.queueName}/${t.id}`); return { kind: "resubmitted", row: r, previous: n }; } function purgeChannelIngressInDatabase(e, t) { return affectedRows(executeSqliteQuerySync(e, getQueue(e).deleteFrom("channel_ingress_events").where("queue_name", "=", t.queueName))); } function listChannelIngressRowsInDatabase(e, t) { const n = selectQueueRows(e, t.queueName).where("status", "in", t.status === "unsettled" ? ["pending", "claimed"] : [t.status]); if (t.status === "claimed" || t.status === "failed") { const r = (t.status === "claimed" ? n.orderBy("claimed_at", "asc").orderBy("received_at", "asc") : n.orderBy("failed_at", (e) => e.asc().nullsFirst())).orderBy("event_id", "asc"); return executeSqliteQuerySync(e, t.status === "failed" ? r.limit(normalizeLimit(t.limit)) : r).rows; } const r = t.orderBy === "id" ? n.orderBy("event_id", "asc") : n.orderBy("received_at", "asc").orderBy("event_id", "asc"); if (t.status === "unsettled") return executeSqliteQuerySync(e, r).rows; const i = normalizeLimit(t.limit); const a = []; let o; while (a.length < i) { let n = r; if (o) { const e = o; n = t.orderBy === "id" ? n.where("event_id", ">", e.event_id) : n.where((t) => t.or([t("received_at", ">", e.received_at), t.and([t("received_at", "=", e.received_at), t("event_id", ">", e.event_id)])])); } const s = executeSqliteQuerySync(e, n.limit(LIST_PENDING_BATCH_SIZE)).rows; for (const e of s) if (baseRecord(e)) { a.push(e); if (a.length === i) break; } if (s.length < LIST_PENDING_BATCH_SIZE) break; o = s.at(-1); } return a; } //#endregion export { enqueueChannelIngressInDatabase as a, listStaleChannelIngressClaimsInDatabase as c, readChannelIngressClaimSnapshotInDatabase as d, recoverChannelIngressClaimInDatabase as f, resubmitChannelIngressInDatabase as h, deleteChannelIngressInDatabase as i, pruneChannelIngressInDatabase as l, releaseChannelIngressInDatabase as m, claimNextChannelIngressInDatabase as n, failChannelIngressInDatabase as o, refreshChannelIngressClaimInDatabase as p, completeChannelIngressInDatabase as r, listChannelIngressRowsInDatabase as s, claimChannelIngressInDatabase as t, purgeChannelIngressInDatabase as u };