Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: set fixed timeout on each stop promise in shutdown procedure #283

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

hlolli
Copy link
Contributor

@hlolli hlolli commented Jan 24, 2025

No description provided.

Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Warning

Rate limit exceeded

@hlolli has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 16 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 62fdec3 and b733b67.

📒 Files selected for processing (1)
  • src/system.ts (1 hunks)
📝 Walkthrough

Walkthrough

The changes introduce a new withTimeout function that wraps promises with a timeout mechanism for error handling during shutdown procedures. A new type, ShutdownEntry, is defined to encapsulate shutdown functions and their descriptions. The shutdown function is refactored to utilize an array of shutdownProcedures, ensuring each task is awaited with a specified timeout and any errors are logged, thereby enhancing the clarity and maintainability of the shutdown process.

Changes

File Change Summary
src/system.ts - Added withTimeout function for promise timeout handling
- Introduced ShutdownEntry type for structured shutdown procedures
- Modified shutdown function to utilize timeout-wrapped shutdown tasks

Sequence Diagram

sequenceDiagram
    participant System
    participant ShutdownManager
    participant Component1
    participant Component2

    System->>ShutdownManager: Initiate Shutdown
    ShutdownManager->>Component1: Stop with Timeout
    ShutdownManager->>Component2: Stop with Timeout
    ShutdownManager-->>System: Log Shutdown Results
    System->>System: Exit Process
Loading

The sequence diagram illustrates the new shutdown process, where the ShutdownManager coordinates stopping different components with individual timeouts, logs the results, and then exits the process.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/system.ts (3)

699-716: Use consistent logging mechanism instead of console.error.

Within withTimeout, the code uses console.error to log the timeout error, whereas the rest of the system logs using the log logger. Consider replacing console.error with the project's log.error or another uniform logging approach for consistency.

     new Promise((_, reject) =>
       setTimeout(() => {
-        console.error(
-          `Shutdown Promise timed out after ${timeoutMs}ms: ${description}`,
-        );
+        log.error(
+          `Shutdown Promise timed out after ${timeoutMs}ms: ${description}`,
+        );
         reject(new Error(`Shutdown Timeout: ${description}`));
       }, timeoutMs),
     ),

719-723: Align function/method type definitions with intended usage.

The fn is defined as (() => any) | undefined; but is generally used as an async or promise-returning function. To ensure type safety, consider enforcing an async function or returning a Promise explicitly in the signature for better clarity.

