Skip to content

feat: fix gRPC server #55

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

Closed
wants to merge 3 commits into from
Closed

feat: fix gRPC server #55

wants to merge 3 commits into from

Conversation

randygrok
Copy link
Contributor

@randygrok randygrok commented Apr 23, 2025

Overview

gRPC server started after executing the node, so it never was executed.

Summary by CodeRabbit

  • Refactor
    • Improved startup sequence and error handling for gRPC server, Rollkit node, and API server.
    • Enhanced logging for greater visibility during server initialization and shutdown.
  • Bug Fixes
    • More robust error reporting and handling during server startup.

Copy link
Contributor

coderabbitai bot commented Apr 23, 2025

Walkthrough

The changes refactor the startup sequence within the startInProcess function, clarifying the order in which the gRPC server, Rollkit node, and API server are initialized. Enhanced logging and error handling are added throughout the process. The gRPC server is now started first if enabled and not in gRPC-only mode, with immediate error reporting. The Rollkit node is started next unless in gRPC-only mode, and its cleanup is properly deferred. Service registration for transaction, Tendermint, and node services is now conditional on API/gRPC enablement and Rollkit RPC server availability. In gRPC-only mode, Rollkit node startup and related service registration are skipped. The API server starts afterward if enabled. A PostSetup hook is executed if provided. Detailed logs are added at each step, improving observability.

Changes

File(s) Change Summary
server/start.go Refactored startup sequence in startInProcess to start gRPC server before Rollkit node; added detailed logging and error handling in startInProcess and startGrpcServer; conditional service registration based on mode and server availability; improved control flow for gRPC-only mode; deferred Rollkit node cleanup; added PostSetup hook execution with logging.

Sequence Diagram(s)

sequenceDiagram
    participant Main as startInProcess
    participant GRPC as startGrpcServer
    participant Rollkit as startNode
    participant API as startAPIServer
    participant Hook as PostSetupHook

    Main->>GRPC: Start gRPC server (if enabled and not gRPC-only)
    alt gRPC error
        GRPC-->>Main: Return error
    end
    alt not gRPC-only
        Main->>Rollkit: Start Rollkit node
        Rollkit-->>Main: Node started (defer cleanup)
        Main->>Main: Register services if API/gRPC enabled and Rollkit RPC available
    else gRPC-only
        Main->>Main: Skip Rollkit node and service registration
    end
    alt gRPC enabled but not started
        Main->>GRPC: Start gRPC server
    end
    Main->>API: Start API server (if enabled)
    alt API error
        API-->>Main: Return error
    end
    Main->>Hook: Run PostSetup hook (if provided)
    Main->>Main: Wait for termination signals and errgroup completion
Loading

Possibly related PRs

  • fix(server): improve flag parsing #48: Modifies startInProcess and startNode functions similarly but focuses on simplifying function signatures and removing Cobra command dependencies for configuration loading; related by touching the same functions with different concerns.

Suggested reviewers

  • facundomedica
  • tac0turtle

Poem

In the warren where servers awake,
Startup order’s no longer opaque.
With logs that now gleam,
And errors that scream,
Each service hops in for the sake!
Genesis state’s tucked in so neat—
This launch is a rabbit’s small treat! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34fc297 and bb8e3c2.

📒 Files selected for processing (1)
  • server/start.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/start.go

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.
    • 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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.

@RollkitBot RollkitBot requested review from a team, tuxcanfly, yarikbratashchuk and Manav-Aggarwal and removed request for a team April 23, 2025 08:15
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

🔭 Outside diff range comments (1)
server/start.go (1)

254-265: 🛠️ Refactor suggestion

⚠️ Potential issue

grpc.NewClient does not exist – compilation will fail

The canonical way to obtain a client connection is grpc.DialContext (or grpc.Dial). grpc.NewClient is not part of google.golang.org/grpc.

