( baseDir: string, lockPath: string, lockData: DaemonLockInfo, )
| 69 | } |
| 70 | |
| 71 | export function acquireDaemonLock( |
| 72 | baseDir: string, |
| 73 | lockPath: string, |
| 74 | lockData: DaemonLockInfo, |
| 75 | ): boolean { |
| 76 | if (!fs.existsSync(baseDir)) fs.mkdirSync(baseDir, { recursive: true }); |
| 77 | const payload = JSON.stringify(lockData, null, 2); |
| 78 | |
| 79 | const tryWriteLock = (): boolean => { |
| 80 | try { |
| 81 | fs.writeFileSync(lockPath, payload, { flag: 'wx', mode: 0o600 }); |
| 82 | return true; |
| 83 | } catch (err) { |
| 84 | if ((err as NodeJS.ErrnoException).code === 'EEXIST') return false; |
| 85 | throw err; |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | if (tryWriteLock()) return true; |
| 90 | const existing = readLockInfo(lockPath); |
| 91 | if ( |
| 92 | existing?.pid && |
| 93 | existing.pid !== process.pid && |
| 94 | isAgentDeviceDaemonProcess(existing.pid, existing.processStartTime) |
| 95 | ) { |
| 96 | return false; |
| 97 | } |
| 98 | try { |
| 99 | fs.unlinkSync(lockPath); |
| 100 | } catch {} |
| 101 | return tryWriteLock(); |
| 102 | } |
| 103 | |
| 104 | export function releaseDaemonLock(lockPath: string): void { |
| 105 | const existing = readLockInfo(lockPath); |
no test coverage detected