openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 9.89 kB
JavaScript
import{At as e,Pt as t,t as n}from"./session-transcript-reconcile.worker-subsystem-Bf1bEeg_.mjs";import{At as r,It as i,La as a,N as o,Nn as s,P as c,Xt as l,Zt as u,a as d,bt as f,c as p,cn as m,d as h,l as g,no as _,o as v,on as y,rt as b,t as x,u as S}from"./session-transcript-reconcile.worker-openclaw-state-db-cache-IWT1d-ro.mjs";import{t as C}from"./session-transcript-reconcile.worker-src-jeYnv-1j.mjs";import{a as w,c as T,i as E,n as D,o as O,r as k,s as A,t as j}from"./session-transcript-reconcile.worker.js";import{AsyncLocalStorage as M}from"node:async_hooks";import{isDeepStrictEqual as N}from"node:util";function assertOpenClawStateWorkerActorPath(e){if(v.getKnownOpenClawStateDatabaseIdentity(e.databasePath)?.key!==e.key)throw new s(`Shared-state worker opening path changed`)}function runWithCapturedWorkerContext(e,t){let n=e.maintenanceScope,run=()=>n?n.run(()=>n.track(t())):t();return e.runInCapturedSchemaScope?e.runInCapturedSchemaScope(run):run()}function runWithOpenClawStateWorkerStore(e,t,n,r,i,a){let{admission:o}=t,s=D(e);return A(e,e=>n(a?{execute:(t,n)=>e.execute(t,{...n,signal:n?.signal?AbortSignal.any([a,n.signal]):a})}:e),t,e=>{o.assertCurrent(),assertOpenClawStateWorkerActorPath(s),r?.(e)},i)}function assertOpenClawStateWorkerSchemaContext(e){if(c(e.admission.databasePath),o()!==e.existingSchemaPath)throw Error(`Shared-state worker schema context does not match its caller`)}function captureOpenClawStateWorkerOpeningGuard(e){let t=e.admission,n=t.identity,r=M.bind(()=>t.assertCurrent()),assertCurrent=()=>{if(!r)throw Error(`Shared-state worker opening admission is closed`);r()};return{assertCurrent,createAdmission:()=>{let e=!1;return{nativeLocations:[t.databasePath],databaseIdentity:{databasePath:t.databasePath,key:n.key,birthtime:n.birthtime},admission:f((t,n)=>{if(e||t.stage!==`open`)throw Error(`Shared-state worker open admission requested out of order`);if(assertCurrent(),!n())throw Error(`Shared-state worker open admission expired`);e=!0})}},async run(e){try{return await e()}finally{r=void 0}}}}const P=n(`state/worker`);function createSharedStateWorkerOwner(){let t=m(`sharedStateStore`),n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,o=l(()=>n.size>0||i.size>0||r.size>0,retireIdleWorkers),matches=(e,t)=>t===void 0||e.context.admission.identity.key===t.key,hasActiveActorOperations=e=>[...r].some(t=>e.actor?t.actor===e.actor:t===e),clearIdleRetirement=e=>{e.idleSince=void 0,clearTimeout(e.idleTimer),e.idleTimer=void 0},hasPendingCleanup=e=>e.cleanup?.pending??(!e.context.maintenanceScope&&k(e.context.admission.databasePath)),retire=e=>{clearIdleRetirement(e),n.delete(e);let t=i.get(e);if(t||(t={},i.set(e,t)),o(),t.pending)return t.pending;let r=e.store?e.store.close():e.opening.then(e=>e?.close(),()=>e.cleanup?e.cleanup.close():e.context.maintenanceScope?void 0:j(e.context.admission.databasePath));t.pending=r;let settled=()=>{t.pending=void 0,hasPendingCleanup(e)||i.delete(e),o()};return r.then(settled,settled),r},scheduleIdleRetirement=t=>{if(t.activeOperations!==0||t.idleTimer||t.context.maintenanceScope||!t.store||!n.has(t))return;t.idleSince=performance.now();let r=e(()=>setTimeout(()=>{t.idleTimer===r&&t.activeOperations===0&&n.has(t)&&(t.idleTimer=void 0,retire(t).catch(e=>{P.warn(`Idle shared-state worker retirement failed`,{path:t.context.admission.databasePath,error:e})}))},b));t.idleTimer=r,r.unref?.()},retireAfterFailure=async(e,t,n)=>{try{await retire(e)}catch(e){throw AggregateError([t,e],`Shared-state worker ${n} and cleanup failed`,{cause:e})}throw t},retainOperation=(e,t)=>{let i=[...n].find(t=>t.store===e);if(!i)throw Error(`Shared-state worker operation lost its actor owner`);clearIdleRetirement(i),i.activeOperations+=1,r.add(i),t&&(i.nativeLostListeners.add(t),E(e)||t());let a=!1;return()=>{if(!a){if(a=!0,t&&i.nativeLostListeners.delete(t),--i.activeOperations,i.activeOperations===0&&r.delete(i),o(),n.has(i)&&!E(e)&&!hasActiveActorOperations(i)){let e=i.actor?retireActor(i.actor):retire(i);return e.catch(e=>{P.warn(`Shared-state worker retirement failed`,{path:i.context.admission.databasePath,error:e})}),e}scheduleIdleRetirement(i)}}},retireActor=e=>{let t=O(e);for(let t of/* @__PURE__ */ new Set([...n,...i.keys()]))t.actor===e&&retire(t);return t};async function close(e){for(let t of n.values())matches(t,e)&&retire(t);let t=(await Promise.allSettled([...i.keys()].filter(t=>matches(t,e)).map(retire))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(o(),t.length)throw AggregateError(t,`Failed to close shared-state SQLite workers`)}S({phase:`after-resources`,close}),h(e=>{if(e.kind!==`opened`){if(!e.identity)return;close(e.identity).catch(t=>{P.warn(`Shared-state worker retirement failed`,{path:e.path,error:t})})}});function retireIdleWorkers(t){for(let r of n)u(r.idleSince,t)&&e(()=>retireIdle(r))?.catch(e=>{P.warn(`Idle shared-state worker retirement failed`,{path:r.context.admission.databasePath,error:e})})}let retireIdle=e=>e.idleTimer&&e.store&&n.has(e)&&!e.context.maintenanceScope&&!hasActiveActorOperations(e)?retire(e):void 0;return{close,retainOperation,async openCleanup(e,a,o,s,c){let l={...s};if(o(),!l.key.startsWith(`file:`))return;let assertCurrent=()=>{o();for(let e of r)if(matches(e,l)&&e.store&&!E(e.store))throw new _(`Shared-state cleanup is waiting for accepted operations to settle`,`unavailable`)};assertCurrent();for(let e of/* @__PURE__ */ new Set([...n,...i.keys()]))(n.has(e)||i.has(e))&&matches(e,l)&&e.store&&!E(e.store)&&(assertCurrent(),await(e.actor?retireActor(e.actor):retire(e)),assertCurrent());return w({...y(t),databasePath:e,existingOnly:!0,admission:{identity:l.key,birthtime:l.birthtime,assertCurrent}},a,assertCurrent,{cleanupAccess:c&&{assertDatabaseAccess:c.assertCleanupDatabaseAccess}})},async open(r,s={}){let{existingOnly:c=!1,assertCurrent:l,signal:u}=s,{admission:d}=r,wait=e=>C(e,u),f=y(t),assertAdmission=()=>{u?.throwIfAborted(),d.assertCurrent(),l?.()};assertAdmission(),assertOpenClawStateWorkerSchemaContext(r);for(let e of/* @__PURE__ */ new Set([...n,...i.keys()]))if(matches(e,d.identity)&&n.has(e)&&(e.context.existingSchemaPath!==r.existingSchemaPath||!N(e.context.gatewayServiceInstallation,r.gatewayServiceInstallation)||e.source.moduleUrl.href!==f.moduleUrl.href)){if(hasActiveActorOperations(e))throw Error(`Shared-state worker policy changed while its actor is in use; close its leases first`);await wait(e.actor?retireActor(e.actor):retire(e)),assertAdmission()}for(let[e,t]of i)if(matches(e,d.identity)&&e.context.maintenanceScope===r.maintenanceScope){if(hasActiveActorOperations(e))throw Error(`Shared-state worker is retiring while its actor is in use; close its leases first`);if(!t.pending){if(!hasPendingCleanup(e)){i.delete(e),o();continue}throw Error(`Shared-state SQLite cleanup is pending; close the database before reopening`)}try{await wait(t.pending)}catch(n){if(i.get(e)===t)throw n}assertAdmission()}assertAdmission();let m=[...n].find(e=>matches(e,d.identity)&&e.context.maintenanceScope===r.maintenanceScope&&e.context.existingSchemaPath===r.existingSchemaPath&&N(e.context.gatewayServiceInstallation,r.gatewayServiceInstallation)),h=!m;if(!m){let t=captureOpenClawStateWorkerOpeningGuard(r),s=/* @__PURE__ */ new Set,open=()=>t.run(()=>w({...f,databasePath:d.databasePath,existingOnly:c},r,t.assertCurrent,{maintenanceScope:r.maintenanceScope,...c&&d.identity.key.startsWith(`file:`)?{createAdmission:t.createAdmission}:{},retireIdle:retireIdle.bind(void 0,l),retainCleanup:e=>{l.cleanup=e},onNativeLost:a.bind(void 0,s,void 0,void 0)})),l={source:f,context:r,existingOnly:c,nativeLostListeners:s,activeOperations:0,opening:Promise.resolve(void 0)};l.opening=r.maintenanceScope?open():e(open),m=l,l.opening=l.opening.then(e=>(e?(l.store=e,l.actor=D(e),scheduleIdleRetirement(l)):(n.delete(l),o()),e)),n.add(m),o(),r.maintenanceScope?.own(m,`shared-resources`,()=>retire(l)),m.opening.catch(()=>{n.delete(l),hasPendingCleanup(l)&&!i.has(l)&&i.set(l,{}),o()})}let g=await(h?m.opening:wait(m.opening));try{d.assertCurrent()}catch(e){return retireAfterFailure(m,e,`admission`)}if(u?.throwIfAborted(),l?.(),!g)return!c&&m.existingOnly?this.open(r,{...s,existingOnly:!1}):void 0;if(!n.has(m))return this.open(r,s);if(clearIdleRetirement(m),!E(g)&&!hasActiveActorOperations(m))return await wait(m.actor?retireActor(m.actor):retire(m)),this.open(r,s);try{m.bound||(p(m.context.admission,D(g).identity),m.bound=!0)}catch(e){return retireAfterFailure(m,e,`binding`)}return m.actor&&assertOpenClawStateWorkerActorPath(m.actor),n.delete(m),n.add(m),g}}}function getOpenClawStateWorkerOwner(){return x(),t(Symbol.for(`openclaw.sharedStateWorkerOwner`),createSharedStateWorkerOwner)}async function executeOpenClawStateWorker(e,t){let n=await runOpenClawStateWorkerOperation(e,e=>e.execute(t));return e.admission.assertCurrent(),n}async function runOpenClawStateWorkerOperation(e,t,n){return T(()=>runWithCapturedWorkerContext(e,async()=>{try{n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.();let r=await d(e,n?.signal);if(r)throw r;e.admission.assertCurrent(),n?.assertCurrent?.();let i=await getOpenClawStateWorkerOwner().open(e,n);if(!i){if(n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.existingOnly)return;throw Error(`Canonical shared-state worker did not open its database`)}let a=getOpenClawStateWorkerOwner().retainOperation(i);try{return n?.signal?.throwIfAborted(),e.admission.assertCurrent(),n?.assertCurrent?.(),await runWithOpenClawStateWorkerStore(i,e,t,n?.assertCurrent,n?.createAdmission,n?.signal)}finally{a()}}catch(t){let n=r(t),a=i(n,e.admission.databasePath);if(a&&!v.getOpenClawStateDatabaseRecordedFailure(e.admission.databasePath)){try{e.admission.assertCurrent()}catch{throw n}g(e.admission.databasePath,a)}throw n}}))}export{executeOpenClawStateWorker,runOpenClawStateWorkerOperation};