-    grpcClient, err := grpc.NewClient(
-        config.Address,
+    grpcClient, err := grpc.DialContext(
+        ctx,
+        config.Address,
         grpc.WithTransportCredentials(insecure.NewCredentials()),
         grpc.WithDefaultCallOptions(
             grpc.ForceCodec(codec.NewProtoCodec(clientCtx.InterfaceRegistry).GRPCCodec()),
             grpc.MaxCallRecvMsgSize(maxRecvMsgSize),
             grpc.MaxCallSendMsgSize(maxSendMsgSize),
         ),
     )

This returns *grpc.ClientConn, which satisfies grpc.ClientConnInterface, so clientCtx.WithGRPCClient continues to work.

🧹 Nitpick comments (2)
server/start.go (2)

256-264: Consider replacing deprecated grpc.ForceCodec

grpc.ForceCodec is deprecated; modern gRPC prefers grpc.ForceServerCodec / grpc.ForceClientCodec (or interceptors). Deprecations don’t break compilation today but create tech‑debt.


361-370: Variable shadows imported package signer, harming readability

Declaring var signer signer.Signer overshadows the imported signer package for the entire function scope.
While it compiles, it surprises readers and prevents accidental future use of the package inside the function.

-    var signer signer.Signer
+    var seqSigner signer.Signer

Rename the variable (and subsequent references) to avoid shadowing.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d40c982 and e0db3d2.

📒 Files selected for processing (1)
  • server/start.go (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/start.go (1)
rpc/rpc.go (1)
  • RPCServer (57-65)
🔇 Additional comments (2)
server/start.go (2)

168-175: svrCfg mutation only local – verify expectations

Setting svrCfg.GRPC.Enable = true in gRPC‑only mode alters only the local copy (the struct is passed by value). That is fine here, but double‑check that no pointer to the original config is shared elsewhere and relied upon later (e.g. in hooks).


450-451: Nil‑safety for appGenesis.AppState

appGenesis.AppState is passed into genesis.NewGenesis; ensure the value is never nil, otherwise Rollkit genesis may marshal to an empty state and nodes started from the same genesis file could disagree.

server/start.go Outdated
Comment on lines 119 to 130
// 1. Start gRPC server FIRST (if enabled and not gRPC-only mode initially)
// Uses the main errgroup 'g' and context 'ctx'
if !gRPCOnly && svrCfg.GRPC.Enable {
svrCtx.Logger.Info("Attempting to start gRPC server before Rollkit node...")
grpcSrv, clientCtx, err = startGrpcServer(ctx, g, svrCfg.GRPC, clientCtx, svrCtx, app)
if err != nil {
return err
svrCtx.Logger.Error("Failed to start gRPC server early", "error", err)
// Decide whether to proceed or return the error
return fmt.Errorf("failed to start gRPC server: %w", err) // Return error if gRPC is essential
}
defer cleanupFn()

// Add the tx service to the gRPC router. We only need to register this
// service if API or gRPC is enabled, and avoid doing so in the general
// case, because it spawns a new local CometBFT RPC client.
if svrCfg.API.Enable || svrCfg.GRPC.Enable {
// Re-assign for making the client available below do not use := to avoid
// shadowing the clientCtx variable.
clientCtx = clientCtx.WithClient(rpcServer)
svrCtx.Logger.Info("Successfully started gRPC server early.")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Early‑started gRPC server is left running when a later step fails

startGrpcServer is spawned before the Rollkit node and API server.
If startGrpcServer succeeds but startNode (or any step that follows) returns an error, startInProcess bails out immediately (e.g. line 141). The context that the gRPC goroutine is listening to (ctx) is never cancelled and g.Wait() is never reached, leaving the gRPC listener alive and leaking the port and goroutine.

A minimal fix is to ensure the context is cancelled on every early‑return path after the server could have been spawned.

-        grpcSrv, clientCtx, err = startGrpcServer(ctx, g, svrCfg.GRPC, clientCtx, svrCtx, app)
+        grpcSrv, clientCtx, err = startGrpcServer(ctx, g, svrCfg.GRPC, clientCtx, svrCtx, app)
         if err != nil {
             svrCtx.Logger.Error("Failed to start gRPC server early", "error", err)
-            return fmt.Errorf("failed to start gRPC server: %w", err) // Return error if gRPC is essential
+            cancel()                       // new ‑‑ ensure all sub‑goroutines terminate
+            return fmt.Errorf("failed to start gRPC server: %w", err)
         }

You need a cancel handle; the simplest way is to capture it from getCtx (return (g, ctx, cancel) or similar).

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Member

Choose a reason for hiding this comment

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

Can we keep this logic as close as possible to the SDK server/start.go? And remove the bunch of added info logs, that's a bit too verbose otherwise.

@tac0turtle tac0turtle closed this Apr 30, 2025
@github-project-automation github-project-automation bot moved this to Done in Rollkit Apr 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants