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(katana): config file #2667

Closed
wants to merge 12 commits into from

Conversation

glihm
Copy link
Collaborator

@glihm glihm commented Nov 9, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced configuration options for the Katana CLI, including new fields for metrics and server settings.
    • Introduced logging format options in the utilities.
  • Bug Fixes

    • Updated CORS configuration handling to improve clarity and functionality.
  • Documentation

    • Improved documentation comments for better understanding of new configurations.
  • Chores

    • Updated dependency management in various Cargo.toml files to streamline workspace configurations.

shramee and others added 12 commits November 8, 2024 11:11
* feat: add sozo dev back

* fix: add debounce logic for better experience
…ine#2660)

* Updated functions to clear up naming with serialized

* Removed some redundecies in the code

* Removed some redundecies in the code

* updated benchmarks

* chore: bump scarb

* fix: rebuild test database

---------

Co-authored-by: glihm <[email protected]>
* Updated functions to clear up naming with serialized

* Removed some redundecies in the code

* Removed some redundecies in the code

* updated benchmarks

* Reduced events geenrated code and updated to match model convention

* feat: add EventValue for ABI

* fix: tests

---------

Co-authored-by: glihm <[email protected]>
…#2646)

* feat(torii): configutation file for all torii cli options

* fix: config

* skip config

* wrap up config

* optional world address

* hisotrical event message sconfig

* remove upgrade

* fmt clippy
…ngine#2665)

* fix: ensure tests and other commands are using the config world block

* refactor: refacto auth including external resources

* fix: add world as valid keyword for grant/revoke
* docs: fix typo

* docs: clarify syscall behavior
…gine#2640)

* fix: ensure proper documentation for the Resource enum

* fix: fmt
…ojoengine#2639)

* refactor: apply code simplification to break with bool value

* tests: regenerate test db

* fix: update policies

* fix: update policies
@glihm glihm changed the base branch from main to katana/cli-breaking November 9, 2024 20:01
Copy link

coderabbitai bot commented Nov 9, 2024

Walkthrough

Ohayo, sensei! This pull request introduces several changes primarily focused on the configuration and functionality of the katana CLI application and its dependencies. Key modifications include updates to the CI workflow for invoking the katana binary, enhancements in dependency management, and significant restructuring of configuration options within various components. Notable changes involve the introduction of new fields in configuration structs, adjustments in method calls, and the addition of serialization capabilities, all aimed at improving usability and flexibility in handling configurations.

Changes

File Path Change Summary
.github/workflows/ci.yml Updated test-hurl job command to include --dev flag and modified existing flags.
Cargo.toml Added new dependency clap_config = "0.1.1".
bin/katana/Cargo.toml Added dependencies: clap_config.workspace = true, serde.workspace = true.
bin/katana/src/cli/mod.rs Updated run method to require a configuration file via with_config_file().
bin/katana/src/cli/node.rs Enhanced NodeArgs struct with new fields and methods for better configuration.
bin/katana/src/utils.rs Introduced new LogFormat enum with implementations for ValueEnum and Display.
bin/torii/Cargo.toml Changed clap_config dependency to workspace specification.
crates/dojo/test-utils/src/sequencer.rs Renamed field allowed_origins to cors_domain in RpcConfig.
crates/katana/core/src/service/messaging/mod.rs Added Serialize trait to MessagingConfig struct.
crates/katana/node-bindings/src/lib.rs Renamed fields in Katana struct for better clarity and restructured server options.
crates/katana/node/src/config/dev.rs Added default gas price constants and a default method for FixedL1GasPriceConfig.
crates/katana/node/src/config/metrics.rs Replaced SocketAddr with IpAddr in MetricsConfig and added new constants.
crates/katana/node/src/config/rpc.rs Removed allowed_origins and added cors_domain in RpcConfig.
crates/katana/node/src/lib.rs Updated metrics server address handling and CORS configuration.
crates/katana/primitives/src/genesis/mod.rs Added Deserialize trait to Genesis and GenesisClass structs.
crates/katana/runner/src/lib.rs Updated method call to use rpc_max_connections instead of max_connections.

Possibly related PRs


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 86c6a6c and 6c379a0.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (16)
  • .github/workflows/ci.yml (1 hunks)
  • Cargo.toml (1 hunks)
  • bin/katana/Cargo.toml (1 hunks)
  • bin/katana/src/cli/mod.rs (1 hunks)
  • bin/katana/src/cli/node.rs (13 hunks)
  • bin/katana/src/utils.rs (2 hunks)
  • bin/torii/Cargo.toml (1 hunks)
  • crates/dojo/test-utils/src/sequencer.rs (1 hunks)
  • crates/katana/core/src/service/messaging/mod.rs (2 hunks)
  • crates/katana/node-bindings/src/lib.rs (6 hunks)
  • crates/katana/node/src/config/dev.rs (2 hunks)
  • crates/katana/node/src/config/metrics.rs (1 hunks)
  • crates/katana/node/src/config/rpc.rs (2 hunks)
  • crates/katana/node/src/lib.rs (3 hunks)
  • crates/katana/primitives/src/genesis/mod.rs (3 hunks)
  • crates/katana/runner/src/lib.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Cargo.toml
🔇 Additional comments (17)
crates/katana/node/src/config/metrics.rs (1)

1-6: Ohayo! Clean and well-documented constants, sensei!

The default configuration using localhost:9100 follows common metrics server conventions, and the type choices provide good flexibility.

bin/katana/Cargo.toml (1)

20-20: Ohayo! Clean dependency additions, sensei! ✨

The addition of clap_config and serde as workspace dependencies aligns perfectly with the config file feature implementation. Both dependencies follow the project's workspace pattern consistently.

Also applies to: 25-25

crates/katana/node/src/config/rpc.rs (1)

27-27: Ohayo! The field renaming improves semantic clarity.

The rename from allowed_origins to cors_domain better reflects the CORS-specific nature of this configuration option.

Let's check for any documentation that needs updating:

bin/katana/src/cli/mod.rs (1)

28-28: Ohayo! Verify config file handling and update documentation.

The addition of with_config_file()? introduces a new requirement for configuration files. While the error handling looks good, we should ensure this change doesn't break existing workflows.

Let's verify the config file handling:

Consider:

  1. Adding documentation about the config file requirement
  2. Ensuring there's a clear fallback mechanism (like --dev) for users without custom configs
  3. Including an example config file in the repository
✅ Verification successful

Based on the shell script results, I can now generate the final response:

Ohayo sensei! The config file handling is well-implemented with proper fallbacks

The verification shows that the config file handling is properly implemented with good defaults and dev mode support:

  • Config file is optional via --config flag
  • --dev flag provides sensible defaults for local development
  • Multiple dev-related options available (--dev.no-fee, --dev.no-account-validation, etc.)
  • Error handling is properly implemented with the ? operator

The only missing piece is documentation about the config file format, but this doesn't block existing workflows since the --dev flag provides a complete fallback mechanism.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for default config handling and documentation

# Test 1: Look for default config or --dev related code
rg -A 5 "with_config_file|--dev" 

# Test 2: Check if there's documentation about config files
fd -g "README*" -X cat {} | rg -A 10 "config.*file|configuration"

Length of output: 6318

bin/torii/Cargo.toml (1)

51-51: Ohayo sensei! The workspace dependency addition looks good!

The change to use clap_config as a workspace dependency aligns well with the project's dependency management approach, where other dependencies are also using workspace specifications. This promotes consistent versioning across the workspace.

crates/katana/node/src/config/dev.rs (2)

1-4: Ohayo! Clean and focused imports, sensei!

The imports are well-organized and bring in specific gas price constants needed for the default configuration.


Line range hint 8-41: Verify documentation coverage for gas price configuration behavior

While the individual fields are well-documented, we should ensure there's clear documentation about the gas price configuration behavior, particularly:

  • The implications of setting fixed_gas_prices to None vs Some
  • Where the gas prices are sourced from when fixed_gas_prices is None
✅ Verification successful

Gas price configuration behavior is well documented, sensei!

The codebase shows clear implementation and documentation of gas price behavior:

  • When fixed_gas_prices is None (default), the node uses a default gas oracle that returns hardcoded values:

    • ETH L1 gas price: 20 Gwei (20 * 10^9 Wei)
    • STRK L1 gas price: 20 * 10^9 FRI
    • ETH L1 data gas price: 1 * 10^6 Wei
    • STRK L1 data gas price: 1 * 10^6 FRI
  • When fixed_gas_prices is Some, the provided values override the defaults and are used for calculating transaction fees

The implementation in katana/core/src/backend/gas_oracle.rs clearly indicates this is a temporary solution with a TODO to implement proper L1 gas price sampling in the future.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for documentation about gas price configuration behavior
echo "Searching for gas price configuration documentation..."
rg -l "gas.?price" --type md

# Look for related test cases
echo "Searching for related test cases..."
rg -l "fixed_gas_prices" --type rust | grep test

Length of output: 319


Script:

#!/bin/bash
# Let's check the content of the test file to understand the behavior
echo "Checking test file content..."
rg -A 10 "fixed_gas_prices" crates/dojo/test-utils/src/sequencer.rs

# Let's also search for gas price related code in the implementation
echo "Searching for gas price implementation..."
ast-grep --pattern 'impl $_ {
  $$$
  gas_price$$$
  $$$
}'

# Look for any comments or documentation about gas prices in rust files
echo "Searching for gas price documentation in code..."
rg -B 2 -A 2 "gas.?price" --type rust

Length of output: 74707

bin/katana/src/utils.rs (2)

1-1: Ohayo! The imports look well-organized, sensei!

The new imports are properly organized and provide the necessary traits for enum serialization, CLI integration, and display formatting.

Also applies to: 5-6, 10-10


41-68: Verify the LogFormat integration with the configuration system.

Let's ensure this new enum is properly integrated with the configuration system and CLI arguments.

✅ Verification successful

Let me explain my approach:

  1. First, I'm doing a broader search for LogFormat with context
  2. Looking for configuration and CLI-related files
  3. Specifically searching for clap (CLI argument parsing) usage with LogFormat

This should give us a better picture of how LogFormat is integrated into the system.


LogFormat is properly integrated with the system

The verification shows that LogFormat is well-integrated:

  • It's used in bin/katana/src/cli/node.rs as part of the LoggingOptions struct
  • Properly implemented in CLI arguments with default value
  • Correctly used in the logging system setup with both JSON and Full format handling
  • Integration points found:
    • CLI argument definition: #[arg(default_value_t = LogFormat::Full)]
    • Format selection in subscriber setup: match self.logging.log_format
    • Runtime format checking: if args.logging.log_format == LogFormat::Json
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check how LogFormat is used in the configuration and CLI system

# Look for LogFormat usage in configuration structs
echo "Checking LogFormat usage in configuration structs..."
rg -p "struct.*LogFormat" 

# Look for CLI argument definitions using LogFormat
echo "Checking CLI argument definitions..."
rg -p "LogFormat.*arg" 

Length of output: 250


Script:

#!/bin/bash
# Let's try a broader search for LogFormat usage
echo "Checking all LogFormat references..."
rg "LogFormat" -A 3 -B 3

# Check for configuration-related files
echo "Checking configuration-related files..."
fd "config|cli" --type f --extension rs

# Check for command-line argument parsing
echo "Checking command-line argument parsing..."
rg "clap::.*LogFormat|LogFormat.*clap" -A 3 -B 3

Length of output: 3526

crates/dojo/test-utils/src/sequencer.rs (1)

121-121: Ohayo! Verify CORS configuration alignment with production code.

The change from allowed_origins to cors_domain looks good, sensei! However, let's ensure everything is properly aligned.

Consider adding a doc comment to explain the expected format and purpose of the cors_domain field, especially if it handles CORS differently than the previous allowed_origins.

✅ Verification successful

Ohayo! The CORS configuration change is consistent across the codebase, sensei!

The change from allowed_origins to cors_domain in the test utilities correctly aligns with the production code:

  • The cors_domain field is consistently used in Katana's RPC configuration (crates/katana/node/src/config/rpc.rs)
  • The field is properly handled in the node implementation (crates/katana/node/src/lib.rs)
  • The test utility implementation matches the default configuration pattern used elsewhere

