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): update cli to match katana's #2672

Merged
merged 1 commit into from
Nov 10, 2024
Merged

Conversation

kariy
Copy link
Member

@kariy kariy commented Nov 10, 2024

ref #2663

standardize cli args across katana and torii

Summary by CodeRabbit

  • New Features
    • Introduced structured options for server and metrics configurations, enhancing command-line argument organization.
  • Improvements
    • Streamlined server address and metrics handling for better clarity and maintainability.
    • Updated logging to reflect the new address format.

@kariy kariy requested review from Larkooo, glihm and steebchen November 10, 2024 15:37
Copy link

coderabbitai bot commented Nov 10, 2024

Walkthrough

Ohayo, sensei! This pull request introduces modifications to the main.rs file of the Torii binary. It adds ServerOptions and MetricsOptions structs for better organization of server and metrics configurations. The Args struct is updated to incorporate these new options, replacing direct fields for server address and allowed origins. The main function's logic is adjusted to align with these changes, enhancing clarity and maintainability in handling command-line arguments.

Changes

File Change Summary
bin/torii/src/main.rs - Added struct MetricsOptions and struct ServerOptions.
- Updated Args struct to include server: ServerOptions and metrics: MetricsOptions.
- Removed addr field; replaced with http_addr and http_port in ServerOptions.
- Modified allowed origins handling to use http_cors_origins from ServerOptions.
- Streamlined metrics configuration with metrics_addr and metrics_port in MetricsOptions.
- Added constants for default metrics and HTTP options.
- Adjusted main function logic and logging statements to reflect new structure.

Possibly related PRs


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

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

153-174: Clean metrics configuration structure, sensei!

The MetricsOptions struct is well-organized with proper field dependencies. However, there's a minor documentation inconsistency.

Consider updating this comment to reflect the current behavior:

-    /// For now, metrics will still be collected even if this flag is not set. This only
-    /// controls whether the metrics server is started or not.
+    /// Controls whether the metrics server is started and metrics are exposed via HTTP endpoint.

179-196: Consider adding CORS origin validation, sensei!

The ServerOptions struct looks good, but the CORS origins could benefit from validation to ensure they are valid URLs or patterns.

Consider adding a custom parser for http_cors_origins:

fn parse_cors_origin(s: &str) -> Result<String, String> {
    // Allow * for all origins
    if s == "*" {
        return Ok(s.to_string());
    }
    
    // Validate URL-like patterns
    if !(s.starts_with("http://") || s.starts_with("https://")) {
        return Err(format!("Invalid CORS origin: {}. Must start with http:// or https://", s));
    }
    Ok(s.to_string())
}

321-328: Consider enhancing error handling for server initialization, sensei!

While the server and metrics initialization logic is correct, we could improve error handling and logging.

Consider this approach for metrics initialization:

 if args.metrics.metrics {
     let addr = SocketAddr::new(args.metrics.metrics_addr, args.metrics.metrics_port);
-    info!(target: LOG_TARGET, %addr, "Starting metrics endpoint.");
     let prometheus_handle = PrometheusRecorder::install("torii")?;
     let server = dojo_metrics::Server::new(prometheus_handle).with_process_metrics();
-    tokio::spawn(server.start(addr));
+    info!(target: LOG_TARGET, %addr, "Starting metrics endpoint...");
+    tokio::spawn(async move {
+        if let Err(e) = server.start(addr).await {
+            error!(target: LOG_TARGET, error = %e, "Failed to start metrics server");
+        }
+    });
+    info!(target: LOG_TARGET, %addr, "Metrics endpoint started successfully.");
 }

Also applies to: 355-360


340-345: Consider using Url type for safer explorer URL construction, sensei!

The current string manipulation approach for constructing the explorer URL could be made more robust.

Consider using the Url type for safer URL manipulation:

let mut base_url = Url::parse("https://worlds.dev/torii").expect("Static URL is valid");
let gql_url = format!("http://{}/graphql", addr.to_string().replace("0.0.0.0", "localhost"));
base_url.query_pairs_mut().append_pair("url", &gql_url);
let explorer_url = base_url.to_string();
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 69e4393 and 85619e6.

📒 Files selected for processing (1)
  • bin/torii/src/main.rs (8 hunks)
🔇 Additional comments (2)
bin/torii/src/main.rs (2)

148-151: Ohayo sensei! Nice work on the default configuration constants!

The default values are well-chosen for local development:

  • HTTP server defaults to localhost:8080
  • Metrics server defaults to localhost:9200

Also applies to: 176-177


64-65: Clean integration of the new options structs, sensei!

The use of #[command(flatten)] for both server and metrics options provides a well-organized CLI structure while maintaining a clean Args definition.

Also applies to: 98-99

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.

That's great, thank you @kariy to take the time for this adjustment. 🙏

Copy link

codecov bot commented Nov 10, 2024

Codecov Report

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

Project coverage is 57.42%. Comparing base (69e4393) to head (85619e6).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
bin/torii/src/main.rs 0.00% 25 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2672      +/-   ##
==========================================
- Coverage   57.43%   57.42%   -0.02%     
==========================================
  Files         403      403              
  Lines       50818    50833      +15     
==========================================
  Hits        29189    29189              
- Misses      21629    21644      +15     

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

@kariy kariy closed this Nov 10, 2024
@kariy kariy reopened this Nov 10, 2024
@kariy
Copy link
Member Author

kariy commented Nov 10, 2024

That's great, thank you @kariy to take the time for this adjustment. 🙏

i assume i don't need to update the config file format manually as it's already handled by clap

@glihm
Copy link
Collaborator

glihm commented Nov 10, 2024

That's great, thank you @kariy to take the time for this adjustment. 🙏

i assume i don't need to update the config file format manually as it's already handled by clap

Exactly.

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.

3 participants