UNPKG

eve

Version:

Filesystem-first framework for durable backend AI agents that run anywhere.

1 lines 2.06 kB
import{dirname,join}from"node:path";import{mkdir,rm,stat,writeFile}from"node:fs/promises";import{resolveSandboxCacheDirectory}from"#internal/application/paths.js";const LOCK_TIMEOUT_MS=900*1e3;async function waitForSandboxTemplatePrewarmLock(e){await waitForLockRelease(resolveSandboxTemplatePrewarmLockPath(e),e.log)}async function withSandboxTemplatePrewarmLock(e,t){let n=resolveSandboxTemplatePrewarmLockPath(e);await acquireLock(n);try{return await t()}finally{await rm(n,{force:!0,recursive:!0}).catch(()=>{})}}function resolveSandboxTemplatePrewarmLockPath(e){return join(resolveSandboxCacheDirectory(e.appRoot),`template-locks`,e.backendName,`${e.templateKey}.lock`)}async function acquireLock(r){let i=Date.now();for(;;){await mkdir(dirname(r),{recursive:!0});try{await mkdir(r),await writeFile(join(r,`owner.json`),`${JSON.stringify({createdAt:new Date().toISOString(),pid:process.pid})}\n`);return}catch(e){if(!isFileExistsError(e))throw e;await waitForExistingLock(r,i,void 0)}}}async function waitForLockRelease(e,t){let n=Date.now(),r=n+1e4;for(;;){try{await stat(e)}catch(e){if(isNotFoundError(e))return;throw e}let a=Date.now();if(t!==void 0&&a>=r){let e=Math.round((a-n)/1e3);t(e===0?`waiting for sandbox template prewarm to finish`:`waiting for sandbox template prewarm to finish (${e}s elapsed)`),r=a+1e4}await waitForExistingLock(e,n,t)}}async function waitForExistingLock(e,t,n){let a=await stat(e).catch(e=>{if(isNotFoundError(e))return null;throw e});if(a!==null){if(Date.now()-a.mtimeMs>18e5){n?.(`removing stale sandbox template prewarm lock`),await rm(e,{force:!0,recursive:!0}).catch(()=>{});return}if(Date.now()-t>LOCK_TIMEOUT_MS)throw Error(`Timed out waiting for sandbox template prewarm lock "${e}" after ${LOCK_TIMEOUT_MS}ms.`);await new Promise(e=>setTimeout(e,250))}}function isFileExistsError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`EEXIST`}function isNotFoundError(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}export{waitForSandboxTemplatePrewarmLock,withSandboxTemplatePrewarmLock};