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

fix(torii): ensure correct serde of args in config file #2704

Merged
merged 4 commits into from
Nov 19, 2024

Conversation

glihm
Copy link
Collaborator

@glihm glihm commented Nov 19, 2024

Description

This PR ensures that the serialized contracts in a config files are actually compliant with the expected format.

Also, the version of Torii is now removed from the ToriiArgs to be used at the binary level. This helps re-using the torii/cli crates without having version conflicting with the binary importing the crate.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new command-line interface (CLI) for the Torii application, enhancing command parsing and structure.
    • Added support for generating command-line completions.
  • Improvements

    • Enhanced serialization of contract data within the IndexingOptions struct for better handling during serialization processes.
    • Implemented string formatting for Contract instances, improving usability.
    • Added default implementations for several configuration option structs, simplifying instantiation.
  • Bug Fixes

    • Removed the version attribute from command attributes in ToriiArgs to streamline command-line interactions.

Copy link

coderabbitai bot commented Nov 19, 2024

Walkthrough

Ohayo, sensei! This pull request introduces several enhancements to the Torii project, primarily focusing on the command-line interface (CLI) and dependency management. A new dependency, clap_complete, is added to facilitate command-line completions. The CLI is restructured with the introduction of a Cli struct for better argument parsing. Modifications to existing structures, such as ToriiArgs and IndexingOptions, enhance serialization and streamline command handling while maintaining existing functionalities.

Changes

File Change Summary
bin/torii/Cargo.toml Added dependency: clap_complete.workspace = true.
bin/torii/src/cli.rs Added struct: pub struct Cli; added field: pub args: ToriiArgs in Cli.
bin/torii/src/main.rs Replaced ToriiArgs with Cli for argument parsing; updated method signature for parsing args.
crates/torii/cli/src/args.rs Modified ToriiArgs struct: removed #[command(version)] attribute.
crates/torii/cli/src/options.rs Added serialize_contracts method for contracts field in IndexingOptions.
crates/torii/core/src/types.rs Implemented std::fmt::Display for Contract struct for string formatting.
crates/katana/cli/src/options.rs Added Default implementations for several option structs, enhancing usability.

Possibly related PRs

Suggested reviewers

  • steebchen

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

🧹 Outside diff range and nitpick comments (4)
bin/torii/src/cli.rs (1)

9-14: Clean and efficient CLI structure implementation!

The Cli struct implementation demonstrates good practices:

  • Uses clap::Parser derive macro for automatic CLI argument parsing
  • Properly configured command attributes for name, author, version, and description
  • Smart use of #[command(flatten)] to incorporate ToriiArgs fields directly

This aligns with the PR objective of removing version from ToriiArgs while maintaining clean configuration handling.

Consider adding examples in the command's long help text using long_about for better user experience. For instance:

-#[command(name = "torii", author, version, about, long_about = None)]
+#[command(
+    name = "torii",
+    author,
+    version,
+    about,
+    long_about = "Torii server for Dojo engine\n\nExample:\n  torii --world-address 0x123..."
+)]
crates/torii/core/src/types.rs (1)

159-163: Consider adding documentation for the Display implementation

While the implementation is clear, it would be helpful to add documentation explaining the format and its intended use in configuration files.

