Files
Kelx/utils/keyed-async-lock.js
2026-11-30 16:32:37 +00:00

59 lines
1.9 KiB
JavaScript

"use strict";
const { createHash } = require("node:crypto");
const path = require("node:path");
const { createCrossProcessOperationMutex } = require("./cross-process-mutex");
//
// Not reentrant: a task running under a key must not await another task under
// the same key (the inner task would queue behind the outer one and deadlock).
const _tails = new Map();
// adpanel:port-allocation-lock - every panel worker must honor a pending
// port allocation until the owner commits it or stops using it.
function nodePortMutex(key) {
if (!key.startsWith("node-ports:")) return null;
const digest = createHash("sha256").update(key).digest("hex");
return createCrossProcessOperationMutex({
label: "[node-ports]", lockFilePath: path.join(__dirname, "..", `.node-ports-${digest}.lock`),
});
}
function enqueue(key, task) {
const k = key;
const tail = _tails.get(k) || Promise.resolve();
const run = tail.then(task, task);
const settled = run.then(() => undefined, () => undefined);
_tails.set(k, settled);
settled.then(() => {
// Drop quiescent chains so the map cannot grow with one-off keys; a newer
// chain for the same key always wins this comparison.
if (_tails.get(k) === settled) _tails.delete(k);
});
return run;
}
function withKeyedLock(key, task) {
const normalizedKey = String(key || "");
const mutex = nodePortMutex(normalizedKey);
return enqueue(normalizedKey, mutex ? () => mutex.runExclusive(task) : task);
}
function tryWithKeyedLock(key, task) {
const normalizedKey = String(key || "");
if (_tails.has(normalizedKey)) return null;
const mutex = nodePortMutex(normalizedKey);
if (!mutex) return enqueue(normalizedKey, task);
const release = mutex.tryAcquire();
if (!release) return null;
return enqueue(normalizedKey, async () => {
try {
return await task();
} finally {
release();
}
});
}
module.exports = { withKeyedLock, tryWithKeyedLock };