-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess-lock.ts
More file actions
464 lines (425 loc) · 14.7 KB
/
process-lock.ts
File metadata and controls
464 lines (425 loc) · 14.7 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
/**
* @fileoverview Process locking utilities with stale detection and exit cleanup.
* Provides cross-platform inter-process synchronization using directory-based locks.
* Aligned with npm's npx locking strategy (5-second stale timeout, periodic touching).
*
* ## Why directories instead of files?
*
* This implementation uses `mkdir()` to create lock directories (not files) because:
*
* 1. **Atomic guarantee**: `mkdir()` is guaranteed atomic across ALL filesystems,
* including NFS. Only ONE process can successfully create the directory. If it
* exists, `mkdir()` fails with EEXIST instantly with no race conditions.
*
* 2. **File-based locking issues**:
* - `writeFile()` with `flag: 'wx'` - atomicity can fail on NFS
* - `open()` with `O_EXCL` - not guaranteed atomic on older NFS
* - Traditional lockfiles - can have race conditions on network filesystems
*
* 3. **Simplicity**: No need to write/read file content, track PIDs, or manage
* file descriptors. Just create/delete directory and check mtime.
*
* 4. **Historical precedent**: Well-known Unix locking pattern used by package
* managers for decades. Git uses similar approach for `.git/index.lock`.
*
* ## The mtime trick
*
* We periodically update the lock directory's mtime (modification time) by
* "touching" it to signal "I'm still actively working". This prevents other
* processes from treating the lock as stale and removing it.
*
* **The lock directory remains empty** - it's just a sentinel that signals
* "locked". The mtime is the only data needed to track lock freshness.
*
* ## npm npx compatibility
*
* This implementation matches npm npx's concurrency.lock approach:
* - Lock created via `mkdir(path.join(installDir, 'concurrency.lock'))`
* - 5-second stale timeout (if mtime is older than 5s, lock is stale)
* - 2-second touching interval (updates mtime every 2s to keep lock fresh)
* - Automatic cleanup on process exit
*/
import { safeDeleteSync } from './fs'
import { getDefaultLogger } from './logger'
import { pRetry } from './promises'
import { onExit } from './signal-exit'
let _fs: typeof import('node:fs') | undefined
/**
* Lazily load the fs module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getFs() {
if (_fs === undefined) {
_fs = /*@__PURE__*/ require('node:fs')
}
return _fs as typeof import('node:fs')
}
let _path: typeof import('node:path') | undefined
/**
* Lazily load the path module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getPath() {
if (_path === undefined) {
_path = /*@__PURE__*/ require('node:path')
}
return _path as typeof import('node:path')
}
const logger = getDefaultLogger()
/**
* Lock acquisition options.
*/
export interface ProcessLockOptions {
/**
* Maximum number of retry attempts.
* @default 3
*/
retries?: number | undefined
/**
* Base delay between retries in milliseconds.
* @default 100
*/
baseDelayMs?: number | undefined
/**
* Maximum delay between retries in milliseconds.
* @default 1000
*/
maxDelayMs?: number | undefined
/**
* Stale lock timeout in milliseconds.
* Locks older than this are considered abandoned and can be reclaimed.
* Aligned with npm's npx locking strategy (5 seconds).
* @default 5000 (5 seconds)
*/
staleMs?: number | undefined
/**
* Interval for touching lock file to keep it fresh in milliseconds.
* Set to 0 to disable periodic touching.
* @default 2000 (2 seconds)
*/
touchIntervalMs?: number | undefined
}
/**
* Process lock manager with stale detection and exit cleanup.
* Provides cross-platform inter-process synchronization using file-system
* based locks.
*/
class ProcessLockManager {
private activeLocks = new Set<string>()
private touchTimers = new Map<string, NodeJS.Timeout>()
private exitHandlerRegistered = false
/**
* Ensure process exit handler is registered for cleanup.
* Registers a handler that cleans up all active locks when the process exits.
*/
private ensureExitHandler() {
if (this.exitHandlerRegistered) {
return
}
onExit(() => {
// Clear all touch timers.
for (const timer of this.touchTimers.values()) {
clearInterval(timer)
}
this.touchTimers.clear()
// Clean up all active locks.
const fs = getFs()
for (const lockPath of this.activeLocks) {
try {
if (fs.existsSync(lockPath)) {
safeDeleteSync(lockPath, { recursive: true })
}
} catch {
// Ignore cleanup errors during exit.
}
}
})
this.exitHandlerRegistered = true
}
/**
* Touch a lock file to update its mtime.
* This prevents the lock from being detected as stale during long operations.
*
* @param lockPath - Path to the lock directory
*/
private touchLock(lockPath: string): void {
try {
const fs = getFs()
if (fs.existsSync(lockPath)) {
// utimesSync accepts numeric timestamps (seconds). Pass Date.now() / 1000
// to avoid the Date allocation on every touch tick.
const now = Date.now() / 1000
fs.utimesSync(lockPath, now, now)
}
} catch (error) {
logger.warn(
`Failed to touch lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,
)
}
}
/**
* Start periodic touching of a lock file.
* Aligned with npm npx strategy to prevent false stale detection.
*
* @param lockPath - Path to the lock directory
* @param intervalMs - Touch interval in milliseconds
*/
private startTouchTimer(lockPath: string, intervalMs: number): void {
if (intervalMs <= 0 || this.touchTimers.has(lockPath)) {
return
}
const timer = setInterval(() => {
this.touchLock(lockPath)
}, intervalMs)
// Prevent timer from keeping process alive.
timer.unref()
this.touchTimers.set(lockPath, timer)
}
/**
* Stop periodic touching of a lock file.
*
* @param lockPath - Path to the lock directory
*/
private stopTouchTimer(lockPath: string): void {
const timer = this.touchTimers.get(lockPath)
if (timer) {
clearInterval(timer)
this.touchTimers.delete(lockPath)
}
}
/**
* Check if a lock is stale based on mtime.
* Uses second-level granularity to avoid APFS floating-point precision issues.
* Aligned with npm's npx locking strategy.
*
* @param lockPath - Path to the lock directory
* @param staleMs - Stale timeout in milliseconds
* @returns True if lock exists and is stale
*/
private isStale(lockPath: string, staleMs: number): boolean {
try {
// Use single statSync call instead of existsSync + statSync.
// throwIfNoEntry: false returns undefined if path doesn't exist.
const stats = getFs().statSync(lockPath, { throwIfNoEntry: false })
if (!stats) {
return false
}
// Compare in milliseconds. The previous implementation floored
// both sides to seconds, which silently rounded sub-second
// `staleMs` values up to ~1s (staleMs=500 → staleSeconds=0, so
// the lock had to be 1s+ past mtime before being considered
// stale). Node returns mtime with ms precision on all platforms
// we support; APFS's second-level filesystem precision just
// means the low bits are zero, which the subtraction handles.
return Date.now() - stats.mtime.getTime() > staleMs
} catch {
return false
}
}
/**
* Acquire a lock using mkdir for atomic operation.
* Handles stale locks and includes exit cleanup.
*
* This method attempts to create a lock directory atomically. If the lock
* already exists, it checks if it's stale and removes it before retrying.
* Uses exponential backoff with jitter for retry attempts.
*
* @param lockPath - Path to the lock directory
* @param options - Lock acquisition options
* @returns Release function to unlock
* @throws Error if lock cannot be acquired after all retries
*
* @example
* ```typescript
* const release = await processLock.acquire('/tmp/my-lock')
* try {
* // Critical section
* } finally {
* release()
* }
* ```
*/
async acquire(
lockPath: string,
options: ProcessLockOptions = {},
): Promise<() => void> {
const {
baseDelayMs = 100,
maxDelayMs = 1000,
retries = 3,
staleMs = 5000,
touchIntervalMs = 2000,
} = options
// Ensure exit handler is registered before any lock acquisition.
this.ensureExitHandler()
return (await pRetry(
async () => {
try {
// Check for stale lock and remove if necessary.
// isStale() handles non-existent paths efficiently with single statSync call.
if (this.isStale(lockPath, staleMs)) {
logger.log(`Removing stale lock: ${lockPath}`)
try {
safeDeleteSync(lockPath, { recursive: true })
} catch {
// Ignore errors removing stale lock - will retry.
}
}
// Ensure parent directory exists. Use path.dirname() so that both
// POSIX and Windows separators (and mixed-separator inputs) are
// handled correctly — the previous Math.max(lastIndexOf('/'), '\\')
// approach failed on relative paths and mixed-separator inputs.
const fs = getFs()
const parent = getPath().dirname(lockPath)
if (parent && parent !== '.' && parent !== lockPath) {
fs.mkdirSync(parent, { recursive: true })
}
// Atomic lock acquisition via mkdir (without recursive).
// Without recursive, mkdirSync throws EEXIST if another process
// already owns the directory. No pre-check: an existsSync +
// mkdirSync pair opens a TOCTOU window without adding safety,
// because mkdirSync is atomic on its own.
fs.mkdirSync(lockPath)
// Track lock for cleanup.
this.activeLocks.add(lockPath)
// Start periodic touching to prevent stale detection.
this.startTouchTimer(lockPath, touchIntervalMs)
// Return release function.
return () => this.release(lockPath)
} catch (error) {
const code = (error as NodeJS.ErrnoException).code
// Handle lock contention - lock already exists.
if (code === 'EEXIST') {
if (this.isStale(lockPath, staleMs)) {
throw new Error(`Stale lock detected: ${lockPath}`)
}
throw new Error(`Lock already exists: ${lockPath}`)
}
// Handle permission errors - not retryable.
if (code === 'EACCES' || code === 'EPERM') {
throw new Error(
`Permission denied creating lock: ${lockPath}. ` +
'Check directory permissions or run with appropriate access.',
{ cause: error },
)
}
// Handle read-only filesystem - not retryable.
if (code === 'EROFS') {
throw new Error(
`Cannot create lock on read-only filesystem: ${lockPath}`,
{ cause: error },
)
}
// Handle parent path issues - not retryable.
if (code === 'ENOTDIR') {
const lastSlashIndex = Math.max(
lockPath.lastIndexOf('/'),
lockPath.lastIndexOf('\\'),
)
const parentDir =
lastSlashIndex === -1 ? '.' : lockPath.slice(0, lastSlashIndex)
throw new Error(
`Cannot create lock directory: ${lockPath}\n` +
'A path component is a file when it should be a directory.\n' +
`Parent path: ${parentDir}\n` +
'To resolve:\n' +
` 1. Check if "${parentDir}" contains a file instead of a directory\n` +
' 2. Remove any conflicting files in the path\n' +
' 3. Ensure the full parent directory structure exists',
{ cause: error },
)
}
if (code === 'ENOENT') {
const lastSlashIndex = Math.max(
lockPath.lastIndexOf('/'),
lockPath.lastIndexOf('\\'),
)
const parentDir =
lastSlashIndex === -1 ? '.' : lockPath.slice(0, lastSlashIndex)
throw new Error(
`Cannot create lock directory: ${lockPath}\n` +
`Parent directory does not exist: ${parentDir}\n` +
'To resolve:\n' +
` 1. Ensure the parent directory "${parentDir}" exists\n` +
` 2. Create the directory structure: mkdir -p "${parentDir}"\n` +
' 3. Check filesystem permissions allow directory creation',
{ cause: error },
)
}
// Re-throw other errors with context.
throw new Error(`Failed to acquire lock: ${lockPath}`, {
cause: error,
})
}
},
{
retries,
baseDelayMs,
maxDelayMs,
jitter: true,
},
))!
}
/**
* Release a lock and remove from tracking.
* Stops periodic touching and removes the lock directory.
*
* @param lockPath - Path to the lock directory
*
* @example
* ```typescript
* processLock.release('/tmp/my-lock')
* ```
*/
release(lockPath: string): void {
// Stop periodic touching.
this.stopTouchTimer(lockPath)
try {
if (getFs().existsSync(lockPath)) {
safeDeleteSync(lockPath, { recursive: true })
}
this.activeLocks.delete(lockPath)
} catch (error) {
logger.warn(
`Failed to release lock ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,
)
}
}
/**
* Execute a function with exclusive lock protection.
* Automatically handles lock acquisition, execution, and cleanup.
*
* This is the recommended way to use process locks, as it guarantees
* cleanup even if the callback throws an error.
*
* @param lockPath - Path to the lock directory
* @param fn - Function to execute while holding the lock
* @param options - Lock acquisition options
* @returns Result of the callback function
* @throws Error from callback or lock acquisition failure
*
* @example
* ```typescript
* const result = await processLock.withLock('/tmp/my-lock', async () => {
* // Critical section
* return someValue
* })
* ```
*/
async withLock<T>(
lockPath: string,
fn: () => Promise<T>,
options?: ProcessLockOptions,
): Promise<T> {
const release = await this.acquire(lockPath, options)
try {
return await fn()
} finally {
release()
}
}
}
// Export singleton instance.
export const processLock = new ProcessLockManager()