|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT License. |
| 3 | + |
| 4 | +import * as crypto from 'crypto'; |
| 5 | +import * as fsapi from 'fs-extra'; |
| 6 | +import * as path from 'path'; |
| 7 | + |
| 8 | +export interface AcquireFileLockOptions { |
| 9 | + readonly timeoutMs: number; |
| 10 | + readonly retryIntervalMs: number; |
| 11 | +} |
| 12 | + |
| 13 | +export interface AcquiredFileLock { |
| 14 | + readonly release: () => Promise<void>; |
| 15 | + /** Keep the lock and make later acquisition attempts fail immediately. */ |
| 16 | + readonly retain: () => Promise<void>; |
| 17 | +} |
| 18 | + |
| 19 | +type LockState = 'held' | 'released' | 'retained'; |
| 20 | + |
| 21 | +/** Acquire an atomic lock released only explicitly; interrupted operations remain locked. */ |
| 22 | +export async function acquireFileLock(filePath: string, options: AcquireFileLockOptions): Promise<AcquiredFileLock> { |
| 23 | + const lockPath = `${path.resolve(filePath)}.lock`; |
| 24 | + const ownerMarker = path.join(lockPath, `owner-${process.pid}-${crypto.randomBytes(16).toString('hex')}`); |
| 25 | + const retainedMarker = path.join(lockPath, 'retained'); |
| 26 | + const deadline = Date.now() + options.timeoutMs; |
| 27 | + |
| 28 | + while (true) { |
| 29 | + try { |
| 30 | + await fsapi.mkdir(lockPath); |
| 31 | + try { |
| 32 | + await fsapi.writeFile(ownerMarker, '', { flag: 'wx' }); |
| 33 | + } catch (error) { |
| 34 | + try { |
| 35 | + await fsapi.rmdir(lockPath); |
| 36 | + } catch { |
| 37 | + throw createLockError( |
| 38 | + 'Lock initialization failed and left an owner-less lock directory', |
| 39 | + 'ELOCKORPHANED', |
| 40 | + lockPath, |
| 41 | + ); |
| 42 | + } |
| 43 | + throw error; |
| 44 | + } |
| 45 | + |
| 46 | + let state: LockState = 'held'; |
| 47 | + return { |
| 48 | + retain: async () => { |
| 49 | + if (state !== 'held') { |
| 50 | + return; |
| 51 | + } |
| 52 | + state = 'retained'; |
| 53 | + try { |
| 54 | + await fsapi.writeFile(retainedMarker, '', { flag: 'wx' }); |
| 55 | + } catch (error) { |
| 56 | + if (hasErrorCode(error, 'EEXIST')) { |
| 57 | + return; |
| 58 | + } |
| 59 | + try { |
| 60 | + await fsapi.rename(ownerMarker, retainedMarker); |
| 61 | + } catch (renameError) { |
| 62 | + if (!hasErrorCode(renameError, 'EEXIST')) { |
| 63 | + throw createLockError( |
| 64 | + 'Failed to mark the lock as retained', |
| 65 | + 'ERETAINFAILED', |
| 66 | + lockPath, |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + }, |
| 72 | + release: async () => { |
| 73 | + if (state !== 'held') { |
| 74 | + return; |
| 75 | + } |
| 76 | + state = 'released'; |
| 77 | + try { |
| 78 | + await fsapi.unlink(ownerMarker); |
| 79 | + } catch (error) { |
| 80 | + if (hasErrorCode(error, 'ENOENT')) { |
| 81 | + throw createLockError('Lock ownership was compromised', 'ECOMPROMISED', lockPath); |
| 82 | + } |
| 83 | + throw error; |
| 84 | + } |
| 85 | + await fsapi.rmdir(lockPath); |
| 86 | + }, |
| 87 | + }; |
| 88 | + } catch (error) { |
| 89 | + if (!hasErrorCode(error, 'EEXIST')) { |
| 90 | + throw error; |
| 91 | + } |
| 92 | + if (await isRetainedLock(lockPath)) { |
| 93 | + throw createLockError('Lock was retained after an interrupted operation', 'ELOCKRETAINED', lockPath); |
| 94 | + } |
| 95 | + if (Date.now() >= deadline) { |
| 96 | + throw createLockError('Lock is already being held', 'ELOCKED', lockPath); |
| 97 | + } |
| 98 | + await delay(Math.min(options.retryIntervalMs, Math.max(0, deadline - Date.now()))); |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +async function isRetainedLock(lockPath: string): Promise<boolean> { |
| 104 | + try { |
| 105 | + await fsapi.lstat(path.join(lockPath, 'retained')); |
| 106 | + return true; |
| 107 | + } catch (error) { |
| 108 | + if (hasErrorCode(error, 'ENOENT')) { |
| 109 | + return false; |
| 110 | + } |
| 111 | + throw error; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +function hasErrorCode(error: unknown, code: string): boolean { |
| 116 | + return ( |
| 117 | + typeof error === 'object' && error !== null && 'code' in error && (error as NodeJS.ErrnoException).code === code |
| 118 | + ); |
| 119 | +} |
| 120 | + |
| 121 | +function createLockError(message: string, code: string, lockPath: string): NodeJS.ErrnoException { |
| 122 | + return Object.assign(new Error(message), { code, path: lockPath }); |
| 123 | +} |
| 124 | + |
| 125 | +async function delay(milliseconds: number): Promise<void> { |
| 126 | + return new Promise((resolve) => setTimeout(resolve, milliseconds)); |
| 127 | +} |
0 commit comments