openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 9.76 kB
JavaScript
import"./src-0ci69Prg.mjs";import{n as safeParseJsonRecord}from"./json-coercion-DNNwq4_v.mjs";import{T as publishSqliteDatabaseAdmission}from"./sqlite-database-admission-B3KDkUt-.mjs";import{i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{a as runSqliteImmediateTransactionSync}from"./sqlite-transaction-CON-dGDv.mjs";import{t as coerceRequiredSqliteNumber}from"./sqlite-number-B9pFqi3P.mjs";import{a as resolveDeliveryQueueAttemptCount,c as inflateDeliveryQueueRows,d as pruneDeliveryQueueTombstones,f as terminalizeBoundDeliveryQueueEntry,h as failedDeliveryQueueHealthAdmission,i as projectDeliveryQueueTerminalEntry,l as loadDeliveryQueueEntryInDatabase,n as inferDeliveryQueueFailureRetention,o as bindDeliveryQueueEntry,p as upsertBoundDeliveryQueueEntryInDatabase,r as parseDeliveryQueueCompletionRetention,s as deliveryQueueEntriesQuery,t as hasLiveDeliveryQueueClaim,u as pruneDeliveryQueueTombstoneAges,y as oldestDeliveryQueueMediaStageAdmission}from"./delivery-queue-sqlite.types-glc5FW3-.mjs";import{t as chunkItems}from"./chunk-items-CsdD1uHV.mjs";import{n as DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME}from"./delivery-queue-namespaces-BNCoN9F0.mjs";
//!src/infra/delivery-queue-sqlite.kernel.ts
function deliveryQueueEntryNotFoundError(e,t){return Object.assign(/* @__PURE__ */ new Error(`No pending ${e} delivery queue entry ${t}`),{code:`ENOENT`})}function upsertDeliveryQueueEntryInDatabase(e,t){return upsertBoundDeliveryQueueEntryInDatabase(bindDeliveryQueueEntry(e),t)}function expireStagingAndLoadDeliveryQueueEntriesInDatabase(e,t){const n=runSqliteImmediateTransactionSync(e.db,()=>{executeSqliteQuerySync(e.db,getNodeSqliteKysely(e.db).deleteFrom(`delivery_queue_entries`).where(`queue_name`,`=`,DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME).where(`status`,`=`,`pending`).where(`enqueued_at`,`<=`,t.expireBeforeMs));const n=executeSqliteQuerySync(e.db,deliveryQueueEntriesQuery(e,[...t.queueNames,DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME],`unfinished`).select(`queue_name`).orderBy(`enqueued_at`,`asc`).orderBy(`id`,`asc`)).rows;const r=n.find(e=>e.queue_name===DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME);publishSqliteDatabaseAdmission(e.db,oldestDeliveryQueueMediaStageAdmission,r?coerceRequiredSqliteNumber(r.enqueued_at):null);return n},{databaseLabel:`openclaw-state`,operationLabel:`expire delivery queue staging entries`});return{entries:inflateDeliveryQueueRows(n.filter(e=>e.queue_name!==DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME)),stagingEntries:inflateDeliveryQueueRows(n.filter(e=>e.queue_name===DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME))}}function getDeliveryQueueEntryOwnersInDatabase(e,t,n){return getDeliveryQueueEntriesOwnersInDatabase(e,t,[n]).get(n)??/* @__PURE__ */ new Map}function getDeliveryQueueEntriesOwnersInDatabase(e,t,n){if(t.length===0||n.length===0)return/* @__PURE__ */ new Map;return runSqliteImmediateTransactionSync(e.db,()=>selectDeliveryQueueEntryOwners(e,t,n),{databaseLabel:`openclaw-state`,operationLabel:`read delivery queue status`})}function inspectDeliveryQueueReceiptInDatabase(e,t){return runSqliteImmediateTransactionSync(e.db,()=>{const n=selectDeliveryQueueEntryOwners(e,[t.queueName],[t.id]).get(t.id)?.get(t.queueName)?.status;return{status:n,pendingEntry:t.includePending&&n===`pending`?loadDeliveryQueueEntryInDatabase(e,t.queueName,t.id,`pending`):null}},{databaseLabel:`openclaw-state`,operationLabel:`read delivery queue receipt`})}function selectDeliveryQueueEntryOwners(e,t,n){const r=getNodeSqliteKysely(e.db);const i=[...new Set(n)];const readExact=()=>{const n=r.selectFrom(`delivery_queue_entries`).select([`id`,`queue_name`,`status`,`recovery_state`]).select(e=>e.case(`recovery_state`).when(`completed_bounded`).then(e.ref(`entry_json`)).else(null).end().as(`entry_json`)).where(`queue_name`,`in`,t);const readChunk=t=>{const r=t.length===1?t[0]:void 0;return executeSqliteQuerySync(e.db,r===void 0?n.where(`id`,`in`,t):n.where(`id`,`=`,r)).rows};return chunkItems(i,500).flatMap(readChunk)};let a=readExact();let o=false;const s=/* @__PURE__ */ new Map;for(const t of a){if(t.entry_json===null)continue;const n=safeParseJsonRecord(t.entry_json);const r=parseDeliveryQueueCompletionRetention(n?.completionRetention,t.id);if(typeof r===`object`){const n=s.get(t.queue_name)??/* @__PURE__ */ new Set;if(n.has(r.idPrefix))continue;n.add(r.idPrefix);s.set(t.queue_name,n);o=pruneDeliveryQueueTombstones(e.db,Date.now(),{queueName:t.queue_name,idPrefix:r.idPrefix})||o}}if(o)a=readExact();const c=/* @__PURE__ */ new Map;for(const e of a)if(e.status){const t=c.get(e.id)??/* @__PURE__ */ new Map;t.set(e.queue_name,{status:e.status,...e.status===`failed`&&e.recovery_state===`settlement_pending`?{settlementPending:true}:{}});c.set(e.id,t)}return c}function loadDeliveryQueueEntriesInDatabase(e,t){const n=executeSqliteQuerySync(e.db,deliveryQueueEntriesQuery(e,[t],`pending`).orderBy(`enqueued_at`,`asc`).orderBy(`id`,`asc`)).rows;return inflateDeliveryQueueRows(n)}function deleteDeliveryQueueEntryInDatabase(e,t,n){const r=getNodeSqliteKysely(e.db);executeSqliteQuerySync(e.db,r.deleteFrom(`delivery_queue_entries`).where(`queue_name`,`=`,t).where(`id`,`=`,n).where(`status`,`=`,`pending`))}function completeDeliveryQueueEntryInDatabase(e,t,n){const r=Date.now();completeLoadedDeliveryQueueEntryInDatabase(e,t,n,loadDeliveryQueueEntryInDatabase(e,t,n,`pending`),r)}function pruneBoundedDeliveryQueueTombstones(e,t,n){if(typeof n===`object`)runSqliteImmediateTransactionSync(e.db,()=>pruneDeliveryQueueTombstones(e.db,Date.now(),{queueName:t,idPrefix:n.idPrefix}),{databaseLabel:`openclaw-state`,operationLabel:`read delivery queue status`})}function completeLoadedDeliveryQueueEntryInDatabase(e,t,n,r,i=Date.now()){const a=r?.completionRetention;const o=parseDeliveryQueueCompletionRetention(a,n);if(a&&!o)throw new Error(`Invalid bounded delivery completion retention: ${t}/${n}`);if(!upsertDeliveryQueueEntryInDatabase({queueName:t,entry:projectDeliveryQueueTerminalEntry({id:n,retryCount:0},i,`completed`,o),metadata:{},status:`completed`,completeExisting:true},e)){if(getDeliveryQueueEntryOwnersInDatabase(e,[t],n).get(t)?.status===`completed`)return;throw deliveryQueueEntryNotFoundError(t,n)}pruneBoundedDeliveryQueueTombstones(e,t,o)}function updateDeliveryQueueEntryInDatabase(e,t,n,r){const i=loadDeliveryQueueEntryInDatabase(e,t,n,`pending`);if(!i)throw deliveryQueueEntryNotFoundError(t,n);upsertDeliveryQueueEntryInDatabase({queueName:t,entry:r(i)},e)}function reserveDeliveryQueueEntryAttemptInDatabase(e,t){if(!Number.isInteger(t.maxAttempts)||t.maxAttempts<=0)throw new Error(`Invalid delivery attempt budget: ${t.maxAttempts}`);const n=loadDeliveryQueueEntryInDatabase(e,t.queueName,t.id,`pending`);if(!n)throw deliveryQueueEntryNotFoundError(t.queueName,t.id);if(t.expectedPlatformSendAttemptId&&!hasLiveDeliveryQueueClaim(n,t.expectedPlatformSendAttemptId,Date.now()))throw new Error(`Delivery platform claim was lost: ${t.id}`);const r=resolveDeliveryQueueAttemptCount(n);if(r>=t.maxAttempts)return{status:`exhausted`,attemptCount:r};const i=r+1;if(!upsertDeliveryQueueEntryInDatabase({queueName:t.queueName,entry:{...n,attemptCount:i},updatePendingOnly:true},e))throw deliveryQueueEntryNotFoundError(t.queueName,t.id);return{status:`reserved`,attemptCount:i}}function countFailedDeliveryQueueEntriesInDatabase(e){const t=getNodeSqliteKysely(e.db);const n=executeSqliteQuerySync(e.db,t.selectFrom(`delivery_queue_entries`).select(e=>[`queue_name as queueName`,e.fn.countAll().as(`count`),e.fn.min(`failed_at`).as(`oldestFailedAt`)]).where(`status`,`=`,`failed`).groupBy(`queue_name`).orderBy(`queue_name`,`asc`)).rows.map(({oldestFailedAt:e,...t})=>e==null?t:Object.assign(t,{oldestFailedAt:e}));publishSqliteDatabaseAdmission(e.db,failedDeliveryQueueHealthAdmission,n);return n}function countPendingDeliveryQueueEntriesInDatabase(e,t){const n=getNodeSqliteKysely(e.db);const[r]=executeSqliteQuerySync(e.db,n.selectFrom(`delivery_queue_entries`).select(e=>e.fn.countAll().as(`count`)).where(`queue_name`,`in`,t).where(`status`,`=`,`pending`)).rows;return r?.count??0}function pruneExpiredDeliveryQueueTombstonesInDatabase(e){pruneDeliveryQueueTombstoneAges(e.db,Date.now())}function prepareDeliveryQueueTerminalEntry(e){if(e.entry.id!==e.id)throw new Error(`Delivery queue entry id mismatch: ${e.entry.id} != ${e.id}`);const t=Date.now();const n=JSON.stringify(e.entry);const r=inferDeliveryQueueFailureRetention(e.entry,e.id,e.queueName);const i=r?projectDeliveryQueueTerminalEntry(e.entry,t,`failed`,r):void 0;return{queueName:e.queueName,id:e.id,expectedStatus:e.expectedStatus,now:t,expectedJson:n,retention:r,failedEntry:i}}function terminalizePendingDeliveryQueueEntryInDatabase(e,t){const{queueName:n,id:r,expectedJson:i,failedEntry:a,now:o,expectedStatus:s,retention:c}=t;if(!terminalizeBoundDeliveryQueueEntry(e.db,n,r,i,a,o,s))return{status:`not_pending`};pruneBoundedDeliveryQueueTombstones(e,n,c);return{status:`terminalized`,retained:c!==void 0}}export{upsertDeliveryQueueEntryInDatabase as _,deleteDeliveryQueueEntryInDatabase as a,getDeliveryQueueEntriesOwnersInDatabase as c,loadDeliveryQueueEntriesInDatabase as d,prepareDeliveryQueueTerminalEntry as f,updateDeliveryQueueEntryInDatabase as g,terminalizePendingDeliveryQueueEntryInDatabase as h,countPendingDeliveryQueueEntriesInDatabase as i,getDeliveryQueueEntryOwnersInDatabase as l,reserveDeliveryQueueEntryAttemptInDatabase as m,completeLoadedDeliveryQueueEntryInDatabase as n,deliveryQueueEntryNotFoundError as o,pruneExpiredDeliveryQueueTombstonesInDatabase as p,countFailedDeliveryQueueEntriesInDatabase as r,expireStagingAndLoadDeliveryQueueEntriesInDatabase as s,completeDeliveryQueueEntryInDatabase as t,inspectDeliveryQueueReceiptInDatabase as u};