Repository navigation
Expand file tree
/
Copy pathstore-lock.js
More file actions
200 lines (185 loc) · 5.67 KB
/
Copy pathstore-lock.js
File metadata and controls
200 lines (185 loc) · 5.67 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import fs from 'fs';
import path from 'path';
import { randomUUID } from 'crypto';
import Database from 'better-sqlite3';
function lockPayload(options = {}) {
return {
pid: process.pid,
startedAt: new Date().toISOString(),
...options,
};
}
export function readStoreLock(storeDir) {
const lockPath = path.join(storeDir, 'LOCK');
try {
const raw = fs.readFileSync(lockPath, 'utf8');
return {
exists: true,
path: lockPath,
info: raw.trim(),
};
} catch (error) {
if (error.code === 'ENOENT') {
return { exists: false, path: lockPath, info: null };
}
throw error;
}
}
export function isPidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (error) {
if (error?.code === 'ESRCH') return false;
if (error?.code === 'EPERM') return true;
throw error;
}
}
export function parseStoreLock(raw) {
try {
const parsed = JSON.parse(raw);
return parsed && typeof parsed.pid === 'number' ? parsed : null;
} catch {
return null;
}
}
function parseLockPid(raw) {
return parseStoreLock(raw)?.pid ?? null;
}
function removeStaleLockFile(lockPath, pid, label) {
try {
fs.unlinkSync(lockPath);
} catch (error) {
if (error?.code === 'ENOENT') {
return;
}
const details = error?.message ? `: ${error.message}` : '';
throw new Error(`Found stale ${label} for dead pid ${pid}, but could not remove ${lockPath}${details}`);
}
}
function getAliveReadLocks(storeDir) {
let entries;
try {
entries = fs.readdirSync(storeDir);
} catch {
return [];
}
const alive = [];
for (const name of entries) {
if (!name.startsWith('LOCK.read.')) continue;
const filePath = path.join(storeDir, name);
let raw;
try { raw = fs.readFileSync(filePath, 'utf8').trim(); } catch { continue; }
const pid = parseLockPid(raw);
if (!pid) continue;
if (isPidAlive(pid)) {
alive.push({ name, pid });
} else {
removeStaleLockFile(filePath, pid, 'read lock');
}
}
return alive;
}
export function acquireOwnerLock(storeDir, options = {}) {
const lockPath = path.join(storeDir, 'LOCK');
fs.mkdirSync(storeDir, { recursive: true });
// Check for alive read locks before acquiring write lock
const aliveReaders = getAliveReadLocks(storeDir);
if (aliveReaders.length > 0) {
const pids = aliveReaders.map(r => r.pid).join(', ');
throw new Error(`Store has active readers (pids: ${pids}), cannot acquire write lock`);
}
const ownerId = randomUUID();
const details = lockPayload({
ownerId,
kind: options.kind ?? 'transient',
state: options.state ?? 'transient',
protocolVersion: options.protocolVersion ?? 1,
socketPath: options.socketPath ?? null,
});
// This independent SQLite transaction is the lifetime ownership guard. The OS
// releases it after an abrupt exit, so stale metadata cannot strand the store.
const guardPath = path.join(storeDir, 'LOCK.guard.db');
const guard = new Database(guardPath, { timeout: 0 });
fs.chmodSync(guardPath, 0o600);
let guardHeld = false;
try {
try {
guard.exec('BEGIN IMMEDIATE');
guardHeld = true;
} catch (error) {
if (error.code === 'SQLITE_BUSY') {
throw new Error('Store is locked by another process');
}
throw error;
}
const reclaimPath = `${lockPath}.reclaim`;
if (fs.existsSync(reclaimPath)) {
const reclaimPid = parseLockPid(fs.readFileSync(reclaimPath, 'utf8'));
if (!reclaimPid || isPidAlive(reclaimPid)) {
throw new Error('Store lock recovery is already in progress');
}
removeStaleLockFile(reclaimPath, reclaimPid, 'recovery lock');
}
const current = readStoreLock(storeDir);
if (current.exists) {
const pid = parseLockPid(current.info);
if (!pid || isPidAlive(pid)) {
const extra = current.info ? ` (${current.info})` : '';
throw new Error(`Store is locked by another process${extra}`);
}
removeStaleLockFile(lockPath, pid, 'store lock');
}
const fd = fs.openSync(lockPath, 'wx', 0o600);
try {
fs.writeFileSync(fd, JSON.stringify(details));
} finally {
fs.closeSync(fd);
}
} catch (error) {
if (guardHeld) guard.exec('ROLLBACK');
guard.close();
throw error;
}
let released = false;
const update = (patch) => {
if (released) throw new Error('Cannot update a released store lock');
const current = parseStoreLock(readStoreLock(storeDir).info);
if (current?.ownerId !== ownerId) throw new Error('Store lock ownership changed');
Object.assign(details, patch);
const tempPath = `${lockPath}.${ownerId}.tmp`;
try {
fs.writeFileSync(tempPath, JSON.stringify(details), { mode: 0o600 });
fs.renameSync(tempPath, lockPath);
} finally {
try { fs.unlinkSync(tempPath); } catch (error) {
if (error?.code !== 'ENOENT') throw error;
}
}
};
const release = () => {
if (released) {
return;
}
try {
const current = parseStoreLock(readStoreLock(storeDir).info);
if (current?.ownerId !== ownerId) throw new Error('Store lock ownership changed');
fs.unlinkSync(lockPath);
} catch (error) {
if (error.code !== 'ENOENT') throw error;
} finally {
released = true;
guard.exec('ROLLBACK');
guard.close();
}
};
return { info: details, update, release };
}
export function acquireStoreLock(storeDir) {
return acquireOwnerLock(storeDir).release;
}
export function acquireReadLock(storeDir) {
// Legacy callers open writable services and a Telegram session even for reads.
// Until they use the read-only archive or owner IPC, they need exclusive ownership.
return acquireStoreLock(storeDir);
}