openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines (6 loc) • 10.8 kB
JavaScript
import{Lt as e,T as t,f as n,t as r,tt as i,u as a}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{Et as o}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import{n as s}from"./sqlite-readonly-runtime-worker-url-Ca-_reGi.mjs";import{J as c,Y as l,it as u}from"./sqlite-readonly-location.worker.js";import d from"node:path";import{accessSync as f,constants as p,statSync as m}from"node:fs";import h from"node:fs/promises";import{BroadcastChannel as g,MessageChannel as _,Worker as v,isMainThread as y,threadId as b,workerData as x}from"node:worker_threads";import{stripVTControlCharacters as S}from"node:util";import{AsyncLocalStorage as C}from"node:async_hooks";import{execFile as w,spawnSync as T}from"node:child_process";import{channel as E}from"node:diagnostics_channel";const D=e(Symbol.for(`openclaw.databaseEngineSelection`),()=>({})),O=e(Symbol.for(`openclaw.databaseEngineMaintenanceSelection`),()=>new C);function getDatabaseEngineSelection(){return O.getStore()??D.selection}function getDatabaseEngineInput(e){let t=getDatabaseEngineSelection();return t?.effectiveEngines[e]===`postgres`?t.postgres:void 0}const k=new t(Symbol(`spawnBroker`)),A={startupDisabled:!1};function getSpawnBroker(){let e=k.getStore();return A.startupDisabled||e===null?void 0:e??A.host}const j=new TextDecoder,M=/* @__PURE__ */ new Map([[` `,` `],[`
`,`
`],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]]);function renderOutput(e){let t=typeof e==`string`?e:j.decode(e);return t.endsWith(`
`)&&(t=t.slice(0,t.endsWith(`\r
`)?-2:-1)),S(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=M.get(e);if(t!==void 0)return t;let n=e.codePointAt(0),r=n.toString(16);return n<=65535?`\\u${r.padStart(4,`0`)}`:`\\U${r}`})}function decodeExecaMessage(e,t){return e.messageOutputs?[e.message,...e.messageOutputs.map(e=>renderOutput(t[e]))].join(`
`):e.message}function restoreError(e,t){let n=Error(decodeExecaMessage(e,t),{cause:e.cause?restoreError(e.cause,t):void 0});return Object.assign(n,{name:e.name,code:e.code})}function restoreExecaResult(e){let{error:t,...n}=e,r={...n,stdout:n.stdout,stderr:n.stderr,shortMessage:n.shortMessage,code:n.code};if(t){let e=restoreError(t,r);return Object.assign(e,r,{cause:e.cause})}return{...r,cause:void 0}}const N=e(Symbol.for(`openclaw.childRuntimeViability`),()=>({initialPath:process.execPath,initialIdentity:executableIdentity(process.execPath)})),P=/(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i,F=/(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i;function executableIdentity(e){try{return formatExecutableIdentity(m(e))}catch{return}}function formatExecutableIdentity({dev:e,ino:t,size:n,mtimeMs:r,mode:i}){return`${e}:${t}:${n}:${r}:${i}`}function publishRuntimeViability(e,t){return(o(t,`ENOENT`)||o(t,`ENOTDIR`))&&recordUnavailableRuntime(e,t),{execPath:e,available:!(N.execPath===e&&N.failure)}}function readChildRuntimeViability(e){let t=e?.execPath??process.execPath;if(N.execPath===t&&N.failure)return{execPath:t,available:!1};try{f(t,p.X_OK)}catch(e){return publishRuntimeViability(t,e)}return publishRuntimeViability(t)}async function prepareChildRuntimeViability(e){let t=e?.execPath??process.execPath,n=!(N.execPath===t&&N.failure);if(n)try{let e=await probeChildRuntimeExecutable(t);n=!classifyRuntimeProbe(t,e,await h.stat(t).then(formatExecutableIdentity,()=>void 0),e.error)}catch(e){n=publishRuntimeViability(t,await h.stat(t).then(()=>e,e=>e)).available}return{publish:()=>({execPath:t,available:n&&publishRuntimeViability(t).available})}}function recoverUnavailableRuntime(){if(N.execPath!==process.execPath||!N.failure||!N.recover||N.recoveryStarted)return;N.recoveryStarted=!0;let e=N.recover;n(()=>Promise.resolve().then(e).catch(()=>({status:`report-only`,reason:`Automatic runtime recovery is report-only: service or restart preparation failed. Inspect the service runtime and restart through its owner.`})).then(e=>{r(`gateway/runtime`).warn(`${e.status}: ${e.reason}`)}))}function runtimeProbeOptions(e={}){return{encoding:`utf8`,cwd:e.cwd??d.parse(process.execPath).root,env:e.env??{...process.env,NODE_OPTIONS:void 0},timeout:1e3,maxBuffer:8192}}async function probeChildRuntimeExecutable(e,t={}){let n=getSpawnBroker();if(n){let r=n.spawnExeca([e,`--version`],{...runtimeProbeOptions(t),extendEnv:!1,stripFinalNewline:!1,stdin:`ignore`});r.child.once(`spawn`,()=>{r.child.stdout?.resume(),r.child.stderr?.resume()});let i=restoreExecaResult(await r.result);return await r.child.waitForClose(),{stdout:typeof i.stdout==`string`?i.stdout:``,stderr:typeof i.stderr==`string`?i.stderr:``,error:i instanceof Error?i:void 0,status:i.exitCode??null,signal:i.signal??null}}return new Promise(n=>{w(e,[`--version`],runtimeProbeOptions(t),(e,t,r)=>n({stdout:t,stderr:r,error:e??void 0,status:e?typeof e.code==`number`?e.code:null:0,signal:e?.signal??null}))})}function formatMissingChildRuntimeWarning(e){return e.available?void 0:`The Node.js runtime this Gateway started with (${i(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`}function assertChildRuntimeAvailable(){if(N.execPath===process.execPath&&N.failure)throw N.failure}function recordUnavailableRuntime(e,t,n){if(N.execPath===e&&N.failure)return N.failure;N.execPath=e;let i=formatMissingChildRuntimeWarning({execPath:e,available:!1}),a=n?.trim();return N.failure=Object.assign(Error(a?`${i}\n${a}`:i,{cause:t}),{code:`NODE_RUNTIME_UNAVAILABLE`}),r(`gateway/runtime`).error(N.failure.message),recoverUnavailableRuntime(),N.failure}function needsRuntimeProbe(e){return!!(e.error||e.signal===`SIGABRT`||F.test(e.stderr??``))}function classifyRuntimeProbe(e,t,n,r){if(N.execPath===e&&N.failure)return N.failure;let i=e!==N.initialPath||n!==N.initialIdentity;return P.test(t.stderr)||F.test(t.stderr)||o(t.error,`ENOENT`)||o(t.error,`ENOTDIR`)||i&&(t.signal===`SIGABRT`||o(t.error,`ENOEXEC`)||o(t.error,`EACCES`)||o(t.error,`EPERM`))?recordUnavailableRuntime(e,r,t.stderr):void 0}function classifyChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(N.execPath===t&&N.failure)return N.failure;if(P.test(e.stderr??``)||e.error&&!readChildRuntimeViability({execPath:t}).available)return recordUnavailableRuntime(t,e.error,e.stderr);if(needsRuntimeProbe(e))return classifyRuntimeProbe(t,T(t,[`--version`],runtimeProbeOptions()),t===N.initialPath?executableIdentity(t):void 0,e.error)}async function prepareChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(N.execPath===t&&N.failure)return N.failure;if(P.test(e.stderr??``)||e.error&&!(await prepareChildRuntimeViability({execPath:t})).publish().available)return recordUnavailableRuntime(t,e.error,e.stderr);if(!e.error&&needsRuntimeProbe(e))return classifyRuntimeProbe(t,await probeChildRuntimeExecutable(t),t===N.initialPath?await h.stat(t).then(formatExecutableIdentity,()=>void 0):void 0,e.error)}function observeChildRuntime(e,t=process.execPath){let n=!1,r,i=``;return e.once(`message`,()=>{n=!0,i=``}),e.on(`error`,e=>{r??=e}),e.stderr?.on(`data`,e=>{n||(i=(i+e.toString()).slice(-8192))}),async()=>e.exitCode===0&&!r?void 0:prepareChildRuntimeFailure({execPath:t,error:r,stderr:i,signal:e.signalCode,started:n})}const I=x,L=e(Symbol.for(`openclaw.postgresIoPool`),()=>({endpoints:I?.postgresPool,workers:void 0,nextStep:void 0,ready:[],refresh:void 0,failure:void 0}));function recordPostgresPoolFailure(e){!L.nextStep&&!L.endpoints?.nextStep&&(L.failure??=e)}async function closePostgresPool(){let e=L.workers;L.workers=void 0;for(let{port:e}of L.endpoints?.services??[])e.close();L.endpoints=void 0,L.ready=[],L.refresh=void 0,L.failure=void 0,await Promise.all(e?.map(e=>e.terminate())??[])}const R=E(`openclaw.postgres.pool.self-root`);function startPool(){if(!y&&c()){let e={threadId:b,owner:a(process.argv[1]??``)};R.publish(e);let t=new g(`openclaw.postgres.pool.self-root`);t.unref(),t.postMessage(e),t.close(),r(`postgres`).warn(`PostgreSQL worker ${e.owner} (thread ${b}) has no inherited pool; starting its own four I/O services.`)}let e=new SharedArrayBuffer(4),t=Array.from({length:4},()=>({channel:new _,signal:new SharedArrayBuffer(8),peers:[]}));for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let{port1:r,port2:i}=new _;t[e].peers.push({port:r,signal:t[n].signal}),t[n].peers.push({port:i,signal:t[e].signal})}let n={services:t.map(({channel:e,signal:t})=>({port:e.port1,signal:t})),allocation:e,nextStep:L.nextStep},i=u(`postgresBridge`),o=s(i),d=[];L.endpoints=n,L.workers=d;let launch=e=>{let n=t[e],r=new Int32Array(n.signal),a=!1,s=new v(i,{workerData:{host:n.channel.port2,signal:n.signal,peers:n.peers},transferList:[n.channel.port2,...n.peers.map(({port:e})=>e)],execArgv:o});l(s,i),s.unref(),n.channel.port1.unref(),d[e]=s;let c=new Promise((e,t)=>{s.once(`error`,t),s.once(`exit`,()=>t(/* @__PURE__ */ Error(`PostgreSQL I/O service exited before readiness.${L.nextStep?` Run ${L.nextStep}.`:``}`))),s.once(`message`,()=>e())});c.catch(()=>{}),L.ready[e]=c,s.on(`error`,()=>{}),s.once(`exit`,()=>{a=!0,Atomics.store(r,1,1),Atomics.notify(r,1),f.add(e)}),Promise.resolve(Atomics.waitAsync(r,1,0).value).then(async()=>{a||await s.terminate()})},f=/* @__PURE__ */ new Set;L.refresh=()=>{for(let e of f){f.delete(e);let r={channel:new _,signal:new SharedArrayBuffer(8),peers:[]};t[e]=r,n.services[e]={port:r.channel.port1,signal:r.signal};for(let n=0;n<t.length;n++){if(n===e)continue;let i=t[n],{port1:a,port2:o}=new _;r.peers.push({port:a,signal:i.signal}),d[n].postMessage({watch:{port:o,signal:r.signal}},[o])}launch(e)}};try{for(let e=0;e<t.length;e++)launch(e)}catch(e){throw closePostgresPool(),e}return n}function getPostgresPool(){return L.nextStep||L.refresh?.(),L.endpoints??startPool()}function createPostgresPoolEndpoints(e=getDatabaseEngineSelection()){if(!L.endpoints&&(!e||!Object.values(e.effectiveEngines).includes(`postgres`)))return;let t=getPostgresPool();return{...t,services:t.services.map(({port:e,signal:t})=>{let n=new _;return e.postMessage({host:n.port2},[n.port2]),{port:n.port1,signal:t}})}}function postgresPoolTransferList(e){return e?.services.map(({port:e})=>e)??[]}function selectPostgresPoolService(){let e=getPostgresPool(),t=(Atomics.add(new Uint32Array(e.allocation),0,1)>>>0)%4;return{...e.services[t],nextStep:e.nextStep}}export{recordPostgresPoolFailure as a,observeChildRuntime as c,getDatabaseEngineInput as d,getDatabaseEngineSelection as f,selectPostgresPoolService as i,prepareChildRuntimeFailure as l,getPostgresPool as n,assertChildRuntimeAvailable as o,postgresPoolTransferList as r,classifyChildRuntimeFailure as s,createPostgresPoolEndpoints as t,getSpawnBroker as u};