(
launcherRoot: string,
opts: WorkspaceProcessLockOptions = {},
)
| 44 | * and the owner token keeps a stale handle from deleting a newer lock. |
| 45 | */ |
| 46 | export async function acquireWorkspaceProcessLock( |
| 47 | launcherRoot: string, |
| 48 | opts: WorkspaceProcessLockOptions = {}, |
| 49 | ): Promise<WorkspaceProcessLock> { |
| 50 | const lockDir = join(launcherRoot, LOCK_DIR_REL) |
| 51 | const owner: WorkspaceRootLockOwner = { |
| 52 | pid: opts.owner?.pid ?? process.pid, |
| 53 | hostname: opts.owner?.hostname ?? osHostname(), |
| 54 | token: randomUUID(), |
| 55 | acquiredAt: new Date().toISOString(), |
| 56 | } |
| 57 | const isProcessAlive = opts.isProcessAlive ?? defaultIsProcessAlive |
| 58 | |
| 59 | for (let attempt = 0; attempt < 3; attempt++) { |
| 60 | try { |
| 61 | await mkdir(lockDir) |
| 62 | await writeOwner(lockDir, owner) |
| 63 | return makeLock(lockDir, owner) |
| 64 | } catch (err) { |
| 65 | if (!isErrno(err, 'ENOENT') && !isErrno(err, 'EEXIST')) throw err |
| 66 | if (isErrno(err, 'ENOENT')) { |
| 67 | await mkdir(dirname(lockDir), { recursive: true }) |
| 68 | continue |
| 69 | } |
| 70 | |
| 71 | const existing = await readOwner(lockDir).catch(() => null) |
| 72 | if (existing && isProcessAlive(existing.pid, existing.hostname)) { |
| 73 | throw new WorkspaceRootLockedError(lockDir, existing) |
| 74 | } |
| 75 | await rm(lockDir, { recursive: true, force: true }) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | const existing = await readOwner(lockDir).catch(() => null) |
| 80 | throw new WorkspaceRootLockedError(lockDir, existing) |
| 81 | } |
| 82 | |
| 83 | function makeLock(lockDir: string, owner: WorkspaceRootLockOwner): WorkspaceProcessLock { |
| 84 | return { |
no test coverage detected