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): enable any build (not just wasm) to connect to Slot #2147

Merged
merged 4 commits into from
Aug 14, 2024

Conversation

caillef
Copy link
Contributor

@caillef caillef commented Jul 6, 2024

Description

We couldn't connect to a remote Slot using dojo.c. Only the Unity game built with a web build could connect.
This PR fix this issue. Thanks @steebchen for the help to understand what was wrong.

The issue was that GRPC didn't handled the right uri, we are now using with_origin method to connect to GRPC.

There is also a part of the code retrieving the public certs to handle HTTPS.

Added to documentation?

Once dojo.c uses this commit, we can update the doc to say that any build can connect to Slot, not just wasm.

Checklist

  • I've formatted my code (scripts/prettier.sh, scripts/rust_fmt.sh, scripts/cairo_fmt.sh)
  • I've linted my code (scripts/clippy.sh, scripts/docs.sh)
  • I've commented my code

Summary by CodeRabbit

  • New Features

    • Enabled TLS support by updating the library to version 0.11, enhancing security for communication.
  • Chores

    • Updated dependencies for gRPC libraries to their latest versions, ensuring improved performance and capabilities.
  • Refactor

    • Improved connection handling in the client to support SSL/TLS based on URI, ensuring secure connections and enhancing error reporting capabilities.

Copy link

coderabbitai bot commented Jul 6, 2024

Walkthrough

Ohayo, sensei! The recent changes focus on upgrading the tonic crate to version 0.11, enhancing TLS support with new features. The WorldClient in the torii/grpc module has been refined for better error handling and simplified parameters. Stricter version constraints for various cairo-lang libraries have also been implemented. These adjustments aim to improve security and clarity across the codebase while streamlining client initialization.

Changes

File Summary
Cargo.toml Updated tonic and related dependencies to version 0.11; enforced exact version for cairo-lang-* libraries.
.../torii/grpc/src/client.rs Enhanced WorldClient::new method to simplify parameters and improve error handling related to endpoints.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: Request connection with TLS
    Server->>Client: Send certificate info
    Client->>Server: Establish SSL/TLS connection
    Server->>Client: Confirm connection established
Loading
sequenceDiagram
    participant Relay
    participant Event
    Relay->>Event: Handle ServerEvent::Identify
    Event-->>Relay: Extract peer_id and other fields
    Relay->>Event: Process event with extracted fields
Loading

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bb34d52 and 5dc1ad3.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (1)
  • crates/torii/grpc/src/client.rs (3 hunks)
Additional comments not posted (1)
crates/torii/grpc/src/client.rs (1)

21-23: Ohayo, sensei! Enhanced error handling with Endpoint variant looks solid.

The addition of the Endpoint variant in the Error enum improves clarity and robustness in error reporting for endpoint-related issues. Well done!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0c50c7d and 5a88ff4.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • crates/torii/grpc/Cargo.toml (1 hunks)
  • crates/torii/grpc/src/client.rs (2 hunks)
  • crates/torii/libp2p/src/server/mod.rs (1 hunks)
Files skipped from review due to trivial changes (1)
  • crates/torii/grpc/Cargo.toml
Additional comments not posted (5)
crates/torii/grpc/src/client.rs (2)

2-3: Imports for SSL/TLS connections.

The added imports for handling SSL/TLS connections are necessary and correctly used in the code.

Also applies to: 8-8, 10-10


47-83: Connection handling logic for WorldClient.

The changes to the new function in the WorldClient struct correctly handle different connection scenarios based on the URI, including SSL/TLS configuration.

However, ensure that all function calls to WorldClient::new match the new signature.

Verification successful

The output shows two instances of WorldClient::new usage:

  1. crates/torii/grpc/src/client.rs
  2. crates/torii/client/src/client/mod.rs

We need to inspect the relevant lines in these files to ensure they match the new function signature new(dst: String, _world_address: Felt).


Connection handling logic for WorldClient.

The changes to the new function in the WorldClient struct correctly handle different connection scenarios based on the URI, including SSL/TLS configuration. Additionally, all function calls to WorldClient::new match the new signature.

  • crates/torii/client/src/client/mod.rs: The usage of WorldClient::new matches the new signature.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `WorldClient::new` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type rust $'WorldClient::new'

Length of output: 293


Script:

#!/bin/bash
# Display the relevant lines where `WorldClient::new` is used to verify the function signature.

# Fetching the line from crates/torii/grpc/src/client.rs
sed -n '47,83p' crates/torii/grpc/src/client.rs

# Fetching the line from crates/torii/client/src/client/mod.rs
rg --context 5 'WorldClient::new' crates/torii/client/src/client/mod.rs

Length of output: 1963

Cargo.toml (2)

