From d4b944aef41d94ec9c7380b9388bcbaeeb5e8a69 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sat, 1 Oct 2022 19:53:15 +0200 Subject: [PATCH] Run ATG as an AsyncResource MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Close #53 Signed-off-by: Jérôme Benoit --- .../AutomaticTransactionGenerator.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index 9b196ed9..fb04d709 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -1,5 +1,7 @@ // Partial Copyright Jerome Benoit. 2021. All Rights Reserved. +import { AsyncResource } from 'async_hooks'; + import BaseError from '../exception/BaseError'; import PerformanceStatistics from '../performance/PerformanceStatistics'; import { @@ -23,7 +25,9 @@ import Utils from '../utils/Utils'; import type ChargingStation from './ChargingStation'; import { ChargingStationUtils } from './ChargingStationUtils'; -export default class AutomaticTransactionGenerator { +const moduleName = 'AutomaticTransactionGenerator'; + +export default class AutomaticTransactionGenerator extends AsyncResource { private static readonly instances: Map = new Map< string, AutomaticTransactionGenerator @@ -39,6 +43,7 @@ export default class AutomaticTransactionGenerator { automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration, chargingStation: ChargingStation ) { + super(moduleName); this.started = false; this.configuration = automaticTransactionGeneratorConfiguration; this.chargingStation = chargingStation; @@ -87,12 +92,11 @@ export default class AutomaticTransactionGenerator { throw new BaseError(`Connector ${connectorId} does not exist`); } if (this.connectorsStatus.get(connectorId)?.start === false) { - // Avoid hogging the event loop with a busy loop - setImmediate(() => { - this.internalStartConnector(connectorId).catch(() => { - /* This is intentional */ - }); - }); + this.runInAsyncScope( + this.internalStartConnector.bind(this) as (this: this, ...args: any[]) => unknown, + this, + connectorId + ); } else if (this.connectorsStatus.get(connectorId)?.start === true) { logger.warn(`${this.logPrefix(connectorId)} is already started on connector`); } -- 2.34.1