Skip to content

Commit 18c9919

Browse files
committed
fix: stop infinite loop on app shutdown
1 parent 49162ef commit 18c9919

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

src/helpers/strategies.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,14 @@ export async function run() {
5454
}
5555
log.error(`[strategies] failed to load ${JSON.stringify(e)}`);
5656
}
57+
58+
// if stop() has been called after sleep started,
59+
// the loop will exit only after the sleep has completed
5760
await snapshot.utils.sleep(RUN_INTERVAL);
5861
}
5962
}
6063

6164
export function stop() {
65+
log.info('[strategies] Stopping strategies refresh');
6266
shouldStop = true;
6367
}

src/index.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import initMetrics from './helpers/metrics';
88
import refreshModeration from './helpers/moderation';
99
import rateLimit from './helpers/rateLimit';
1010
import shutter from './helpers/shutter';
11-
import { run as refreshStrategies } from './helpers/strategies';
11+
import { run as refreshStrategies, stop as stopStrategies } from './helpers/strategies';
1212
import { trackTurboStatuses } from './helpers/turbo';
1313

1414
const app = express();
@@ -31,4 +31,23 @@ app.use('/shutter', shutter);
3131
fallbackLogger(app);
3232

3333
const PORT = process.env.PORT || 3001;
34-
app.listen(PORT, () => log.info(`Started on: http://localhost:${PORT}`));
34+
const server = app.listen(PORT, () => log.info(`Started on: http://localhost:${PORT}`));
35+
36+
const gracefulShutdown = (signal: string) => {
37+
log.info(`Received ${signal}, shutting down gracefully...`);
38+
39+
stopStrategies();
40+
41+
server.close(() => {
42+
log.info('Server closed');
43+
process.exit(0);
44+
});
45+
46+
setTimeout(() => {
47+
log.error('Could not close connections in time, forcefully shutting down');
48+
process.exit(1);
49+
}, 10000);
50+
};
51+
52+
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
53+
process.on('SIGINT', () => gracefulShutdown('SIGINT'));

0 commit comments

Comments
 (0)