MCPcopy Create free account
hub / github.com/TraderAlice/OpenAlice / acquireWorkspaceProcessLock

Function acquireWorkspaceProcessLock

src/workspaces/process-lock.ts:46–81  ·  view source on GitHub ↗
(
  launcherRoot: string,
  opts: WorkspaceProcessLockOptions = {},
)

Source from the content-addressed store, hash-verified

44 * and the owner token keeps a stale handle from deleting a newer lock.
45 */
46export 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
83function makeLock(lockDir: string, owner: WorkspaceRootLockOwner): WorkspaceProcessLock {
84 return {

Callers 2

createWorkspaceServiceFunction · 0.85

Calls 4

writeOwnerFunction · 0.85
makeLockFunction · 0.85
isErrnoFunction · 0.85
readOwnerFunction · 0.85

Tested by

no test coverage detected