+/// Formats a Contract as "{type}:{address}" where address is in lowercase hex.
+/// This format is used for serialization in configuration files.
 impl std::fmt::Display for Contract {
bin/torii/src/main.rs (1)

Line range hint 52-248: Consider breaking down the main function, sensei!

The main function handles multiple responsibilities including:

  • Configuration initialization
  • Database setup
  • Server initialization
  • Component orchestration

This could be split into smaller, focused functions for better maintainability.

Consider extracting these into separate functions:

async fn initialize_database(args: &Args) -> Result<SqlitePool> {
    // Database initialization logic
}

async fn initialize_servers(
    pool: Arc<SqlitePool>,
    args: &Args,
    shutdown_tx: Sender<()>
) -> Result<(Engine, Executor, Vec<JoinHandle<()>>)> {
    // Server initialization logic
}

async fn main() -> anyhow::Result<()> {
    let args = Cli::parse().args.with_config_file()?;
    let pool = initialize_database(&args).await?;
    let (engine, executor, handles) = initialize_servers(pool, &args, shutdown_tx).await?;
    // Main orchestration logic
}
crates/torii/cli/src/options.rs (1)

332-343: Ohayo! Implementation looks solid, but let's add tests!

The serialization logic is well-implemented with proper error handling. However, it would be beneficial to add unit tests to verify the serialization format matches the expected output, especially since this is a critical part of the config file handling.

Would you like me to help generate unit tests for the serialize_contracts function? We should test various scenarios including:

  • Empty vector
  • Single contract
  • Multiple contracts
  • Different contract types
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0aa330d and d835965.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • bin/torii/Cargo.toml (1 hunks)
  • bin/torii/src/cli.rs (1 hunks)
  • bin/torii/src/main.rs (2 hunks)
  • crates/torii/cli/src/args.rs (1 hunks)
  • crates/torii/cli/src/options.rs (3 hunks)
  • crates/torii/core/src/types.rs (1 hunks)
🔇 Additional comments (11)
bin/torii/src/cli.rs (1)

1-5: Ohayo! Well-documented module purpose and design decisions, sensei!

The documentation clearly explains the module's purpose and future extensibility considerations. This forward-thinking approach aligns well with the PR's objectives of improving configuration handling.

bin/torii/Cargo.toml (1)

15-15: Ohayo! The new dependency looks good, sensei!

The addition of clap_complete with workspace version is well-placed and follows the project's dependency management pattern.

crates/torii/core/src/types.rs (2)

159-163: Ohayo sensei! The Display implementation looks good!

The implementation provides a clean string representation of Contract instances, formatting them as {type}:{address}. This aligns well with the PR's objective of ensuring correct serialization in config files.


159-163: Verify the string format usage in CLI serialization

Let's ensure this format is consistently used in the CLI serialization code.

✅ Verification successful

Display implementation is correctly used in CLI serialization, sensei!

The Contract's Display implementation (type:address) format is perfectly aligned with:

  • CLI parsing in parse_erc_contract which expects type:address format
  • CLI serialization which uses contract.to_string() to serialize back to the same format
  • CLI deserialization which parses the string using the same format
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of Contract serialization in CLI code
rg -t rust "serialize.*Contract" crates/torii/cli/

Length of output: 296


Script:

#!/bin/bash
# Let's check the implementation of these serialize/deserialize functions
rg -A 10 -B 2 "serialize_contracts|deserialize_contracts" crates/torii/cli/src/options.rs

Length of output: 1261


Script:

#!/bin/bash
# Let's check how the contract is parsed to understand the format
rg -A 10 "parse_erc_contract" crates/torii/cli/src/options.rs

Length of output: 1309

crates/torii/cli/src/args.rs (2)

Line range hint 1-256: Ohayo sensei! Excellent implementation of args handling!

The implementation demonstrates robust handling of CLI arguments and configuration files with:

  • Clear precedence rules (CLI over config file)
  • Proper serialization/deserialization
  • Comprehensive test coverage
  • Clean separation of concerns

This aligns perfectly with the PR objective of ensuring correct serde of args in the config file.


17-17: Ohayo sensei! Version removal looks good!

Removing the version from ToriiArgs is a positive change that aligns with the PR objectives. This modification will allow the torii/cli crates to be reused without version conflicts when imported as a dependency.

Let's verify there are no remaining version dependencies:

✅ Verification successful

Ohayo sensei! The version removal is indeed verified!

The removal of the version attribute from ToriiArgs is safe and aligns with the codebase. The search results confirm that:

  1. The version attribute is correctly removed from the command in crates/torii/cli/src/args.rs
  2. Other binaries in the codebase (sozo, katana, etc.) maintain their own version attributes independently
  3. No other parts of the codebase depend on the version from ToriiArgs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining version-related code
# Test: Search for version-related attributes or methods
rg -i 'version|vers' --type rust

Length of output: 44196

bin/torii/src/main.rs (2)

21-21: Ohayo sensei! Clean modularization of CLI concerns!

The separation of CLI logic into a dedicated module improves code organization and maintainability.

Also applies to: 49-49


53-53: Verify CLI backward compatibility, sensei!

While the new Cli structure improves reusability, let's ensure existing command-line usage patterns are preserved.

✅ Verification successful

Ohayo sensei! CLI backward compatibility is preserved

The change from ToriiArgs::parse() to Cli::parse().args maintains backward compatibility because:

  1. The Cli struct wraps ToriiArgs and delegates to its parsing functionality
  2. The with_config_file() method continues to work as before
  3. Test cases in crates/torii/cli/src/args.rs verify the expected behavior:
    • Command-line arguments take precedence over config file
    • All existing ToriiArgs fields are preserved and parsed correctly
    • Config file parsing remains unchanged
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any changes in command-line argument patterns

# Search for ToriiArgs usage patterns in tests and documentation
rg -t rust "ToriiArgs::" -A 3
rg -t md "torii.*--" -A 3

# Look for any command-line examples in documentation
fd -t f "README" -X cat {} 2>/dev/null | rg "torii.*--" -A 3

Length of output: 843


Script:

#!/bin/bash
# Let's check the implementation and usage of both Cli and ToriiArgs

# Check Cli implementation
ast-grep --pattern 'struct Cli {
  $$$
}'

# Check ToriiArgs implementation and its fields
ast-grep --pattern 'struct ToriiArgs {
  $$$
}'

# Check for any CLI argument parsing tests
rg -t rust "test.*cli|test.*args" -B 2 -A 5

# Check for command-line argument handling
ast-grep --pattern 'fn parse($$$) {
  $$$
}'

# Look for any integration tests that might use CLI
fd -e rs -t f integration_test -X cat {}

Length of output: 4717


Script:

#!/bin/bash
# Let's look more specifically at the CLI argument handling changes

# Check the implementation of with_config_file
ast-grep --pattern 'fn with_config_file($$$) {
  $$$
}'

# Look for CLI argument parsing in main.rs files
fd -t f "main.rs" -X cat {}

# Check for any argument parsing tests
rg -t rust "parse.*args|args.*parse" -B 2 -A 5

# Look for any CLI usage examples in tests
rg -t rust "Cli::parse|ToriiArgs::parse" -B 2 -A 5

Length of output: 48938

crates/torii/cli/src/options.rs (3)

6-6: Ohayo sensei! LGTM on the SerializeSeq import!

The import is correctly placed and necessary for the sequence serialization implementation.


145-147: Symmetrical serde implementation looks good!

The addition of serialize_with complements the existing deserialize_with, ensuring consistent contract handling in both directions.


338-340: Verify Contract's Display implementation

The serialization relies on contract.to_string(). Let's verify the Display implementation matches the expected format for the config file.

✅ Verification successful

Display implementation is correct and consistent

The Contract's Display implementation in crates/torii/core/src/types.rs matches the format expected by parse_erc_contract:

  • Display outputs {type}:{address} format (e.g. "ERC20:0x123")
  • This matches the parsing logic in parse_erc_contract which splits on ':'
  • ContractType's Display implementation correctly outputs the type strings that ContractType::from_str accepts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find and verify Contract's Display implementation
# Expected: Implementation that matches the format used in parse_erc_contract

# Look for Display implementation for Contract
ast-grep --pattern 'impl Display for Contract {
  $$$
  fn fmt($_, $_, $_) {
    $$$
  }
}'

# Look for any tests of the Display implementation
rg -l "impl.*Display.*for.*Contract" | xargs rg "mod.*test.*Display"

Length of output: 164


