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

opt(torii-server): initializing handlers #3078

Merged
merged 4 commits into from
Mar 4, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Mar 3, 2025

Summary by CodeRabbit

  • Chores

    • Enhanced system diagnostics by introducing improved debugging visibility across multiple service handlers. These enhancements help simplify troubleshooting and support a smoother operational experience when examining system logs.
  • New Features

    • Introduced dynamic configuration for request handlers that allows flexible management of processing workflows. This enhancement enables external customization of request handling, thereby increasing adaptability and overall system performance.
    • Streamlined request handling mechanism by consolidating multiple handlers into a single vector, improving the efficiency of processing requests.

@Larkooo Larkooo marked this pull request as draft March 3, 2025 09:08
Copy link

coderabbitai bot commented Mar 3, 2025

Ohayo sensei! Here’s the update on the pull request:

Walkthrough

This pull request introduces the Debug trait to several handler structs in the Torii server, including GraphQLHandler, GrpcHandler, McpHandler, SqlHandler, and StaticHandler. The Handler trait is modified to require std::fmt::Debug along with Send + Sync. Additionally, the Proxy struct is updated to manage handlers dynamically through a new field, with adjustments to its constructor and methods to ensure proper utilization of the provided handlers during request processing.

Changes

File(s) Change Summary
crates/torii/server/src/handlers/graphql.rs, crates/torii/server/src/handlers/grpc.rs, crates/torii/server/src/handlers/sql.rs, crates/torii/server/src/handlers/static_files.rs Added #[derive(Debug)] attribute to enable automatic implementation of the Debug trait. Removed client_ip field and modified constructors and handle methods to accept client_addr.
crates/torii/server/src/handlers/mcp.rs Updated derive attribute from #[derive(Clone)] to #[derive(Debug, Clone)], adding the Debug trait while retaining Clone. Modified handle method to include _client_addr: IpAddr.
crates/torii/server/src/handlers/mod.rs Updated the Handler trait to require the std::fmt::Debug trait in addition to Send + Sync. Modified handle method to include client_addr: IpAddr.
crates/torii/server/src/proxy.rs Introduced a new field handlers: Arc<RwLock<Vec<Box<dyn Handler>>>> in the Proxy struct, updated the constructor (new), and modified the start and handle methods to utilize the handlers.

Suggested reviewers

  • kariy
  • glihm sensei

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 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: 2

🔭 Outside diff range comments (1)
crates/torii/server/src/proxy.rs (1)

179-183: ⚠️ Potential issue

Undefined variable 'handlers' in function!

Ohayo sensei! The handlers variable is referenced here but it's not defined in the function scope. This code is trying to iterate over a variable that doesn't exist, which will result in a compilation error.

This is related to the earlier issue where the handlers from the Proxy struct aren't being passed to this function. You'll need to both update the function signature to accept handlers and ensure they're passed correctly when the function is called.

If no handlers were defined previously in this function, you might need to create them locally if external handlers aren't provided:

