| 1 | const writeLocks = new Map<string, Promise<void>>() |
| 2 | |
| 3 | /** |
| 4 | * Serializes async writes per presentation resource. The operation itself stays |
| 5 | * with its caller; this module only guarantees ordering and releases the lock |
| 6 | * after either success or failure. |
| 7 | */ |
| 8 | export function serializedWrite<T>(lockKey: string, fn: () => Promise<T>): Promise<T> { |
| 9 | const chain = writeLocks.get(lockKey) || Promise.resolve() |
| 10 | const run = chain.then(fn) |
| 11 | const next = run.then( |
| 12 | () => undefined, |
| 13 | () => undefined |
| 14 | ) |
| 15 | writeLocks.set(lockKey, next) |
| 16 | return run.finally(() => { |
| 17 | if (writeLocks.get(lockKey) === next) writeLocks.delete(lockKey) |
| 18 | }) |
| 19 | } |
| 20 |