Skip to content

Commit 85c1fb0

Browse files
fix(bootstrap): make start/stop idempotent and signal handler re-entrant safe (#1905)
- Memoize startPromise/stopPromise so concurrent callers await the same in-flight transition instead of silently no-op'ing. - Extract start()/stop() bodies into private doStart()/doStop() so the public methods are thin memoization wrappers. - Demote idempotent guard hits from error to warn (matches sister ChargingStation convention) for "Cannot start/stop already ..." paths and to debug for "Awaiting in-flight ..." concurrency observations. - Make gracefulShutdown re-entrant safe via shuttingDown flag -- multiple SIGTERM/SIGINT/SIGQUIT no longer race the in-flight stop. - On the no-op stop path with reason=user, ensure .simulator-state.json still reflects the authoritative state (writes started:false if file says started:true). Fixes UI clients reading stale started:true after a UI-driven stop on an already-stopped sim. - Document Bootstrap.stop coalescing semantics: the FIRST caller's reason controls the in-flight transition; later callers' reasons are ignored. - Add 'entrancy' to cspell dictionary (re-entrancy is the standard concurrency-engineering spelling). Tests: tests/charging-station/Bootstrap.test.ts (new file, 11 tests) - concurrent stop() / start() callers observe the same in-flight transition - gracefulShutdown is re-entrant: 3 synchronous calls invoke stop() exactly once (direct unit test on Bootstrap.prototype, runs on every platform including Windows) - multiple SIGTERM produce a single 'Graceful shutdown' log line (POSIX-only spawn-based integration smoke; skipped on Windows where child.kill('SIGTERM') maps to TerminateProcess and bypasses the handler -- coverage for that platform comes from the unit test above) - state-file consistency on the no-op stop path (3 sub-cases: reason=user, reason=shutdown, real-stop-then-no-op-stop) - idempotent guards log at warn or debug, not error (4 sub-cases) Reproduction: 5x kill -TERM in tight loop, before fix produces 'Cannot stop an already stopping' error log; after fix produces a single 'Graceful shutdown' info log with no error. Refs: review feedback on PR #1905 -- 1 BLOCKER, 4 MAJOR, 4 MINOR findings, all addressed in this amended commit.
1 parent f9e8ddf commit 85c1fb0

3 files changed

Lines changed: 755 additions & 136 deletions

File tree

‎cspell.config.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ words:
3333
- measurands
3434
- mikro
3535
- neostandard
36+
- entrancy
3637
- recurrency
3738
- shutdowning
3839
- VCAP

‎src/charging-station/Bootstrap.ts‎

Lines changed: 189 additions & 136 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ enum exitCodes {
6666
gracefulShutdownError = 4,
6767
}
6868

69+
/**
70+
* Reason for a `Bootstrap.stop` invocation. Drives state-file persistence:
71+
* `user` persists `started:false` to disk; `shutdown` and `reload` do not.
72+
*
73+
* Coalescing semantics: when multiple callers invoke `stop` concurrently they
74+
* all observe the same in-flight transition. The FIRST caller's `reason`
75+
* controls persistence; later callers' `reason` values are ignored. A `user`
76+
* stop coalescing onto an in-flight `shutdown` or `reload` therefore does not
77+
* persist `started:false`.
78+
*/
6979
enum StopReason {
7080
reload = 'reload',
7181
shutdown = 'shutdown',
@@ -94,10 +104,13 @@ export class Bootstrap extends EventEmitter implements IBootstrap {
94104

95105
private readonly assetsDir: string
96106
private readonly configurationsDir: string
107+
private shuttingDown: boolean
97108
private started: boolean
98109
private starting: boolean
110+
private startPromise?: Promise<void>
99111
private readonly stateFilePath: string
100112
private stopping: boolean
113+
private stopPromise?: Promise<void>
101114
private storage?: Storage
102115
private readonly templateStatistics: Map<string, TemplateStatistics>
103116
private readonly uiServer: AbstractUIServer
@@ -148,6 +161,7 @@ export class Bootstrap extends EventEmitter implements IBootstrap {
148161
this.started = false
149162
this.starting = false
150163
this.stopping = false
164+
this.shuttingDown = false
151165
this.uiServerStarted = false
152166
this.templateStatistics = new Map<string, TemplateStatistics>()
153167
this.assetsDir = join(dirname(fileURLToPath(import.meta.url)), 'assets')
@@ -240,119 +254,22 @@ export class Bootstrap extends EventEmitter implements IBootstrap {
240254
}
241255

242256
public async start (): Promise<void> {
243-
if (!this.started) {
244-
if (!this.starting) {
245-
this.starting = true
246-
try {
247-
this.on(ChargingStationWorkerMessageEvents.added, this.workerEventAdded)
248-
this.on(ChargingStationWorkerMessageEvents.deleted, this.workerEventDeleted)
249-
this.on(ChargingStationWorkerMessageEvents.started, this.workerEventStarted)
250-
this.on(ChargingStationWorkerMessageEvents.stopped, this.workerEventStopped)
251-
this.on(ChargingStationWorkerMessageEvents.updated, this.workerEventUpdated)
252-
this.on(
253-
ChargingStationWorkerMessageEvents.performanceStatistics,
254-
this.workerEventPerformanceStatistics
255-
)
256-
// eslint-disable-next-line @typescript-eslint/unbound-method
257-
if (isAsyncFunction(this.workerImplementation?.start)) {
258-
await this.workerImplementation.start()
259-
} else {
260-
;(this.workerImplementation?.start as () => void)()
261-
}
262-
const performanceStorageConfiguration =
263-
Configuration.getConfigurationSection<StorageConfiguration>(
264-
ConfigurationSection.performanceStorage
265-
)
266-
if (performanceStorageConfiguration.enabled === true) {
267-
const storageType = performanceStorageConfiguration.type
268-
const storageUri = performanceStorageConfiguration.uri
269-
if (storageType != null && storageUri != null) {
270-
this.storage = StorageFactory.getStorage(storageType, storageUri, this.logPrefix())
271-
await this.storage.open()
272-
}
273-
}
274-
this.startUIServer()
275-
// Start ChargingStation object instance in worker thread
276-
for (const stationTemplateUrl of Configuration.getStationTemplateUrls() ?? []) {
277-
const nbStations = stationTemplateUrl.numberOfStations
278-
const sequentialAdd =
279-
(Configuration.getConfigurationSection<WorkerConfiguration>(
280-
ConfigurationSection.worker
281-
).elementAddDelay ?? 0) > 0
282-
if (sequentialAdd) {
283-
for (let index = 1; index <= nbStations; index++) {
284-
try {
285-
await this.addChargingStation(index, stationTemplateUrl.file)
286-
} catch (error) {
287-
logger.error(
288-
`${this.logPrefix()} ${moduleName}.start: Error at starting charging station with template file ${stationTemplateUrl.file}:`,
289-
error
290-
)
291-
}
292-
}
293-
} else {
294-
const results = await Promise.allSettled(
295-
Array.from({ length: nbStations }, (_, i) =>
296-
this.addChargingStation(i + 1, stationTemplateUrl.file)
297-
)
298-
)
299-
for (const result of results) {
300-
if (result.status === 'rejected') {
301-
logger.error(
302-
`${this.logPrefix()} ${moduleName}.start: Error at starting charging station with template file ${stationTemplateUrl.file}:`,
303-
result.reason
304-
)
305-
}
306-
}
307-
}
308-
}
309-
const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
310-
ConfigurationSection.worker
311-
)
312-
logger.info(
313-
`${this.logPrefix()} ${moduleName}.start: Charging stations simulator ${this.version} started with ${this.numberOfConfiguredChargingStations.toString()} configured and ${this.numberOfProvisionedChargingStations.toString()} provisioned charging station(s) from ${this.numberOfChargingStationTemplates.toString()} charging station template(s) and ${
314-
Configuration.workerDynamicPoolInUse()
315-
? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
316-
`${workerConfiguration.poolMinSize?.toString()}/`
317-
: ''
318-
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
319-
}${this.workerImplementation?.size.toString()}${
320-
Configuration.workerPoolInUse()
321-
? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
322-
`/${workerConfiguration.poolMaxSize?.toString()}`
323-
: ''
324-
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
325-
} worker(s) concurrently running in '${workerConfiguration.processType}' mode${
326-
this.workerImplementation?.maxElementsPerWorker != null
327-
? ` (${this.workerImplementation.maxElementsPerWorker.toString()} charging station(s) per worker)`
328-
: ''
329-
}`
330-
)
331-
Configuration.workerDynamicPoolInUse() &&
332-
logger.warn(
333-
`${this.logPrefix()} ${moduleName}.start: Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using fixed pool or worker set mode instead`
334-
)
335-
logger.info(
336-
`${this.logPrefix()} ${moduleName}.start: Worker set/pool information:`,
337-
this.workerImplementation?.info
338-
)
339-
this.started = true
340-
if (this.persistStateEnabled) {
341-
await writeStateFile(this.stateFilePath, true, this.logPrefix)
342-
}
343-
} finally {
344-
this.starting = false
345-
}
346-
} else {
347-
logger.error(
348-
`${this.logPrefix()} ${moduleName}.start: Cannot start an already starting charging stations simulator`
349-
)
350-
}
351-
} else {
352-
logger.error(
257+
if (this.started) {
258+
logger.warn(
353259
`${this.logPrefix()} ${moduleName}.start: Cannot start an already started charging stations simulator`
354260
)
261+
return
262+
}
263+
if (this.startPromise != null) {
264+
logger.debug(
265+
`${this.logPrefix()} ${moduleName}.start: Awaiting an already in-flight start of the charging stations simulator`
266+
)
267+
return this.startPromise
355268
}
269+
this.startPromise = this.doStart().finally(() => {
270+
this.startPromise = undefined
271+
})
272+
return this.startPromise
356273
}
357274

358275
public startUIServer (): void {
@@ -370,44 +287,180 @@ export class Bootstrap extends EventEmitter implements IBootstrap {
370287
this.uiServerStarted = true
371288
}
372289

290+
/**
291+
* Stops the simulator. Idempotent and concurrency-safe.
292+
*
293+
* If a stop is already in flight, returns the same `Promise<void>` to all
294+
* callers. The FIRST caller's `reason` controls the in-flight transition's
295+
* persistence semantics; later callers' `reason` values are ignored. See
296+
* the {@link StopReason} doc-comment for the coalescing contract.
297+
*
298+
* If the simulator is already stopped and `reason === StopReason.user`,
299+
* reconciles a stale `started:true` state file by writing `started:false`.
300+
* For `reason !== StopReason.user` the no-op branch returns silently
301+
* without touching the state file; a stale `started:true` is then
302+
* reconciled only by the next `stop(user)` or successful `start()`.
303+
* @param reason - Stop reason; defaults to {@link StopReason.user}.
304+
* @returns A `Promise<void>` that resolves when the stop transition finishes.
305+
*/
373306
public async stop (reason: StopReason = StopReason.user): Promise<void> {
374-
if (this.started) {
375-
if (!this.stopping) {
376-
this.stopping = true
377-
try {
378-
await this.uiServer.sendInternalRequest(
379-
this.uiServer.buildProtocolRequest(
380-
generateUUID(),
381-
ProcedureName.STOP_CHARGING_STATION,
382-
Constants.EMPTY_FROZEN_OBJECT
307+
if (!this.started) {
308+
logger.warn(
309+
`${this.logPrefix()} ${moduleName}.stop: Cannot stop an already stopped charging stations simulator`
310+
)
311+
if (this.persistStateEnabled && reason === StopReason.user) {
312+
const stateFile = readStateFile(this.stateFilePath, this.logPrefix)
313+
if (stateFile?.started === true) {
314+
await writeStateFile(this.stateFilePath, false, this.logPrefix)
315+
}
316+
}
317+
return
318+
}
319+
if (this.stopPromise != null) {
320+
logger.debug(
321+
`${this.logPrefix()} ${moduleName}.stop: Awaiting an already in-flight stop of the charging stations simulator`
322+
)
323+
return this.stopPromise
324+
}
325+
this.stopPromise = this.doStop(reason).finally(() => {
326+
this.stopPromise = undefined
327+
})
328+
return this.stopPromise
329+
}
330+
331+
private async doStart (): Promise<void> {
332+
this.starting = true
333+
try {
334+
this.on(ChargingStationWorkerMessageEvents.added, this.workerEventAdded)
335+
this.on(ChargingStationWorkerMessageEvents.deleted, this.workerEventDeleted)
336+
this.on(ChargingStationWorkerMessageEvents.started, this.workerEventStarted)
337+
this.on(ChargingStationWorkerMessageEvents.stopped, this.workerEventStopped)
338+
this.on(ChargingStationWorkerMessageEvents.updated, this.workerEventUpdated)
339+
this.on(
340+
ChargingStationWorkerMessageEvents.performanceStatistics,
341+
this.workerEventPerformanceStatistics
342+
)
343+
// eslint-disable-next-line @typescript-eslint/unbound-method
344+
if (isAsyncFunction(this.workerImplementation?.start)) {
345+
await this.workerImplementation.start()
346+
} else {
347+
;(this.workerImplementation?.start as () => void)()
348+
}
349+
const performanceStorageConfiguration =
350+
Configuration.getConfigurationSection<StorageConfiguration>(
351+
ConfigurationSection.performanceStorage
352+
)
353+
if (performanceStorageConfiguration.enabled === true) {
354+
const storageType = performanceStorageConfiguration.type
355+
const storageUri = performanceStorageConfiguration.uri
356+
if (storageType != null && storageUri != null) {
357+
this.storage = StorageFactory.getStorage(storageType, storageUri, this.logPrefix())
358+
await this.storage.open()
359+
}
360+
}
361+
this.startUIServer()
362+
// Start ChargingStation object instance in worker thread
363+
for (const stationTemplateUrl of Configuration.getStationTemplateUrls() ?? []) {
364+
const nbStations = stationTemplateUrl.numberOfStations
365+
const sequentialAdd =
366+
(Configuration.getConfigurationSection<WorkerConfiguration>(ConfigurationSection.worker)
367+
.elementAddDelay ?? 0) > 0
368+
if (sequentialAdd) {
369+
for (let index = 1; index <= nbStations; index++) {
370+
try {
371+
await this.addChargingStation(index, stationTemplateUrl.file)
372+
} catch (error) {
373+
logger.error(
374+
`${this.logPrefix()} ${moduleName}.start: Error at starting charging station with template file ${stationTemplateUrl.file}:`,
375+
error
376+
)
377+
}
378+
}
379+
} else {
380+
const results = await Promise.allSettled(
381+
Array.from({ length: nbStations }, (_, i) =>
382+
this.addChargingStation(i + 1, stationTemplateUrl.file)
383383
)
384384
)
385-
await this.waitChargingStationsStopped()
386-
await this.workerImplementation?.stop()
387-
this.removeAllListeners()
388-
this.uiServer.clearCaches()
389-
await this.storage?.close()
390-
delete this.storage
391-
this.started = false
392-
if (this.persistStateEnabled && reason === StopReason.user) {
393-
await writeStateFile(this.stateFilePath, false, this.logPrefix)
385+
for (const result of results) {
386+
if (result.status === 'rejected') {
387+
logger.error(
388+
`${this.logPrefix()} ${moduleName}.start: Error at starting charging station with template file ${stationTemplateUrl.file}:`,
389+
result.reason
390+
)
391+
}
394392
}
395-
} finally {
396-
this.stopping = false
397393
}
398-
} else {
399-
logger.error(
400-
`${this.logPrefix()} ${moduleName}.stop: Cannot stop an already stopping charging stations simulator`
394+
}
395+
const workerConfiguration = Configuration.getConfigurationSection<WorkerConfiguration>(
396+
ConfigurationSection.worker
397+
)
398+
logger.info(
399+
`${this.logPrefix()} ${moduleName}.start: Charging stations simulator ${this.version} started with ${this.numberOfConfiguredChargingStations.toString()} configured and ${this.numberOfProvisionedChargingStations.toString()} provisioned charging station(s) from ${this.numberOfChargingStationTemplates.toString()} charging station template(s) and ${
400+
Configuration.workerDynamicPoolInUse()
401+
? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
402+
`${workerConfiguration.poolMinSize?.toString()}/`
403+
: ''
404+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
405+
}${this.workerImplementation?.size.toString()}${
406+
Configuration.workerPoolInUse()
407+
? // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
408+
`/${workerConfiguration.poolMaxSize?.toString()}`
409+
: ''
410+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
411+
} worker(s) concurrently running in '${workerConfiguration.processType}' mode${
412+
this.workerImplementation?.maxElementsPerWorker != null
413+
? ` (${this.workerImplementation.maxElementsPerWorker.toString()} charging station(s) per worker)`
414+
: ''
415+
}`
416+
)
417+
Configuration.workerDynamicPoolInUse() &&
418+
logger.warn(
419+
`${this.logPrefix()} ${moduleName}.start: Charging stations simulator is using dynamic pool mode. This is an experimental feature with known issues.\nPlease consider using fixed pool or worker set mode instead`
401420
)
421+
logger.info(
422+
`${this.logPrefix()} ${moduleName}.start: Worker set/pool information:`,
423+
this.workerImplementation?.info
424+
)
425+
this.started = true
426+
if (this.persistStateEnabled) {
427+
await writeStateFile(this.stateFilePath, true, this.logPrefix)
402428
}
403-
} else {
404-
logger.error(
405-
`${this.logPrefix()} ${moduleName}.stop: Cannot stop an already stopped charging stations simulator`
429+
} finally {
430+
this.starting = false
431+
}
432+
}
433+
434+
private async doStop (reason: StopReason): Promise<void> {
435+
this.stopping = true
436+
try {
437+
await this.uiServer.sendInternalRequest(
438+
this.uiServer.buildProtocolRequest(
439+
generateUUID(),
440+
ProcedureName.STOP_CHARGING_STATION,
441+
Constants.EMPTY_FROZEN_OBJECT
442+
)
406443
)
444+
await this.waitChargingStationsStopped()
445+
await this.workerImplementation?.stop()
446+
this.removeAllListeners()
447+
this.uiServer.clearCaches()
448+
await this.storage?.close()
449+
delete this.storage
450+
this.started = false
451+
if (this.persistStateEnabled && reason === StopReason.user) {
452+
await writeStateFile(this.stateFilePath, false, this.logPrefix)
453+
}
454+
} finally {
455+
this.stopping = false
407456
}
408457
}
409458

410459
private gracefulShutdown (): void {
460+
if (this.shuttingDown) {
461+
return
462+
}
463+
this.shuttingDown = true
411464
this.stop(StopReason.shutdown)
412465
.then(() => {
413466
logger.info(`${this.logPrefix()} ${moduleName}.gracefulShutdown: Graceful shutdown`)

0 commit comments

Comments
 (0)