Standardized shutdown processing with GitHub Copilot 1 +test#150
Standardized shutdown processing with GitHub Copilot 1 +test#150ryo8000 wants to merge 3 commits into
Conversation
WalkthroughIntroduces a centralized graceful shutdown utility and integrates it with the HTTP server and shutdown route. The server now registers a global shutdown handler and handles SIGTERM via this handler. The shutdown route triggers a deferred shutdown via triggerShutdown after responding. New unit tests cover the utilities and updated route behavior. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Route as /shutdown route
participant Shutdown as triggerShutdown
participant Global as GlobalHandler
participant Server
participant Process
Client->>Route: POST /shutdown
Route-->>Client: 200 OK
Route->>Shutdown: triggerShutdown("Manual shutdown")
alt handler registered
Shutdown->>Global: invoke("Manual shutdown")
Global->>Server: server.close(cb)
Note over Server: Wait up to 10s
Server-->>Global: cb(err?)
alt no error
Global->>Process: exit(0)
else error
Global->>Process: exit(1)
end
else no handler
Shutdown->>Process: exit(0)
end
sequenceDiagram
participant OS
participant Process
participant Handler as shutdownHandler
participant Server
OS-->>Process: SIGTERM
Process->>Handler: shutdownHandler("SIGTERM")
Handler->>Server: server.close(cb)
Note over Server: 10s timeout guard
Server-->>Handler: cb(err?)
alt success
Handler->>Process: exit(0)
else failure or timeout
Handler->>Process: exit(1)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~30 minutes Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @ryo8000, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a standardized and more robust mechanism for handling application shutdown. It centralizes the graceful termination logic into a new utility module, allowing for consistent logging, timeout management, and error handling during server closure. The changes integrate this new utility into the main server setup and the dedicated shutdown API route, ensuring that all shutdown requests trigger a controlled and predictable process. This significantly improves the application's resilience and reliability during termination.
Highlights
- Centralized Shutdown Utility: A new
src/utils/shutdown.tsfile has been introduced to centralize and standardize the application's shutdown logic. This module provides functions for graceful server termination, including timeout management and consistent logging. - Unified Shutdown Triggering: The application now uses a unified
triggerShutdownfunction. This allows various parts of the application, such as API routes or system signal handlers, to initiate the same controlled shutdown process, ensuring consistency. - Improved Signal Handling: The
SIGTERMsignal handler insrc/server.tshas been refactored to leverage the newgracefulShutdownutility. This provides more robust control over process termination, including better logging and error handling for server closure. - Updated Shutdown API Route: The
/shutdownAPI endpoint insrc/routes/shutdown.tshas been updated to call the newtriggerShutdownfunction instead of directly invokingprocess.exit(). This ensures that manual shutdowns via the API adhere to the new graceful shutdown protocol. - Comprehensive Unit Testing: New and updated unit tests have been added across
tests/ut/routes/shutdown.test.tsandtests/ut/utils/shutdown.test.tsto thoroughly validate the functionality and integration of the new shutdown utilities.
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Server's gentle close, No abrupt, harsh exit now, Graceful end, it flows.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request refactors the server shutdown logic into a centralized utility, which is a good improvement for standardization. However, the current implementation introduces significant code duplication between src/server.ts and the new src/utils/shutdown.ts file. The core shutdown logic is implemented in both places, differing only by the logger used. This should be consolidated into the utility to improve maintainability. I've also found a critical syntax error in one of the new test files that needs to be fixed, and I've suggested an improvement to make the shutdown fallback behavior more robust.
|
|
||
| // Reset the shutdown utility module's state by re-importing | ||
| jest.resetModules(); | ||
| }); afterEach(() => { |
| // Fallback for when no global handler is set (e.g., in tests) | ||
| process.exit(0); |
There was a problem hiding this comment.
The fallback to process.exit(0) is not ideal. It causes an abrupt, non-graceful shutdown and exits with a success code (0), which might hide a configuration issue where the global shutdown handler was not set. It would be safer to log an error and exit with a non-zero status code to indicate that the shutdown was not graceful and that there's a potential configuration problem.
// Fallback for when no global handler is set (e.g., in tests)
console.error('triggerShutdown called but no global handler is set. Exiting non-gracefully.');
process.exit(1);There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (7)
src/utils/shutdown.ts (2)
12-12: Replace console. with centralized logger to satisfy ESLint and keep consistency*ESLint flags no-console here, and the rest of the codebase (e.g., server.ts) uses the shared logger. Consider switching to the logger for consistency and to eliminate warnings.
Apply this diff in the selected lines:
- console.warn('Shutdown already in progress...'); + log.warn('Shutdown already in progress...');- console.info(`${reason} signal received: closing HTTP server`); + log.info(`${reason} signal received: closing HTTP server`);- console.error('Server close timed out, forcing exit'); + log.error('Server close timed out, forcing exit');- console.error('Error during server close:', err); + log.error({ err }, 'Error during server close');- console.info('HTTP server closed'); + log.info('HTTP server closed');Additionally, add the import at the top of the file:
import { log } from '../logger.js';Note: If you'd prefer to avoid touching tests right now (they spy on console.*), we can instead add a narrow eslint-disable just for this file or for the affected statements.
Also applies to: 17-17, 20-20, 28-28, 32-32
49-55: Provide a first-class way to clear the global shutdown handler (simplifies tests and avoids casts)Tests currently have to cast to any to reset the handler. Exposing a small helper improves ergonomics and type safety.
Apply this diff near the setter:
export function setGlobalShutdownHandler(handler: (reason?: string) => void): void { globalShutdownHandler = handler; } + +/** + * Clears the global shutdown handler (useful in tests) + */ +export function clearGlobalShutdownHandler(): void { + globalShutdownHandler = null; +}tests/ut/utils/shutdown.test.ts (1)
36-39: Prefer a dedicated clearer over casting to anyOnce clearGlobalShutdownHandler is available, use it instead of
setGlobalShutdownHandler(null as any)to avoid unsafe casts.Suggested change:
- const { setGlobalShutdownHandler: initialSetGlobalShutdownHandler } = await import('../../../src/utils/shutdown.js'); - initialSetGlobalShutdownHandler(null as any); + const { clearGlobalShutdownHandler } = await import('../../../src/utils/shutdown.js'); + clearGlobalShutdownHandler();src/routes/shutdown.ts (1)
18-21: Ensure shutdown starts after the response is fully flushedCalling triggerShutdown immediately after res.json is generally okay, but hooking on 'finish' guarantees the response has been sent to the client before initiating shutdown.
Apply this diff:
- res.json({ message: 'Server shutting down' }); - - // Trigger shutdown after response is sent - triggerShutdown('Manual shutdown'); + res.json({ message: 'Server shutting down' }); + + // Trigger shutdown after response is fully flushed + res.on('finish', () => triggerShutdown('Manual shutdown'));tests/ut/routes/shutdown.test.ts (2)
7-7: Type the mock as jest.Mock (it isn’t a spy)
jest.fn()returns a mock function, not a spy. Typing as jest.Mock better reflects usage and unlocks proper helpers.Apply this diff:
- let mockTriggerShutdown: jest.SpyInstance; + let mockTriggerShutdown: jest.Mock;
46-46: Use mockReset (or mockClear) instead of mockRestore on a plain jest.fnmockRestore is for spies created via jest.spyOn. For a plain jest.fn, use mockReset() to reset call history and implementation.
Apply this diff:
- mockTriggerShutdown.mockRestore(); + mockTriggerShutdown.mockReset();src/server.ts (1)
16-42: Reduce duplication: delegate to the shared shutdown utilityThis block re-implements graceful shutdown that's already available in the utils module. Reuse it to keep behavior consistent and maintain a single source of truth.
Apply this diff:
-import { setGlobalShutdownHandler } from './utils/shutdown.js'; +import { setGlobalShutdownHandler, createShutdownHandler } from './utils/shutdown.js'; @@ -let isShuttingDown = false; - -// Create a shutdown handler that uses the logger -const shutdownHandler = (reason = 'shutdown') => { - if (isShuttingDown) { - log.warn('Shutdown already in progress...'); - return; - } - isShuttingDown = true; - - log.info(`${reason} signal received: closing HTTP server`); - - const forceExitTimeout = setTimeout(() => { - log.error('Server close timed out, forcing exit'); - process.exit(1); - }, 10_000); - - server.close((err) => { - clearTimeout(forceExitTimeout); - - if (err) { - log.error({ err }, 'Error during server close'); - process.exit(1); - } - - log.info('HTTP server closed'); - process.exit(0); - }); -}; +const shutdownHandler = createShutdownHandler(server);Optional: Also handle SIGINT for local dev interrupts.
process.on('SIGTERM', () => { shutdownHandler('SIGTERM'); }); + +process.on('SIGINT', () => { + shutdownHandler('SIGINT'); +});
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
src/routes/shutdown.ts(2 hunks)src/server.ts(3 hunks)src/utils/shutdown.ts(1 hunks)tests/ut/routes/shutdown.test.ts(5 hunks)tests/ut/utils/shutdown.test.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/routes/shutdown.ts (1)
src/utils/shutdown.ts (1)
triggerShutdown(59-66)
src/server.ts (2)
src/logger.ts (1)
log(22-29)src/utils/shutdown.ts (1)
setGlobalShutdownHandler(52-54)
🪛 GitHub Check: test (22.x)
tests/ut/utils/shutdown.test.ts
[failure] 148-148:
Expected an assignment or function call and instead saw an expression
[failure] 134-134:
Expected an assignment or function call and instead saw an expression
[failure] 74-74:
Expected an assignment or function call and instead saw an expression
[failure] 56-56:
Expected an assignment or function call and instead saw an expression
src/utils/shutdown.ts
[warning] 32-32:
Unexpected console statement
[warning] 28-28:
Unexpected console statement
[warning] 20-20:
Unexpected console statement
[warning] 17-17:
Unexpected console statement
[warning] 12-12:
Unexpected console statement
🪛 ESLint
tests/ut/utils/shutdown.test.ts
[error] 56-56: Expected an assignment or function call and instead saw an expression.
(@typescript-eslint/no-unused-expressions)
[error] 74-74: Expected an assignment or function call and instead saw an expression.
(@typescript-eslint/no-unused-expressions)
[error] 134-134: Expected an assignment or function call and instead saw an expression.
(@typescript-eslint/no-unused-expressions)
[error] 148-148: Expected an assignment or function call and instead saw an expression.
(@typescript-eslint/no-unused-expressions)
🪛 GitHub Actions: CI
tests/ut/utils/shutdown.test.ts
[error] 56-56: ESLint: Expected an assignment or function call and instead saw an expression. (@typescript-eslint/no-unused-expressions)
src/utils/shutdown.ts
[warning] 12-12: ESLint: Unexpected console statement (no-console)
[warning] 17-17: ESLint: Unexpected console statement (no-console)
[warning] 20-20: ESLint: Unexpected console statement (no-console)
[warning] 28-28: ESLint: Unexpected console statement (no-console)
[warning] 32-32: ESLint: Unexpected console statement (no-console)
🔇 Additional comments (1)
src/utils/shutdown.ts (1)
10-35: Graceful shutdown flow is solid and idempotentGood guard against re-entrancy, clear logging, 10s force-exit to avoid hanging, and proper error/success exit codes. The callback clears the timer to prevent double-exit. Looks correct.
| mockServer.close.mockImplementation((callback) => { | ||
| callback && callback(); | ||
| return mockServer; | ||
| }); | ||
|
|
There was a problem hiding this comment.
Fix ESLint no-unused-expressions (CI is failing)
The short-circuit form callback && callback() is flagged by @typescript-eslint/no-unused-expressions. Replace with a simple if-statement. This should resolve the CI failure.
Apply these diffs:
@@
- mockServer.close.mockImplementation((callback) => {
- callback && callback();
+ mockServer.close.mockImplementation((callback) => {
+ if (callback) callback();
return mockServer;
});
@@
- mockServer.close.mockImplementation((callback) => {
- callback && callback(testError);
+ mockServer.close.mockImplementation((callback) => {
+ if (callback) callback(testError);
return mockServer;
});
@@
- mockServer.close.mockImplementation((callback) => {
- callback && callback();
+ mockServer.close.mockImplementation((callback) => {
+ if (callback) callback();
return mockServer;
});
@@
- mockServer.close.mockImplementation((callback) => {
- callback && callback();
+ mockServer.close.mockImplementation((callback) => {
+ if (callback) callback();
return mockServer;
});Also applies to: 73-77, 133-137, 147-151
🧰 Tools
🪛 GitHub Check: test (22.x)
[failure] 56-56:
Expected an assignment or function call and instead saw an expression
🪛 ESLint
[error] 56-56: Expected an assignment or function call and instead saw an expression.
(@typescript-eslint/no-unused-expressions)
🪛 GitHub Actions: CI
[error] 56-56: ESLint: Expected an assignment or function call and instead saw an expression. (@typescript-eslint/no-unused-expressions)
🤖 Prompt for AI Agents
In tests/ut/utils/shutdown.test.ts around lines 55-59, 73-77, 133-137, and
147-151 the short-circuit expression "callback && callback()" triggers
@typescript-eslint/no-unused-expressions; replace each occurrence with an
explicit if-statement that checks the callback and invokes it (e.g., if
(callback) { callback(); }) to satisfy the linter and preserve behavior.
Summary by CodeRabbit