Skip to content

Commit be66a84

Browse files
gxklkillagu
andauthored
fix(cluster): harden worker thread lifecycle (#6043)
## Summary Hardens the `worker_threads` cluster lifecycle on top of the bundle and startup-snapshot support merged in #6042: - add an explicit master-to-worker graceful-exit message instead of attempting asynchronous cleanup from the worker `exit` event; - wait for app/agent cleanup and fall back to `Worker.terminate()` after the configured timeout; - consume and log worker `error` events during graceful shutdown, then continue with the termination fallback without exposing an unhandled EventEmitter error; - reject `sticky: true` with `startMode: worker_threads`, because sticky socket handoff requires process IPC; - preserve the existing master-port and `reusePort` listen semantics, with focused server-error and hostname regression coverage. ## Why A worker thread's `exit` event is emitted after the thread has already stopped, so cleanup cannot reliably be initiated from that event. The new protocol asks the worker to close while it is still alive and keeps forced termination as a bounded fallback. Sticky mode is rejected explicitly because its socket handoff mechanism is only available to process workers. ## Validation - `ut run test --workspace @eggjs/cluster -- test/worker-thread-utils.test.ts test/worker-protocol.test.ts test/worker-protocol-io.test.ts` — 24 passed - `vitest run test/options.test.ts -t 'should reject sticky mode with worker_threads'` — 1 passed - `ut run typecheck --workspace @eggjs/cluster` — passed The full cross-platform suite is covered by CI. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Worker threads now wait for application and agent cleanup to finish during shutdown. * If cleanup fails or exceeds the configured timeout, workers are terminated. * **Bug Fixes** * Workers are no longer started or restarted after shutdown begins. * Sticky-session mode now rejects unsupported worker-thread configurations. * Workers use the application’s configured port when the master port is set to zero. * **Documentation** * Clarified worker-thread shutdown behavior and supported startup configurations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: killagu <killa07071201@gmail.com>
1 parent 170ec7f commit be66a84

21 files changed

Lines changed: 676 additions & 26 deletions

‎packages/cluster/src/master.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,7 @@ export class Master extends ReadyEventEmitter {
381381
if (this.isStarted) {
382382
this.log('[master] try to start a new agent_worker after 1s ...');
383383
setTimeout(() => {
384+
if (this.closed) return;
384385
this.logger.info('[master] new agent_worker starting...');
385386
this.forkAgentWorker();
386387
}, 1000);
@@ -643,6 +644,7 @@ export class Master extends ReadyEventEmitter {
643644
// kill app workers
644645
// kill agent worker
645646
// exit itself
647+
const errors: unknown[] = [];
646648
const legacyTimeout = process.env.EGG_MASTER_CLOSE_TIMEOUT || '5000';
647649
const appTimeout = parseInt(process.env.EGG_APP_CLOSE_TIMEOUT || legacyTimeout);
648650
const agentTimeout = parseInt(process.env.EGG_AGENT_CLOSE_TIMEOUT || legacyTimeout);
@@ -652,13 +654,18 @@ export class Master extends ReadyEventEmitter {
652654
await this.killAppWorkers(appTimeout);
653655
} catch (e) {
654656
this.logger.error('[master] app workers exit error: ', e);
657+
errors.push(e);
655658
}
656659
this.logger.info('[master] send kill SIGTERM to agent worker, will exit with code:0 after %sms', agentTimeout);
657660
this.logger.info('[master] wait %sms', agentTimeout);
658661
try {
659662
await this.killAgentWorker(agentTimeout);
660663
} catch (e) {
661664
this.logger.error('[master] agent worker exit error: ', e);
665+
errors.push(e);
666+
}
667+
if (this.options.startMode === 'worker_threads' && errors.length) {
668+
throw new AggregateError(errors, 'worker threads failed during graceful shutdown');
662669
}
663670
}
664671
}

‎packages/cluster/src/utils/mode/impl/worker_threads/agent.ts‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1+
import { once } from 'node:events';
2+
import { setTimeout as sleep } from 'node:timers/promises';
13
import workerThreads, { type Worker } from 'node:worker_threads';
24

35
import { ClusterAgentWorkerError } from '../../../../error/ClusterAgentWorkerError.ts';
6+
import { WORKER_THREAD_GRACEFUL_EXIT } from '../../../../worker_protocol/worker-thread.ts';
47
import type { MessageBody } from '../../../messenger.ts';
58
import { BaseAgentUtils, BaseAgentWorker } from '../../base/agent.ts';
69

@@ -17,9 +20,11 @@ export class AgentThreadWorker extends BaseAgentWorker<Worker> {
1720
export class AgentThreadUtils extends BaseAgentUtils {
1821
#worker: Worker;
1922
#id = 0;
23+
#closing = false;
2024
instance: AgentThreadWorker;
2125

2226
fork(): void {
27+
if (this.#closing) return;
2328
this.startTime = Date.now();
2429

2530
// start agent worker
@@ -69,11 +74,35 @@ export class AgentThreadUtils extends BaseAgentUtils {
6974
this.#worker.removeAllListeners();
7075
}
7176

72-
async kill(): Promise<void> {
73-
if (this.#worker) {
74-
this.log(`[master] kill agent worker#${this.#id} (worker_threads) by worker.terminate()`);
77+
async kill(timeout: number): Promise<void> {
78+
this.#closing = true;
79+
const worker = this.#worker;
80+
if (worker && worker.threadId !== -1) {
81+
this.log(`[master] gracefully close agent worker#${this.#id} (worker_threads)`);
7582
this.clean();
76-
await this.#worker.terminate();
83+
let shutdownError: unknown;
84+
const exited = once(worker, 'exit').then(
85+
([code]) => {
86+
if (code !== 0) throw new Error(`agent worker#${this.#id} exited with code:${code} during graceful shutdown`);
87+
return true;
88+
},
89+
(err) => {
90+
this.logger.error('[master] agent worker#%s error during graceful shutdown: ', this.#id, err);
91+
shutdownError = err;
92+
return false;
93+
},
94+
);
95+
worker.postMessage(WORKER_THREAD_GRACEFUL_EXIT);
96+
const timeoutController = new AbortController();
97+
try {
98+
if (!(await Promise.race([exited, sleep(timeout, false, { signal: timeoutController.signal })]))) {
99+
this.log(`[master] terminate agent worker#${this.#id} after ${timeout}ms timeout`);
100+
await worker.terminate();
101+
if (shutdownError) throw shutdownError;
102+
}
103+
} finally {
104+
timeoutController.abort();
105+
}
77106
}
78107
}
79108
}

‎packages/cluster/src/utils/mode/impl/worker_threads/app.ts‎

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { once } from 'node:events';
12
import { setTimeout as sleep } from 'node:timers/promises';
23
import { Worker as ThreadWorker, type WorkerOptions } from 'node:worker_threads';
34

5+
import { WORKER_THREAD_GRACEFUL_EXIT } from '../../../../worker_protocol/worker-thread.ts';
46
import type { MessageBody } from '../../../messenger.ts';
57
import { BaseAppWorker, BaseAppUtils } from '../../base/app.ts';
68

@@ -48,15 +50,17 @@ export class AppThreadWorker extends BaseAppWorker<ThreadWorker> {
4850
}
4951

5052
export class AppThreadUtils extends BaseAppUtils {
51-
#workers: ThreadWorker[] = [];
53+
#workers: AppThreadWorker[] = [];
54+
#closing = false;
5255

5356
#forkSingle(appPath: string, options: WorkerOptions, id: number): void {
57+
if (this.#closing) return;
5458
// start app worker
5559
const worker = new ThreadWorker(appPath, options);
56-
this.#workers.push(worker);
5760

5861
// wrap app worker
5962
const appWorker = new AppThreadWorker(worker, id);
63+
this.#workers.push(appWorker);
6064
this.emit('worker_forked', appWorker);
6165
appWorker.disableRefork = true;
6266
worker.on('message', (msg: MessageBody) => {
@@ -114,7 +118,8 @@ export class AppThreadUtils extends BaseAppUtils {
114118
if (this.options.reusePort) {
115119
// When reusePort is enabled, all workers share the same port
116120
// and each worker has its own socket
117-
if (!this.options.port) {
121+
// Port 0 defers to the application's shared listen port.
122+
if (!this.options.port && this.options.port !== 0) {
118123
throw new Error('options.port must be specified when reusePort is enabled');
119124
}
120125
for (let i = 0; i < this.options.workers; i++) {
@@ -139,12 +144,40 @@ export class AppThreadUtils extends BaseAppUtils {
139144
return this;
140145
}
141146

142-
async kill(): Promise<void> {
143-
for (const worker of this.#workers) {
144-
const id = Reflect.get(worker, 'id');
145-
this.log(`[master] kill app worker#${id} (worker_threads) by worker.terminate()`);
146-
worker.removeAllListeners();
147-
worker.terminate();
148-
}
147+
async kill(timeout: number): Promise<void> {
148+
this.#closing = true;
149+
const results = await Promise.allSettled(
150+
this.#workers.map(async (appWorker) => {
151+
const { id, instance: worker } = appWorker;
152+
if (appWorker.state === 'dead' || worker.threadId === -1) return;
153+
this.log(`[master] gracefully close app worker#${id} (worker_threads)`);
154+
worker.removeAllListeners();
155+
let shutdownError: unknown;
156+
const exited = once(worker, 'exit').then(
157+
([code]) => {
158+
if (code !== 0) throw new Error(`app worker#${id} exited with code:${code} during graceful shutdown`);
159+
return true;
160+
},
161+
(err) => {
162+
this.logger.error('[master] app worker#%s error during graceful shutdown: ', id, err);
163+
shutdownError = err;
164+
return false;
165+
},
166+
);
167+
worker.postMessage(WORKER_THREAD_GRACEFUL_EXIT);
168+
const timeoutController = new AbortController();
169+
try {
170+
if (!(await Promise.race([exited, sleep(timeout, false, { signal: timeoutController.signal })]))) {
171+
this.log(`[master] terminate app worker#${id} after ${timeout}ms timeout`);
172+
await worker.terminate();
173+
if (shutdownError) throw shutdownError;
174+
}
175+
} finally {
176+
timeoutController.abort();
177+
}
178+
}),
179+
);
180+
const errors = results.filter((result) => result.status === 'rejected').map((result) => result.reason);
181+
if (errors.length) throw new AggregateError(errors, 'app workers failed during graceful shutdown');
149182
}
150183
}

‎packages/cluster/src/utils/options.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,11 @@ export async function parseOptions(options?: ClusterOptions): Promise<ParsedClus
202202
assert(fs.existsSync(options[optionName]), `options.${optionName} file should exist: ${options[optionName]}`);
203203
assert(options.startMode !== 'worker_threads', `options.${optionName} only supports startMode "process"`);
204204
}
205+
assert(
206+
!(options.sticky && options.startMode === 'worker_threads'),
207+
'options.sticky only supports startMode "process"',
208+
);
209+
205210
// don't print deprecated message in production env.
206211
// it will print to stderr.
207212
if (process.env.NODE_ENV === 'production') {

‎packages/cluster/src/worker_protocol/app.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ export function startAppWorker(
7777
...clusterConfig.https,
7878
...options.https,
7979
};
80+
// A master-level port of 0 means that the application listen config still
81+
// decides the worker port. This is required by reusePort workers, which
82+
// must all bind the same configured port rather than separate ephemeral
83+
// ports.
8084
const port = (app.options.port = options.port || listenConfig.port);
8185
const debugPort = options.debugPort;
8286
const protocol = httpsOptions.key && httpsOptions.cert ? 'https' : 'http';

‎packages/cluster/src/worker_protocol/worker-thread.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import type { Options as GracefulExitOptions } from 'graceful-process';
55
import type { MessageBody } from '../utils/messenger.ts';
66
import type { AppWorkerIO } from './app.ts';
77

8+
export const WORKER_THREAD_GRACEFUL_EXIT = '@eggjs/cluster:graceful-exit';
9+
810
/**
911
* Worker-thread-backed transport shared by the standard worker entries and
1012
* generated bundle entries.
@@ -30,11 +32,19 @@ export function createWorkerThreadIO(): AppWorkerIO {
3032
},
3133
gracefulExit(options: GracefulExitOptions): void {
3234
const { beforeExit } = options;
33-
process.on('exit', async (code) => {
34-
if (typeof beforeExit === 'function') {
35-
await beforeExit();
35+
let closing = false;
36+
port.on('message', async (message: unknown) => {
37+
if (message !== WORKER_THREAD_GRACEFUL_EXIT || closing) return;
38+
closing = true;
39+
try {
40+
if (typeof beforeExit === 'function') {
41+
await beforeExit();
42+
}
43+
process.exit(0);
44+
} catch (err) {
45+
options.logger?.error('[worker_thread] graceful exit failed:', err);
46+
process.exit(1);
3647
}
37-
process.exit(code);
3848
});
3949
},
4050
};

‎packages/cluster/test/app_worker.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,20 @@ describe.skipIf(process.version.startsWith('v24') || process.platform === 'win32
311311
await request('http://127.0.0.1:17010').get('/port').expect('17010').expect(200);
312312
});
313313

314+
it.each(process.platform === 'linux' ? [1, 2] : [1])(
315+
'worker threads use the configured port with %i workers when the master port is zero',
316+
async (workers) => {
317+
const options = { startMode: 'worker_threads' as const, port: 0, reusePort: true, workers };
318+
app = cluster('apps/app-listen-reusePort', options);
319+
await app.ready();
320+
321+
app.expect('code', 0);
322+
app.expect('stdout', /egg started on http:\/\/127.0.0.1:17010/);
323+
await request('http://127.0.0.1:17010').get('/').expect('done').expect(200);
324+
await request('http://127.0.0.1:17010').get('/port').expect('17010').expect(200);
325+
},
326+
);
327+
314328
it('should set reusePort=true in config (non-Linux will fallback to false)', async () => {
315329
app = cluster('apps/app-listen-reusePort', { port: 0 });
316330
// app.debug();

‎packages/cluster/test/fixtures/apps/before-close/agent.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ module.exports = (agent) => {
44
agent.beforeClose(async () => {
55
console.log('agent closing');
66
await scheduler.wait(10);
7+
if (process.env.WORKER_CLOSE_FAIL === 'agent') throw new Error('agent cleanup failed');
78
console.log('agent closed');
89
});
910
};

‎packages/cluster/test/fixtures/apps/before-close/app.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ module.exports = (app) => {
44
app.beforeClose(async () => {
55
console.log('app closing');
66
await scheduler.wait(10);
7+
if (process.env.WORKER_CLOSE_FAIL === 'app') throw new Error('app cleanup failed');
78
console.log('app closed');
89
});
910
};
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { once } from 'node:events';
2+
import path from 'node:path';
3+
import { setTimeout as sleep } from 'node:timers/promises';
4+
5+
import { detectPort } from 'detect-port';
6+
7+
import { Master } from '../../src/index.ts';
8+
const mode = process.argv[2];
9+
const master = new Master({
10+
baseDir: path.join(import.meta.dirname, 'apps', mode === 'hang' ? 'worker-close-timeout' : 'before-close'),
11+
framework: path.join(import.meta.dirname, '../../../egg'),
12+
startMode: 'worker_threads',
13+
workers: 1,
14+
port: await detectPort(),
15+
});
16+
await master.ready();
17+
if (mode === 'race') {
18+
// Close apps while their cluster-client leader is still alive; isolate the agent race.
19+
await master.killAppWorkers(5000);
20+
let forks = 0;
21+
master.agentWorker.on('agent_forked', () => forks++);
22+
const exited = once(master.agentWorker.instance.instance, 'exit');
23+
await master.agentWorker.instance.instance.terminate();
24+
await exited;
25+
master.closed = true;
26+
const started = Date.now();
27+
await master._doClose();
28+
console.log('shutdown-duration', Date.now() - started);
29+
await sleep(1200);
30+
console.log('shutdown-reforks', forks);
31+
process.exit(0);
32+
} else {
33+
await master.close();
34+
}

0 commit comments

Comments
 (0)