cross-process-lock.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { open } from 'node:fs/promises';
  2. import lockfile from 'proper-lockfile';
  3. import { ensurePrivateDirectory } from './fs/atomic-write.js';
  4. import { dirname } from 'node:path';
  5. export interface CrossProcessAuthLockOptions {
  6. staleMs?: number;
  7. retries?: number;
  8. }
  9. export class CrossProcessAuthLock {
  10. private readonly staleMs: number;
  11. private readonly retries: number;
  12. constructor(
  13. private readonly lockPath: string,
  14. options: CrossProcessAuthLockOptions = {},
  15. ) {
  16. this.staleMs = options.staleMs ?? 30_000;
  17. this.retries = options.retries ?? 120;
  18. }
  19. async withLock<T>(operation: () => Promise<T>): Promise<T> {
  20. await ensurePrivateDirectory(dirname(this.lockPath));
  21. const handle = await open(this.lockPath, 'a', 0o600);
  22. await handle.close();
  23. let compromise: Error | undefined;
  24. const release = await lockfile.lock(this.lockPath, {
  25. realpath: false,
  26. stale: this.staleMs,
  27. retries: {
  28. retries: this.retries,
  29. factor: 1.15,
  30. minTimeout: 5,
  31. maxTimeout: 250,
  32. },
  33. onCompromised: (error) => {
  34. compromise ??= error;
  35. },
  36. });
  37. try {
  38. return await operation();
  39. } finally {
  40. try {
  41. await release();
  42. } catch (error) {
  43. if (!compromise) throw error;
  44. }
  45. if (compromise) throw compromise;
  46. }
  47. }
  48. }