Make locks deadlock-safe

This commit is contained in:
Andras Schmelczer 2025-08-23 12:37:05 +01:00
commit 022c57e88a
No known key found for this signature in database
GPG key ID: FC8F2C3D3D1A718C
4 changed files with 112 additions and 98 deletions

View file

@ -24,15 +24,18 @@ export function flakyWebSocketFactory(
public set onmessage(callback: (event: MessageEvent) => void) { public set onmessage(callback: (event: MessageEvent) => void) {
super.onmessage = async (event: MessageEvent): Promise<void> => { super.onmessage = async (event: MessageEvent): Promise<void> => {
await this.locks.waitForLock(FlakyWebSocket.RECEIVE_KEY); await this.locks.withLock(
FlakyWebSocket.RECEIVE_KEY,
async () => {
if (jitterScaleInSeconds > 0) { if (jitterScaleInSeconds > 0) {
await sleep(Math.random() * jitterScaleInSeconds * 1000); await sleep(
Math.random() * jitterScaleInSeconds * 1000
);
} }
callback(event); callback(event);
}
this.locks.unlock(FlakyWebSocket.RECEIVE_KEY); );
}; };
} }
@ -66,15 +69,12 @@ export function flakyWebSocketFactory(
data: string | ArrayBufferLike | Blob | ArrayBufferView data: string | ArrayBufferLike | Blob | ArrayBufferView
): Promise<void> { ): Promise<void> {
// maintain message order // maintain message order
await this.locks.waitForLock(FlakyWebSocket.SEND_KEY); await this.locks.withLock(FlakyWebSocket.SEND_KEY, async () => {
if (jitterScaleInSeconds > 0) { if (jitterScaleInSeconds > 0) {
await sleep(Math.random() * jitterScaleInSeconds * 1000); await sleep(Math.random() * jitterScaleInSeconds * 1000);
} }
super.send(data); super.send(data);
});
this.locks.unlock(FlakyWebSocket.SEND_KEY);
} }
} as unknown as typeof WebSocket; } as unknown as typeof WebSocket;
} }

View file

