openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 8.77 kB
JavaScript
import{createRequire}from"node:module";
//!src/gateway/worker-environments/workspace-quiescence-renew.generated.worker.mjs
const require=createRequire(import.meta.url);process.argv.splice(1,1);require("node:child_process");const crypto=require("node:crypto");const fs=require("node:fs");const os=require("node:os");const path=require("node:path");const root=fs.realpathSync(process.argv[1]);const workspaceKey=crypto.createHash(`sha256`).update(root).digest(`hex`);const leaseDirectory=path.join(os.homedir(),`.openclaw-worker`,`quiescence`);const windowsLeaseDatabasePath=path.join(leaseDirectory,`windows-shared-host.sqlite`);const nonce=process.argv[2];const leasePath=path.join(leaseDirectory,workspaceKey+`.`+nonce+`.json`);function validProcessReference(e){return e&&Number.isSafeInteger(e.pid)&&e.pid>0&&typeof e.start===`string`&&e.start.length>0&&e.start.length<=128}function parseLease(e,t,n={}){const r=JSON.parse(e);if(!r||r.version!==1||r.nonce!==t||r.sharedHost!==void 0&&typeof r.sharedHost!==`boolean`||!Array.isArray(r.processes)||r.processes.length>4096||r.processes.some(e=>!validProcessReference(e))||r.watchdog!==null&&!validProcessReference(r.watchdog)||r.recoveryError!==void 0&&typeof r.recoveryError!==`string`||!Number.isSafeInteger(r.expiresAtMs)||r.expiresAtMs<1)throw new Error(n.errorMessage||`invalid workspace quiescence lease`);if(r.recoveryError)process.stderr.write(r.recoveryError+`
`);if(n.requireWatchdog&&r.watchdog===null||n.minimumRemainingMs&&r.expiresAtMs-Date.now()<n.minimumRemainingMs)throw new Error(n.errorMessage||`invalid workspace quiescence lease`);return r}function parseWindowsLease(e,t,n){const r=parseLease(e,t,n);if(r.sharedHost!==true||r.processes.length!==0||r.watchdog!==null)throw new Error(`invalid Windows shared-host workspace quiescence lease`);return r}function persistLease(e,t,n){const r=require("node:fs");const i=require("node:crypto");if(n)n(JSON.parse(r.readFileSync(e,`utf8`)));const a=e+`.`+process.pid+`.`+i.randomBytes(8).toString(`hex`);r.writeFileSync(a,JSON.stringify(t),{mode:384,flag:`wx`});r.renameSync(a,e)}function withWindowsWorkspaceLease(e,t,n){const{DatabaseSync:r}=require("node:sqlite");const i=new r(e);try{i.exec(`PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL; BEGIN IMMEDIATE`);if(!i.prepare(`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'workspace_leases'`).get())i.exec(`CREATE TABLE IF NOT EXISTS workspace_leases (workspace_key TEXT PRIMARY KEY, lease_json TEXT NOT NULL)`);i.prepare(`DELETE FROM workspace_leases WHERE json_extract(lease_json, '$.expiresAtMs') <= ?`).run(Date.now());const e=i.prepare(`SELECT lease_json FROM workspace_leases WHERE workspace_key = ?`).get(t);const r=n(e?e.lease_json:null);if(r===null)i.prepare(`DELETE FROM workspace_leases WHERE workspace_key = ?`).run(t);else if(r!==void 0)i.prepare(`INSERT INTO workspace_leases (workspace_key, lease_json) VALUES (?, ?) ON CONFLICT(workspace_key) DO UPDATE SET lease_json = excluded.lease_json`).run(t,r);i.exec(`COMMIT`);return r}catch(e){if(i.isTransaction)i.exec(`ROLLBACK`);throw e}finally{i.close()}}function createProcessProbe(){const e=performance.now()+3e4;let t=false;return(n,r)=>{let i=2e3;for(;;){const a=Math.ceil(e-performance.now());if(a<=0){const e=`workspace quiescence process check budget exhausted after 30000 ms; check host load and ps availability`;process.stderr.write(e+`
`);throw Object.assign(/* @__PURE__ */ new Error(e),{code:`WORKSPACE_PROBE_BUDGET_EXHAUSTED`})}try{return require("node:child_process").execFileSync(`ps`,n,{encoding:`utf8`,maxBuffer:r,timeout:Math.min(i,a),killSignal:`SIGKILL`})}catch(e){if(!e||e.code!==`ETIMEDOUT`)throw e;if(!t){process.stderr.write(`workspace quiescence: slow ps check; retrying within the shared 30000 ms budget
`);t=true}i*=2}}}}let processProbe=createProcessProbe();function processes(){const e=processProbe([`-axo`,`pid=,ppid=,uid=,stat=,lstart=`],4194304);const t=/* @__PURE__ */ new Map;for(const n of e.split(`
`)){const e=n.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);if(!e)continue;t.set(Number(e[1]),{ppid:Number(e[2]),uid:Number(e[3]),state:e[4],start:e[5]})}return t}function ancestors(e){const t=/* @__PURE__ */ new Set;let n=process.pid;while(n>0&&!t.has(n)){t.add(n);n=e.get(n)?.ppid||0}return t}function processIdentity(e,t=false){try{const n=processProbe([`-o`,t?`stat=,lstart=`:`lstart=`,`-p`,String(e)],4096).trim();if(!t)return n||null;const r=/^(\S+)\s+(.+)$/u.exec(n);return r?{state:r[1],start:r[2]}:null}catch(e){if(e&&e.status===1)return null;throw e}}function quiescenceCandidates(e,t,n,r){const i=ancestors(e);return[...e.entries()].filter(([e,a])=>a.uid===t&&!i.has(e)&&a.ppid!==process.pid&&!n.has(e)&&(!r||!r.has(e))&&!a.state.startsWith(`T`)&&!a.state.startsWith(`Z`)&&!a.state.startsWith(`X`))}function freezeWorkspaceProcesses(e,t,n,r=false){let i=0;const a=new Int32Array(new SharedArrayBuffer(4));const refresh=()=>n([...t].map(([e,t])=>({pid:e,start:t})));for(let n=0;n<250&&i<3;n+=1){const n=quiescenceCandidates(processes(),process.getuid(),/* @__PURE__ */ new Set([e.watchdog.pid]),r?t:void 0);if(n.length+t.size>4096)throw new Error(`too many worker processes to quiesce safely`);if(!r){for(const[e,r]of n)t.set(e,r.start);refresh()}for(const[i,a]of n)try{if(r){t.set(i,a.start);refresh()}else if(e.expiresAtMs-Date.now()<5e3)refresh();if((r?processIdentity(i):processIdentity(i,true)?.start)!==a.start){t.delete(i);if(r)refresh();continue}if(!r&&e.expiresAtMs-Date.now()<2500)refresh();process.kill(i,`SIGSTOP`)}catch(e){if(!e||e.code!==`ESRCH`&&e.code!==`EPERM`)throw e;if(!r||e.code===`EPERM`){t.delete(i);if(r)refresh()}}if(!r)refresh();Atomics.wait(a,0,0,20);i=quiescenceCandidates(processes(),process.getuid(),/* @__PURE__ */ new Set([e.watchdog.pid])).length>0||!r&&n.length>0?0:i+1}if(i<3)throw new Error(`worker processes did not `+(r?`reach`:`return to`)+` a quiescent state`)}function renewWorkspaceLease(e,t,n,r){if(!/^[a-f0-9]{32}$/.test(nonce||``))throw new Error(`invalid workspace quiescence nonce`);if(!Number.isSafeInteger(e)||e<1e4)throw new Error(`invalid watchdog timeout`);if(t!==`heartbeat`&&t!==`final`)throw new Error(`invalid workspace quiescence validation mode`);if(n!==`dedicated`&&n!==`shared-host`)throw new Error(`invalid workspace quiescence isolation mode`);const i=n===`shared-host`;if(process.platform===`win32`&&i){withWindowsWorkspaceLease(windowsLeaseDatabasePath,workspaceKey,t=>{if(t===null)throw new Error(`workspace quiescence lease is no longer active`);const n={...parseWindowsLease(t,nonce,{minimumRemainingMs:5e3,errorMessage:`workspace quiescence lease is no longer active`}),expiresAtMs:Date.now()+e};return JSON.stringify(n)});return`renewed `+nonce+`
`}if(typeof process.getuid!==`function`)throw new Error(`workspace quiescence requires POSIX`);const a=parseLease(fs.readFileSync(leasePath,`utf8`),nonce,{requireWatchdog:true,minimumRemainingMs:5e3,errorMessage:`workspace quiescence lease is no longer active`});if(a.sharedHost===true!==i)throw new Error(`workspace quiescence isolation mode changed`);function assertWatchdogActive(){if(r){if(a.sharedHost!==true||a.processes.length!==0||a.watchdog.pid!==r.pid||a.watchdog.start!==r.start)throw new Error(`native quiescence lease changed its process scope or watchdog`);return}const e=processIdentity(a.watchdog.pid,true);if(!e||e.start!==a.watchdog.start)throw new Error(`workspace quiescence watchdog identity changed unexpectedly`);try{process.kill(a.watchdog.pid,0)}catch(e){if(e&&e.code===`ESRCH`)throw new Error(`workspace quiescence watchdog exited unexpectedly`,{cause:e});throw e}}function refreshLease(t){assertWatchdogActive();a.expiresAtMs=Date.now()+e;persistLease(leasePath,{...a,processes:t},e=>{if(e.nonce!==nonce||e.watchdog?.pid!==a.watchdog.pid||e.watchdog?.start!==a.watchdog.start)throw new Error(`workspace quiescence lease changed during renewal`);if(e.expiresAtMs<=Date.now())throw new Error(`workspace quiescence lease expired during process checking`)})}assertWatchdogActive();for(const e of a.processes){const t=processIdentity(e.pid,true);if(!t||t.start!==e.start)continue;if(t.state&&!t.state.startsWith(`T`))throw new Error(`workspace quiescence process resumed unexpectedly`)}if(t===`final`&&!i){refreshLease(a.processes);const e=new Map(a.processes.map(e=>[e.pid,e.start]));freezeWorkspaceProcesses(a,e,refreshLease);a.processes=[...e].map(([e,t])=>({pid:e,start:t}))}refreshLease(a.processes);const o=JSON.parse(fs.readFileSync(leasePath,`utf8`));if(o.nonce!==nonce||o.expiresAtMs!==a.expiresAtMs)throw new Error(`workspace quiescence renewal was not durable`);return`renewed `+nonce+`
`}process.stdout.write(renewWorkspaceLease(Number(process.argv[3]||72e4),process.argv[4]||`final`,process.argv[5]||`dedicated`));export{};