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-grpc): subscribe to token updates (metadata etc.) #2990

Merged
merged 5 commits into from
Feb 10, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 4, 2025

Summary by CodeRabbit

  • New Features
    • Tokens now include a unique identifier for enhanced tracking.
    • Clients can subscribe to token updates, receiving real-time streaming notifications for token-related changes.
    • New structures and methods introduced for managing token subscriptions and updates, including a dedicated service for handling subscription logic.

Copy link

coderabbitai bot commented Feb 4, 2025

Walkthrough

Ohayo, sensei! This PR enhances the gRPC service's token functionality by adding a token_id field to the Token message. It introduces a new RPC method, SubscribeTokens, along with the SubscribeTokensResponse message for managing token updates. Additionally, the server code has been refactored with organized imports and a new type alias for the token subscription stream. A new token module has been created, which includes structures and methods for managing subscribers and processing token updates.

Changes

File(s) Change Summary
crates/torii/grpc/proto/types.proto Added token_id field to the Token message.
crates/torii/grpc/proto/world.proto Introduced new RPC method SubscribeTokens and message SubscribeTokensResponse for token update subscriptions.
crates/torii/grpc/src/server/mod.rs Reorganized import statements; added a new asynchronous method subscribe_tokens and a type alias SubscribeTokensResponseStream.
crates/torii/grpc/src/server/subscriptions/mod.rs
crates/torii/grpc/src/server/subscriptions/token.rs
Added a new token module; introduced TokenSubscriber, TokenManager, and Service with methods to manage subscribers and process token updates.

Possibly related issues

Possibly related PRs

  • feat(torii-grpc): erc tokens and balances #2698: The changes in the main PR, which add a new field to the Token message in types.proto, are related to the retrieved PR as both involve modifications to the Token structure in the same file.
  • feat(torii): token balances subscription #2831: The changes in the main PR, which add a new field to the Token message, are related to the retrieved PR as both involve modifications to the Token structure, specifically in the context of token management and subscription functionalities.

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. (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 (4)
crates/torii/grpc/src/server/subscriptions/token.rs (4)

34-59: Ohayo sensei! Consider using a globally unique subscription ID generator.

Storing subscription IDs generated with a random u64 may risk collisions over a large number of subscriptions. Using a time-based or atomic counter-based ID might reduce the already small probability of collisions.


60-60: Ohayo sensei! Fix Rust formatting to pass CI.

The CI pipeline indicates code formatting issues on lines 60, 98, and 135. Please run Rust’s built-in formatter (cargo fmt) to comply with the project formatting guidelines.

Also applies to: 98-98, 135-135

🧰 Tools
🪛 GitHub Actions: ci

[warning] 60-60: Code formatting issues detected. Please adhere to the Rust formatting guidelines.


111-120: Ohayo sensei! Consider graceful shutdown for publish_updates.

When shutting down, the infinite loop in publish_updates may continue receiving from the channel until it empties or indefinitely if no complete signal is sent. You could add a cancellation mechanism or a select statement that also listens for a shutdown request to ensure a clean exit.


122-162: Ohayo sensei! Confirm the performance of process_balance_update under high load.

Looping over all subscribers in process_balance_update may become costly if there are many subscribers. Consider using a more scalable data structure or partitioning subscriptions by contract address to avoid iterating the entire map.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 135-135: Code formatting issues detected. Please adhere to the Rust formatting guidelines.

📜 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 e984885.

📒 Files selected for processing (5)
  • crates/torii/grpc/proto/types.proto (1 hunks)
  • crates/torii/grpc/proto/world.proto (2 hunks)
  • crates/torii/grpc/src/server/mod.rs (3 hunks)
  • crates/torii/grpc/src/server/subscriptions/mod.rs (1 hunks)
  • crates/torii/grpc/src/server/subscriptions/token.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/torii/grpc/src/server/subscriptions/mod.rs
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/grpc/src/server/subscriptions/token.rs

[warning] 60-60: Code formatting issues detected. Please adhere to the Rust formatting guidelines.


[warning] 98-98: Code formatting issues detected. Please adhere to the Rust formatting guidelines.


[warning] 135-135: Code formatting issues detected. Please adhere to the Rust formatting guidelines.

crates/torii/grpc/src/server/mod.rs

[warning] 56-56: Code formatting issues detected. Please adhere to the Rust formatting guidelines.


[warning] 1256-1256: Code formatting issues detected. Please adhere to the Rust formatting guidelines.

🔇 Additional comments (6)
crates/torii/grpc/src/server/subscriptions/token.rs (1)

91-110: Ohayo sensei! Verify concurrency in the Service::new method.

Spawning a new task to run publish_updates might lead to potential race conditions if other tasks modify shared states unexpectedly. Ensure that the references to subs_manager remain valid for the duration of the spawned task, and confirm that the manager’s concurrency design is robust (e.g. no risk of partial updates or deadlocks).

🧰 Tools
🪛 GitHub Actions: ci

[warning] 98-98: Code formatting issues detected. Please adhere to the Rust formatting guidelines.

crates/torii/grpc/src/server/mod.rs (2)

59-59: Ohayo sensei! Great job consolidating these imports.

All relevant proto::world entities are neatly grouped. This improves readability and maintainability.


1246-1247: Ohayo sensei! Confirm consistent naming for token subscription streams.

The introduction of SubscribeTokensResponseStream and aliasing it with SubscribeTokensStream is appropriate. Just ensure a consistent naming convention throughout the codebase so it’s easy to locate references.

Also applies to: 1258-1259

crates/torii/grpc/proto/types.proto (1)

165-165: Ohayo sensei! Validate the usage of token_id in upstream logic.

Adding this field is helpful to distinguish tokens, but ensure that instrumentation code and any references to Token in logic or tests properly handle token_id so we don’t accidentally break backward compatibility.

crates/torii/grpc/proto/world.proto (2)

43-45: Ohayo sensei: New RPC method for token updates!

The addition of the SubscribeTokens RPC method correctly follows the structure of existing subscription RPCs. This new method enhances the service's token handling capability by providing a stream of token updates. Please ensure that client documentation and integration tests are updated accordingly to include this new branch of functionality.


91-95: Ohayo sensei: Clean and clear SubscribeTokensResponse message!

The new SubscribeTokensResponse message neatly encapsulates a types.Token, aligning well with the new RPC. Do verify that the Token message in the imported types.proto includes the token_id field as per the overarching PR objectives, to guarantee that token updates carry the correct metadata.

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: 1

🧹 Nitpick comments (4)
crates/torii/grpc/src/server/subscriptions/token.rs (4)

23-23: Update LOG_TARGET constant value

Ohayo sensei! The LOG_TARGET constant appears to be copied from a balance-related module. The value should be updated to reflect the token module.

-pub(crate) const LOG_TARGET: &str = "torii::grpc::server::subscriptions::balance";
+pub(crate) const LOG_TARGET: &str = "torii::grpc::server::subscriptions::token";

63-80: Optimize update_subscriber to reduce lock contention

The current implementation acquires a read lock followed by a write lock. This can be optimized by using a single write lock.

 pub async fn update_subscriber(&self, id: u64, contract_addresses: Vec<Felt>) {
-    let sender = {
-        let subscribers = self.subscribers.read().await;
-        if let Some(subscriber) = subscribers.get(&id) {
-            subscriber.sender.clone()
-        } else {
-            return; // Subscriber not found, exit early
-        }
-    };
-
-    self.subscribers.write().await.insert(
-        id,
-        TokenSubscriber {
-            contract_addresses: contract_addresses.into_iter().collect(),
-            sender,
-        },
-    );
+    let mut subscribers = self.subscribers.write().await;
+    if let Some(subscriber) = subscribers.get(&id) {
+        subscribers.insert(
+            id,
+            TokenSubscriber {
+                contract_addresses: contract_addresses.into_iter().collect(),
+                sender: subscriber.sender.clone(),
+            },
+        );
+    }
 }

48-50: Improve error handling for initial response

The initial response error is silently ignored. Consider logging the error or handling it appropriately.

-        let _ = sender
-            .send(Ok(SubscribeTokenBalancesResponse { subscription_id, balance: None }))
-            .await;
+        if let Err(e) = sender
+            .send(Ok(SubscribeTokenBalancesResponse { subscription_id, balance: None }))
+            .await
+        {
+            error!(target = LOG_TARGET, error = %e, "Failed to send initial response");
+            return Err(Error::Custom("Failed to send initial response".into()));
+        }

109-113: Improve error handling in publish_updates

Consider implementing a retry mechanism or graceful shutdown for repeated errors.

         while let Some(balance) = balance_receiver.recv().await {
+            let mut consecutive_errors = 0;
             if let Err(e) = Self::process_balance_update(&subs, &balance).await {
                 error!(target = LOG_TARGET, error = %e, "Processing balance update.");
+                consecutive_errors += 1;
+                if consecutive_errors > 3 {
+                    error!(target = LOG_TARGET, "Too many consecutive errors, shutting down.");
+                    break;
+                }
+            } else {
+                consecutive_errors = 0;
             }
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e984885 and e008740.

📒 Files selected for processing (3)
  • crates/torii/grpc/src/server/mod.rs (3 hunks)
  • crates/torii/grpc/src/server/subscriptions/mod.rs (1 hunks)
  • crates/torii/grpc/src/server/subscriptions/token.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/torii/grpc/src/server/subscriptions/mod.rs
  • crates/torii/grpc/src/server/mod.rs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (1)
crates/torii/grpc/src/server/subscriptions/token.rs (1)

25-32: LGTM! Well-structured subscriber implementation

The TokenSubscriber struct is well-documented and uses appropriate data structures for efficient contract address lookups.

crates/torii/grpc/src/server/subscriptions/token.rs Outdated Show resolved Hide resolved
@Larkooo Larkooo changed the title feat(torii): subscribe to token updates (metadata etc.) feat(torii-grpc): subscribe to token updates (metadata etc.) Feb 5, 2025
Copy link

codecov bot commented Feb 5, 2025

Codecov Report

Attention: Patch coverage is 20.17544% with 91 lines in your changes missing coverage. Please review.

Project coverage is 57.06%. Comparing base (99d2e60) to head (1c0bcc5).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
...rates/torii/grpc/src/server/subscriptions/token.rs 20.87% 72 Missing ⚠️
crates/torii/grpc/src/server/mod.rs 17.39% 19 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2990      +/-   ##
==========================================
- Coverage   57.14%   57.06%   -0.08%     
==========================================
  Files         429      430       +1     
  Lines       56834    56948     +114     
==========================================
+ Hits        32477    32498      +21     
- Misses      24357    24450      +93     

☔ 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

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

800-805: Consider adding error handling for empty contract addresses.

The subscribe_tokens implementation is clean, but it might benefit from validating the input.

Consider adding validation:

 async fn subscribe_tokens(
     &self,
     contract_addresses: Vec<Felt>,
 ) -> Result<Receiver<Result<SubscribeTokensResponse, tonic::Status>>, Error> {
+    if contract_addresses.is_empty() {
+        return Err(Error::from(QueryError::MissingParam("contract_addresses".into())));
+    }
     self.token_manager.add_subscriber(contract_addresses).await
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2717fcd and 1c0bcc5.

📒 Files selected for processing (3)
  • crates/torii/grpc/proto/types.proto (1 hunks)
  • crates/torii/grpc/proto/world.proto (2 hunks)
  • crates/torii/grpc/src/server/mod.rs (11 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/torii/grpc/proto/world.proto
  • crates/torii/grpc/proto/types.proto
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: clippy
  • GitHub Check: ensure-wasm
  • GitHub Check: docs
🔇 Additional comments (3)
crates/torii/grpc/src/server/mod.rs (3)

37-37: LGTM! Clean integration of TokenManager.

The import and struct field additions are well-organized and follow the existing pattern.

Also applies to: 132-132


149-149: LGTM! Proper initialization and service setup.

The TokenManager is correctly initialized and its service is spawned following the same pattern as other managers.

Also applies to: 172-172, 184-184


1298-1299: LGTM! Well-structured gRPC implementation.

The type alias and trait implementation follow the established patterns in the codebase. The error handling in the gRPC implementation properly maps internal errors to gRPC status codes.

Also applies to: 1310-1310, 1358-1373

@Larkooo Larkooo enabled auto-merge (squash) February 6, 2025 19:39
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.

As mentioned to you @Larkooo except the weird hex value returned in some occasion where the hex value contains a 1 like this: 0x0000000000000000000000000000000000000000000000000010000000000069, where 0x69 is expected, works fine!

Let's investigate in subsequent work done on tokens. 👍

@Larkooo Larkooo merged commit d9227db into dojoengine:main Feb 10, 2025
13 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