From 83b62bfdcb139108a0848b95808f58d70f070950 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Sat, 26 Nov 2022 17:53:16 -0500 Subject: [PATCH] *Refactor mutex lock logic --- src/modules/rpc/server.ts | 33 +++++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/src/modules/rpc/server.ts b/src/modules/rpc/server.ts index 43bc235..08ff6c7 100644 --- a/src/modules/rpc/server.ts +++ b/src/modules/rpc/server.ts @@ -185,6 +185,8 @@ export class RPCServer extends EventEmitter { this.cache.addItem(request, rpcResult); } + this.getRequestLock(request)?.release(); + return rpcResult; } @@ -225,16 +227,13 @@ export class RPCServer extends EventEmitter { return; } - const reqId = RPCServer.hashQuery(request); - - let lock: Mutex = this.pendingRequests.get(reqId) as Mutex; - const lockExists = !!lock; - - if (!lockExists) { - lock = new Mutex(); - this.pendingRequests.set(reqId, lock); + if (!this.getRequestLock(request)) { + this.createRequestLock(request); } + const reqId = RPCServer.hashQuery(request); + const lock: Mutex = this.getRequestLock(request) as Mutex; + if (lock.isLocked()) { await lock.waitForUnlock(); if (reqId in this._cache.data) { @@ -244,4 +243,22 @@ export class RPCServer extends EventEmitter { await lock.acquire(); } + + private getRequestLock(request: RPCRequest): Mutex | null { + const reqId = RPCServer.hashQuery(request); + + let lock: Mutex = this.pendingRequests.get(reqId) as Mutex; + + if (!lock) { + return null; + } + + return lock; + } + + private createRequestLock(request: RPCRequest) { + const reqId = RPCServer.hashQuery(request); + + this.pendingRequests.set(reqId, new Mutex()); + } }