Make locks deadlock-safe

This commit is contained in:
Andras Schmelczer 2025-08-23 12:37:05 +01:00
parent 115c1067f9
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

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