json-crdt-server
Version:
JSON CRDT server and syncing local-first browser client
50 lines (49 loc) • 1.44 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.Mutex = void 0;
const Defer_1 = require("thingies/lib/Defer");
class Entry {
constructor(code, future) {
this.code = code;
this.future = future;
}
}
class Mutex {
constructor() {
this.queue = new Map();
this.acquire = async (key, code) => {
const queue = this.queue.get(key);
const entry = new Entry(code, new Defer_1.Defer());
if (queue instanceof Array)
queue.push(entry);
else {
this.queue.set(key, []);
this.run(key, entry).catch(() => { });
}
return await entry.future.promise;
};
}
async run(key, entry) {
try {
const result = await entry.code();
entry.future.resolve(result);
}
catch (error) {
entry.future.reject(error);
}
finally {
const queue = this.queue;
const entries = queue.get(key);
if (entries instanceof Array) {
if (!entries.length)
queue.delete(key);
else {
const next = entries.shift();
if (next instanceof Entry)
this.run(key, next).catch(() => { });
}
}
}
}
}
exports.Mutex = Mutex;
;