* Acquire an advisory lock for the given path and hold it for the duration of the callback. * * The lock will be released automatically when the callback resolves or rejects. * Concurrent calls to withLock() for the same path will wait until the lock is released.
(lockPath, cb)
| 46 | * Concurrent calls to withLock() for the same path will wait until the lock is released. |
| 47 | */ |
| 48 | async function withLock (lockPath, cb) { |
| 49 | try { |
| 50 | const signal = await acquireLock(lockPath) |
| 51 | return await new Promise((resolve, reject) => { |
| 52 | signal.addEventListener('abort', () => { |
| 53 | reject(Object.assign(new Error('Lock compromised'), { code: 'ECOMPROMISED' })) |
| 54 | }); |
| 55 | |
| 56 | (async () => { |
| 57 | try { |
| 58 | resolve(await cb(signal)) |
| 59 | } catch (err) { |
| 60 | reject(err) |
| 61 | } |
| 62 | })() |
| 63 | }) |
| 64 | } finally { |
| 65 | releaseLock(lockPath) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | function acquireLock (lockPath) { |
| 70 | return promiseRetry(async (retry) => { |
no test coverage detected