MCPcopy Create free account
hub / github.com/appium/appium / getLockFileGuard

Function getLockFileGuard

packages/support/lib/util.ts:504–552  ·  view source on GitHub ↗
(lockFile: string, opts: LockFileOptions = {})

Source from the content-addressed store, hash-verified

502 * @returns Async function that accepts a callback to run under the lock, plus a `.check()` method
503 */
504export function getLockFileGuard<T>(lockFile: string, opts: LockFileOptions = {}): LockFileGuard<T> {
505 const {timeout = 120, tryRecovery = false} = opts;
506
507 const lock = promisify(_lockfile.lock) as (lockfile: string, opts: {wait: number}) => Promise<void>;
508 const checkLock = promisify(_lockfile.check) as (lockfile: string) => Promise<boolean>;
509 const unlock = promisify(_lockfile.unlock) as (lockfile: string) => Promise<void>;
510
511 const guard: LockFileGuard<T> = Object.assign(
512 async (behavior: () => Promise<T> | T): Promise<T> => {
513 let triedRecovery = false;
514 let acquired = false;
515 while (!acquired) {
516 try {
517 try {
518 _lockfile.lockSync(lockFile);
519 } catch (e) {
520 const lockErr = e as NodeJS.ErrnoException;
521 if (lockErr.code !== 'EEXIST') {
522 throw lockErr;
523 }
524 // Someone else is holding the lock (possibly grabbed it between us checking and
525 // locking) -- wait for them to release it instead of failing outright.
526 await lock(lockFile, {wait: timeout * 1000});
527 }
528 acquired = true;
529 } catch (e) {
530 const err = e as Error;
531 if (err.message?.includes('EEXIST') && tryRecovery && !triedRecovery) {
532 _lockfile.unlockSync(lockFile);
533 triedRecovery = true;
534 } else {
535 throw new Error(
536 `Could not acquire lock on '${lockFile}' after ${timeout}s. ` + `Original error: ${err.message}`,
537 {cause: e},
538 );
539 }
540 }
541 }
542 try {
543 return await behavior();
544 } finally {
545 await unlock(lockFile);
546 }
547 },
548 {check: () => checkLock(lockFile)},
549 );
550
551 return guard;
552}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected