Skip to content

Standardized shutdown processing with GitHub Copilot 1 +test#150

Open
ryo8000 wants to merge 3 commits into
mainfrom
copilot/shutdown
Open

Standardized shutdown processing with GitHub Copilot 1 +test#150
ryo8000 wants to merge 3 commits into
mainfrom
copilot/shutdown

Conversation

@ryo8000

@ryo8000 ryo8000 commented Aug 18, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features
    • Introduces a graceful shutdown mechanism for the server, reducing downtime and preventing abrupt terminations.
    • Manual shutdown endpoint now returns a response before initiating shutdown.
    • OS signal handling is centralized, enabling consistent, contextual shutdown messages (e.g., SIGTERM, manual).
  • Refactor
    • Consolidated shutdown logic to a single, reusable handler to improve reliability and avoid duplicate shutdown attempts.
  • Tests
    • Added comprehensive unit tests for shutdown behavior, including success, error, timeout, and concurrency scenarios.

@coderabbitai

coderabbitai Bot commented Aug 18, 2025

Copy link
Copy Markdown

Walkthrough

Introduces 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

Cohort / File(s) Summary
Shutdown route integration
src/routes/shutdown.ts
Replace direct process.exit with triggerShutdown('Manual shutdown') after sending response; import added; control flow otherwise unchanged.
Server shutdown handler
src/server.ts
Adds shutdownHandler with re-entrancy guard, logs, server.close with 10s timeout; registers via setGlobalShutdownHandler; wires SIGTERM to handler.
Shutdown utilities
src/utils/shutdown.ts
New module providing gracefulShutdown, createShutdownHandler, setGlobalShutdownHandler, triggerShutdown; manages isShuttingDown flag and force-exit timeout.
Route tests update
tests/ut/routes/shutdown.test.ts
Mocks triggerShutdown; asserts it’s called on enabled path and not called when disabled; replaces process.exit expectations; ensures mocks lifecycle.
Utilities tests
tests/ut/utils/shutdown.test.ts
New suite covering success, error, concurrent, and timeout paths of gracefulShutdown; tests createShutdownHandler and global trigger behavior with mocked timers and exits.

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
Loading
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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

A whisk of wind, a gentle thrum—
I press the switch: shutdown will come.
No hasty hop, we pause with grace,
Close burrow doors, no frantic race.
Ten ticks pass; if not, we bail—
Ears up, logs neat, a tidy trail. 🐇🔌

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 Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch copilot/shutdown

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.ts file 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 triggerShutdown function. 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 SIGTERM signal handler in src/server.ts has been refactored to leverage the new gracefulShutdown utility. This provides more robust control over process termination, including better logging and error handling for server closure.
  • Updated Shutdown API Route: The /shutdown API endpoint in src/routes/shutdown.ts has been updated to call the new triggerShutdown function instead of directly invoking process.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.ts and tests/ut/utils/shutdown.test.ts to 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

  1. 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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

There's a syntax error on this line. The afterEach block is appended to the closing of the beforeEach block, which will cause the test suite to fail.

Suggested change
}); afterEach(() => {
});
afterEach(() => {

Comment thread src/utils/shutdown.ts
Comment on lines +63 to +64
// Fallback for when no global handler is set (e.g., in tests)
process.exit(0);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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);

@ryo8000 ryo8000 changed the title Standardized shutdown processing with GitHub Copilot 2 Standardized shutdown processing with GitHub Copilot 1 +test Aug 18, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 any

Once 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 flushed

Calling 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.fn

mockRestore 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 utility

This 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 826537d and e264658.

📒 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 idempotent

Good 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.

Comment on lines +55 to +59
mockServer.close.mockImplementation((callback) => {
callback && callback();
return mockServer;
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

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.

@ryo8000 ryo8000 added enhancement New feature or request experiment Experiment labels Aug 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request experiment Experiment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant