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

refactor(katana-node): flatten rpc server building logic #2792

Merged
merged 2 commits into from
Dec 10, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Dec 10, 2024

move all the code that is in spawn to katana_node::build function, and include the RpcServer struct in the Node struct

Summary by CodeRabbit

  • New Features

    • Integrated RPC server functionality directly into the node's lifecycle.
    • Added a new field for RPC server management in the Node structure.
  • Bug Fixes

    • Updated error handling and method calls related to the RPC component for improved functionality.
  • Documentation

    • Enhanced documentation for the RpcServerHandle struct and its methods for better clarity.
  • Chores

    • Added katana-rpc as a workspace dependency in the project configuration.

Copy link

coderabbitai bot commented Dec 10, 2024

Walkthrough

Ohayo, sensei! This pull request introduces significant modifications to the NodeStoppedFuture struct in exit.rs and the Node struct in lib.rs. The NodeStoppedFuture now uses an RPC-based stopping mechanism, altering its control flow. In lib.rs, a new rpc_server field is added to the Node struct, and the launch method has been updated to accept ownership of self. These changes streamline the RPC server's initialization and enhance the overall structure of the node's lifecycle management.

Changes

File Path Change Summary
crates/katana/node/src/exit.rs Modified NodeStoppedFuture::new to await handle.rpc.clone().stopped() instead of handle.stop().
crates/katana/node/src/lib.rs Added rpc_server: RpcServer field to Node struct; updated launch method to take ownership of self; refactored RPC server initialization directly in launch; adjusted API configurations to reference config.rpc.
crates/dojo/test-utils/Cargo.toml Added katana-rpc.workspace = true as a new dependency.
crates/dojo/test-utils/src/sequencer.rs Changed error import from jsonrpsee::core::Error to katana_rpc::Error; updated URL construction and stop method calls.
crates/katana/rpc/rpc/src/lib.rs Updated RpcServerHandle to implement Clone, added addr method, and enhanced documentation.

Possibly related PRs

Suggested reviewers

  • glihm

🪧 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. (Experiment)
  • @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.

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

@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

🧹 Outside diff range and nitpick comments (2)
crates/katana/node/src/lib.rs (2)

86-86: Consider making rpc_server a private field

Ohayo, sensei! The rpc_server field in the Node struct is currently public. If it's not intended to be accessed outside of the Node implementation, making it private can enhance encapsulation and prevent unintended usage.


253-253: Avoid using .unwrap() with header parsing

Ohayo, sensei! Using .unwrap() on header parsing can cause a panic if the header name is invalid. Consider using .expect("Valid header name") for better error messages or handling the potential error gracefully.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 71db0b4 and d281cb4.

📒 Files selected for processing (2)
  • crates/katana/node/src/exit.rs (1 hunks)
  • crates/katana/node/src/lib.rs (6 hunks)
🔇 Additional comments (2)
crates/katana/node/src/lib.rs (1)

97-97: Verify ownership change in launch method

Ohayo, sensei! The launch method now consumes self instead of borrowing it mutably. Please ensure that this change doesn't affect other parts of the code where Node might be used after launching.

To check for any usages of Node after launch, you can run the following script:

✅ Verification successful

The previous search wasn't effective because the pattern was too specific. Let's broaden our search to find all usages of launch() and understand the context better, along with the Node struct definition and test cases.


The previous results show that launch() is used in several places, but we need to verify the ownership patterns and see if there are any post-launch usages of the Node instance.


Ownership change in launch method is safe

Ohayo, sensei! After analyzing the codebase, the ownership change is correct and safe. The Node instance is properly consumed by launch() and transformed into a LaunchedNode struct, which contains all the necessary components. Looking at the implementation:

  1. The launch() method takes ownership of self and returns a LaunchedNode
  2. All usages of Node::launch() show that the node is only used through the returned LaunchedNode afterward
  3. The LaunchedNode struct receives ownership of all important components from the original Node
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usages of `Node` after the `launch` method is called.

# Test: Find instances where `Node` is used after `launch` is invoked.
# Expect: No usages of `Node` after `launch` method is called.

rg -A5 'let\s+.*=\s+Node::.*;\s+.*\.launch\(\)' --threads 1 | rg -A5 'Node::' --threads 1

Length of output: 89


Script:

#!/bin/bash
# Let's search for all usages of the launch method
rg "\.launch\(\)" -B 5 -A 2

# Also search for Node struct definition and its usages
ast-grep --pattern 'struct Node {
  $$$
}'

# Find all test cases involving Node and launch
rg "test.*Node.*launch" -A 5

Length of output: 1730


Script:

#!/bin/bash
# Let's find the Node struct and its methods to understand ownership patterns
ast-grep --pattern 'impl Node {
  $$$
}'

# Search for any references to Node after launch
rg "node\." -A 3 crates/katana/cli/src/args.rs

# Look for any potential clones or references of Node
rg "Clone|&Node|&mut Node" crates/katana/node/src/

