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(torii): retrieve controllers & usernames graphql and grpc #2992

Merged
merged 5 commits into from
Feb 6, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 5, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new message type Controller to capture essential details like address, username, and deployment timestamp.
    • Added a new API endpoint to retrieve controller information based on provided contract addresses, enhancing data access capabilities.
    • Expanded GraphQL schema with a new ControllerObject for handling controller-related queries.
    • Introduced a new module for controller functionalities within the GraphQL interface.
    • Added new constants and mappings related to the Controller entity for improved structure and access.

Copy link

coderabbitai bot commented Feb 5, 2025

Walkthrough

Ohayo, sensei! This pull request introduces new protocol buffer definitions and extends the gRPC service. A new message type, Controller, is defined with fields for address, username, and deployment timestamp. Additionally, a new RPC method, RetrieveControllers, is added to the World service along with the accompanying request and response messages. On the server side, a method is implemented in the DojoWorld struct to handle controller retrieval by querying the database based on provided contract addresses.

Changes

File(s) Change Summary
crates/torii/grpc/proto/{types.proto, world.proto} Added new protocol buffer definitions: a Controller message in types.proto and a RetrieveControllers RPC method plus request/response messages in world.proto.
crates/torii/grpc/src/server/mod.rs Implemented retrieve_controllers methods in the DojoWorld struct and its World trait implementation to process requests, execute SQL queries, and return controller data.
crates/torii/graphql/src/{constants.rs, mapping.rs, object/{controller.rs, mod.rs}} Introduced new constants and mappings related to the Controller, and added a ControllerObject struct for handling GraphQL queries, along with a new controller module.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant W as WorldService
    participant D as DojoWorld
    participant DB as Database

    C->>W: RetrieveControllersRequest (contract_addresses)
    W->>D: retrieve_controllers(contract_addresses)
    D->>DB: Execute SQL query on 'controllers'
    DB-->>D: Return controller data (address, username, timestamp)
    D-->>W: RetrieveControllersResponse (controllers)
    W-->>C: RetrieveControllersResponse (controllers)
Loading

Possibly related PRs

Suggested reviewers

  • glihm: Suggested for review based on their expertise in the related codebase.

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

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

🧹 Nitpick comments (5)
crates/torii/grpc/src/server/mod.rs (2)

1047-1077: Ohayo sensei! The SQL query looks good but let's handle invalid addresses gracefully.

The SQL query construction is safe with proper parameterization. However, the address parsing could panic if the database contains invalid addresses.

Apply this diff to handle invalid addresses:

-                address: address.parse::<Felt>().unwrap().to_bytes_be().to_vec(),
+                address: address.parse::<Felt>()
+                    .map_err(|e| Error::from(ParseError::FromStr(e)))?
+                    .to_bytes_be()
+                    .to_vec(),

1307-1322: Consider adding input validation for empty contract addresses.

While the error handling is good, consider validating that the contract addresses are not empty byte arrays before parsing them.

Apply this diff to add validation:

         let contract_addresses = contract_addresses
             .iter()
+            .filter(|address| !address.is_empty())
             .map(|address| Felt::from_bytes_be_slice(address))
             .collect::<Vec<_>>();
crates/torii/grpc/proto/types.proto (1)

190-194: Ohayo! Let's add documentation for the Controller message fields.

The field types and numbers look good, but documentation would help users understand the purpose of each field.

Apply this diff to add documentation:

 message Controller {
+    // The controller's address in bytes
     bytes address = 1;
+    // The username associated with the controller
     string username = 2;
+    // Unix timestamp when the controller was deployed
     uint64 deployed_at_timestamp = 3;
 }
crates/torii/grpc/proto/world.proto (2)

58-60: Add documentation for the RetrieveControllers RPC method.

The method signature looks good, but documentation would help users understand its purpose.

Apply this diff to add documentation:

+    // Retrieves controller information based on provided contract addresses.
+    // If no addresses are provided, returns all controllers.
     rpc RetrieveControllers (RetrieveControllersRequest) returns (RetrieveControllersResponse);

62-68: Add documentation for the request and response messages.

The message structures look good, but documentation would help users understand their fields.

Apply this diff to add documentation:

 message RetrieveControllersRequest {
+    // List of contract addresses to retrieve controllers for.
+    // If empty, returns all controllers.
     repeated bytes contract_addresses = 1;
 }

 message RetrieveControllersResponse {
+    // List of controllers matching the requested contract addresses
     repeated types.Controller controllers = 1;
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bf0c5ee and 65d1c41.

📒 Files selected for processing (3)
  • crates/torii/grpc/proto/types.proto (1 hunks)
  • crates/torii/grpc/proto/world.proto (1 hunks)
  • crates/torii/grpc/src/server/mod.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt

Copy link

codecov bot commented Feb 5, 2025

Codecov Report

Attention: Patch coverage is 43.28358% with 38 lines in your changes missing coverage. Please review.

Project coverage is 57.14%. Comparing base (bf0c5ee) to head (bee7157).
Report is 8 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/grpc/src/server/mod.rs 0.00% 38 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2992      +/-   ##
==========================================
+ Coverage   56.97%   57.14%   +0.17%     
==========================================
  Files         426      428       +2     
  Lines       56376    56802     +426     
==========================================
+ Hits        32119    32461     +342     
- Misses      24257    24341      +84     

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

@Larkooo Larkooo changed the title feat(torii): retrieve controllers with usernames feat(torii): retrieve controllers & usernames Feb 5, 2025
@Larkooo Larkooo changed the title feat(torii): retrieve controllers & usernames feat(torii): retrieve controllers & usernames graphql and grpc Feb 5, 2025
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 (4)
crates/torii/graphql/src/object/controller.rs (2)

8-9: Ohayo sensei! Consider removing unnecessary derive.

The #[derive(Debug)] seems unnecessary for an empty struct that's only used as a type marker.

-#[derive(Debug)]
pub struct ControllerObject;

11-45: Implementation looks good but could be generalized.

The implementation follows the established pattern and is correct. However, since this pattern is repeated across multiple entity types, consider extracting it into a macro or default implementation to reduce boilerplate.

crates/torii/graphql/src/constants.rs (2)

12-12: Consider grouping with other table constants.

Move CONTROLLER_TABLE constant to be grouped with other table constants for better organization.

pub const METADATA_TABLE: &str = "metadata";
+pub const CONTROLLER_TABLE: &str = "controllers";
-pub const CONTROLLER_TABLE: &str = "controllers";

69-70: Consider alphabetical ordering of type names.

Move CONTROLLER_TYPE_NAME and CONTROLLER_NAMES to maintain alphabetical ordering with other type names and name tuples.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 65d1c41 and 3841392.

📒 Files selected for processing (4)
  • crates/torii/graphql/src/constants.rs (2 hunks)
  • crates/torii/graphql/src/mapping.rs (1 hunks)
  • crates/torii/graphql/src/object/controller.rs (1 hunks)
  • crates/torii/graphql/src/object/mod.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/torii/graphql/src/object/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: clippy
  • GitHub Check: ensure-wasm
  • GitHub Check: docs
🔇 Additional comments (1)
crates/torii/graphql/src/mapping.rs (1)

180-188: Ohayo sensei! The type mapping looks perfect!

The controller mapping is well-defined with appropriate non-null constraints and correct type usage for each field.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

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

Thanks @Larkooo! gRPC needs a fix, but GraphQL looks good.

crates/torii/grpc/src/server/mod.rs Outdated Show resolved Hide resolved
crates/torii/grpc/src/server/mod.rs Outdated Show resolved Hide resolved
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 (1)
crates/torii/grpc/src/server/mod.rs (1)

1307-1322: Consider more specific error handling.

The implementation is good, but we could improve error handling by providing more specific error statuses:

-            .map_err(|e| Status::internal(e.to_string()))?;
+            .map_err(|e| match e {
+                Error::Sql(sqlx::Error::RowNotFound) => Status::not_found("Controllers not found"),
+                e => Status::internal(e.to_string()),
+            })?;

This would provide better error context to API consumers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7160679 and bee7157.

📒 Files selected for processing (1)
  • crates/torii/grpc/src/server/mod.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (2)
crates/torii/grpc/src/server/mod.rs (2)

59-65: LGTM!

The new imports for controller-related types are properly organized.


1047-1077: Verify the database schema for deployed_at field.

Ohayo, sensei! The implementation looks good, but based on past review comments, there might be a mismatch between the database schema (TEXT) and the code's expectation (DateTime). Let's verify the schema:

The timestamp conversion from DateTime<Utc> to u64 is handled correctly, but ensure that the database schema matches these expectations.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check the schema of the controllers table
echo "Checking controllers table schema..."
sqlite3 .sqlite_db ".schema controllers"

Length of output: 223


🏁 Script executed:

#!/bin/bash
echo "Ohayo, sensei! Let's search for the controllers table schema and the deployed_at column definition in the repository..."
echo "Searching for controllers table definition (e.g., CREATE TABLE controllers)..."
rg -i "CREATE TABLE.*controllers" .
echo "Searching for deployed_at column within the repository..."
rg -i "deployed_at" .

Length of output: 1555


Ohayo, sensei! The controllers table’s schema now shows that the deployed_at column is defined as TIMESTAMP (see crates/torii/migrations/20250128051146_controllers.sql), which matches the code’s expectation of a DateTime<Utc>. No action is necessary here.

@glihm glihm merged commit a3181d8 into dojoengine:main Feb 6, 2025
14 of 15 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