-    for handler in handlers {
+    // Use the passed handlers, or create default ones if none were provided
+    if handlers.is_empty() {
+        // Create default handlers
+        let handlers: Vec<Box<dyn Handler>> = vec![
+            Box::new(GrpcHandler::new(client_ip, grpc_addr)),
+            Box::new(GraphQLHandler::new(client_ip, graphql_addr)),
+            Box::new(SqlHandler::new(pool.clone())),
+            Box::new(McpHandler::new()),
+            Box::new(StaticHandler::new(artifacts_addr)),
+        ];
+        
+        for handler in handlers {
+            if handler.should_handle(&req) {
+                return Ok(handler.handle(req).await);
+            }
+        }
+    } else {
+        // Use the handlers passed to the function
+        for handler in handlers {
+            if handler.should_handle(&req) {
+                return Ok(handler.handle(req).await);
+            }
+        }
+    }

Or a simpler approach:

-    for handler in handlers {
+    // Use the passed handlers, or create default ones if none were provided
+    let default_handlers: Vec<Box<dyn Handler>> = if handlers.is_empty() {
+        vec![
+            Box::new(GrpcHandler::new(client_ip, grpc_addr)),
+            Box::new(GraphQLHandler::new(client_ip, graphql_addr)),
+            Box::new(SqlHandler::new(pool.clone())),
+            Box::new(McpHandler::new()),
+            Box::new(StaticHandler::new(artifacts_addr)),
+        ]
+    } else {
+        handlers
+    };
+    
+    for handler in default_handlers {
        if handler.should_handle(&req) {
            return Ok(handler.handle(req).await);
        }
    }
🧹 Nitpick comments (1)
crates/torii/server/src/proxy.rs (1)

74-92: Please update constructor to accept handlers parameter

Ohayo sensei! Since you've added the handlers field to the Proxy struct and are using it in the start method, you should update the constructor to accept an optional list of handlers.

pub fn new(
    addr: SocketAddr,
    allowed_origins: Option<Vec<String>>,
    grpc_addr: Option<SocketAddr>,
    graphql_addr: Option<SocketAddr>,
    artifacts_addr: Option<SocketAddr>,
    pool: Arc<SqlitePool>,
+   handlers: Option<Vec<Box<dyn Handler>>>,
) -> Self {
    Self {
        addr,
        allowed_origins,
        grpc_addr,
        graphql_addr: Arc::new(RwLock::new(graphql_addr)),
        artifacts_addr,
        pool,
-       handlers: None,
+       handlers,
    }
}
🧰 Tools
🪛 GitHub Actions: ci

[error] 87-87: Rust formatting check failed. There is a missing comma after 'handlers: None'.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 429f238 and 2d1a6f3.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • crates/torii/server/src/handlers/graphql.rs (1 hunks)
  • crates/torii/server/src/handlers/grpc.rs (1 hunks)
  • crates/torii/server/src/handlers/mcp.rs (1 hunks)
  • crates/torii/server/src/handlers/mod.rs (1 hunks)
  • crates/torii/server/src/handlers/sql.rs (1 hunks)
  • crates/torii/server/src/handlers/static_files.rs (1 hunks)
  • crates/torii/server/src/proxy.rs (3 hunks)
✅ Files skipped from review due to trivial changes (4)
  • crates/torii/server/src/handlers/mcp.rs
  • crates/torii/server/src/handlers/graphql.rs
  • crates/torii/server/src/handlers/sql.rs
  • crates/torii/server/src/handlers/static_files.rs
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/server/src/proxy.rs

[error] 87-87: Rust formatting check failed. There is a missing comma after 'handlers: None'.

🔇 Additional comments (3)
crates/torii/server/src/handlers/grpc.rs (1)

11-11: Improved debugging capability added!

Ohayo sensei! The addition of #[derive(Debug)] trait to the GrpcHandler struct is perfect for providing better debugging information. This aligns well with the changes to the Handler trait.

crates/torii/server/src/handlers/mod.rs (1)

10-10: Well structured trait extension!

Ohayo sensei! Adding the std::fmt::Debug trait requirement to Handler is a solid design decision. This ensures all handlers can be properly debugged and inspected at runtime.

crates/torii/server/src/proxy.rs (1)

71-71: Good addition for dynamic handler management!

Ohayo sensei! Adding the handlers field to store externally provided handlers is a great approach to make the proxy more flexible.

@Larkooo Larkooo marked this pull request as ready for review March 3, 2025 09:39
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

🧹 Nitpick comments (5)
crates/torii/server/src/proxy.rs (5)

67-67: Ohayo sensei, nice addition of handlers field!
Storing a dynamic list of handlers behind a shared lock is flexible. Make sure writes are not frequent enough to cause lock contention.


79-85: Ohayo sensei, watch out for indexing fragility!
The order of handlers in the vector is significant since you’re referencing handlers[0] elsewhere. Consider using a dedicated structure or an enum-based approach to avoid confusion if you introduce or reorder handlers.


91-92: Ohayo sensei, referencing handlers[0] is fragile.
If the order changes, you might accidentally replace a different handler. Consider a named approach or searching for GraphQLHandler in the vector.


138-138: Ohayo sensei, repeated Arc clones might add overhead!
Though minimal, consider capturing the pre-cloned Arc if done repeatedly in a hot path.


140-140: Ohayo sensei, consider avoiding the second clone.
You’re already cloning handlers in line 138. Reusing that reference might reduce overhead.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2d1a6f3 and 6d05a84.

📒 Files selected for processing (7)
  • crates/torii/server/src/handlers/graphql.rs (2 hunks)
  • crates/torii/server/src/handlers/grpc.rs (2 hunks)
  • crates/torii/server/src/handlers/mcp.rs (5 hunks)
  • crates/torii/server/src/handlers/mod.rs (1 hunks)
  • crates/torii/server/src/handlers/sql.rs (3 hunks)
  • crates/torii/server/src/handlers/static_files.rs (2 hunks)
  • crates/torii/server/src/proxy.rs (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • crates/torii/server/src/handlers/sql.rs
  • crates/torii/server/src/handlers/mcp.rs
  • crates/torii/server/src/handlers/graphql.rs
  • crates/torii/server/src/handlers/static_files.rs
  • crates/torii/server/src/handlers/grpc.rs
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: ensure-windows
🔇 Additional comments (9)
crates/torii/server/src/handlers/mod.rs (3)

7-8: Ohayo sensei, good addition for client IP usage!
The import of IpAddr is essential for the newly introduced parameter in handle.


12-13: Ohayo sensei, including Debug is helpful but watch for sensitive data!
Adding the std::fmt::Debug bound is beneficial for troubleshooting, but ensure no private info is inadvertently exposed in logs.


17-17: Ohayo sensei, nice approach for capturing the client address!
The introduction of the client_addr: IpAddr parameter is consistent and clarifies the request origin.

crates/torii/server/src/proxy.rs (6)

87-87: Ohayo sensei, good job finalizing the new Proxy structure!
This constructor neatly initializes the handlers.


105-105: Ohayo sensei, well done setting up the CORS layer!
This ensures cross-origin resource sharing is properly configured.


142-143: Ohayo sensei, concurrency approach looks good!
Reading the handlers inside an async block ensures a consistent snapshot.


163-163: Ohayo sensei, passing handlers as a slice is a flexible design!
This approach allows you to reuse the same handle function for any subset or ordering of handlers.


165-165: Ohayo sensei, straightforward iteration approach!
You handle the first matching handler. If you need multiple handlers per request, consider continuing the iteration or collecting responses.


167-167: Ohayo sensei, direct short-circuit return is clean!
The first matching handler processes the request, and we exit immediately. This is a neat chain-of-responsibility pattern.

Copy link

codecov bot commented Mar 3, 2025

Codecov Report

Attention: Patch coverage is 0% with 35 lines in your changes missing coverage. Please review.

Project coverage is 57.25%. Comparing base (429f238) to head (6d05a84).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/server/src/proxy.rs 0.00% 19 Missing ⚠️
crates/torii/server/src/handlers/graphql.rs 0.00% 4 Missing ⚠️
crates/torii/server/src/handlers/grpc.rs 0.00% 4 Missing ⚠️
crates/torii/server/src/handlers/static_files.rs 0.00% 4 Missing ⚠️
crates/torii/server/src/handlers/mcp.rs 0.00% 3 Missing ⚠️
crates/torii/server/src/handlers/sql.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3078      +/-   ##
==========================================
+ Coverage   57.24%   57.25%   +0.01%     
==========================================
  Files         441      441              
  Lines       60135    60119      -16     
==========================================
  Hits        34422    34422              
+ Misses      25713    25697      -16     

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

@Larkooo Larkooo changed the title refactorC(torii-server): initializing handlers opt(torii-server): initializing handlers Mar 3, 2025
@Larkooo Larkooo merged commit 296162d into dojoengine:main Mar 4, 2025
15 of 16 checks passed
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.

2 participants