From 0801f3a2288bf0e36158d4b11cf50f152a0544cb Mon Sep 17 00:00:00 2001 From: Gian Ortiz Date: Mon, 29 Apr 2024 16:23:11 -0300 Subject: [PATCH] Remove timeouts of messages when the connection is closed in either side --- docs/modules/cs/index.ts.md | 2 +- src/ws/connection.ts | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/docs/modules/cs/index.ts.md b/docs/modules/cs/index.ts.md index 531d035..1157ba3 100644 --- a/docs/modules/cs/index.ts.md +++ b/docs/modules/cs/index.ts.md @@ -77,7 +77,7 @@ public addConnectionListener(listener: ConnectionListener) **Signature** ```ts -public close(): Promise +public async close(): Promise ``` ### sendRequest (method) diff --git a/src/ws/connection.ts b/src/ws/connection.ts index d1d2eec..0fa4cc8 100644 --- a/src/ws/connection.ts +++ b/src/ws/connection.ts @@ -12,6 +12,8 @@ const debug = Debug("ts-ocpp:ws"); export default class Connection> { private messageTriggers: Record void> = {}; + private timeouts: Record = {}; + constructor( public readonly socket: WebSocket, private readonly requestHandler: RequestHandler, @@ -32,6 +34,7 @@ export default class Connection> { const id = uuid.v4(); const waitResponse: Promise = new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new OCPPRequestTimedOutError(action)), this.requestTimeout ?? 30_000); + this.timeouts[id] = timeoutId; this.messageTriggers[id] = function (ocppMessage) { resolve(ocppMessage); clearTimeout(timeoutId); @@ -57,6 +60,7 @@ export default class Connection> { debug(`received response %o`, responseMessage); // cleanup function to avoid memory leak delete this.messageTriggers[id]; + delete this.timeouts[id]; this.handlers?.onReceiveResponse(responseMessage); if (responseMessage.type === MessageType.CALL) return Left( @@ -79,6 +83,11 @@ export default class Connection> { } public close() { + Object.entries(this.timeouts).forEach(([requestId, timeout]) => { + clearTimeout(timeout); + delete this.messageTriggers[requestId]; + delete this.timeouts[requestId]; + }); this.socket.close(); }