211-211: Updated tonic dependency.

The tonic dependency version has been correctly updated to include TLS features.


211-211: Added openssl dependency.

The openssl dependency has been correctly added to support SSL/TLS functionality.

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

399-399: Destructuring peer_id in Identify variant.

The peer_id field is correctly destructured along with other fields in the Identify variant of ServerEvent.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5a88ff4 and edcb761.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (1)
  • Cargo.toml (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml

@caillef caillef marked this pull request as draft July 6, 2024 08:45
@glihm glihm changed the title Enable any build (not just wasm) to connect to Slot feat(torii): enable any build (not just wasm) to connect to Slot Jul 6, 2024
@caillef caillef force-pushed the debug-http2 branch 2 times, most recently from e544c63 to 15544e6 Compare July 7, 2024 08:05
@caillef caillef marked this pull request as ready for review July 7, 2024 08:07
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between edcb761 and 15544e6.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (4)
  • Cargo.toml (1 hunks)
  • crates/torii/grpc/Cargo.toml (1 hunks)
  • crates/torii/grpc/src/client.rs (2 hunks)
  • crates/torii/libp2p/src/server/mod.rs (1 hunks)
Files skipped from review as they are similar to previous changes (4)
  • Cargo.toml
  • crates/torii/grpc/Cargo.toml
  • crates/torii/grpc/src/client.rs
  • crates/torii/libp2p/src/server/mod.rs

@caillef caillef marked this pull request as draft July 7, 2024 08:15
@caillef
Copy link
Contributor Author

caillef commented Jul 7, 2024

I need to remove all the unwrap to avoid crashes.
I also have an error when I import the library made with dojo.c in my c++ project, some ssl symbols are missing

@caillef caillef marked this pull request as ready for review July 8, 2024 19:13
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 15544e6 and 93350e5.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (4)
  • Cargo.toml (2 hunks)
  • crates/torii/grpc/Cargo.toml (1 hunks)
  • crates/torii/grpc/src/client.rs (4 hunks)
  • crates/torii/libp2p/src/server/mod.rs (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • Cargo.toml
  • crates/torii/grpc/src/client.rs
  • crates/torii/libp2p/src/server/mod.rs
Additional comments not posted (1)
crates/torii/grpc/Cargo.toml (1)

9-9: Addition of openssl dependency.

The addition of openssl is necessary for handling SSL/TLS connections. Ensure that the version compatibility and security implications are considered.

@caillef
Copy link
Contributor Author

caillef commented Jul 8, 2024

@glihm would like to have your review on this one please. I need to know if importing openssl is ok, and also is openssl import mandatory: I'm not 100% sure fetching the certificates is the right way to do this. Maybe we could use another certs and avoid the openssl import.

Also I didn't changed how it worked with http, so that localhost server still works, but we could also handle the "with_origin" like I did with https so that we can handle http url where torii is not exposed at the root domain (localhost:8080/torii for example)

I am currently trying to use 1.0 with dojo.c but the FieldElement/Felt changes is a lot of work, so I didn't test using dojo.c, I only had a temporary test to run from the dojo repo:

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_client_new() {
        let torii_url = "https://api.cartridge.gg/x/spawn-and-move-cubzh/torii".to_string();
        let rpc_url = "https://api.cartridge.gg/x/spawn-and-move-cubzh/katana".to_string();
        // let torii_url = "http://localhost:8080".to_string();
        // let rpc_url = "http://localhost:5050".to_string();
        let relay_url = "/ip4/127.0.0.1/tcp/9090".to_string();
        let world = FieldElement::from_hex_be("0x7efebb0c2d4cc285d48a97a7174def3be7fdd6b7bd29cca758fa2e17e03ef30").unwrap();
        let models_keys = None; // or Some(Vec<KeysClause>) if you have keys

        let client = Client::new(torii_url, rpc_url, relay_url, world, models_keys).await;

        assert!(client.is_ok(), "Error creating client");
    }
}

The test was not passing with the api.cartridge.gg domain at the beginning and now it works. So I guess it will also work when used with dojo.c.

Cargo.toml Outdated
@@ -162,6 +162,7 @@ log = "0.4.21"
metrics = "0.21.1"
num-traits = { version = "0.2", default-features = false }
once_cell = "1.0"
openssl = "0.10.64"
Copy link
Collaborator

Choose a reason for hiding this comment

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

We don't want to use openssl for the requirement it has on the host, but rustls instead. You can achieve a similar syntax using tokio_rustls. 👍

Cargo.toml Outdated
tonic-build = "0.10.1"
tonic-reflection = "0.10.1"
tonic-web = "0.10.1"
tonic = { version = "0.11", features = [ "tls" ] }
Copy link
Collaborator

Choose a reason for hiding this comment

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

This feature is actually using rustls under the hood.

crates/torii/grpc/src/client.rs Outdated Show resolved Hide resolved
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
})
pub async fn new(dst: String, _world_address: Felt) -> Result<Self, Error> {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
pub async fn new(dst: String, _world_address: Felt) -> Result<Self, Error> {
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {

World address is actually used, we can remove the _ at this occasion. :)

@caillef
Copy link
Contributor Author

caillef commented Jul 23, 2024

@glihm Thanks for the review, I found another way to do it without openssl with a feature of tonis tls-roots. It's working with 0.0.73, but had troubles testing with 1.0.0-alpha.

@glihm
Copy link
Collaborator

glihm commented Jul 25, 2024

@glihm Thanks for the review, I found another way to do it without openssl with a feature of tonis tls-roots. It's working with 0.0.73, but had troubles testing with 1.0.0-alpha.

Nice! Happy to discuss on discord about that if you need support for the alpha integration.

Copy link

codecov bot commented Aug 13, 2024

Codecov Report

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

Project coverage is 69.60%. Comparing base (6878242) to head (5dc1ad3).
Report is 1 commits behind head on main.

Files Patch % Lines
crates/torii/grpc/src/client.rs 0.00% 6 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2147   +/-   ##
=======================================
  Coverage   69.60%   69.60%           
=======================================
  Files         352      352           
  Lines       46034    46034           
=======================================
  Hits        32040    32040           
  Misses      13994    13994           

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

Comment on lines 47 to 53
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
println!("{}", dst.clone());
let channel = endpoint.connect().await.map_err(Error::Transport)?;
Ok(Self {
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),
Copy link

Choose a reason for hiding this comment

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

Ohayo, sensei! Connection handling improvements look solid.

The refactoring of the new function to use a String for dst and the improved error handling are great enhancements. However, consider removing the println! statement used for debugging to keep the code clean.

-  println!("{}", dst.clone());
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
println!("{}", dst.clone());
let channel = endpoint.connect().await.map_err(Error::Transport)?;
Ok(Self {
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
let channel = endpoint.connect().await.map_err(Error::Transport)?;
Ok(Self {
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),

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

Comment on lines 47 to 53
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
println!("{}", dst.clone());
let channel = endpoint.connect().await.map_err(Error::Transport)?;
println!("{}", "channel done");
Ok(Self {
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),
Copy link

Choose a reason for hiding this comment

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

Refactor suggestion: Extract TLS initialization into a separate function.

Consider refactoring the TLS initialization logic into a separate function. This will improve code clarity and facilitate reuse, especially if similar logic is needed elsewhere.

// Example of a possible refactor
async fn initialize_tls_channel(dst: String) -> Result<tonic::transport::Channel, Error> {
    let endpoint = Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
    endpoint.connect().await.map_err(Error::Transport)
}

// Usage in `new` function
let channel = initialize_tls_channel(dst.clone()).await?;

Remove debugging println! statements.

The println! statements used for debugging should be removed to keep the code clean for production.

-  println!("{}", dst.clone());
-  println!("{}", "channel done");
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
println!("{}", dst.clone());
let channel = endpoint.connect().await.map_err(Error::Transport)?;
println!("{}", "channel done");
Ok(Self {
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
let channel = endpoint.connect().await.map_err(Error::Transport)?;
Ok(Self {
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),

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

Comment on lines +49 to +55
pub async fn new(dst: String, world_address: Felt) -> Result<Self, Error> {
let endpoint =
Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
let channel = endpoint.connect().await.map_err(Error::Transport)?;
Ok(Self {
_world_address,
inner: world_client::WorldClient::connect(dst).await.map_err(Error::Transport)?,
_world_address: world_address,
inner: world_client::WorldClient::with_origin(channel, endpoint.uri().clone()),
Copy link

Choose a reason for hiding this comment

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

Refactor suggestion: Extract TLS initialization into a separate function.

Consider refactoring the TLS initialization logic into a separate function. This will improve code clarity and facilitate reuse, especially if similar logic is needed elsewhere.

// Example of a possible refactor
async fn initialize_tls_channel(dst: String) -> Result<tonic::transport::Channel, Error> {
    let endpoint = Endpoint::from_shared(dst.clone()).map_err(|e| Error::Endpoint(e.to_string()))?;
    endpoint.connect().await.map_err(Error::Transport)
}

// Usage in `new` function
let channel = initialize_tls_channel(dst.clone()).await?;

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.

Thank you @caillef for this contribution.

For the record, we needed to actually pin the version of cairo-* package because some recent changes are breaking change but don't respect the semver.

@glihm glihm merged commit 5b3ae8a into dojoengine:main Aug 14, 2024
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants