Files
Online-Topup-V1/application/tests/graceful-shutdown.test.js
T
2026-11-26 17:18:30 +07:00

310 lines
8.8 KiB
JavaScript

const http = require('node:http');
const { EventEmitter } = require('node:events');
const {
createGracefulShutdown,
createClusterShutdown,
} = require('../../infrastructure/graceful-shutdown');
function createLoggerSpy() {
return {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
};
}
test('menunggu request HTTP aktif selesai sebelum menutup resource dan keluar dengan kode 0', async () => {
const order = [];
let releaseInFlight;
const inFlightStarted = new Promise((resolve) => {
releaseInFlight = resolve;
});
let respondNow;
const holdResponse = new Promise((resolve) => {
respondNow = resolve;
});
const server = http.createServer(async (req, res) => {
order.push('http:start');
releaseInFlight();
await holdResponse;
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
order.push('http:end');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address();
const exit = jest.fn();
const logger = createLoggerSpy();
const onBeforeClose = jest.fn(() => order.push('before-close'));
const cleanupTasks = [
{ name: 'postgres', close: jest.fn(async () => order.push('cleanup:postgres')) },
{ name: 'redis', close: jest.fn(async () => order.push('cleanup:redis')) },
];
const manager = createGracefulShutdown({
servers: [server],
cleanupTasks,
onBeforeClose,
timeoutMs: 2000,
logger,
exit,
});
const responsePromise = fetch(`http://127.0.0.1:${port}/test`);
await inFlightStarted;
const shutdownPromise = manager.shutdown('SIGTERM');
expect(manager.isShuttingDown()).toBe(true);
expect(onBeforeClose).toHaveBeenCalledWith('SIGTERM');
// Cleanup belum boleh jalan selama request HTTP aktif belum selesai.
expect(cleanupTasks[0].close).not.toHaveBeenCalled();
respondNow();
const response = await responsePromise;
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ ok: true });
await shutdownPromise;
expect(order).toEqual([
'http:start',
'before-close',
'http:end',
'cleanup:postgres',
'cleanup:redis',
]);
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(0);
});
test('panggilan shutdown berulang bersifat idempoten dan hanya menjalankan cleanup sekali', async () => {
const server = {
listening: true,
close: jest.fn((cb) => cb()),
closeIdleConnections: jest.fn(),
};
const cleanup = jest.fn(async () => {});
const onBeforeClose = jest.fn();
const exit = jest.fn();
const manager = createGracefulShutdown({
servers: [server],
cleanupTasks: [{ name: 'db', close: cleanup }],
onBeforeClose,
timeoutMs: 1000,
exit,
});
const p1 = manager.shutdown('SIGTERM');
const p2 = manager.shutdown('SIGINT');
expect(p1).toBe(p2);
await Promise.all([p1, p2]);
expect(onBeforeClose).toHaveBeenCalledTimes(1);
expect(server.close).toHaveBeenCalledTimes(1);
expect(server.closeIdleConnections).toHaveBeenCalledTimes(1);
expect(cleanup).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(0);
});
test('kegagalan salah satu cleanup tidak menghentikan cleanup lain dan keluar dengan kode 1', async () => {
const logger = createLoggerSpy();
const exit = jest.fn();
const failingCleanup = jest.fn(async () => {
throw new Error('redis quit error');
});
const healthyCleanup = jest.fn(async () => {});
const manager = createGracefulShutdown({
servers: [],
cleanupTasks: [
{ name: 'redis', close: failingCleanup },
{ name: 'postgres', close: healthyCleanup },
],
timeoutMs: 1000,
logger,
exit,
});
await manager.shutdown('SIGTERM');
expect(failingCleanup).toHaveBeenCalledTimes(1);
expect(healthyCleanup).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('redis: redis quit error'));
expect(exit).toHaveBeenCalledWith(1);
});
test('memaksa tutup koneksi dan keluar dengan kode 1 jika shutdown melewati batas waktu', async () => {
jest.useFakeTimers();
try {
const server = {
listening: true,
close: jest.fn(() => {
// Simulasikan server menggantung dan tidak pernah memanggil callback close.
}),
closeIdleConnections: jest.fn(),
closeAllConnections: jest.fn(),
};
const logger = createLoggerSpy();
const exit = jest.fn();
const manager = createGracefulShutdown({
servers: [server],
timeoutMs: 500,
logger,
exit,
});
void manager.shutdown('SIGTERM');
await jest.advanceTimersByTimeAsync(500);
expect(server.closeAllConnections).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('timed out'));
expect(exit).toHaveBeenCalledWith(1);
} finally {
jest.useRealTimers();
}
});
test('installSignalHandlers mendaftarkan SIGTERM/SIGINT dan uninstall melepas listener', async () => {
const targetProcess = new EventEmitter();
const exit = jest.fn();
const manager = createGracefulShutdown({
servers: [],
cleanupTasks: [],
timeoutMs: 1000,
exit,
});
const uninstall = manager.installSignalHandlers(targetProcess);
expect(targetProcess.listenerCount('SIGTERM')).toBe(1);
expect(targetProcess.listenerCount('SIGINT')).toBe(1);
targetProcess.emit('SIGINT');
await new Promise((resolve) => setImmediate(resolve));
expect(manager.isShuttingDown()).toBe(true);
expect(exit).toHaveBeenCalledWith(0);
uninstall();
expect(targetProcess.listenerCount('SIGTERM')).toBe(0);
expect(targetProcess.listenerCount('SIGINT')).toBe(0);
});
test('cluster primary mematikan worker tanpa respawn dan keluar dengan kode 0 saat semua worker berhenti', async () => {
const clusterModule = new EventEmitter();
const worker1 = Object.assign(new EventEmitter(), {
id: 1,
isDead: () => false,
kill: jest.fn(),
});
const worker2 = Object.assign(new EventEmitter(), {
id: 2,
isDead: () => false,
kill: jest.fn(),
});
clusterModule.workers = { 1: worker1, 2: worker2 };
const exit = jest.fn();
const clusterShutdown = createClusterShutdown({
clusterModule,
timeoutMs: 2000,
logger: createLoggerSpy(),
exit,
});
const promise = clusterShutdown.shutdown('SIGTERM');
expect(clusterShutdown.isShuttingDown()).toBe(true);
expect(worker1.kill).toHaveBeenCalledWith('SIGTERM');
expect(worker2.kill).toHaveBeenCalledWith('SIGTERM');
clusterModule.emit('exit', worker1);
expect(exit).not.toHaveBeenCalled();
clusterModule.emit('exit', worker2);
await promise;
expect(exit).toHaveBeenCalledTimes(1);
expect(exit).toHaveBeenCalledWith(0);
});
test('cluster primary mengirim SIGKILL dan keluar kode 1 jika worker melewati timeout', async () => {
jest.useFakeTimers();
try {
const clusterModule = new EventEmitter();
const stuckWorker = Object.assign(new EventEmitter(), {
id: 1,
isDead: () => false,
kill: jest.fn(),
process: { kill: jest.fn() },
});
clusterModule.workers = { 1: stuckWorker };
const exit = jest.fn();
const clusterShutdown = createClusterShutdown({
clusterModule,
timeoutMs: 300,
logger: createLoggerSpy(),
exit,
});
void clusterShutdown.shutdown('SIGTERM');
await jest.advanceTimersByTimeAsync(300);
expect(stuckWorker.kill).toHaveBeenCalledWith('SIGTERM');
expect(stuckWorker.process.kill).toHaveBeenCalledWith('SIGKILL');
expect(exit).toHaveBeenCalledWith(1);
} finally {
jest.useRealTimers();
}
});
test('closeRedis menutup koneksi terbuka dengan quit dan fallback disconnect saat quit gagal', async () => {
const mockClient = {
isOpen: false,
isReady: false,
on: jest.fn(),
connect: jest.fn(async () => {}),
quit: jest.fn(async () => {}),
disconnect: jest.fn(async () => {}),
};
let closeRedis;
try {
jest.isolateModules(() => {
jest.doMock('redis', () => ({ createClient: () => mockClient }));
({ closeRedis } = require('../middlewares/redis.middleware'));
});
await closeRedis();
expect(mockClient.quit).not.toHaveBeenCalled();
mockClient.isOpen = true;
await closeRedis();
expect(mockClient.quit).toHaveBeenCalledTimes(1);
mockClient.quit.mockRejectedValueOnce(new Error('quit failed'));
await closeRedis();
expect(mockClient.disconnect).toHaveBeenCalledTimes(1);
} finally {
jest.dontMock('redis');
}
});
test('melempar error jika SHUTDOWN_TIMEOUT_MS tidak valid', () => {
const previous = process.env.SHUTDOWN_TIMEOUT_MS;
process.env.SHUTDOWN_TIMEOUT_MS = '0';
try {
expect(() => createGracefulShutdown()).toThrow('SHUTDOWN_TIMEOUT_MS must be a positive integer');
} finally {
if (previous === undefined) delete process.env.SHUTDOWN_TIMEOUT_MS;
else process.env.SHUTDOWN_TIMEOUT_MS = previous;
}
});