First basic version

This commit is contained in:
Fabian Stamm
2019-11-04 00:45:30 +01:00
parent a78e98a0c8
commit 68011e3866
10 changed files with 431 additions and 393 deletions

View File

@ -1,43 +1,23 @@
export type Release = { release: () => void };
export default class PathLock {
locks: {
path: string[],
next: (() => void)[]
}[] = [];
export default class DocumentLock {
private locks = new Map<string, (() => void)[]>();
constructor() { }
async lock(path: string[]) {
let locks = this.locks.filter(lock => {
let idxs = Math.min(lock.path.length, path.length);
if (idxs === 0) return true;
for (let i = 0; i < idxs; i++) {
if (lock.path[i] !== path[i])
return false;
}
return true;
})
if (locks.length > 0) { // await till release
await Promise.all(locks.map(l => new Promise(res => l.next.push(res))))
} else {
let lock = {
path: path,
next: []
}
this.locks.push(lock);
locks = [lock];
async lock(collection: string = "", document: string = "") {
let key = collection + "/" + document;
let l = this.locks.get(key);
if (l)
await new Promise(resolve => { l.push(resolve); this.locks.set(key, l) });
else {
l = [];
this.locks.set(key, l);
}
return () => {
locks.forEach(lock => {
if (lock.next.length > 0) {
setImmediate(() => lock.next.shift()());
} else {
this.locks.splice(this.locks.indexOf(lock), 1);
}
})
if (l.length > 0)
setImmediate(() => l.shift());
else
this.locks.delete(key)
}
}
}