UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 6.83 kB
import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{n as notifyListeners}from"./listeners-awzYn4LE.mjs";import{v as NODE_WORKER_BUNDLE_INSTALL_COMMAND}from"./node-commands-BbC002V7.mjs";import{r as WORKER_BUNDLE_PREWARM_VERSION}from"./worker-admission-B_YnpbP9.mjs";import"./node-runner-inventory-0_sWHjPC.mjs";import{t as sameWorkerBuild}from"./worker-build-identity-K5xlOZic.mjs";import{a as workerBootstrapOperationTimeoutMs}from"./bootstrap-timeouts-DTWxPvhX.mjs";import{o as parseNodeWorkerBundleInstallResult}from"./node-bundle-install-protocol-DsQ70tqL.mjs"; //!src/gateway/worker-environments/node-worker-bundle-installer.ts const megabytes=e=>(e/1e6).toFixed(1);function sameNodeAuthority(e,t){return e.nodeId===t.nodeId&&e.pairingIdentity===t.pairingIdentity&&e.pairingGeneration===t.pairingGeneration&&e.clientId===t.clientId&&e.clientMode===t.clientMode&&e.protocolFeature===t.protocolFeature}function createGatewayNodeWorkerBundleInstaller(e){const t=/* @__PURE__ */ new Map;let n=0;const publish=(t,n=t.observation.environmentIds)=>{t.lastPublicationAtMs=Date.now();try{e.onObservationChange?.(t.observation.nodeId,n)}catch{}notifyListeners(t.progressListeners,void 0)};const install=async r=>{let i=Date.now();const a=`worker runtime install: node=${r.deviceId} bundle=${r.artifact.bundleHash.slice(0,12)}`;const elapsedSeconds=()=>Math.max(0,(Date.now()-i)/1e3);try{r.signal?.throwIfAborted();const o=e.getTransport();if(!o)throw new Error(`Device worker node transport is unavailable`);const s=await racePromiseWithAbortSignal(o.getCurrentNode(r.deviceId),r.signal);r.signal?.throwIfAborted();if(!s)throw new Error(`Device worker node is not connected with the installer dialect`);if(r.reason===`prefetch`&&s.workerHost.bundlePrefetch!==1)throw new Error(`Device worker node does not support bundle prefetch`);const{artifact:c}=r;const isAuthorized=()=>{r.assertCurrent?.();return!r.signal?.aborted&&e.getTransport()===o&&o.isCurrent(s)};if(!isAuthorized())throw new Error(`Device worker installation connection is no longer current`);const l=r.prewarm&&(s.workerHost.bundlePrewarm??0)>=1?1:void 0;const u=`${s.nodeId}:${c.bundleHash}`;let d=t.get(u);if(!d){i=Date.now();d={observation:{nodeId:s.nodeId,environmentIds:[],bundleHash:c.bundleHash,totalBytes:c.tarballBytes,transferredBytes:0,phase:`transferring`,startedAtMs:i,updatedAtMs:i},environmentReferences:/* @__PURE__ */ new Map,progressListeners:/* @__PURE__ */ new Set,lastProgressLogAtMs:i,lastPublicationAtMs:i};t.set(u,d);e.log.info(`worker runtime install started (${r.reason}): node=${s.nodeId} bundle=${c.bundleHash.slice(0,12)} size=${megabytes(c.tarballBytes)} MB`)}const f=r.onProgress&&(()=>r.onProgress?.());if(f)d.progressListeners.add(f);const p=d.environmentReferences.get(r.environmentId)??0;d.environmentReferences.set(r.environmentId,p+1);if(p===0){d.observation={...d.observation,environmentIds:[...d.environmentReferences.keys()].filter(e=>e!==void 0)};n++;publish(d)}else if(f)notifyListeners([f],void 0);const m=d;i=m.observation.startedAtMs;let h;let g;try{h=e.transfer.prepare({gatewayNamespace:e.gatewayNamespace,artifact:c,...l?{bundlePrewarm:l}:{},...r.reason===`prefetch`?{prefetch:1}:{},isAuthorized,signal:r.signal,onProgress:t=>{const r=Date.now();if(g?.interrupted)g=void 0;else if(g&&m.serve!==g)return;g??={startedAtMs:r,interrupted:false};const i=m.serve!==g;if(i){if(m.serve?.interrupted)e.log.info(`${a} transfer restarted`);m.serve=g;m.lastProgressLogAtMs=r}const o=m.observation;const s=Math.min(o.totalBytes,t);if(!i&&s<=o.transferredBytes)return;const c=Math.max(0,(r-g.startedAtMs)/1e3);const l=s===o.totalBytes?`installing`:`transferring`;const u=l!==o.phase;m.observation={...o,transferredBytes:s,updatedAtMs:r,phase:l};n++;if(l===`installing`&&(u||i))e.log.info(`${a} transfer complete after ${c.toFixed(1)}s; node is installing`);else if(r-m.lastProgressLogAtMs>=3e4){m.lastProgressLogAtMs=r;const t=s/Math.max(1,c);const n=t>=1e6?`${megabytes(t)} MB/s`:`${(t/1e3).toFixed(1)} KB/s`;e.log.info(`${a} ${megabytes(s)}/${megabytes(o.totalBytes)} MB (${Math.round(s/o.totalBytes*100)}%) ${n}`)}if(i||u||r-m.lastPublicationAtMs>=2e3)publish(m)},onInterrupted:(t,n)=>{if(g?.interrupted)return;g??={startedAtMs:Date.now(),interrupted:false};g.interrupted=true;m.serve??=g;e.log.warn(`${a} transfer interrupted at ${megabytes(Math.min(c.tarballBytes,t))}/${megabytes(c.tarballBytes)} MB: ${n}`)}});const t=await o.invoke({node:s,command:NODE_WORKER_BUNDLE_INSTALL_COMMAND,params:h.input,timeoutMs:workerBootstrapOperationTimeoutMs(c),idempotencyKey:`${e.gatewayNamespace}:${c.bundleHash}`,isDispatchAuthorized:isAuthorized,...r.signal?{signal:r.signal}:{}});if(!isAuthorized()){if(r.signal?.aborted)throw new Error(`Device worker installation connection is no longer current`);r.assertCurrent?.();const t=e.getTransport()===o?await racePromiseWithAbortSignal(o.getCurrentNode(r.deviceId),r.signal):void 0;r.signal?.throwIfAborted();r.assertCurrent?.();if(e.getTransport()!==o||t===void 0||!sameNodeAuthority(s,t)||!o.isCurrent(t))throw new Error(`Device worker installation connection is no longer current`)}if(!t.ok)throw new Error(t.error?.message?`Device worker bundle installation failed: ${t.error.message}`:`Device worker bundle installation failed`);let i=t.payload;if(t.payloadJSON)try{i=JSON.parse(t.payloadJSON)}catch{i=void 0}const u=parseNodeWorkerBundleInstallResult(i);if(!u||!sameWorkerBuild(u,c))throw new Error(`Device worker bundle installer returned a mismatched build receipt`);if(m.environmentReferences.size===1&&m.environmentReferences.get(r.environmentId)===1)e.log.info(`${a} ${r.reason===`prefetch`?`prefetched`:`installed`} in ${elapsedSeconds().toFixed(1)}s`);return u}finally{if(h)e.transfer.revoke(h.token);if(f)m.progressListeners.delete(f);const i=m.environmentReferences.get(r.environmentId)-1;if(i===0){m.environmentReferences.delete(r.environmentId);m.observation={...m.observation,environmentIds:[...m.environmentReferences.keys()].filter(e=>e!==void 0)};if(m.environmentReferences.size===0)t.delete(u);n++;publish(m,r.environmentId===void 0?m.observation.environmentIds:[...m.observation.environmentIds,r.environmentId])}else m.environmentReferences.set(r.environmentId,i)}}catch(t){const n=t instanceof Error?t.message:String(t);e.log.warn(`${a} failed after ${elapsedSeconds().toFixed(1)}s: ${n}`);throw t}};const readInstall=e=>{let n;for(const r of t.values())if(e(r)&&(!n||r.observation.updatedAtMs>=n.updatedAtMs))n=r.observation;return n?{...n,environmentIds:[...n.environmentIds]}:void 0};return Object.assign(install,{readInstall:e=>readInstall(t=>t.observation.nodeId===e),readInstallForEnvironment:e=>readInstall(t=>t.environmentReferences.has(e)),version:()=>n})}export{createGatewayNodeWorkerBundleInstaller};