Script:

#!/bin/bash
# Let's try a different approach to find the Contract type and its Display implementation

# First, find the Contract type definition
ast-grep --pattern 'struct Contract {
  $$$
}'

# Look for Display implementation with a more flexible pattern
ast-grep --pattern 'impl Display for Contract'

# Search for Contract type and Display implementation using ripgrep
rg "struct Contract" -A 10
rg "impl.*Display.*Contract" -A 10

# Look for contract parsing code that might show expected format
rg "parse.*contract" -A 10

Length of output: 53367

@@ -12,6 +12,7 @@ base64.workspace = true
camino.workspace = true
chrono.workspace = true
clap.workspace = true
clap_complete.workspace = true
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Ohayo sensei! The clap_complete dependency in torii seems unused!

The dependency is added to torii's Cargo.toml but there's no actual usage of it in the crate. While clap_complete is properly used in katana and sozo for shell completion generation, it appears to be an unnecessary dependency for torii at this time.

  • Consider removing clap_complete from bin/torii/Cargo.toml if there are no immediate plans to implement shell completions for torii
🔗 Analysis chain

Let's verify the usage of clap_complete, sensei!

We should ensure this new dependency is being utilized in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if clap_complete is being used in the codebase

# Search for clap_complete usage in Rust files
rg -t rust "use.*clap_complete" 

# Search for shell completion generation code
ast-grep --pattern 'clap_complete::generate'

Length of output: 323


Script:

#!/bin/bash
# Let's check if clap_complete is also used in the torii crate
rg -t rust "use.*clap_complete" bin/torii/

# Check for any shell completion generation in torii
ast-grep --pattern 'clap_complete::generate' bin/torii/

# Let's see if there's a completions command or similar functionality
rg -t rust "completions" bin/torii/

Length of output: 136

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 (1)
crates/katana/cli/src/options.rs (1)

Line range hint 58-373: Ohayo sensei! Consider enhancing the documentation

While the implementations are solid, it would be helpful to document the actual default values in the struct field documentation. For example:

/// The metrics will be served at the given port.
/// Default: 8081
#[arg(requires = "metrics")]
#[arg(long = "metrics.port", value_name = "PORT")]
#[arg(default_value_t = DEFAULT_METRICS_PORT)]
#[serde(default = "default_metrics_port")]
pub metrics_port: u16,
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between d835965 and 8f8e643.

📒 Files selected for processing (1)
  • crates/katana/cli/src/options.rs (2 hunks)
🔇 Additional comments (3)
crates/katana/cli/src/options.rs (3)

Line range hint 58-66: Ohayo sensei! LGTM - Default implementation for MetricsOptions looks good!

The implementation correctly uses the predefined constants and aligns with the struct's field documentation.


Line range hint 111-121: Ohayo sensei! The ServerOptions default implementation is well-structured!

The implementation provides secure defaults and correctly uses the predefined constants. Setting http_cors_origins to None by default is a good security practice.


370-373: Ohayo sensei! The default_page_size function is properly implemented!

The function follows the established pattern for default value functions and is correctly feature-gated.

Copy link

codecov bot commented Nov 19, 2024

Codecov Report

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

Project coverage is 56.15%. Comparing base (0aa330d) to head (8f8e643).

Files with missing lines Patch % Lines
crates/torii/cli/src/options.rs 0.00% 9 Missing ⚠️
crates/torii/core/src/types.rs 0.00% 3 Missing ⚠️
bin/torii/src/main.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2704      +/-   ##
==========================================
- Coverage   56.17%   56.15%   -0.02%     
==========================================
  Files         411      411              
  Lines       52947    52958      +11     
==========================================
- Hits        29742    29738       -4     
- Misses      23205    23220      +15     

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


🚨 Try these New Features:

@glihm glihm merged commit 0342464 into main Nov 19, 2024
12 of 14 checks passed
@glihm glihm deleted the fix/torii-args-serde branch November 19, 2024 18:48
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