Skip to content

feat: grpc graceful shutdown#850

Merged
devhaozi merged 5 commits intomasterfrom
haozi/grpc
Feb 5, 2025
Merged

feat: grpc graceful shutdown#850
devhaozi merged 5 commits intomasterfrom
haozi/grpc

Conversation

@devhaozi
Copy link
Member

@devhaozi devhaozi commented Feb 5, 2025

📑 Description

Closes goravel/goravel#575

Summary by CodeRabbit

  • New Features

    • Introduced enhanced server management capabilities, including new options to start listening for connections and to shut down the service gracefully or forcefully.
  • Tests

    • Added comprehensive tests to verify the proper operation of the new listening and shutdown functionalities, ensuring improved service reliability.

✅ Checks

  • Added test cases for my code

@devhaozi devhaozi requested a review from a team as a code owner February 5, 2025 11:24
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Walkthrough

The changes introduce new gRPC server management functionalities. Two methods—Listen for starting the server on a given listener and Shutdown for stopping the server, either gracefully or forcefully—are added to the gRPC interface, the application struct, and their corresponding mocks. Additionally, unit tests have been implemented to verify the behaviors of these methods, ensuring correct listener binding and shutdown procedures.

Changes

File(s) Change Summaries
contracts/grpc/grpc.go, mocks/…/Grpc.go Added new methods Listen(net.Listener) error and Shutdown(...bool). The gRPC interface is updated and mocks enhanced with helper types and methods for configuring and testing these behaviors.
grpc/application.go, grpc/application_test.go Extended the Application struct with Listen and Shutdown methods, reintroduced the Server method, and modified Run to directly return the Serve call result. Added tests (TestListen, TestShutdown) to validate functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Client as External Caller
    participant App as Application
    participant Server as gRPC Server
    participant L as net.Listener

    Client->>App: Call Listen(listener)
    App->>L: Bind to provided listener
    App->>Server: Serve(listener)
    note right of Server: Server starts handling requests
    Client->>App: Request Shutdown(force?)
    alt Force Shutdown
        App->>Server: Stop()
    else Graceful Shutdown
        App->>Server: GracefulStop()
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Add Shutdown() and Listen() to support graceful gRPC shutdown (#575)

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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.

@devhaozi devhaozi closed this Feb 5, 2025
@devhaozi devhaozi reopened this Feb 5, 2025
@codecov
Copy link

codecov bot commented Feb 5, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 67.22%. Comparing base (ffb840d) to head (84f346f).
Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master     #850      +/-   ##
==========================================
+ Coverage   67.16%   67.22%   +0.06%     
==========================================
  Files         150      150              
  Lines       10442    10449       +7     
==========================================
+ Hits         7013     7024      +11     
+ Misses       3055     3052       -3     
+ Partials      374      373       -1     

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

@devhaozi devhaozi self-assigned this Feb 5, 2025
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 (2)
grpc/application_test.go (2)

210-253: Consider enhancing shutdown test coverage.

While the test covers both graceful and forced shutdown scenarios, consider adding verification of server state after shutdown.

 func TestShutdown(t *testing.T) {
   // ...existing test code...
   for _, test := range tests {
     t.Run(test.name, func(t *testing.T) {
       beforeEach()
       test.setup()
+      // Start server
+      listener, _ := net.Listen("tcp", "127.0.0.1:0")
+      go app.Listen(listener)
+      time.Sleep(100 * time.Millisecond)
+
       if test.force {
         app.Shutdown(true)
       } else {
         app.Shutdown()
       }
+
+      // Verify server state
+      conn, err := net.Dial("tcp", listener.Addr().String())
+      assert.Error(t, err, "Server should not accept new connections after shutdown")
+      if conn != nil {
+        conn.Close()
+      }
     })
   }
 }

255-295: Consider adding error case test for Listen.

The test only covers the success case. Consider adding a test for when the listener is already in use.

 func TestListen(t *testing.T) {
   // ...existing test setup...
   tests := []struct {
     name      string
     setup     func() net.Listener
+    expectErr bool
   }{
     {
       name: "success",
       setup: func() net.Listener {
         listener, _ := net.Listen("tcp", "127.0.0.1:0")
         return listener
       },
+      expectErr: false,
+    },
+    {
+      name: "error - listener in use",
+      setup: func() net.Listener {
+        listener, _ := net.Listen("tcp", "127.0.0.1:0")
+        // Start another server on the same port
+        go grpc.NewServer().Serve(listener)
+        time.Sleep(100 * time.Millisecond)
+        return listener
+      },
+      expectErr: true,
     },
   }
   // ...rest of the test...
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ffb840d and 84f346f.

📒 Files selected for processing (4)
  • contracts/grpc/grpc.go (1 hunks)
  • grpc/application.go (3 hunks)
  • grpc/application_test.go (2 hunks)
  • mocks/grpc/Grpc.go (3 hunks)
⏰ Context from checks skipped due to timeout of 300000ms (2)
  • GitHub Check: test / windows (1.23)
  • GitHub Check: test / windows (1.22)
🔇 Additional comments (4)
contracts/grpc/grpc.go (1)

11-15: LGTM! Well-designed interface changes.

The new methods Listen and Shutdown are well-documented and provide a clean interface for managing gRPC server lifecycle. The optional force parameter in Shutdown offers flexibility in shutdown behavior.

Also applies to: 19-20

grpc/application.go (2)

58-61: LGTM! Clean implementation of Listen method.

The implementation correctly logs the listening address and delegates to the gRPC server's Serve method.


94-101: LGTM! Well-implemented shutdown logic.

The implementation correctly handles both graceful and forced shutdown scenarios using appropriate gRPC server methods:

  • Graceful shutdown using GracefulStop()
  • Forced shutdown using Stop()
mocks/grpc/Grpc.go (1)

87-131: LGTM! Auto-generated mock implementation.

The mock implementation correctly follows the interface changes and includes all necessary helper methods for testing.

Also applies to: 239-283

Copy link
Contributor

@hwbrzzl hwbrzzl left a comment

Choose a reason for hiding this comment

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

Perfect

@devhaozi devhaozi merged commit dc45fb9 into master Feb 5, 2025
14 checks passed
@devhaozi devhaozi deleted the haozi/grpc branch February 5, 2025 12:57
hwbrzzl added a commit that referenced this pull request Dec 30, 2025
hwbrzzl added a commit that referenced this pull request Dec 30, 2025
hwbrzzl added a commit that referenced this pull request Dec 30, 2025
* fix: [#850] artisan help incorrect behavior

* optimize
hwbrzzl added a commit that referenced this pull request Dec 30, 2025
* fix: [#850] artisan help incorrect behavior

* optimize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Grpc support graceful shutdown

3 participants