openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 10.1 kB
JavaScript
import{l as runOpenClawStateWriteTransaction}from"./openclaw-state-db-BlgxYkYw.mjs";import{r as normalizeOutboundReplyFacts}from"./reply-policy-DefDdtMb.mjs";import{c as OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME,i as OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME,n as DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME,o as OUTBOUND_DELIVERY_QUEUE_NAME,r as LEGACY_OUTBOUND_DELIVERY_QUEUE_NAME}from"./delivery-queue-namespaces-BNCoN9F0.mjs";import{n as resolveDeliveryQueueStateEnv}from"./delivery-queue-state-context-hv3uu8YS.mjs";import{c as terminalizePendingDeliveryQueueEntry,r as countPendingDeliveryQueueEntriesForMaintenance}from"./delivery-queue-sqlite-BtAn8uTD.mjs";import{o as settleDurableDelivery}from"./delivery-completion-BlzQI4lt.mjs";import{n as collectEntrySpoolPaths}from"./delivery-queue-media-paths-0MyGAFWA.mjs";import{l as resolveOutboundMediaAccessForSend,t as collectPayloadMediaSources}from"./deliver-payload-Bx3MDf5n.mjs";import{i as reconcileUnknownQueuedDelivery}from"./delivery-queue-reconciliation-DlzlSS9B.mjs";import{a as createRenderedMessageBatchPlan,t as prepareOutboundPayloadBatch}from"./deliver-prepare-BZF1WFGi.mjs";import{c as mapPreparedOutboundAcceptedPayloads,d as projectPreparedOutboundBatchForStorage,i as projectQueuedDeliveryOptions,l as preparedOutboundPayloads,o as createUnavailablePreparedOutboundBatch}from"./delivery-queue-projection-BtyjW4EQ.mjs";import{a as resolveOutboundMediaMaxBytes}from"./configured-max-bytes-D7sE4PVV.mjs";import{i as cancelDeliveryQueueMediaRetention,n as releaseSpoolArtifacts,r as stageQueuePayloadMedia}from"./delivery-queue-media-spool-D-fYGPHv.mjs";import{f as loadPendingDeliveryMigrations,p as loadPendingLegacyDeliveryPreparations,u as loadLegacyPendingDeliveries}from"./delivery-queue-storage-C8t9UjDJ.mjs";import{i as replacePendingDeliveryQueueEntryInDatabase,r as movePendingDeliveryQueueEntryNamespaceInDatabase}from"./delivery-queue-sqlite-namespace.kernel-ndHvkDe1.mjs";import{randomUUID}from"node:crypto";
//!src/infra/delivery-queue-sqlite-namespace.ts
function replacePendingDeliveryQueueEntry(e,t){return runOpenClawStateWriteTransaction(t=>replacePendingDeliveryQueueEntryInDatabase(t,e),{env:resolveDeliveryQueueStateEnv(e.stateDir,t)},{operationLabel:`replace pending delivery queue entry`})}function movePendingDeliveryQueueEntryNamespace(e,t){return runOpenClawStateWriteTransaction(t=>movePendingDeliveryQueueEntryNamespaceInDatabase(t,e),{env:resolveDeliveryQueueStateEnv(e.stateDir,t)},{operationLabel:`migrate delivery queue namespace`})}
//!src/infra/outbound/delivery-queue-migration.ts
const LEGACY_PREPARATION_LEASE_MS=3e5;function withLegacyPreparationLease(e,t){return{...e,retainOnFailure:true,legacyPreparationOwnerId:t,legacyPreparationLeaseExpiresAt:Date.now()+LEGACY_PREPARATION_LEASE_MS}}function hasActiveLegacyPreparationLease(e){return Boolean(e.legacyPreparationOwnerId&&typeof e.legacyPreparationLeaseExpiresAt===`number`&&e.legacyPreparationLeaseExpiresAt>Date.now())}function buildLegacyPreparationParams(e,t){const n=normalizeOutboundReplyFacts({reply:e.reply,replyToId:e.replyToId,replyToMode:e.replyToMode});return{cfg:t,...projectQueuedDeliveryOptions(e),queuePolicy:e.queuePolicy,requireUnknownSendReconciliation:e.requireUnknownSendReconciliation,payloads:e.payloads,reply:n,replyPayloadSendingHook:e.replyPayloadSendingHook,deliveryCompletion:e.deliveryCompletion,completionRetention:e.completionRetention}}async function prepareLegacyEntryCheckpoint(e){const t=buildLegacyPreparationParams(e.entry,e.cfg);const n=t.reply;const r=e.entry.recoveryState===`send_attempt_started`||e.entry.recoveryState===`unknown_after_send`;const i=r?await reconcileUnknownQueuedDelivery({entry:{...e.entry,reply:n},payloads:e.entry.payloads,cfg:e.cfg,warn:t=>e.log.warn(t)}):void 0;if(r&&(i==null||i.status===`unresolved`)){await failInterruptedLegacyPreparation({entry:e.entry,log:e.log,stateDir:e.stateDir});return`skipped`}const a=!r||e.entry.recoveryState===`send_attempt_started`&&i?.status===`not_sent`;let o=e.entry;let s;if(a){const replaceSourceEntry=t=>{const n=replacePendingDeliveryQueueEntry({queueName:OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME,expectedEntry:o,replacementEntry:t,stateDir:e.stateDir});if(n)o=t;return n};try{s=await prepareOutboundPayloadBatch(t,{hookRunner:e.hookRunner,onBeforeFirstModifier:async()=>{if(!replaceSourceEntry({...o,legacyPreparationState:`modifiers_started`}))throw new Error(`Legacy delivery ${e.entry.id} preparation ownership changed`)}})}catch(t){if(o.legacyPreparationState===`modifiers_started`)await failInterruptedLegacyPreparation({entry:o,log:e.log,stateDir:e.stateDir});else replaceSourceEntry({...o,legacyPreparationOwnerId:void 0,legacyPreparationLeaseExpiresAt:void 0});throw t}}else s=createUnavailablePreparedOutboundBatch(e.entry.payloads.length);const c=preparedOutboundPayloads(s);const{payloads:l,replyPayloadSendingHook:u,replyToId:d,replyToMode:f,legacyPreparationState:p,legacyPreparationOwnerId:m,legacyPreparationLeaseExpiresAt:h,...g}=e.entry;let _=g;if(a&&r){const{availableAt:e,producerClaimId:t,platformSendAttemptId:n,platformSendStartedAt:r,effectiveReplyToId:i,recoveryState:a,...o}=g;_=o}const v={..._,retainOnFailure:true,preparedBatch:projectPreparedOutboundBatchForStorage(s),renderedBatchPlan:createRenderedMessageBatchPlan(c),...n?{reply:n}:{},...!a&&(i?.status===`sent`||i?.status===`not_sent`)?{legacyUnknownSendReconciliation:i}:{},...!a?{legacyPreparedContentUnavailable:true}:{}};const y=movePendingDeliveryQueueEntryNamespace({sourceQueueName:OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME,destinationQueueName:OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME,expectedSourceEntry:o,destinationEntry:v,stateDir:e.stateDir});if(y!==`moved`){e.log.warn(`Legacy delivery ${e.entry.id} preparation deferred: ${y}`);return`skipped`}return`checkpointed`}async function failInterruptedLegacyPreparation(e){if(terminalizePendingDeliveryQueueEntry({queueName:`outbound-legacy-preparing-v1`,id:e.entry.id,entry:e.entry,stateDir:e.stateDir}).status!==`terminalized`){e.log.warn(`Legacy delivery ${e.entry.id} preparation owner was already settled`);return}if(e.entry.deliveryCompletion)try{await settleDurableDelivery(e.entry.deliveryCompletion,{platformSendStarted:true},e.stateDir)}catch(t){e.log.warn(`Legacy delivery ${e.entry.id} interrupted preparation owner could not be marked unknown: ${String(t)}`)}await releaseSpoolArtifacts(collectEntrySpoolPaths(e.entry.payloads,e.stateDir),e.stateDir)}function claimLegacyPreparation(e){const t=withLegacyPreparationLease({...e.entry,legacyPreparationState:`claimed`},e.ownerId);return(e.source===`preparing`?replacePendingDeliveryQueueEntry({queueName:`outbound-legacy-preparing-v1`,expectedEntry:e.entry,replacementEntry:t,stateDir:e.stateDir}):movePendingDeliveryQueueEntryNamespace({sourceQueueName:`outbound`,destinationQueueName:`outbound-legacy-preparing-v1`,expectedSourceEntry:e.entry,destinationEntry:t,retainSourceCompletionFence:e.entry.requiresProducerClaim===true||e.entry.completionRetention!==void 0,stateDir:e.stateDir})===`moved`)?t:null}async function finalizePreparedMigration(e){const t=preparedOutboundPayloads(e.entry.preparedBatch);const n=e.entry.legacyPreparedContentUnavailable!==true;let r=t;let i;let a=[];if(n){const n={...e.entry,cfg:e.cfg,payloads:t};const o=await stageQueuePayloadMedia({payloads:t,mediaAccess:resolveOutboundMediaAccessForSend(n,collectPayloadMediaSources(t)),maxBytes:resolveOutboundMediaMaxBytes({cfg:e.cfg,channel:e.entry.channel,accountId:e.entry.accountId}),stateDir:e.stateDir});if(o.status!==`staged`){e.log.warn(`Legacy delivery ${e.entry.id} cannot be migrated: ${o.reason} is not durable`);return`skipped`}r=o.payloads;i=o.mediaStageId;a=o.artifacts}let o=false;try{const a=mapPreparedOutboundAcceptedPayloads(e.entry.preparedBatch,r);const s={...e.entry,preparedBatch:a,renderedBatchPlan:e.entry.renderedBatchPlan??createRenderedMessageBatchPlan(t)};const c=movePendingDeliveryQueueEntryNamespace({sourceQueueName:OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME,destinationQueueName:OUTBOUND_DELIVERY_QUEUE_NAME,expectedSourceEntry:e.entry,destinationEntry:s,...i?{stagingQueueName:DELIVERY_QUEUE_MEDIA_STAGING_QUEUE_NAME,stagingId:i}:{},stateDir:e.stateDir});if(c!==`moved`){e.log.warn(`Legacy delivery ${e.entry.id} migration deferred: ${c}`);return`skipped`}o=true;if(n)await releaseSpoolArtifacts(collectEntrySpoolPaths(t,e.stateDir),e.stateDir);return`moved`}finally{if(!o){await cancelDeliveryQueueMediaRetention(i,e.stateDir);await releaseSpoolArtifacts(a,e.stateDir)}}}async function migrateLegacyPendingOutboundDeliveries(e){let t=0;let n=0;const r=randomUUID();const i=[];for(const t of loadPendingLegacyDeliveryPreparations(e.stateDir)){if(hasActiveLegacyPreparationLease(t)){n+=1;e.log.info(`Legacy delivery ${t.id} preparation is leased by another owner`);continue}if(t.legacyPreparationState!==`claimed`){await failInterruptedLegacyPreparation({...e,entry:t});n+=1;continue}const a=claimLegacyPreparation({entry:t,ownerId:r,stateDir:e.stateDir,source:`preparing`});if(!a){n+=1;e.log.info(`Legacy delivery ${t.id} preparation ownership changed`);continue}i.push(a)}for(const t of loadLegacyPendingDeliveries(e.stateDir)){const a=claimLegacyPreparation({entry:t,ownerId:r,stateDir:e.stateDir,source:`legacy`});if(!a){n+=1;e.log.warn(`Legacy delivery ${t.id} could not acquire preparation ownership`);continue}i.push(a)}for(const t of i)try{if(await prepareLegacyEntryCheckpoint({...e,entry:t})===`skipped`)n+=1}catch(r){n+=1;e.log.warn(`Legacy delivery ${t.id} migration failed: ${String(r)}`)}for(const r of loadPendingDeliveryMigrations(e.stateDir))try{if(await finalizePreparedMigration({...e,entry:r})===`moved`)t+=1;else n+=1}catch(t){n+=1;e.log.warn(`Prepared delivery ${r.id} migration failed: ${String(t)}`)}if(t>0||n>0)e.log.info(`Legacy delivery migration settled moved=${t} skipped=${n}`);const a=countPendingDeliveryQueueEntriesForMaintenance([OUTBOUND_LEGACY_PREPARATION_QUEUE_NAME,LEGACY_OUTBOUND_DELIVERY_QUEUE_NAME,OUTBOUND_DELIVERY_MIGRATION_QUEUE_NAME],e.stateDir);return{moved:t,skipped:n,remaining:a}}export{migrateLegacyPendingOutboundDeliveries};