Repository navigation
Expand file tree
/
Copy pathprocess-lock.js
More file actions
54 lines (49 loc) · 1.36 KB
/
Copy pathprocess-lock.js
File metadata and controls
54 lines (49 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
function isPidAlive(pid) {
const numeric = Number(pid);
if (!Number.isFinite(numeric) || numeric <= 0) return false;
try {
process.kill(numeric, 0);
return true;
} catch {
return false;
}
}
function readLock(path) {
try {
return JSON.parse(readFileSync(path, 'utf8'));
} catch {
return null;
}
}
export function acquireProcessLock(lockPath, metadata = {}) {
const payload = {
pid: process.pid,
acquiredAt: new Date().toISOString(),
...metadata
};
while (true) {
try {
const fd = openSync(lockPath, 'wx');
writeFileSync(fd, JSON.stringify(payload, null, 2));
closeSync(fd);
return { acquired: true, ownerPid: process.pid };
} catch (error) {
if (error?.code !== 'EEXIST') throw error;
const current = readLock(lockPath);
const ownerPid = Number(current?.pid);
if (isPidAlive(ownerPid)) {
return { acquired: false, ownerPid };
}
try { unlinkSync(lockPath); } catch {}
if (existsSync(lockPath)) {
return { acquired: false, ownerPid: ownerPid || null };
}
}
}
}
export function releaseProcessLock(lockPath) {
const current = readLock(lockPath);
if (Number(current?.pid) !== process.pid) return;
try { unlinkSync(lockPath); } catch {}
}