-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-lock.ts
More file actions
508 lines (464 loc) · 18.1 KB
/
Copy pathfile-lock.ts
File metadata and controls
508 lines (464 loc) · 18.1 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/**
* File-based mutex for serializing access to the JSONL data file.
*
* Uses an advisory lock file created with O_CREAT | O_EXCL (atomic
* create-if-not-exists) to ensure only one process at a time can
* perform read-merge-write operations on the shared data file.
*
* The lock file contains the holder's PID, hostname, and acquisition
* timestamp so that stale locks left behind by crashed processes can
* be detected and cleaned up automatically.
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface FileLockOptions {
/** Delay in milliseconds between retry attempts (default 100). This is the initial delay; with exponential backoff it increases on each attempt. */
retryDelay?: number;
/** Overall timeout in milliseconds (default 30 000). The retry loop runs until this deadline is reached. */
timeout?: number;
/** If true, stale locks from dead processes are automatically removed (default true). */
staleLockCleanup?: boolean;
/** Maximum age of a lock file in milliseconds before it is treated as stale regardless of PID status (default 300 000 = 5 minutes). */
maxLockAge?: number;
/** Maximum delay in milliseconds between retry attempts after exponential growth (default 2 000). */
maxRetryDelay?: number;
/** If true and the lock is currently held by a live process, fail fast with a `LockBusyError` instead of retrying until the timeout. Stale/age-expired locks are still cleaned up first. Used by `wl sync --if-idle` so auto-sync spawners skip instead of queueing (lock-storm prevention). */
skipIfLocked?: boolean;
}
/**
* Thrown when `skipIfLocked` is set and the file lock is currently held by
* a live process. Callers (e.g. `wl sync --if-idle`) treat this as "skip —
* another sync is already running" rather than an error.
*/
export class LockBusyError extends Error {
constructor(lockPath: string) {
super(`File lock busy at ${lockPath}; another process holds it`);
this.name = 'LockBusyError';
}
}
export interface FileLockInfo {
pid: number;
hostname: string;
acquiredAt: string; // ISO-8601
}
// ---------------------------------------------------------------------------
// Defaults
// ---------------------------------------------------------------------------
const DEFAULT_RETRY_DELAY_MS = 100;
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_LOCK_AGE_MS = 300_000; // 5 minutes
const DEFAULT_MAX_RETRY_DELAY_MS = 2_000;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
* Emit a debug log line to stderr when `WL_DEBUG` is set.
* All messages are prefixed with `[wl:lock]` for easy filtering.
* When `WL_DEBUG` is not set, this is a no-op with negligible overhead.
*/
function debugLog(...args: unknown[]): void {
if (process.env.WL_DEBUG) {
process.stderr.write(`[wl:lock] ${args.map(String).join(' ')}\n`);
}
}
/**
* Derive the lock file path for a given JSONL data file path.
*
* Example: `/path/to/.worklog/worklog-data.jsonl` → `/path/to/.worklog/worklog-data.jsonl.lock`
*/
export function getLockPathForJsonl(jsonlPath: string): string {
return `${jsonlPath}.lock`;
}
/**
* Check whether a process with the given PID is still running.
* Uses `process.kill(pid, 0)` which sends signal 0 (no-op) — it
* throws ESRCH if the process does not exist, and EPERM if we
* lack permission (but the process *does* exist).
*/
export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true; // signal sent successfully — process is alive
} catch (err: any) {
if (err.code === 'ESRCH') {
return false; // no such process
}
// EPERM means the process exists but we can't signal it — treat as alive
return true;
}
}
/**
* Try to read and parse lock file contents. Returns null if the file
* does not exist or cannot be parsed.
*/
export function readLockInfo(lockPath: string): FileLockInfo | null {
try {
const content = fs.readFileSync(lockPath, 'utf-8');
const info = JSON.parse(content) as FileLockInfo;
if (typeof info.pid === 'number' && typeof info.hostname === 'string') {
return info;
}
return null;
} catch {
return null;
}
}
/**
* Read the raw lock file and indicate whether it parsed and whether
* required fields are present. This lets callers distinguish between
* "unparseable/garbage" (apply grace window) and "valid JSON but
* missing required fields" (treat as immediately corrupted/stale).
*/
export function readRawLock(lockPath: string): { parsed: boolean; info?: FileLockInfo; missingFields?: boolean } {
try {
const content = fs.readFileSync(lockPath, 'utf-8');
const parsed = JSON.parse(content);
if (parsed && typeof parsed === 'object') {
const info = parsed as FileLockInfo;
if (typeof info.pid === 'number' && typeof info.hostname === 'string') {
return { parsed: true, info };
}
return { parsed: true, missingFields: true };
}
return { parsed: true, missingFields: true };
} catch {
return { parsed: false };
}
}
/**
* Synchronous sleep using `Atomics.wait`. Blocks the calling thread
* for the requested number of milliseconds **without** busy-waiting,
* so CPU usage during the sleep is negligible.
*
* Note: `Atomics.wait` is supported in Node.js on all platforms
* (Linux, macOS, Windows / WSL2). It throws in browser main threads,
* but this is a Node.js CLI tool so that is not a concern.
*/
export function sleepSync(ms: number): void {
if (ms <= 0) return;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
/**
* Format a lock's `acquiredAt` timestamp into a human-readable relative
* age string such as "12 minutes ago" or "3 seconds ago".
*
* Exported so that the `wl unlock` command can reuse it.
*/
export function formatLockAge(acquiredAt: string): string {
const ageMs = Date.now() - new Date(acquiredAt).getTime();
if (ageMs <= 0) {
return 'just now';
}
const seconds = Math.floor(ageMs / 1000);
if (seconds < 60) {
return `${seconds} ${seconds === 1 ? 'second' : 'seconds'} ago`;
}
const minutes = Math.floor(seconds / 60);
if (minutes < 60) {
return `${minutes} ${minutes === 1 ? 'minute' : 'minutes'} ago`;
}
const hours = Math.floor(minutes / 60);
return `${hours} ${hours === 1 ? 'hour' : 'hours'} ago`;
}
/**
* Build an enriched error message for lock acquisition failure.
* Includes lock file path, holder metadata, computed age, and recovery guidance.
*/
function buildLockErrorMessage(
lockPath: string,
reason: string,
lockInfo: FileLockInfo | null,
): string {
const lines: string[] = [`Failed to acquire file lock at ${lockPath} (${reason})`];
if (lockInfo) {
const age = formatLockAge(lockInfo.acquiredAt);
lines.push(` Held by PID ${lockInfo.pid} on ${lockInfo.hostname} since ${lockInfo.acquiredAt} (${age})`);
} else {
lines.push(' Lock file appears corrupted (corrupted lock file)');
}
lines.push(" Run 'wl unlock' to remove the stale lock.");
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Reentrancy tracking
// ---------------------------------------------------------------------------
/**
* Per-path counter tracking how many times the current process has acquired
* a lock via `withFileLock`. When the counter is > 0 for a given path the
* process already owns the lock and nested calls to `withFileLock` become
* transparent pass-throughs (no acquire / release).
*
* This is safe because Node.js is single-threaded — the map is only accessed
* from the same event-loop turn that called `withFileLock`.
*/
const heldLocks: Map<string, number> = new Map();
/**
* Resolve a lock path to its canonical (absolute, real) form so that
* different relative references to the same file share one counter.
*/
function canonicalLockPath(lockPath: string): string {
return path.resolve(lockPath);
}
// ---------------------------------------------------------------------------
// Core API
// ---------------------------------------------------------------------------
/**
* Attempt to acquire a file lock at `lockPath`.
*
* On success the lock file is created (atomically via `O_EXCL`) and
* populated with the current process's PID, hostname, and timestamp.
*
* On failure (lock already held by a live process and retries exhausted)
* an error is thrown.
*/
export function acquireFileLock(lockPath: string, options?: FileLockOptions): void {
const retryDelay = options?.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
const timeout = options?.timeout ?? DEFAULT_TIMEOUT_MS;
const staleLockCleanup = options?.staleLockCleanup ?? true;
const maxLockAge = options?.maxLockAge ?? DEFAULT_MAX_LOCK_AGE_MS;
const maxRetryDelay = options?.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY_MS;
const skipIfLocked = options?.skipIfLocked ?? false;
const deadline = Date.now() + timeout;
const lockInfo: FileLockInfo = {
pid: process.pid,
hostname: os.hostname(),
acquiredAt: new Date().toISOString(),
};
const lockContent = JSON.stringify(lockInfo);
// Ensure the parent directory exists
const lockDir = path.dirname(lockPath);
if (!fs.existsSync(lockDir)) {
fs.mkdirSync(lockDir, { recursive: true });
}
let currentDelay = retryDelay;
let attempt = 0;
while (true) {
// Check timeout
if (Date.now() > deadline) {
const existingInfo = readLockInfo(lockPath);
debugLog(`Timeout after ${timeout}ms waiting for lock at ${lockPath}`);
throw new Error(
buildLockErrorMessage(lockPath, `${timeout}ms timeout`, existingInfo)
);
}
try {
// O_CREAT | O_EXCL | O_WRONLY — atomic create-if-not-exists
const fd = fs.openSync(lockPath, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY);
fs.writeSync(fd, lockContent);
// fsync to ensure the lock content is visible to other processes
// before we release the fd — prevents a concurrent reader from
// seeing an empty or partial file.
fs.fsyncSync(fd);
fs.closeSync(fd);
debugLog(`Lock acquired at ${lockPath} (PID ${process.pid}, attempt ${attempt + 1})`);
return; // lock acquired
} catch (err: any) {
if (err.code !== 'EEXIST') {
// Unexpected error (permissions, disk full, etc.)
throw new Error(`Failed to create lock file at ${lockPath}: ${err.message}`);
}
// Lock file already exists — check for stale lock
if (staleLockCleanup) {
// Use readRawLock to distinguish between unparseable content and
// parsed JSON that is missing required fields (pid/hostname).
const raw = readRawLock(lockPath);
const existing = raw.info ?? null;
if (raw.parsed && raw.missingFields) {
// Valid JSON but missing required fields — treat as corrupted/stale
// and remove immediately. This matches test expectations and
// avoids waiting the grace window for what is likely a bogus file.
debugLog(`Corrupted lock file (valid JSON but missing fields), removing ${lockPath}`);
try {
fs.unlinkSync(lockPath);
continue;
} catch {
// Another process may have removed it; retry
continue;
}
}
if (existing) {
const sameHost = existing.hostname === os.hostname();
if (sameHost && !isProcessAlive(existing.pid)) {
// Stale lock from a dead process on this host — remove it
debugLog(`Stale lock detected: PID ${existing.pid} is dead, removing ${lockPath}`);
try {
fs.unlinkSync(lockPath);
// Don't increment attempt counter; retry immediately
continue;
} catch {
// Another process may have removed it; retry
continue;
}
}
// Age-based expiry: if the lock is older than maxLockAge,
// treat it as stale regardless of PID status. This handles
// PID recycling and environments where PID checks are unreliable.
// Guard against clock skew: only expire if age is positive.
const lockAge = Date.now() - new Date(existing.acquiredAt).getTime();
if (lockAge > 0 && lockAge > maxLockAge) {
debugLog(`Stale lock detected: age-expired (${lockAge}ms > ${maxLockAge}ms), removing ${lockPath}`);
try {
fs.unlinkSync(lockPath);
continue;
} catch {
// Another process may have removed it; retry
continue;
}
}
} else if (fs.existsSync(lockPath)) {
// Lock file exists but could not be parsed (garbage, empty), or
// we already handled parsed-but-missing-fields above. For unparseable
// content we must be conservative: it may be a concurrent writer
// that hasn't finished writing+fsyncing yet. Use a small grace
// window before removing to avoid races.
try {
const stat = fs.statSync(lockPath);
const fileAge = Date.now() - stat.mtimeMs;
const graceMs = 1000;
if (fileAge > graceMs) {
debugLog(`Stale lock detected: corrupted lock file (age ${Math.round(fileAge)}ms > grace ${graceMs}ms), removing ${lockPath}`);
try {
fs.unlinkSync(lockPath);
continue;
} catch {
// Another process may have removed it; retry
continue;
}
} else {
debugLog(`Lock file unparseable but young (age ${Math.round(fileAge)}ms < grace ${graceMs}ms), assuming in-flight write`);
}
} catch {
// stat failed (file removed between existsSync and statSync) — retry
continue;
}
}
}
// Lock is held by a live process (or on another host) — wait and retry
// unless the caller asked to skip (lock-aware guard: auto-sync paths use
// this so concurrent panes/TUI instances do not pile up waiting).
if (skipIfLocked) {
const existingInfo = readLockInfo(lockPath);
debugLog(`Lock busy at ${lockPath} and skipIfLocked set; skipping (PID ${existingInfo?.pid ?? 'unknown'})`);
throw new LockBusyError(lockPath);
}
const remaining = deadline - Date.now();
if (remaining <= 0) {
// Will be caught by the timeout check at the top of the loop
continue;
}
// Exponential backoff with jitter
const jitter = Math.random() * currentDelay * 0.25;
const sleepMs = Math.min(currentDelay + jitter, remaining);
debugLog(`Retry attempt ${attempt + 1}: sleeping ${Math.round(sleepMs)}ms (base delay ${Math.round(currentDelay)}ms)`);
sleepSync(sleepMs);
// Grow delay for next iteration (1.5x multiplier, capped)
currentDelay = Math.min(currentDelay * 1.5, maxRetryDelay);
attempt++;
}
}
}
/**
* Release a previously acquired file lock by removing the lock file.
* It is safe to call this even if the lock file does not exist (no-op).
*/
export function releaseFileLock(lockPath: string): void {
try {
fs.unlinkSync(lockPath);
debugLog(`Lock released at ${lockPath} (PID ${process.pid})`);
} catch (err: any) {
if (err.code !== 'ENOENT') {
// If the file doesn't exist, that's fine — lock was already released.
// Any other error is unexpected.
throw new Error(`Failed to release file lock at ${lockPath}: ${err.message}`);
}
}
}
/**
* Execute `fn` while holding the file lock at `lockPath`.
*
* The lock is acquired before `fn` is called and released in a
* `finally` block — even if `fn` throws. Supports both synchronous
* and asynchronous callbacks.
*
* **Reentrancy:** If the current process already holds the lock for
* `lockPath` (via a surrounding `withFileLock` call), the nested
* invocation is a transparent pass-through — `fn` runs immediately
* without touching the lock file.
*/
export function withFileLock<T>(
lockPath: string,
fn: () => T,
options?: FileLockOptions
): T {
const canonical = canonicalLockPath(lockPath);
const depth = heldLocks.get(canonical) ?? 0;
if (depth > 0) {
// Already holding this lock — reentrant call, just run fn.
heldLocks.set(canonical, depth + 1);
try {
const result = fn();
if (result instanceof Promise) {
return result.then(
(value) => {
heldLocks.set(canonical, (heldLocks.get(canonical) ?? 1) - 1);
return value;
},
(err) => {
heldLocks.set(canonical, (heldLocks.get(canonical) ?? 1) - 1);
throw err;
}
) as T;
}
heldLocks.set(canonical, depth);
return result;
} catch (err) {
heldLocks.set(canonical, depth);
throw err;
}
}
// First acquisition — acquire the file lock.
acquireFileLock(lockPath, options);
heldLocks.set(canonical, 1);
try {
const result = fn();
// If fn returns a promise, chain the release onto it
if (result instanceof Promise) {
return result.then(
(value) => {
heldLocks.delete(canonical);
releaseFileLock(lockPath);
return value;
},
(err) => {
heldLocks.delete(canonical);
releaseFileLock(lockPath);
throw err;
}
) as T;
}
heldLocks.delete(canonical);
releaseFileLock(lockPath);
return result;
} catch (err) {
heldLocks.delete(canonical);
releaseFileLock(lockPath);
throw err;
}
}
/**
* Check whether the current process holds the file lock at `lockPath`.
* Useful for testing and diagnostics.
*/
export function isFileLockHeld(lockPath: string): boolean {
return (heldLocks.get(canonicalLockPath(lockPath)) ?? 0) > 0;
}
/**
* Reset reentrancy tracking (for use in tests only).
*/
export function _resetLockState(): void {
heldLocks.clear();
}