Note: The remaining allowed_origins occurrences are in different components (Torii) and variable names in the implementation, which is expected and correct.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the CORS configuration field name is consistent across the codebase
# and check for any documentation about the new field.

# Check for all occurrences of the new field name
echo "Checking for cors_domain usage:"
rg "cors_domain" -A 2

# Check if there's any remaining usage of the old field name
echo -e "\nChecking for any remaining allowed_origins:"
rg "allowed_origins"

# Look for documentation about the CORS configuration
echo -e "\nChecking for CORS documentation:"
rg -i "cors|cross.origin" README.md docs/

Length of output: 3762

crates/katana/primitives/src/genesis/mod.rs (3)

12-12: Ohayo! The serde import looks perfect, sensei! ✨

The addition of Deserialize to the imports aligns perfectly with the configuration file support objectives.


Line range hint 26-35: Excellent implementation of serialization controls, sensei! 🛡️

The addition of Deserialize while maintaining the skip_serializing attributes for sensitive fields (casm and sierra) shows excellent attention to security and data handling.


50-50: The Genesis struct changes look solid, but let's verify the safety nets, sensei! 🎯

While adding Deserialize is perfect for config support, let's ensure we have proper validation during deserialization since this struct contains critical blockchain initialization data.

Let's check for validation implementations:

✅ Verification successful

Ohayo sensei! The Genesis deserialization is well-protected! 🛡️

The implementation includes robust validation during deserialization:

  • Validates class hashes and ensures they exist in the classes map
  • Prevents duplicate class names
  • Verifies all class artifacts are properly resolved
  • Handles class path resolution with proper error handling
  • Validates account and contract allocations against available classes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for validation implementations for Genesis deserialization

# Search for any custom deserialization implementations
rg -A 5 "impl.*Deserialize.*for.*Genesis" 

# Search for validation functions that might be called during or after deserialization
rg -A 5 "fn.*validate" crates/katana/primitives/src/genesis/

Length of output: 106


Script:

#!/bin/bash
# Let's try a broader search for validation patterns in the Genesis struct

# Look for the Genesis struct definition and its implementation blocks
rg -A 20 "struct Genesis" crates/katana/primitives/src/genesis/

# Search for any impl blocks for Genesis
rg -A 10 "impl Genesis" crates/katana/primitives/src/genesis/

# Look for any TryFrom implementations that might contain validation
rg -A 10 "impl.*TryFrom.*for.*Genesis" 

# Search for any methods that might be doing validation
rg -A 5 "(verify|check|valid|ensure)" crates/katana/primitives/src/genesis/

Length of output: 44129


Script:

#!/bin/bash
# Let's check for any custom deserialization or validation in the json module
# since that's where the Genesis struct is converted from JSON

# Look for the TryFrom implementation details
rg -A 20 "impl TryFrom<GenesisJson> for Genesis" crates/katana/primitives/src/genesis/

# Check for any error handling or validation in the json module
rg -A 10 "Error|Invalid|Valid" crates/katana/primitives/src/genesis/json.rs

# Look for any tests that might show validation behavior
rg -A 10 "#\[test\]" crates/katana/primitives/src/genesis/

Length of output: 20550

.github/workflows/ci.yml (1)

196-196: Ohayo sensei! The CLI structure change looks good.

The reorganization of flags under the --dev namespace improves the CLI structure while maintaining the same functionality.

Let's verify if there are other katana invocations that need updating:

✅ Verification successful

Ohayo sensei! The katana CLI changes are properly contained

The search results confirm this is the only instance of katana invocation in the workflow files, so no other updates are needed. The CLI structure change is properly isolated to this single usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other katana invocations in workflow files
rg --type yaml 'katana.*--' .github/workflows/

Length of output: 144

crates/katana/runner/src/lib.rs (1)

124-124: Ohayo sensei! The method renaming looks great! ✨

The change from max_connections to rpc_max_connections improves clarity by explicitly indicating these are RPC connections. This aligns well with the broader configuration updates mentioned in the PR objectives.

crates/katana/core/src/service/messaging/mod.rs (1)

54-54: Ohayo! Clean import addition, sensei!

The Serialize trait import is well-placed and properly scoped.

crates/katana/node/src/lib.rs (1)

Line range hint 110-121: Ohayo! Clean refactor of metrics server configuration, sensei!

The change to use socket_addr() method and the addition of clear logging improves the code structure and observability.


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

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (12)
crates/katana/node/src/config/metrics.rs (2)

9-15: Consider enhancing the documentation, sensei!

While the current documentation is clear, it would be helpful to add examples and explain the relationship between these fields and the socket_addr() method.

 /// Node metrics configurations.
+/// 
+/// # Examples
+/// 
+/// ```
+/// use katana::config::MetricsConfig;
+/// use std::net::{IpAddr, Ipv4Addr};
+/// 
+/// let config = MetricsConfig {
+///     addr: IpAddr::V4(Ipv4Addr::LOCALHOST),
+///     port: 9100,
+/// };
+/// 
+/// // Use socket_addr() to get the combined SocketAddr
+/// let addr = config.socket_addr();
+/// ```
 #[derive(Debug, Copy, Clone)]

17-21: Clean implementation, sensei!

The socket_addr method elegantly combines the configuration fields. Consider adding a note about the return value format in the documentation.

-    /// Returns the [`SocketAddr`] for the metrics server.
+    /// Returns the [`SocketAddr`] for the metrics server by combining the configured address and port.
+    ///
+    /// The returned address will be in the format `addr:port`.
     pub fn socket_addr(&self) -> SocketAddr {
crates/katana/node/src/config/rpc.rs (1)

Line range hint 40-45: Default implementation maintains secure defaults, sensei!

The implementation correctly initializes cors_domain to None, which is secure by default as it effectively disables CORS until explicitly configured.

Consider documenting the CORS configuration process in the README or documentation, especially since this is a breaking change that affects API accessibility.

crates/katana/node/src/config/dev.rs (1)

43-53: Implementation looks solid, but could use some documentation love, sensei!

The Default implementation is clean and well-structured. However, it would be helpful to add documentation explaining:

  • Why these specific default values were chosen
  • When developers might want to override these defaults
  • The relationship between ETH and STRK gas prices

Add documentation like this:

 /// Fixed gas prices for development.
 #[derive(Debug, Clone)]
 pub struct FixedL1GasPriceConfig {
     pub gas_price: GasPrices,
     pub data_gas_price: GasPrices,
 }

+/// Default implementation for development gas prices.
+/// Uses predefined constants that provide reasonable defaults for both ETH and STRK
+/// in a development environment.
 impl std::default::Default for FixedL1GasPriceConfig {
bin/katana/src/utils.rs (2)

41-46: The LogFormat enum looks clean and well-structured, sensei!

Consider adding documentation comments to describe the purpose of each variant and when to use them. This would help other developers understand the implications of choosing each format.

Add documentation like this:

 #[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
+/// Defines the output format for logs
 pub enum LogFormat {
+    /// JSON format for machine-readable logs
     Json,
     #[default]
+    /// Full format for human-readable logs
     Full,
 }

48-68: The trait implementations are solid, sensei!

The ValueEnum and Display implementations provide good CLI integration and string conversion. However, consider adding a TryFrom<String> implementation to handle parsing from strings in a more robust way, which could be useful for configuration file parsing.

Here's a suggested implementation:

impl TryFrom<String> for LogFormat {
    type Error = anyhow::Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match s.to_lowercase().as_str() {
            "json" => Ok(Self::Json),
            "full" => Ok(Self::Full),
            _ => Err(anyhow::anyhow!("Invalid log format: {}", s)),
        }
    }
}
.github/workflows/ci.yml (1)

196-196: Consider documenting the new CLI structure.

Since this is part of a config file feature that changes the CLI structure, it would be helpful to document these changes in the README or CLI help text.

Would you like me to help create documentation for the new CLI structure, sensei?

crates/katana/node-bindings/src/lib.rs (5)

257-259: Ohayo, sensei! Consider renaming method for consistency

The port method sets self.http_port, which could be confusing. To maintain consistency with the field name, consider renaming the method to http_port.


275-276: Ohayo, sensei! Rename parameter for clarity

In the l1_provider method, the parameter is named rpc_url, while the field is l1_provider. For consistency and to avoid confusion, consider renaming the parameter to l1_provider or provider_url.


330-331: Ohayo, sensei! Align parameter name with field

In the http_cors_domain method, the parameter is named allowed_origins, but the field is http_cors_domain. For clarity, consider renaming the parameter to http_cors_domain to match the field name.


449-463: Ohayo, sensei! Refactor duplicate --dev flag handling

The logic to prevent setting the --dev flag multiple times is repeated. Consider refactoring this into a helper function or consolidating conditions to improve code readability and maintainability.


504-521: Ohayo, sensei! Simplify metrics flag handling

Similar to the --dev flag handling, the code for managing the --metrics flag has duplicate logic. Refactoring this section could reduce repetition and potential errors.

🛑 Comments failed to post (6)
crates/katana/core/src/service/messaging/mod.rs (1)

97-97: ⚠️ Potential issue

Ohayo! Consider protecting sensitive data, sensei!

While adding Serialize is great for config management, we should be careful about serializing the private_key field. Consider adding #[serde(skip_serializing)] to the private_key field to prevent accidental exposure in logs or exported configs.

Here's a suggested improvement:

 #[derive(Debug, Default, Deserialize, Clone, Serialize)]
 pub struct MessagingConfig {
     pub chain: String,
     pub rpc_url: String,
     pub contract_address: String,
     pub sender_address: String,
+    #[serde(skip_serializing)]
     pub private_key: String,
     pub interval: u64,
     pub from_block: u64,
 }
📝 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.

#[derive(Debug, Default, Deserialize, Clone, Serialize)]
pub struct MessagingConfig {
    pub chain: String,
    pub rpc_url: String,
    pub contract_address: String,
    pub sender_address: String,
    #[serde(skip_serializing)]
    pub private_key: String,
    pub interval: u64,
    pub from_block: u64,
}
crates/katana/node/src/lib.rs (1)

316-328: 💡 Codebase verification

🛠️ Refactor suggestion

Ohayo! The CORS configuration needs attention across multiple services, sensei!

The review comment's concerns are valid and even more critical than initially thought. The same pattern of double URI parsing and unsafe error handling exists in both katana/node and torii/server:

  • crates/katana/node/src/lib.rs
  • crates/torii/server/src/proxy.rs

Both implementations:

  1. Perform redundant URI parsing
  2. Use expect() which can panic in production
  3. Handle CORS configuration at runtime instead of during initialization

Additionally, the configuration is defined in katana/node/src/config/rpc.rs but lacks proper validation at the config parsing stage.

Suggested improvements:

  1. Move CORS validation to a shared utility
  2. Implement it during config parsing
  3. Use proper error handling instead of expect()
🔗 Analysis chain

Ohayo! Let's enhance the CORS configuration robustness, sensei!

The CORS configuration has a few potential improvements:

  1. The URI validation is performed twice unnecessarily
  2. Using expect() could cause panics in production
  3. Origin validation could be moved to the configuration parsing stage

Here's a suggested improvement:

    let cors = config.cors_domain.clone().map(|allowed_origins| match allowed_origins.as_slice() {
        [origin] if origin == "*" => cors.allow_origin(AllowOrigin::mirror_request()),
        origins => cors.allow_origin(
            origins
                .iter()
                .map(|o| {
-                    let _ = o.parse::<Uri>().expect("Invalid URI");
-
-                    o.parse().expect("Invalid origin")
+                    o.parse().unwrap_or_else(|e| {
+                        tracing::error!("Invalid origin URI '{}': {}", o, e);
+                        panic!("Invalid origin URI: {}", e)
+                    })
                })
                .collect::<Vec<_>>(),
        ),
    });

Consider moving the origin validation to the configuration parsing stage to fail fast and provide better error messages. This would also eliminate the need for runtime validation.

Let's check if the CORS configuration is used consistently across the codebase:


Let me analyze the CORS configuration implementation and error handling across the codebase to provide a comprehensive verification of the concerns raised in the review comment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CORS-related configuration
rg -l "cors|allowed_origins"

Length of output: 294


Script:

#!/bin/bash
# Let's check the CORS configuration in the config file
rg -A 10 "cors" crates/katana/node/src/config/rpc.rs

# Also check how CORS is used in other files
rg -A 5 "cors" crates/torii/server/src/proxy.rs crates/torii/grpc/src/server/mod.rs

# Check if there's any error handling for CORS configuration
ast-grep --pattern 'parse::<Uri>()'

Length of output: 3250

bin/katana/src/cli/node.rs (4)

540-546: 🛠️ Refactor suggestion

Remove Debugging Statements Before Production Use

Ohayo, sensei! The dbg! macros at lines 540 and 546 are useful during development but should be removed to clean up the console output and avoid unnecessary performance overhead in production.

- dbg!(&config);
...
- dbg!(&args);
📝 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.

            NodeArgs::from_merged(matches, Some(config))
        } else {
            NodeArgs::from_arg_matches(&matches)?
        };


860-870: ⚠️ Potential issue

Avoid Temporary String Reference in Test

Ohayo, sensei! In the config_from_file_and_cli test, you're converting the PathBuf to a temporary String and then taking a reference to it, which may lead to a dangling reference.

Consider storing the String before taking a reference:

- let config = NodeArgs::parse_from([
-     "katana",
-     "--config",
-     path.to_string_lossy().to_string().as_str(),
-     "--validate-max-steps",
-     "1234",
-     "--dev",
-     "--dev.no-fee",
- ])
+ let config_path = path.to_string_lossy().to_string();
+ let config = NodeArgs::parse_from([
+     "katana",
+     "--config",
+     config_path.as_str(),
+     "--validate-max-steps",
+     "1234",
+     "--dev",
+     "--dev.no-fee",
+ ]);

This ensures the String remains in scope while it's being used.

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

        let config_path = path.to_string_lossy().to_string();
        let config = NodeArgs::parse_from([
            "katana",
            "--config",
            config_path.as_str(),
            "--validate-max-steps",
            "1234",
            "--dev",
            "--dev.no-fee",
        ])
        .config()
        .unwrap();

537-545: ⚠️ Potential issue

Undefined Type NodeArgsConfig

Ohayo, sensei! In the with_config_file method, the type NodeArgsConfig is used but not defined within the provided code. This will result in a compilation error.

To resolve this, you can define NodeArgsConfig or adjust the code to use NodeArgs directly:

- let config: NodeArgsConfig = serde_json::from_str(&std::fs::read_to_string(path)?)?;
+ let config: NodeArgs = serde_json::from_str(&std::fs::read_to_string(path)?)?;

Ensure that NodeArgs implements Deserialize from serde to support this change.

Committable suggestion skipped: line range outside the PR's diff.


385-389: ⚠️ Potential issue

Possible Type Mismatch in Log Filter Variable

Ohayo, sensei! In the init_logging function, there might be a type mismatch with the filter variable. When self.development.dev is true, filter is a &String due to the use of format!, but when false, it's a &str. This could lead to issues when passing filter to EnvFilter::try_new(filter)?, which expects a type that implements AsRef<str>.

To ensure consistent types, consider modifying the code as follows:

- let filter = if self.development.dev {
-     &format!("{DEFAULT_LOG_FILTER},server=debug")
- } else {
-     DEFAULT_LOG_FILTER
- };
+ let filter = if self.development.dev {
+     format!("{DEFAULT_LOG_FILTER},server=debug")
+ } else {
+     DEFAULT_LOG_FILTER.to_string()
+ };

Then, when using filter, pass it as a reference to str:

- let filter = EnvFilter::try_from_default_env().or(EnvFilter::try_new(filter))?;
+ let filter = EnvFilter::try_from_default_env().or(EnvFilter::try_new(&filter))?;

This ensures filter consistently implements AsRef<str>.

Committable suggestion skipped: line range outside the PR's diff.

@glihm glihm closed this Nov 9, 2024
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.

4 participants