update upgrade node

This commit is contained in:
teddys48
2026-11-26 17:18:30 +07:00
parent 85fa8843d8
commit dd7b081550
14 changed files with 2078 additions and 2457 deletions
+49
View File
@@ -0,0 +1,49 @@
# Dependencies & caches (installed cleanly inside Docker build)
node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.npm
.eslintcache
# Environment & secret files (inject at runtime via --env-file or orchestrator)
.env
.env.*
env
env.copy
# Version control, CI, editor, and agent metadata
.git
.gitignore
.github
.editorconfig
.vscode
.idea
.agents
.gemini
skills
eslint.config.cjs
Dockerfile
.dockerignore
docker-compose*.yml
docker-compose*.yaml
# Logs, audit archives, coverage, and runtime artifacts
logs
*.log
lokiLog
expresswinstonlog
coverage
.nyc_output
*.pid
*.seed
*.pid.lock
report.*.json
# Documentation & tests (not needed in production image)
README.md
*.md
docs
application/tests
**/*.test.js
**/*.spec.js
+1 -1
View File
@@ -31,7 +31,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '24'
node-version: '26.13.1'
cache: npm
- run: npm ci
- run: npm run lint
+59
View File
@@ -0,0 +1,59 @@
# syntax=docker/dockerfile:1
# ==============================================================================
# Stage 1: Production dependencies
# ==============================================================================
FROM node:26.13.1-alpine3.24 AS deps
WORKDIR /app
# Native addon build dependencies
RUN apk add --no-cache python3 make g++
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
npm ci --omit=dev --no-audit --no-fund
# ==============================================================================
# Stage 2: Production runtime
# ==============================================================================
FROM node:26.13.1-alpine3.24 AS runtime
# OS security updates and runtime dependencies
RUN apk upgrade --no-cache \
&& apk add --no-cache tini tzdata
ENV NODE_ENV=production \
PORT=3000 \
TZ=Asia/Jakarta \
NO_COLOR=1
WORKDIR /app
# Runtime writable directories
RUN mkdir -p /app/logs /app/lokiLog/audit \
&& chown -R node:node /app
# Production dependencies
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
# Application files
COPY --chown=node:node package.json knexfile.js index.js ./
COPY --chown=node:node server ./server
COPY --chown=node:node infrastructure ./infrastructure
COPY --chown=node:node application ./application
COPY --chown=node:node public ./public
# Non-root execution
USER node
EXPOSE 3000
# Healthcheck
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
CMD ["node", "-e", "fetch('http://127.0.0.1:' + (process.env.PORT || 3000) + '/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"]
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "index.js"]
+5 -1
View File
@@ -48,4 +48,8 @@ function record(event) {
writeStdoutLine(line);
}
module.exports = { record, auditMetrics: [auditErrors, retentionErrors] };
function close() {
archive.close();
}
module.exports = { record, close, auditMetrics: [auditErrors, retentionErrors] };
+10 -1
View File
@@ -33,4 +33,13 @@ async function redisMiddleware(req, res, next) {
next();
}
module.exports = { redisMiddleware };
async function closeRedis() {
if (!redisClient.isOpen) return;
try {
await redisClient.quit();
} catch {
if (redisClient.isOpen) await redisClient.disconnect().catch(() => {});
}
}
module.exports = { redisMiddleware, closeRedis };
+5 -1
View File
@@ -82,4 +82,8 @@ const syncBatch = () => processBatch("valid", "b_sync", syncLock, async (trx, ca
await knex.transaction((main) => ensureCards(main, "t_m_card_product", cards));
});
module.exports = { insertRawCards, validateBatch, syncBatch };
function closePool() {
return dbPooling.destroy();
}
module.exports = { insertRawCards, validateBatch, syncBatch, closePool };
+309
View File
@@ -0,0 +1,309 @@
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;
}
});
+15 -1
View File
@@ -12,12 +12,26 @@ jest.mock('../middlewares/response-telemetry.middleware', () => ({
const app = require('../../server');
test('entry point menyajikan halaman utama, file publik, dan metrik', async () => {
test('entry point menyajikan halaman utama, file publik, metrik, dan health', async () => {
await request(app).get('/').expect(200, { message: 'Welcome to Topup Online Service.', data: {} });
await request(app).get('/health').expect(200, { status: 'ok' });
await request(app).get('/images/logo_portal_kmt.png').expect(200).expect('Content-Type', /image\/png/);
await request(app).get('/metrics').expect(200).expect('Content-Type', /text\/plain/);
});
test('health mengembalikan 503 dan header Connection close saat proses shutting down', async () => {
try {
app.setShuttingDown(true);
expect(app.isShuttingDown()).toBe(true);
const response = await request(app).get('/health').expect(503, { status: 'shutting_down' });
expect(response.headers.connection).toBe('close');
} finally {
app.setShuttingDown(false);
expect(app.isShuttingDown()).toBe(false);
}
});
test('entry point mempertahankan parse JSON, form, dan header CORS', async () => {
await request(app).post('/api/fixture')
.set('Origin', 'http://localhost:3000')
+53 -3
View File
@@ -3,6 +3,7 @@ require('./infrastructure/transaction-time').configureTransactionClock();
const cluster = require('node:cluster');
const { createServer } = require('node:http');
const { clusterWorkerCount } = require('./infrastructure/runtime-config');
const { createGracefulShutdown, createClusterShutdown } = require('./infrastructure/graceful-shutdown');
require('./knexfile'); // Validate pool limits before starting any workers.
const winston = require('./application/helpers/winston.logger');
@@ -33,23 +34,60 @@ if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
}
}
function createAppCleanupTasks() {
const knex = require('./infrastructure/database/knex');
const { closePool: closePoolingPool } = require('./application/modules/pooling/pooling.model');
const { closeRedis } = require('./application/middlewares/redis.middleware');
const { close: closeAuditArchive } = require('./application/helpers/response-audit');
return [
{ name: 'postgres-primary', close: () => knex.destroy() },
{ name: 'postgres-pooling', close: () => closePoolingPool() },
{ name: 'redis', close: () => closeRedis() },
{ name: 'audit-archive', close: () => closeAuditArchive() },
];
}
function attachWorkerShutdown(app, servers) {
const gracefulShutdown = createGracefulShutdown({
servers,
cleanupTasks: createAppCleanupTasks(),
onBeforeClose: () => app?.setShuttingDown(true),
logger: winston.logger,
});
gracefulShutdown.installSignalHandlers();
return gracefulShutdown;
}
if (clustered) {
if (cluster.isPrimary) {
const workerCount = clusterWorkerCount();
if (stickySession || multiplePorts) {
winston.logger.warn('CLUSTER_NODE=YES takes precedence over sticky session and multiple ports');
}
const clusterShutdown = createClusterShutdown({
clusterModule: cluster,
logger: winston.logger,
});
clusterShutdown.installSignalHandlers();
winston.logger.info(`Starting Node.js cluster with ${workerCount} workers`);
for (let i = 0; i < workerCount; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code) => {
if (clusterShutdown.isShuttingDown()) {
winston.logger.info(`Worker ${worker.process.pid} exited with code ${code} during shutdown`);
return;
}
winston.logger.warn(`Worker ${worker.process.pid} exited with code ${code}. Starting replacement`);
cluster.fork();
});
} else {
require('./server').listen(port, () => logListening(port, ' with cluster node'));
const app = require('./server');
const server = app.listen(port, () => logListening(port, ' with cluster node'));
attachWorkerShutdown(app, [server]);
}
} else if (stickySession) {
const workerCount = clusterWorkerCount();
@@ -60,8 +98,10 @@ if (clustered) {
}
winston.logger.info(`Starting sticky session cluster with ${workerCount} workers`);
}
let workerApp;
const server = sticky(workerCount, () => {
const workerServer = createServer(require('./server'));
workerApp = require('./server');
const workerServer = createServer(workerApp);
workerServer.on('connection', (socket) => socket.resume());
return workerServer;
});
@@ -69,6 +109,14 @@ if (clustered) {
// Keep the first HTTP bytes on the socket until the worker takes ownership.
server.pauseOnConnect = true;
server.listen(port, () => logListening(port, ' with sticky session'));
const clusterShutdown = createClusterShutdown({
clusterModule: cluster,
servers: [server],
logger: winston.logger,
});
clusterShutdown.installSignalHandlers();
} else {
attachWorkerShutdown(workerApp, [server]);
}
} else {
const app = require('./server');
@@ -80,9 +128,11 @@ if (clustered) {
} else if (multiplePorts) {
winston.logger.warn('Running on multiple ports is active but PORTS is unset');
}
const servers = [];
for (const listenPort of ports) {
app.listen(listenPort, () => logListening(listenPort));
servers.push(app.listen(listenPort, () => logListening(listenPort)));
}
attachWorkerShutdown(app, servers);
}
function logListening(listenPort, mode = '') {
+332
View File
@@ -0,0 +1,332 @@
const { positiveIntegerFromEnv } = require('./runtime-config');
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 10000;
const IDLE_SWEEP_INTERVAL_MS = 100;
const noopLogger = { info() {}, warn() {}, error() {} };
function closeHttpServer(server) {
return new Promise((resolve, reject) => {
if (!server || typeof server.close !== 'function') {
resolve();
return;
}
if (server.listening === false) {
resolve();
return;
}
let settled = false;
let idleSweepTimer;
const finish = (error) => {
if (settled) return;
settled = true;
if (idleSweepTimer) clearInterval(idleSweepTimer);
if (error && error.code !== 'ERR_SERVER_NOT_RUNNING') reject(error);
else resolve();
};
try {
server.close(finish);
if (typeof server.closeIdleConnections === 'function') {
server.closeIdleConnections();
// Close keep-alive sockets as soon as their in-flight requests finish.
idleSweepTimer = setInterval(() => {
if (!settled) server.closeIdleConnections();
}, IDLE_SWEEP_INTERVAL_MS);
if (typeof idleSweepTimer.unref === 'function') {
idleSweepTimer.unref();
}
}
} catch (error) {
finish(error);
}
});
}
function forceCloseHttpServer(server) {
if (server && typeof server.closeAllConnections === 'function') {
server.closeAllConnections();
}
}
function createGracefulShutdown({
servers = [],
cleanupTasks = [],
onBeforeClose,
timeoutMs = positiveIntegerFromEnv('SHUTDOWN_TIMEOUT_MS', DEFAULT_SHUTDOWN_TIMEOUT_MS),
logger = noopLogger,
exit = (code) => process.exit(code),
} = {}) {
let shutdownPromise = null;
let shuttingDown = false;
function isShuttingDown() {
return shuttingDown;
}
function shutdown(signal = 'SIGTERM') {
if (shutdownPromise) {
return shutdownPromise;
}
shuttingDown = true;
logger.info(`Received ${signal}; starting graceful shutdown (timeout ${timeoutMs}ms)`);
try {
if (typeof onBeforeClose === 'function') {
onBeforeClose(signal);
}
} catch (error) {
logger.error(`Pre-shutdown hook failed: ${error?.message || error}`);
}
let timedOut = false;
let timer;
shutdownPromise = (async () => {
timer = setTimeout(() => {
timedOut = true;
logger.error(`Graceful shutdown timed out after ${timeoutMs}ms; forcing connections closed`);
for (const server of servers) {
try {
forceCloseHttpServer(server);
} catch {
// Best-effort force close when shutdown deadline expires.
}
}
exit(1);
}, timeoutMs);
if (typeof timer.unref === 'function') {
timer.unref();
}
let hasErrors = false;
const serverResults = await Promise.allSettled(
servers.map((server) => closeHttpServer(server))
);
for (const result of serverResults) {
if (result.status === 'rejected') {
hasErrors = true;
logger.error(`HTTP server close failed: ${result.reason?.message || result.reason}`);
}
}
const taskResults = await Promise.allSettled(
cleanupTasks.map(async (task) => {
const name = task?.name || 'resource';
const close = typeof task === 'function' ? task : task?.close;
if (typeof close !== 'function') return;
try {
await close();
} catch (error) {
throw new Error(`${name}: ${error?.message || error}`);
}
})
);
for (const result of taskResults) {
if (result.status === 'rejected') {
hasErrors = true;
logger.error(`Resource cleanup failed during shutdown (${result.reason?.message || result.reason})`);
}
}
clearTimeout(timer);
if (!timedOut) {
if (hasErrors) {
logger.warn('Graceful shutdown completed with errors');
exit(1);
} else {
logger.info('Graceful shutdown completed cleanly');
exit(0);
}
}
})();
return shutdownPromise;
}
function installSignalHandlers(targetProcess = process, signals = ['SIGTERM', 'SIGINT']) {
const handlers = new Map();
for (const signal of signals) {
const handler = () => {
void shutdown(signal);
};
handlers.set(signal, handler);
targetProcess.on(signal, handler);
}
return () => {
for (const [signal, handler] of handlers.entries()) {
if (typeof targetProcess.off === 'function') {
targetProcess.off(signal, handler);
} else if (typeof targetProcess.removeListener === 'function') {
targetProcess.removeListener(signal, handler);
}
}
};
}
return {
shutdown,
isShuttingDown,
installSignalHandlers,
};
}
function createClusterShutdown({
clusterModule,
servers = [],
onBeforeClose,
timeoutMs = positiveIntegerFromEnv('SHUTDOWN_TIMEOUT_MS', DEFAULT_SHUTDOWN_TIMEOUT_MS),
logger = noopLogger,
exit = (code) => process.exit(code),
} = {}) {
let shutdownPromise = null;
let shuttingDown = false;
function isShuttingDown() {
return shuttingDown;
}
function shutdown(signal = 'SIGTERM') {
if (shutdownPromise) {
return shutdownPromise;
}
shuttingDown = true;
logger.info(`Cluster primary received ${signal}; shutting down workers (timeout ${timeoutMs}ms)`);
try {
if (typeof onBeforeClose === 'function') {
onBeforeClose(signal);
}
} catch (error) {
logger.error(`Cluster pre-shutdown hook failed: ${error?.message || error}`);
}
shutdownPromise = (async () => {
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
logger.error(`Cluster shutdown timed out after ${timeoutMs}ms; sending SIGKILL to remaining workers`);
const activeWorkers = Object.values(clusterModule?.workers || {}).filter(Boolean);
for (const worker of activeWorkers) {
try {
if (worker.process && typeof worker.process.kill === 'function') {
worker.process.kill('SIGKILL');
} else if (typeof worker.kill === 'function') {
worker.kill('SIGKILL');
}
} catch {
// Worker may already have exited.
}
}
exit(1);
}, timeoutMs);
if (typeof timer.unref === 'function') {
timer.unref();
}
if (servers.length > 0) {
await Promise.allSettled(servers.map((server) => closeHttpServer(server)));
}
const workers = Object.values(clusterModule?.workers || {}).filter(
(worker) => worker && !(typeof worker.isDead === 'function' && worker.isDead())
);
if (workers.length > 0 && clusterModule && typeof clusterModule.on === 'function') {
await new Promise((resolve) => {
const remaining = new Set(workers.map((worker) => worker.id));
const onExit = (exitedWorker) => {
if (exitedWorker) {
remaining.delete(exitedWorker.id);
}
if (remaining.size === 0) {
cleanupListener();
resolve();
}
};
const cleanupListener = () => {
if (typeof clusterModule.off === 'function') {
clusterModule.off('exit', onExit);
} else if (typeof clusterModule.removeListener === 'function') {
clusterModule.removeListener('exit', onExit);
}
};
clusterModule.on('exit', onExit);
for (const worker of workers) {
try {
if (typeof worker.removeAllListeners === 'function') {
worker.removeAllListeners('exit');
}
if (typeof worker.kill === 'function') {
worker.kill(signal);
}
} catch {
remaining.delete(worker.id);
}
}
if (remaining.size === 0) {
cleanupListener();
resolve();
}
});
}
clearTimeout(timer);
if (!timedOut) {
logger.info('Cluster primary shutdown completed cleanly');
exit(0);
}
})();
return shutdownPromise;
}
function installSignalHandlers(targetProcess = process, signals = ['SIGTERM', 'SIGINT']) {
const handlers = new Map();
for (const signal of signals) {
const handler = () => {
void shutdown(signal);
};
handlers.set(signal, handler);
targetProcess.on(signal, handler);
}
return () => {
for (const [signal, handler] of handlers.entries()) {
if (typeof targetProcess.off === 'function') {
targetProcess.off(signal, handler);
} else if (typeof targetProcess.removeListener === 'function') {
targetProcess.removeListener(signal, handler);
}
}
};
}
return {
shutdown,
isShuttingDown,
installSignalHandlers,
};
}
module.exports = {
DEFAULT_SHUTDOWN_TIMEOUT_MS,
closeHttpServer,
createGracefulShutdown,
createClusterShutdown,
};
+1024 -2447
View File
File diff suppressed because it is too large Load Diff
+5 -2
View File
@@ -3,6 +3,9 @@
"version": "1.6.7",
"description": "optimize query and coding enhancement",
"main": "index.js",
"engines": {
"node": ">=26.13.1 <27"
},
"scripts": {
"dev": "nodemon index",
"migrate": "knex migrate:latest",
@@ -24,7 +27,7 @@
"homepage": "https://github.com/mohamadihsan/topuponline#readme",
"dependencies": {
"axios": "^1.7.7",
"bcrypt": "^4.0.1",
"bcrypt": "^6.0.0",
"cors": "^2.8.5",
"crypto-js": "^4.1.1",
"dotenv": "^8.2.0",
@@ -35,7 +38,7 @@
"knex": "^3.1.0",
"moment": "^2.29.3",
"pg": "^8.6.0",
"pm2": "^6.0.13",
"pm2": "^7.1.2",
"prom-client": "^14.2.0",
"redis": "^4.6.5",
"response-time": "^2.3.2",
+19
View File
@@ -15,9 +15,28 @@ moment.locale('id');
const app = express();
const port = process.env.PORT || '3000';
let shuttingDown = false;
app.setShuttingDown = (value = true) => {
shuttingDown = Boolean(value);
};
app.isShuttingDown = () => shuttingDown;
app.use((req, res, next) => {
if (shuttingDown) {
res.setHeader('Connection', 'close');
}
next();
});
app.use(correlation);
mountMetrics(app);
app.get('/health', (req, res) => {
if (shuttingDown) {
res.status(503).json({ status: 'shutting_down' });
return;
}
res.status(200).json({ status: 'ok' });
});
app.use(cors({
origin: ['http://localhost:' + port, 'http://localhost:3000'],
exposedHeaders: ['X-Request-Id', 'X-Response-Time'],
+192
View File
@@ -0,0 +1,192 @@
---
name: run-workflow
description: 'How to write and run a dynamic workflow script with the `run_workflow` tool: a Python script that orchestrates many agents with `agent`, `parallel`, `pipeline`, and `phase`. Use when a task splits into many independent or staged pieces of agent work (fan out over files, modules, bugs, or review angles, then aggregate), or when the user asks for a workflow. Don''t use for a single delegated task (use a subagent) or for legacy workflow files (see migrate-workflows).'
metadata:
namespace: system
---
# Dynamic workflows with `run_workflow`
A workflow is a short Python script that the `run_workflow` tool executes. The
script decides which agents to start, in what order, and what to do with their
results. Use it instead of many manual subagent calls when the orchestration
itself is code: loops over a list, fan-out then aggregate, or staged pipelines.
## Steps
1. Pass the script inline as `Script`, or write it to a file (for example in
the conversation scratch directory) and pass its absolute path as
`ScriptPath`. Set exactly one of them; a file is easier to fix and rerun.
2. Call `run_workflow(Script="...", Description="...")` or
`run_workflow(ScriptPath="/abs/path/workflow.py", Description="...")`.
`Description` is a one-line goal shown in the UI.
The workflow runs in the background, and you are notified when it ends.
For a quick script, such as a `call_tool` fan-out, set
`WaitMsBeforeAsync` (up to 10000) to get the result in the same turn if it
finishes in time.
To pass inputs, set `Args` to a JSON object; the script reads it as the
`args` dict. When `ScriptPath` is a saved workflow's entry script, `Args`
is validated against the args schema in its `workflow.json`.
3. Read the tool result: it contains the `log()` output (`Logs:`) and what the
script printed (`Output:`). Each agent is also linked from the workflow
step, so the user can open its conversation.
4. If the tool returns an error, fix the script at the reported line and run
it again.
## Script rules
The script runs in its own `python3` process, which needs Python 3.8 or later
on `PATH`:
- `await` works at the top level, and you can define `async def` helpers.
- Installed library workflows are importable by name (`import <library>` or
`from <library> import <name>`); library modules see the same primitives as
the script.
- What the script prints (`print()`, `stderr`, child-process output, and the
`repr` of a trailing expression) is returned in the tool result's `Output:`
section (and appended to the error when the workflow fails).
- An uncaught exception stops the workflow and reports the script line.
- `CONVERSATION_ID` and `STEP_INDEX` identify the `run_workflow` step.
`WORKSPACES` is a tuple of the workspace directories, primary first (empty
if there are none).
- The working directory is `Cwd` if given, else `WORKSPACES[0]`, so relative
paths resolve against it. Local modules are not importable.
## Primitives
| Primitive | Behavior |
| --- | --- |
| `log(*args)` | Adds a line to the workflow output and the UI. |
| `phase(name)` | Starts a named phase; later logs and agents group under it. |
| `agent(prompt=None, schema=None, role=None, type_name="self", workspace="inherit", model=None)` | Defines an agent; nothing runs yet. `await agent(prompt, schema)` runs it once and returns its result. `a = agent(...)` then `await a(prompt, schema)` runs one turn in a conversation kept across calls. |
| `parallel(items, fn)` | Promise that calls `fn(item)` for each item and awaits all results concurrently; results are in item order. If one fails, the rest are cancelled. |
| `pipeline(items, fn)` | Promise that calls and awaits `fn(item)` one item at a time; results are in item order. |
| `trajectory(last=None, types=None, tools=None, min_index=None, max_index=None)` | `await trajectory()` returns steps before this `run_workflow` call started, oldest first. `min_index` and `max_index` bound `step.index` (inclusive); `types` and `tools` filter by step type or tool name; `last` keeps the last N matching steps. |
Arguments:
- `type_name`: the agent type to run. `"self"` uses the current agent's
configuration; any available custom agent name also works.
- `workspace`: `"inherit"` (the current workspace), `"branch"` (a new isolated
clone, for agents that edit code in parallel), or `"share"` (a new workspace
that shares the underlying repository). Other values are errors.
- `schema` (required): a JSON schema (dict or string) for the agent's result.
The agent returns the result by calling its `finish` tool, which checks it
against the schema, and `await agent(...)` returns the parsed value. An
agent that ends without calling `finish` fails the workflow. Use
`{"type": "string"}` for a free-form answer.
- `role`: an optional short title for the agent's card, such as
`"Security reviewer"`.
- `model`: the agent's model tier: `"inherit"` (default, your model),
`"flash_lite"`, `"flash"`, or `"pro"`. Use a lighter tier for simple,
high-fan-out work.
- `fn`: usually a `lambda` that returns `agent(...)`, or an `async def`
helper that awaits several agents. It must return something awaitable:
an `agent()` or a call on one, a nested `parallel()` / `pipeline()`, or
an `async def` call. Build per-item prompts and roles with f-strings.
Awaiting the same agent twice runs it once and returns the same result. An
`agent()` that is never awaited or called never runs, so always `await` it, or
pass it to `parallel` / `pipeline` and await that.
The workflow step shows one card per agent, in the order agents start, titled
with its `role`, or else the first line of its prompt, so set a role or start
each prompt with a short line that names the job.
## Agents that keep their context
When one agent should do several related turns, such as a reviewer that checks
the fixes for the bugs it found, call it instead of awaiting it. Each
`a(prompt, schema)` is lazy like an awaited `agent()` and returns that turn's
`finish` result; the agent's own `prompt`, if any, is its standing instructions
and leads the first turn. `schema` on a call defaults to the agent's. Turns on
one agent run one at a time, in the order they were started. A failed turn
raises, but the agent stays usable. An agent is either awaited or called, not
both. `del a` ends the agent, unless something else, such as a lambda, still
references it; every agent ends when the workflow ends.
```python
reviewer = agent("You review Go code for correctness.", role="Reviewer")
bugs = await reviewer("List the bugs in foo.go.", {"type": "array", "items": {"type": "string"}})
fixes = await parallel(bugs, lambda b: agent(f"Fix: {b}", {"type": "string"}))
ok = await reviewer(f"Fixes made: {fixes}. Are all your bugs fixed?", {"type": "boolean"})
del reviewer
```
## Calling tools from the script
Where the `run_workflow` tool description lists tools for `call_tool`, the
script can call them directly:
- `call_tool(name, **args)` returns a promise like `agent()` does. Awaiting it
runs the tool with the arguments you would pass to it directly and returns
the tool's output as a `str`.
- It raises `ToolError` (with `.tool` and `.message`) if the tool fails or
the call is denied. `.denied` is `True` when a pre-tool hook or the
permission check rejected the call before the tool ran, so a script can
skip denied calls and still fail on real errors.
- The user cannot be asked anything from a workflow: a call that needs user
approval that has not already been granted is denied.
- Tool outputs are not shown to you unless the script logs or prints them.
## Reading earlier conversation steps
Pass inputs you already have in `Args` (or inline in the script). Use
`await trajectory(...)` when the script needs to inspect steps from earlier in
this conversation—such as mining a failed `run_command` output without
rerunning it—and pass only the relevant slice into child `agent()` prompts.
Each returned `Step` is a `dict` that also supports attribute access (missing
fields return `None` as attributes):
- `index` (`int`): 0-based step index.
- `type` (`str`): step type, e.g. `"USER_INPUT"`, `"PLANNER_RESPONSE"`,
`"SYSTEM_MESSAGE"`, or `"GENERIC"` (tool calls).
- `status` (`str`): e.g. `"DONE"`, `"ERROR"`, or `"CLEARED"`.
- Message steps set `text` (`str`); tool steps set `tool` (`str`), `args`
(parsed `dict`), and `output` (`str`, truncated at 200k characters).
```python
steps = await trajectory(tools=["run_command"], last=20)
errors = [s.output for s in steps if s.status == "ERROR" and s.output]
log(f"Found {len(errors)} failed command(s)")
```
`trajectory()` only returns steps before the `run_workflow` call started (steps
added while the workflow runs in the background are not included). Older tool
steps evicted from memory have `status == "CLEARED"` and `output == None`; read
the conversation's `transcript.jsonl` / `transcript_full.jsonl` when you need
cleared tool outputs or steps added after the workflow started.
## Behavior to know
- Workflow agents are main agents, not subagents. They are hidden from the
conversation list and reachable from the workflow step. An awaited agent
is single-use; a called agent lasts until deleted or the workflow ends.
- `await agent(...)` returns when the agent's run ends, with the result it
passed to `finish`.
- If one agent in `parallel` fails, the whole call fails and the other agents
in it are cancelled. Stopping the parent conversation stops all running
workflow agents.
- Agents do not see the script or each other. Put all the context an agent
needs in its prompt, and ask for a short, well-defined output.
## Example
Fan out over a list that an agent produces:
```python
phase("Discover")
files = await agent(
"List the Go files under pkg/foo that call Bar(). Paths only.",
schema={"type": "array", "items": {"type": "string"}},
)
phase("Review")
reviews = await parallel(files, lambda f: agent(
f"Review {f} for misuse of Bar(). Reply in 3 bullets or 'OK'.",
schema={"type": "string"},
role=f"Review {f}",
))
for r in reviews:
log(r)
```