Stop using global file locks
This commit is contained in:
parent
f8dcd33d3e
commit
3d8067e947
1 changed files with 89 additions and 86 deletions
50
frontend/sync-client/src/sync-operations/document-locks.ts
Normal file
50
frontend/sync-client/src/sync-operations/document-locks.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import type { RelativePath } from "../persistence/database";
|
||||
|
||||
export class DocumentLocks {
|
||||
private readonly locked = new Set<RelativePath>();
|
||||
private readonly waiters = new Map<RelativePath, (() => void)[]>();
|
||||
|
||||
public tryLockDocument(relativePath: RelativePath): boolean {
|
||||
if (this.locked.has(relativePath)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.locked.add(relativePath);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async waitForDocumentLock(
|
||||
relativePath: RelativePath
|
||||
): Promise<void> {
|
||||
if (this.tryLockDocument(relativePath)) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
let waiting = this.waiters.get(relativePath);
|
||||
if (!waiting) {
|
||||
waiting = [];
|
||||
this.waiters.set(relativePath, waiting);
|
||||
}
|
||||
|
||||
waiting.push(resolve);
|
||||
});
|
||||
}
|
||||
|
||||
public unlockDocument(relativePath: RelativePath): void {
|
||||
if (!this.locked.has(relativePath)) {
|
||||
throw new Error(
|
||||
`Document ${relativePath} is not locked, cannot unlock`
|
||||
);
|
||||
}
|
||||
|
||||
// Remove the first element to ensure FIFO unblocking order
|
||||
const nextWaiting = this.waiters.get(relativePath)?.shift();
|
||||
|
||||
if (nextWaiting) {
|
||||
nextWaiting();
|
||||
} else {
|
||||
this.locked.delete(relativePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue