Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript

fix(supervisor): await child exit before restarting services

Samir Hanna Verzaace9b0ff398e
diff --git a/apps/control-center/src/__tests__/control-center.test.js b/apps/control-center/src/__tests__/control-center.test.js
index a770857..59f4c15 100644
--- a/apps/control-center/src/__tests__/control-center.test.js
+++ b/apps/control-center/src/__tests__/control-center.test.js
@@ -1,6 +1,10 @@
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { once } from 'node:events';
import { getAdminToken } from '@youpi/common';
import { startControlCenter } from '../index.js';
import { ProcessManager } from '../process-manager.js';
@@ -121,3 +125,99 @@ describe('Control Center Supervisor Integration Tests', () => {
assert.equal(healthCheck.body.status, 'UP');
});
});
+
+describe('ProcessManager child lifecycle', () => {
+ function fixture(t, shutdownBody, options = {}) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'youpi-process-test-'));
+ const script = path.join(directory, 'service.cjs');
+ fs.writeFileSync(script, `
+ process.on('SIGTERM', () => { ${shutdownBody} });
+ setInterval(() => {}, 1000);
+ process.send('ready');
+ `);
+ const pm = new ProcessManager(options);
+ pm.services = [{ id: 'fixture', name: 'Lifecycle fixture', script, port: 1, status: 'STOPPED', child: null }];
+ const children = [];
+ t.after(async () => {
+ for (const child of children) {
+ if (child.exitCode === null && child.signalCode === null) {
+ const exited = once(child, 'exit');
+ child.kill('SIGKILL');
+ await exited;
+ }
+ }
+ fs.rmSync(directory, { recursive: true, force: true });
+ });
+ return {
+ pm,
+ children,
+ async start() {
+ const svc = await pm.startService('fixture');
+ children.push(svc.child);
+ await once(svc.child, 'message');
+ return svc;
+ }
+ };
+ }
+
+ test('stopService resolves only after the child exits', async (t) => {
+ const { pm, start } = fixture(t, 'setTimeout(() => process.exit(0), 100);');
+ const svc = await start();
+ const child = svc.child;
+ const stopping = pm.stopService('fixture');
+ assert.ok(svc.child === child, 'the process must remain tracked while it is alive');
+ await stopping;
+ assert.equal(child.exitCode, 0);
+ assert.equal(svc.child, null);
+ assert.equal(svc.status, 'STOPPED');
+ assert.equal(svc.pid, null);
+ });
+
+ test('restart waits for a slow shutdown and retains the replacement child', async (t) => {
+ const { pm, start, children } = fixture(t, 'setTimeout(() => process.exit(0), 800);');
+ const svc = await start();
+ const original = svc.child;
+ const originalExit = once(original, 'exit');
+ await pm.restartService('fixture');
+ const replacement = svc.child;
+ children.push(replacement);
+ await once(replacement, 'message');
+ const originalExitedBeforeReplacement = original.exitCode !== null;
+ await originalExit;
+
+ assert.equal(originalExitedBeforeReplacement, true, 'replacement must start after the original exits');
+ assert.notEqual(replacement.pid, original.pid);
+ assert.equal(svc.child, replacement, 'an old exit event must not detach the replacement');
+ assert.equal(svc.pid, replacement.pid);
+ assert.equal(svc.status, 'RUNNING');
+ });
+
+ test('a start arriving during stop waits instead of spawning an overlapping child', async (t) => {
+ const { pm, start, children } = fixture(t, 'setTimeout(() => process.exit(0), 100);');
+ const svc = await start();
+ const original = svc.child;
+ const stopping = pm.stopService('fixture');
+ const restarting = pm.startService('fixture');
+ await stopping;
+ await restarting;
+ const replacement = svc.child;
+ children.push(replacement);
+ await once(replacement, 'message');
+
+ assert.equal(original.exitCode, 0);
+ assert.notEqual(replacement.pid, original.pid);
+ assert.equal(svc.child, replacement);
+ assert.equal(svc.status, 'RUNNING');
+ });
+
+ test('a child ignoring SIGTERM is killed after the graceful shutdown deadline', async (t) => {
+ const { pm, start } = fixture(t, '', { stopTimeoutMs: 50 });
+ const svc = await start();
+ const original = svc.child;
+ await pm.stopService('fixture');
+
+ assert.equal(original.signalCode, 'SIGKILL');
+ assert.equal(svc.status, 'STOPPED');
+ assert.equal(svc.child, null);
+ });
+});
diff --git a/apps/control-center/src/process-manager.js b/apps/control-center/src/process-manager.js
index eb73f02..422e453 100644
--- a/apps/control-center/src/process-manager.js
+++ b/apps/control-center/src/process-manager.js
@@ -9,8 +9,9 @@ const __dirname = path.dirname(__filename);
const rootDir = path.resolve(__dirname, '../../..');
export class ProcessManager extends EventEmitter {
- constructor() {
+ constructor(options = {}) {
super();
+ this.stopTimeoutMs = options.stopTimeoutMs ?? 5000;
// Registry of managed native host services
this.services = [
@@ -125,6 +126,7 @@ export class ProcessManager extends EventEmitter {
async startService(id) {
const svc = this.getService(id);
if (!svc) throw new Error(`Unknown service: ${id}`);
+ if (svc.stopPromise) await svc.stopPromise;
if (svc.status === 'RUNNING' && svc.child) return svc;
svc.status = 'STARTING';
@@ -175,6 +177,7 @@ export class ProcessManager extends EventEmitter {
child.on('exit', (code, signal) => {
this.appendLog(svc.id, 'system', `Process exited with code ${code} (signal: ${signal})`);
+ if (svc.child !== child) return;
svc.status = 'STOPPED';
svc.child = null;
svc.pid = null;
@@ -195,6 +198,10 @@ export class ProcessManager extends EventEmitter {
async stopService(id) {
const svc = this.getService(id);
if (!svc) throw new Error(`Unknown service: ${id}`);
+ if (svc.stopPromise) {
+ await svc.stopPromise;
+ return svc;
+ }
if (!svc.child) {
svc.status = 'STOPPED';
return svc;
@@ -202,24 +209,44 @@ export class ProcessManager extends EventEmitter {
this.appendLog(svc.id, 'system', `Stopping ${svc.name} (PID ${svc.pid})...`);
+ const child = svc.child;
+ // Retain ownership until exit: kill() only sends a signal. A fixed restart
+ // delay can otherwise overlap children and let an old exit detach the new one.
+ const stopping = new Promise((resolve, reject) => {
+ const cleanup = () => {
+ clearTimeout(killTimer);
+ child.removeListener('exit', onExit);
+ child.removeListener('error', onError);
+ };
+ const onExit = () => {
+ cleanup();
+ resolve();
+ };
+ const onError = (err) => {
+ cleanup();
+ reject(err);
+ };
+ const killTimer = setTimeout(() => {
+ this.appendLog(svc.id, 'system', `Graceful shutdown timed out; killing PID ${child.pid}`);
+ try { child.kill('SIGKILL'); } catch (err) { onError(err); }
+ }, this.stopTimeoutMs);
+ killTimer.unref();
+ child.once('exit', onExit);
+ child.once('error', onError);
+ try { child.kill('SIGTERM'); } catch (err) { onError(err); }
+ });
+ svc.stopPromise = stopping;
try {
- svc.child.kill('SIGTERM');
- } catch {
- try { svc.child.kill('SIGKILL'); } catch {}
+ await stopping;
+ } finally {
+ if (svc.stopPromise === stopping) svc.stopPromise = null;
}
- svc.child = null;
- svc.status = 'STOPPED';
- svc.pid = null;
- svc.startTime = null;
-
- this.emit('status_change', { id: svc.id, status: svc.status });
return svc;
}
async restartService(id) {
await this.stopService(id);
- await new Promise(r => setTimeout(r, 500));
return await this.startService(id);
}