Log inside locks

This commit is contained in:
Andras Schmelczer 2025-03-01 17:58:55 +00:00
parent ab5336f567
commit bcf48c428d
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
2 changed files with 11 additions and 2 deletions

View file

@ -1,12 +1,14 @@
import { Logger } from "../tracing/logger";
import type { RelativePath } from "../persistence/database";
import { DocumentLocks } from "./document-locks";
describe("Document lock", () => {
const testPath: RelativePath = "test/document/path";
let locks = new DocumentLocks();
const logger = new Logger();
let locks = new DocumentLocks(logger);
beforeEach(() => {
locks = new DocumentLocks();
locks = new DocumentLocks(logger);
});
test("should lock a document successfully", () => {

View file

@ -1,15 +1,19 @@
import type { Logger } from "../tracing/logger";
import type { RelativePath } from "../persistence/database";
export class DocumentLocks {
private readonly locked = new Set<RelativePath>();
private readonly waiters = new Map<RelativePath, (() => void)[]>();
public constructor(private readonly logger: Logger) {}
public tryLockDocument(relativePath: RelativePath): boolean {
if (this.locked.has(relativePath)) {
return false;
}
this.locked.add(relativePath);
return true;
}
@ -20,6 +24,8 @@ export class DocumentLocks {
return Promise.resolve();
}
this.logger.debug(`Waiting for lock on ${relativePath}`);
return new Promise((resolve) => {
let waiting = this.waiters.get(relativePath);
if (!waiting) {
@ -42,6 +48,7 @@ export class DocumentLocks {
const nextWaiting = this.waiters.get(relativePath)?.shift();
if (nextWaiting) {
this.logger.debug(`Granted lock on ${relativePath}`);
nextWaiting();
} else {
this.locked.delete(relativePath);