Length of output: 11469

crates/katana/node/src/exit.rs (1)

21-21: Ensuring proper shutdown with handle.rpc.handle.clone().stopped().await

Ohayo, sensei! The change correctly waits for the RPC server to stop, ensuring that all asynchronous tasks are fully terminated before the node shuts down.

Copy link

codecov bot commented Dec 10, 2024

Codecov Report

Attention: Patch coverage is 94.73684% with 2 lines in your changes missing coverage. Please review.

Project coverage is 55.61%. Comparing base (71db0b4) to head (45c2f07).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
crates/katana/node/src/exit.rs 0.00% 1 Missing ⚠️
crates/katana/node/src/lib.rs 96.77% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2792   +/-   ##
=======================================
  Coverage   55.60%   55.61%           
=======================================
  Files         439      439           
  Lines       55678    55672    -6     
=======================================
+ Hits        30961    30962    +1     
+ Misses      24717    24710    -7     

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

Copy link

@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

🧹 Outside diff range and nitpick comments (4)
crates/katana/rpc/rpc/src/lib.rs (1)

Line range hint 46-50: Consider adding error documentation

The stop() method's error conditions should be documented to help users handle the AlreadyStopped case appropriately.

     /// Tell the server to stop without waiting for the server to stop.
+    ///
+    /// # Errors
+    /// Returns `Error::AlreadyStopped` if the server has already been stopped.
     pub fn stop(&self) -> Result<(), Error> {
crates/dojo/test-utils/src/sequencer.rs (1)

45-46: Consider error handling improvement

While the URL parsing looks good, we could make the error handling more specific.

-            Url::parse(&format!("http://{}", handle.rpc.addr())).expect("Failed to parse URL");
+            Url::parse(&format!("http://{}", handle.rpc.addr()))
+                .expect("Failed to create URL from valid socket address");
crates/katana/node/src/lib.rs (2)

247-253: Consider documenting the Argent-specific headers, sensei

The CORS configuration includes Argent-specific headers. It would be helpful to document why these headers are needed and if they're required for specific client compatibility.


Line range hint 247-287: Consider extracting RPC module building logic

The RPC module building logic could be extracted into a separate function for better maintainability and testability.

Example refactor:

+ fn build_rpc_modules(
+     config: &Config,
+     backend: Arc<Backend<BlockifierFactory>>,
+     pool: TxPool,
+     block_producer: BlockProducer<BlockifierFactory>,
+     forked_client: Option<ForkedClient>,
+ ) -> Result<RpcModule<()>> {
+     let mut rpc_modules = RpcModule::new(());
+     // ... existing module building logic ...
+     Ok(rpc_modules)
+ }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d281cb4 and 45c2f07.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • crates/dojo/test-utils/Cargo.toml (1 hunks)
  • crates/dojo/test-utils/src/sequencer.rs (3 hunks)
  • crates/katana/node/src/exit.rs (1 hunks)
  • crates/katana/node/src/lib.rs (7 hunks)
  • crates/katana/rpc/rpc/src/lib.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/katana/node/src/exit.rs
🔇 Additional comments (9)
crates/dojo/test-utils/Cargo.toml (1)

17-17: Ohayo! LGTM - Workspace dependency properly added

The addition of katana-rpc as a workspace dependency aligns well with the RPC server restructuring objective.

crates/katana/rpc/rpc/src/lib.rs (2)

36-42: Ohayo sensei! Documentation improvements enhance clarity

The added documentation clearly explains the RPC server handle's components and their purposes.


56-59: LGTM - Getter method follows Rust conventions

The addr() method properly implements the getter pattern, returning a reference to avoid unnecessary cloning.

crates/dojo/test-utils/src/sequencer.rs (2)

13-13: LGTM - Error type import aligned with new architecture

The switch to katana_rpc::Error provides better error handling integration with the RPC subsystem.


108-108: LGTM - Simplified RPC server shutdown

The simplified stop call aligns with the flattened RPC server structure, making the code more maintainable.

crates/katana/node/src/lib.rs (4)

86-86: Ohayo! Nice architectural improvement, sensei!

Moving the RPC server into the Node struct improves encapsulation and makes the ownership model clearer.


97-97: Taking ownership in launch method prevents misuse, excellent work sensei!

The ownership model change ensures that the Node instance cannot be used after launching, preventing potential concurrent access issues.

Also applies to: 138-140


292-300: Clean and well-organized Node construction, sensei!

The Node construction follows a logical order and includes all necessary components.


67-67: Ohayo sensei! Consider implementing graceful shutdown

The TODO comment suggests waiting for the RPC server to stop. Currently, there might be a race condition if new requests arrive during shutdown.

Let's check if there are any existing graceful shutdown implementations we can reference:

@kariy kariy merged commit cc4c800 into main Dec 10, 2024
14 checks passed
@kariy kariy deleted the katana/rpc-flatten branch December 10, 2024 17:23
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