keyed-operation-lane.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /** Serializes operations per key without coupling unrelated keys. */
  2. export class KeyedOperationLane<Key> {
  3. private readonly tails = new Map<Key, Promise<void>>();
  4. async acquire(key: Key): Promise<() => void> {
  5. const previous = this.tails.get(key) ?? Promise.resolve();
  6. let releaseGate: () => void = () => undefined;
  7. const gate = new Promise<void>((resolve) => {
  8. releaseGate = resolve;
  9. });
  10. const current = waitForLane(previous, gate);
  11. this.tails.set(key, current);
  12. await ignoreLaneFailure(previous);
  13. let released = false;
  14. return () => {
  15. if (released) return;
  16. released = true;
  17. releaseGate();
  18. if (this.tails.get(key) === current) this.tails.delete(key);
  19. };
  20. }
  21. async run<T>(key: Key, operation: () => Promise<T>): Promise<T> {
  22. const release = await this.acquire(key);
  23. try {
  24. return await operation();
  25. } finally {
  26. release();
  27. }
  28. }
  29. }
  30. async function waitForLane(previous: Promise<void>, gate: Promise<void>): Promise<void> {
  31. await ignoreLaneFailure(previous);
  32. await gate;
  33. }
  34. async function ignoreLaneFailure(lane: Promise<void>): Promise<void> {
  35. try {
  36. await lane;
  37. } catch {
  38. // A failed predecessor must not poison later operations for the same key.
  39. }
  40. }