-type ShutdownEntry = {
-  fn: (() => any) | undefined;
+type ShutdownEntry = {
+  fn?: () => Promise<any> | any; // Accept both async and sync
   description: string;
 };

800-810: Assess shutdown concurrency vs. sequential stop.

Using Promise.all for parallel shutdown may mask dependency issues if a worker depends on another to halt first. If you suspect ordering constraints, switching to sequential shutdown (e.g., for … await of) might be safer.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b02e18 and 13d5e8f.

📒 Files selected for processing (1)
  • src/system.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test (macos-latest)
  • GitHub Check: test (ubuntu-latest)
🔇 Additional comments (2)
src/system.ts (2)

731-736: Consider event emitter removal timing.

eventEmitter.removeAllListeners() is called before shutting down all workers. If any of the shutdown tasks rely on events to complete gracefully, removing listeners prematurely might prevent them from handling shutdown-related events. Verify that none of your active processes require event mechanisms during shutdown.


737-799: Fix spelling of shutdownProceadures.

The key shutdownProceadures has a minor spelling mistake. Prefer correcting it to shutdownProcedures for consistency and clarity.

-      const shutdownProceadures: ShutdownEntry[] = [
+      const shutdownProcedures: ShutdownEntry[] = [

Check for missing worker shutdowns.

Ensure that all newly introduced or future workers are added to this array so they also get gracefully stopped. Missing a reference could lead to dangling processes.

✅ Verification successful

Fix spelling and confirm shutdown procedures are complete

The shutdown procedures list is comprehensive and includes all components that require graceful shutdown. The only required change is fixing the spelling:

-      const shutdownProceadures: ShutdownEntry[] = [
+      const shutdownProcedures: ShutdownEntry[] = [
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for Worker classes and their stop methods
echo "=== Worker Classes ==="
ast-grep --pattern 'class $_Worker {
  $$$
}'

echo -e "\n=== Worker Instantiations ==="
ast-grep --pattern 'const $_Worker = new $_($$$)'

echo -e "\n=== Stop Method Implementations ==="
ast-grep --pattern 'stop() {
  $$$
}'

echo -e "\n=== Worker-like Variable Declarations ==="
rg "const \w+(?:Worker|Watcher|Indexer|Importer|Unbundler|Emitter)" -A 1

Length of output: 2687


Script:

#!/bin/bash
# Check if DataContentAttributeImporter has a stop method or requires shutdown
echo "=== DataContentAttributeImporter Implementation ==="
rg -A 10 "class DataContentAttributeImporter" 

echo -e "\n=== DataContentAttributeImporter Usage ==="
rg "DataContentAttributeImporter" --context 3

Length of output: 6514

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 71.85%. Comparing base (0b02e18) to head (b733b67).

Additional details and impacted files
@@           Coverage Diff            @@
##           develop     #283   +/-   ##
========================================
  Coverage    71.85%   71.85%           
========================================
  Files           39       39           
  Lines         9804     9804           
  Branches       563      563           
========================================
  Hits          7045     7045           
  Misses        2755     2755           
  Partials         4        4           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@hlolli hlolli force-pushed the orphan/zombie-killer branch from 13d5e8f to 62fdec3 Compare January 24, 2025 10:11
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (5)
src/system.ts (5)

719-722: Improve type safety of ShutdownEntry.

Consider making the description required and specifying a more precise return type for the shutdown function.

 type ShutdownEntry = {
-  fn: (() => any) | undefined;
+  fn: (() => Promise<void>) | undefined;
   description: string;
 };

731-732: Make shutdown timeout configurable.

Consider moving the hardcoded timeout value to configuration for better flexibility across different environments.

-      const stopTimeoutMs = 5000;
+      const stopTimeoutMs = config.SHUTDOWN_TIMEOUT_MS ?? 5000;

737-737: Fix typo in variable name.

Correct the spelling of "Procedures" in the variable name.

-      const shutdownProceadures: ShutdownEntry[] = [
+      const shutdownProcedures: ShutdownEntry[] = [

800-810: Consider sequential shutdown for critical components.

The current implementation shuts down all components in parallel, which might not be ideal for components with dependencies. Consider implementing a sequential shutdown for critical components to ensure proper cleanup.

Example approach:

const criticalProcedures = ['db.stop', 'server.close'];
const regularProcedures = shutdownProcedures.filter(
  proc => !criticalProcedures.includes(proc.description)
);

// First, stop critical procedures sequentially
for (const proc of shutdownProcedures.filter(
  proc => criticalProcedures.includes(proc.description)
)) {
  await withTimeout(
    typeof proc.fn === 'function' ? proc.fn() : Promise.resolve(),
    stopTimeoutMs,
    proc.description
  ).catch((err) => {
    log.error(`Error in ${proc.description}:`, err);
  });
}

// Then stop remaining procedures in parallel
await Promise.all(
  regularProcedures.map(...)
);

806-808: Improve error handling in shutdown procedures.

The current error handling simply logs the error and continues. Consider adding metrics or alerting for failed shutdowns, and potentially implementing retry logic for critical components.

           ).catch((err) => {
             log.error(`Error in ${description}:`, err);
+            metrics.shutdownErrorCounter.inc({ component: description });
+            if (criticalProcedures.includes(description)) {
+              process.exit(1); // Force exit on critical component failure
+            }
           });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 13d5e8f and 62fdec3.

📒 Files selected for processing (1)
  • src/system.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test (macos-latest)
  • GitHub Check: test (ubuntu-latest)

src/system.ts Outdated Show resolved Hide resolved
@hlolli hlolli force-pushed the orphan/zombie-killer branch from 62fdec3 to b733b67 Compare January 24, 2025 10:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant