Skip to content

Commit

Permalink
Remove timeouts of messages when the connection is closed in either side
Browse files Browse the repository at this point in the history
  • Loading branch information
GianOrtiz committed Apr 29, 2024
1 parent 298c82a commit 0801f3a
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
2 changes: 1 addition & 1 deletion docs/modules/cs/index.ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public addConnectionListener(listener: ConnectionListener)
**Signature**

```ts
public close(): Promise<void>
public async close(): Promise<void>
```

### sendRequest (method)
Expand Down
9 changes: 9 additions & 0 deletions src/ws/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const debug = Debug("ts-ocpp:ws");

export default class Connection<ReqAction extends ActionName<'v1.6-json'>> {
private messageTriggers: Record<string, (m: OCPPJMessage) => void> = {};
private timeouts: Record<string, NodeJS.Timeout> = {};

constructor(
public readonly socket: WebSocket,
private readonly requestHandler: RequestHandler<ReqAction, ValidationError | undefined, 'v1.6-json'>,
Expand All @@ -32,6 +34,7 @@ export default class Connection<ReqAction extends ActionName<'v1.6-json'>> {
const id = uuid.v4();
const waitResponse: Promise<OCPPJMessage> = 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);
Expand All @@ -57,6 +60,7 @@ export default class Connection<ReqAction extends ActionName<'v1.6-json'>> {
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(
Expand All @@ -79,6 +83,11 @@ export default class Connection<ReqAction extends ActionName<'v1.6-json'>> {
}

public close() {
Object.entries(this.timeouts).forEach(([requestId, timeout]) => {
clearTimeout(timeout);
delete this.messageTriggers[requestId];
delete this.timeouts[requestId];
});
this.socket.close();
}

Expand Down

0 comments on commit 0801f3a

Please sign in to comment.