@ -31,16 +31,14 @@ export class SafeFileSystemOperations implements FileSystemOperations {
this.logger.debug(`Reading file '${path}'`); this.logger.debug(`Reading file '${path}'`);
return this.safeOperation( return this.safeOperation(
path, path,
this.decorateToHoldLock(path, async () => this.fs.read(path)), async () => this.locks.withLock(path, () => this.fs.read(path)),
"read" "read"
); );
} }
public async write(path: RelativePath, content: Uint8Array): Promise<void> { public async write(path: RelativePath, content: Uint8Array): Promise<void> {
this.logger.debug(`Writing to file '${path}'`); this.logger.debug(`Writing to file '${path}'`);
return this.decorateToHoldLock(path, async () => return this.locks.withLock(path, () => this.fs.write(path, content));
this.fs.write(path, content)
)();
} }
public async atomicUpdateText( public async atomicUpdateText(
@ -50,7 +48,8 @@ export class SafeFileSystemOperations implements FileSystemOperations {
this.logger.debug(`Atomically updating file '${path}'`); this.logger.debug(`Atomically updating file '${path}'`);
return this.safeOperation( return this.safeOperation(
path, path,
this.decorateToHoldLock(path, async () => async () =>
this.locks.withLock(path, () =>
this.fs.atomicUpdateText(path, updater) this.fs.atomicUpdateText(path, updater)
), ),
"atomicUpdateText" "atomicUpdateText"
@ -61,32 +60,25 @@ export class SafeFileSystemOperations implements FileSystemOperations {
// Logging this would be too noisy // Logging this would be too noisy
return this.safeOperation( return this.safeOperation(
path, path,
this.decorateToHoldLock(path, async () => async () =>
this.fs.getFileSize(path) this.locks.withLock(path, () => this.fs.getFileSize(path)),
),
"getFileSize" "getFileSize"
); );
} }
public async exists(path: RelativePath): Promise<boolean> { public async exists(path: RelativePath): Promise<boolean> {
this.logger.debug(`Checking if file '${path}' exists`); this.logger.debug(`Checking if file '${path}' exists`);
return this.decorateToHoldLock(path, async () => return this.locks.withLock(path, () => this.fs.exists(path));
this.fs.exists(path)
)();
} }
public async createDirectory(path: RelativePath): Promise<void> { public async createDirectory(path: RelativePath): Promise<void> {
this.logger.debug(`Creating directory '${path}'`); this.logger.debug(`Creating directory '${path}'`);
return this.decorateToHoldLock(path, async () => return this.locks.withLock(path, () => this.fs.createDirectory(path));
this.fs.createDirectory(path)
)();
} }
public async delete(path: RelativePath): Promise<void> { public async delete(path: RelativePath): Promise<void> {
this.logger.debug(`Deleting file '${path}'`); this.logger.debug(`Deleting file '${path}'`);
return this.decorateToHoldLock(path, async () => return this.locks.withLock(path, async () => this.fs.delete(path));
this.fs.delete(path)
)();
} }
public async rename( public async rename(
@ -96,43 +88,14 @@ export class SafeFileSystemOperations implements FileSystemOperations {
this.logger.debug(`Renaming file '${oldPath}' to '${newPath}'`); this.logger.debug(`Renaming file '${oldPath}' to '${newPath}'`);
return this.safeOperation( return this.safeOperation(
oldPath, oldPath,
this.decorateToHoldLock([oldPath, newPath], async () => async () =>
this.locks.withLock([oldPath, newPath], () =>
this.fs.rename(oldPath, newPath) this.fs.rename(oldPath, newPath)
), ),
"rename" "rename"
); );
} }
/**
* Decorate an operation to ensure that the file is locked before running it
* and that the lock is released afterwards. This results in at-most one
* concurrent operation running per file.
*/
private decorateToHoldLock<T>(
pathOrPaths: RelativePath | RelativePath[],
operation: () => Promise<T>
): () => Promise<T> {
return async () => {
const paths = Array.isArray(pathOrPaths)
? pathOrPaths
: [pathOrPaths];
await Promise.all(
paths.map(async (path) => this.locks.waitForLock(path))
);
try {
return await operation();
} finally {
await Promise.all(
paths.map((path) => {
this.locks.unlock(path);
})
);
}
};
}
/** /**
* Decorate an operation to ensure that the file exists before running it. * Decorate an operation to ensure that the file exists before running it.
* If the operation fails, it will check if the file still exists and throw * If the operation fails, it will check if the file still exists and throw

View file

@ -13,7 +13,54 @@ export class Locks<T> {
/** Queue of resolve functions waiting for each key */ /** Queue of resolve functions waiting for each key */
private readonly waiters = new Map<T, (() => unknown)[]>(); private readonly waiters = new Map<T, (() => unknown)[]>();
public constructor(private readonly logger: Logger) {} public constructor(private readonly logger?: Logger) {}
/**
* Executes a function while holding exclusive locks on one or more keys.
*
* This method ensures that the provided function runs with exclusive access to the
* specified key(s). Multiple keys are sorted to prevent deadlocks when different
* operations request the same keys in different orders.
*
* @template R The return type of the function to execute
* @param keyOrKeys A single key or array of keys to lock during function execution
* @param fn The function to execute while holding the lock(s). Can be sync or async.
* @returns A Promise that resolves to the return value of the executed function
*
* @example
* ```typescript
* // Lock a single key
* const result = await locks.withLock('file1', () => {
* // Critical section - only one operation can access 'file1' at a time
* return processFile('file1');
* });
*
* // Lock multiple keys (prevents deadlocks through consistent ordering)
* await locks.withLock(['file1', 'file2'], async () => {
* // Critical section - exclusive access to both files
* await moveFile('file1', 'file2');
* });
* ```
*
* @throws Any error thrown by the provided function will be propagated after locks are released
*/
public async withLock<R>(
keyOrKeys: T | T[],
fn: () => R | Promise<R>
): Promise<R> {
const keys = Array.isArray(keyOrKeys) ? keyOrKeys : [keyOrKeys];
keys.sort(); // Ensure consistent order to prevent deadlocks
await Promise.all(keys.map(async (key) => this.waitForLock(key)));
try {
return await fn();
} finally {
keys.forEach((key) => {
this.unlock(key);
});
}
}
/** /**
* Attempts to acquire a lock immediately without waiting. * Attempts to acquire a lock immediately without waiting.
@ -22,7 +69,7 @@ export class Locks<T> {
* @param key The key to lock * @param key The key to lock
* @returns `true` if lock acquired, `false` if already locked * @returns `true` if lock acquired, `false` if already locked
*/ */
public tryLock(key: T): boolean { private tryLock(key: T): boolean {
if (this.locked.has(key)) { if (this.locked.has(key)) {
return false; return false;
} }
@ -39,12 +86,12 @@ export class Locks<T> {
* @param key The key to wait for and lock * @param key The key to wait for and lock
* @returns Promise that resolves when lock is acquired * @returns Promise that resolves when lock is acquired
*/ */
public async waitForLock(key: T): Promise<void> { private async waitForLock(key: T): Promise<void> {
if (this.tryLock(key)) { if (this.tryLock(key)) {
return Promise.resolve(); return Promise.resolve();
} }
this.logger.debug(`Waiting for lock on ${key}`); this.logger?.debug(`Waiting for lock on ${key}`);
return new Promise((resolve) => { return new Promise((resolve) => {
// DefaultDict behavior // DefaultDict behavior
@ -65,7 +112,7 @@ export class Locks<T> {
* @param key The key to unlock * @param key The key to unlock
* @throws {Error} If key is not currently locked * @throws {Error} If key is not currently locked
*/ */
public unlock(key: T): void { private unlock(key: T): void {
if (!this.locked.has(key)) { if (!this.locked.has(key)) {
throw new Error(`Key '${key}' is not locked, cannot unlock`); throw new Error(`Key '${key}' is not locked, cannot unlock`);
} }
@ -74,19 +121,22 @@ export class Locks<T> {
const nextWaiting = this.waiters.get(key)?.shift(); const nextWaiting = this.waiters.get(key)?.shift();
if (nextWaiting) { if (nextWaiting) {
this.logger.debug(`Granted lock on ${key}`); this.logger?.debug(`Granted lock on ${key}`);
nextWaiting(); nextWaiting();
} else { } else {
this.locked.delete(key); this.locked.delete(key);
} }
} }
}
/** export class Lock {
* Clears all locks and waiters. Causes waiting operations to hang indefinitely. private readonly locks: Locks<boolean>;
* Use with caution.
*/ public constructor(logger?: Logger) {
public reset(): void { this.locks = new Locks(logger);
this.locked.clear(); }
this.waiters.clear();
public async withLock<R>(fn: () => R | Promise<R>): Promise<R> {
return this.locks.withLock(true, fn);
} }
} }

View file

@ -25,15 +25,18 @@ export function flakyWebSocketFactory(
public set onmessage(callback: (event: MessageEvent) => void) { public set onmessage(callback: (event: MessageEvent) => void) {
super.onmessage = async (event: MessageEvent): Promise<void> => { super.onmessage = async (event: MessageEvent): Promise<void> => {
await this.locks.waitForLock(FlakyWebSocket.RECEIVE_KEY); return this.locks.withLock(
FlakyWebSocket.RECEIVE_KEY,
async () => {
if (jitterScaleInSeconds > 0) { if (jitterScaleInSeconds > 0) {
await sleep(Math.random() * jitterScaleInSeconds * 1000); await sleep(
Math.random() * jitterScaleInSeconds * 1000
);
} }
callback(event); callback(event);
}
this.locks.unlock(FlakyWebSocket.RECEIVE_KEY); );
}; };
} }
@ -67,15 +70,13 @@ export function flakyWebSocketFactory(
data: string | ArrayBufferLike | Blob | ArrayBufferView data: string | ArrayBufferLike | Blob | ArrayBufferView
): Promise<void> { ): Promise<void> {
// maintain message order // maintain message order
await this.locks.waitForLock(FlakyWebSocket.SEND_KEY); return this.locks.withLock(FlakyWebSocket.SEND_KEY, async () => {
if (jitterScaleInSeconds > 0) { if (jitterScaleInSeconds > 0) {
await sleep(Math.random() * jitterScaleInSeconds * 1000); await sleep(Math.random() * jitterScaleInSeconds * 1000);
} }
super.send(data); super.send(data);
});
this.locks.unlock(FlakyWebSocket.SEND_KEY);
} }
} as unknown as typeof WebSocket; } as unknown as typeof WebSocket;
} }