MCPcopy Create free account
hub / github.com/TraderAlice/OpenAlice / installCascadeShutdown

Function installCascadeShutdown

scripts/guardian/shared.ts:304–355  ·  view source on GitHub ↗
(opts: CascadeOpts)

Source from the content-addressed store, hash-verified

302}
303
304export function installCascadeShutdown(opts: CascadeOpts): CascadeControl {
305 let stopping = false
306 const graceMs = opts.graceMs ?? 5_000
307 const expected = opts.expectedExits ?? new Set<ChildProcess>()
308 const children = [...opts.children]
309
310 const shutdown = (): void => {
311 if (stopping) return
312 stopping = true
313 for (const c of children) {
314 if (c.exitCode === null && !c.killed) {
315 killTree(c, 'SIGTERM')
316 }
317 }
318 setTimeout(() => {
319 for (const c of children) {
320 if (c.exitCode === null && !c.killed) {
321 killTree(c, 'SIGKILL')
322 }
323 }
324 process.exit(0)
325 }, graceMs).unref()
326 }
327
328 const attachExitListener = (child: ChildProcess): void => {
329 child.once('exit', (code, signal) => {
330 if (stopping) return
331 if (expected.has(child)) {
332 expected.delete(child)
333 return
334 }
335 console.log(`[guardian] ${childTag(child, children)} exited (code=${code}, signal=${signal}) — cascading shutdown`)
336 shutdown()
337 })
338 }
339
340 for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) {
341 process.on(sig, shutdown)
342 }
343 for (const child of children) attachExitListener(child)
344
345 return {
346 shutdown,
347 expectExit: (child) => { expected.add(child) },
348 trackReplacement: (old, next) => {
349 const idx = children.indexOf(old)
350 if (idx >= 0) children[idx] = next
351 else children.push(next)
352 attachExitListener(next)
353 },
354 }
355}
356
357function childTag(c: ChildProcess, _all: ChildProcess[]): string {
358 // Minimal tagging — argv hint when available. Refined naming requires

Callers 1

mainFunction · 0.85

Calls 3

attachExitListenerFunction · 0.85
addMethod · 0.65
pushMethod · 0.65

Tested by

no test coverage detected