Skip to content

Commit a391dc0

Browse files
authored
fix(api): cleaner exits before respawn (freeCodeCamp#66135)
1 parent b5e3a94 commit a391dc0

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

api/src/app.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
FCC_ENABLE_SWAGGER_UI,
4242
FCC_ENABLE_SHADOW_CAPTURE,
4343
FCC_ENABLE_SENTRY_ROUTES,
44+
FREECODECAMP_NODE_ENV,
4445
GROWTHBOOK_FASTIFY_API_HOST,
4546
GROWTHBOOK_FASTIFY_CLIENT_KEY
4647
} from './utils/env.js';
@@ -86,7 +87,11 @@ export const buildOptions: FastifyHttpOptions<
8687
loggerInstance: getLogger(),
8788
genReqId: () => randomBytes(8).toString('hex'),
8889
// disabled so we can customise the request/response logging
89-
disableRequestLogging: true
90+
disableRequestLogging: true,
91+
// destroy all connections on close to avoid EADDRINUSE
92+
// on restart, in development. Leave default in production.
93+
forceCloseConnections:
94+
FREECODECAMP_NODE_ENV === 'production' ? ('idle' as const) : true
9095
};
9196

9297
/**

api/src/server.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,25 @@ const start = async () => {
88

99
const stop = async (signal: NodeJS.Signals) => {
1010
fastify.log.info(`Received ${signal}, shutting down.`);
11+
12+
fastify.server.closeAllConnections();
13+
await new Promise<void>(resolve => {
14+
fastify.server.close(() => resolve());
15+
});
16+
17+
// Yield one tick so libuv can finalize uv_close() on the TCP handle
18+
// before pino's autoEnd blocks the event loop via Atomics.wait().
19+
await new Promise<void>(resolve => setImmediate(resolve));
20+
1121
await fastify.close();
12-
fastify.log.info('Shutdown complete');
1322
process.exit(0);
1423
};
1524

1625
process.on('SIGINT', signal => void stop(signal));
1726
process.on('SIGTERM', signal => void stop(signal));
1827

1928
try {
20-
const port = Number(PORT);
21-
fastify.log.info(`Starting server on port ${port}`);
22-
await fastify.listen({ port, host: HOST });
29+
await fastify.listen({ port: Number(PORT), host: HOST });
2330
} catch (err) {
2431
fastify.log.error(err);
2532
process.exit(1);

0 commit comments

Comments
 (0)