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-runner): allow configuring chain id #2554

Merged
merged 4 commits into from
Oct 18, 2024
Merged

Conversation

kariy
Copy link
Member

@kariy kariy commented Oct 18, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new configuration option, chain_id, for enhanced customization in the Katana runner.
    • Added support for the chain_id in the configuration parsing logic.
    • Added a new structure for parsing JSON objects containing chain identifiers.
    • Enhanced logging to include the chain ID during node startup.
  • Bug Fixes

    • Corrected the syntax for handling log_path in configuration generation.
  • Tests

    • Implemented a new asynchronous test to verify the accuracy of the chain_id in the provider.
    • Updated existing tests to reflect changes in chain ID handling.

Copy link

coderabbitai bot commented Oct 18, 2024

Walkthrough

Ohayo, sensei! This pull request introduces a new optional field chain_id to multiple structs and functions within the Katana runner codebase. The Configuration struct now includes chain_id, and a corresponding method set_chain_id has been added. The RunnerArg enum has been updated to recognize this new option. The parse_knobs function has been modified to include chain_id in the generated configuration. Additionally, the KatanaRunnerConfig struct has been updated to handle chain_id, and new tests have been added to verify its functionality.

Changes

File Path Change Summary
crates/katana/runner/macro/src/config.rs - Added field pub chain_id: Option<syn::Expr> to Configuration struct.
- Introduced method fn set_chain_id(&mut self, chain_id: syn::Expr, span: proc_macro2::Span) -> Result<(), syn::Error>.
- Added variant ChainId to RunnerArg enum.
- Updated from_str to recognize "chain_id".
- Modified build_config to handle ChainId.
crates/katana/runner/macro/src/entry.rs - Updated pub fn parse_knobs(input: ItemFn, is_test: bool, config: Configuration) -> TokenStream to include chain_id in the generated cfg TokenStream.
crates/katana/runner/src/lib.rs - Added field pub chain_id: Option<Felt> to KatanaRunnerConfig.
- Updated Default implementation to initialize chain_id to None.
- Modified setup_and_start to check and include chain_id in the builder.
crates/katana/runner/tests/runner.rs - Added async test function async fn custom_chain_id(runner: &RunnerCtx).
- Updated async fn with_async(ctx: &RunnerCtx) -> Result<(), Box<dyn std::error::Error>> to assert chain ID.
crates/katana/node-bindings/src/json.rs - Introduced new struct pub struct ChainId with field pub chain: String for JSON deserialization.
crates/katana/node-bindings/src/lib.rs - Added constant const CHAIN_ID_LOG_SUBSTR: &str for log identification.
- Introduced error variant MissingChainId in Error enum.
- Added function fn parse_chain_id_log(log: &str) -> Result<Felt, Error> for log parsing.
crates/katana/node/src/lib.rs - Updated pub async fn launch(self) -> Result<LaunchedNode> to log chain ID.
- Updated pub async fn build(mut config: Config) -> Result<Node> (no logic changes).
- Updated pub async fn spawn<EF: ExecutorFactory>(...) (no logic changes).
crates/katana/primitives/Cargo.toml - Removed dependency strum_macros.workspace = true from [dependencies].
crates/katana/primitives/src/chain.rs - Added fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result for NamedChainId Display implementation.

Possibly related PRs

Suggested reviewers

  • glihm

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai 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)
crates/katana/runner/tests/runner.rs (1)

27-28: Ohayo, sensei! Great improvement to the with_async test!

The changes to this function enhance the test coverage by verifying the default chain ID. It's a good practice to assert the expected values rather than discarding them.

One small suggestion for consistency:

Consider moving the short_string!("KATANA") to a constant at the top of the file, similar to how "SN_SEPOLIA" is used in the custom_chain_id test. This would make it easier to update if needed and maintain consistency across tests.

const DEFAULT_CHAIN_ID: Felt = short_string!("KATANA");

Then you can use it in the assertion:

assert_eq!(id, DEFAULT_CHAIN_ID);

What do you think, sensei?

crates/katana/runner/macro/src/entry.rs (1)

80-82: Ohayo, sensei! Excellent addition of the chain_id configuration.

The new chain_id handling is well-implemented and follows the existing pattern for other configuration options. This change successfully fulfills the PR objective of allowing chain_id configuration.

For consistency with other configuration options, consider adding a newline after the closing brace of this block. Here's a suggested change:

 if let Some(value) = config.chain_id {
     cfg = quote_spanned! (last_stmt_start_span=> #cfg chain_id: Some(#value), );
 }
+

This minor adjustment will maintain the consistent spacing pattern observed throughout the function.

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

70-71: Ohayo, sensei! Nice addition of the chain_id field!

The new chain_id field looks good and provides flexibility for configuration. Great job using Option<Felt> to allow for cases where a chain ID might not be specified.

Consider adding a brief comment explaining the purpose and potential values of the chain_id field for better documentation. For example:

/// The chain id to use. If None, the default chain id will be used.
pub chain_id: Option<Felt>,

129-131: Ohayo once more, sensei! The chain_id setup looks great!

The conditional block to set the chain_id is well-placed and correctly implemented. It seamlessly integrates with the existing builder pattern.

For consistency with other similar blocks in this method, consider using the if let pattern:

if let Some(id) = config.chain_id {
    builder = builder.chain_id(id);
}

This aligns with the style used for block_time, messaging, and db_dir configurations.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bdb8fb5 and 4e52a45.

📒 Files selected for processing (4)
  • crates/katana/runner/macro/src/config.rs (6 hunks)
  • crates/katana/runner/macro/src/entry.rs (1 hunks)
  • crates/katana/runner/src/lib.rs (3 hunks)
  • crates/katana/runner/tests/runner.rs (2 hunks)
🧰 Additional context used
🔇 Additional comments (11)
crates/katana/runner/tests/runner.rs (2)

2-2: Ohayo, sensei! LGTM on the new import!

The short_string macro import is necessary for the new test function. Good job on keeping the imports clean and relevant.


10-16: Ohayo, sensei! Excellent addition of the custom chain ID test!

This new test function custom_chain_id is well-implemented and serves the purpose of verifying the custom chain ID functionality. Here's what looks great:

  1. The use of #[tokio::test(flavor = "multi_thread")] for asynchronous testing.
  2. The #[katana_runner::test(chain_id = short_string!("SN_SEPOLIA"))] attribute to set a custom chain ID.
  3. Proper assertion to check if the provider's chain ID matches the expected value.

This test enhances the coverage and aligns perfectly with the PR objective of allowing configurable chain IDs.

crates/katana/runner/macro/src/entry.rs (1)

77-78: Ohayo, sensei! Nice cleanup of the log_path configuration.

The removal of the trailing comma after the log_path configuration is a good stylistic improvement. It aligns with Rust's convention for the last item in a struct or enum definition. This change doesn't affect functionality but enhances code readability.

crates/katana/runner/macro/src/config.rs (7)

21-21: Ohayo, sensei! The chain_id field looks sharp!

The addition of the chain_id field to the Configuration struct is well-implemented. Using Option<syn::Expr> provides flexibility and aligns with the existing pattern in the struct.


36-36: Ohayo again, sensei! The chain_id initialization is on point!

The initialization of chain_id to None in the new method is consistent with other optional fields and ensures proper default behavior.


111-122: Ohayo once more, sensei! The set_chain_id method is a true katana strike!

The implementation of set_chain_id is well-crafted:

  • It follows the established pattern of other setter methods.
  • It properly handles multiple set attempts with a clear error message.
  • The update logic is concise and effective.

Great job maintaining consistency and robustness!


131-131: Ohayo, sensei! The ChainId variant adds a new move to our kata!

The addition of the ChainId variant to the RunnerArg enum is a necessary and well-placed change to support the new chain_id configuration option.


144-147: Ohayo, sensei! The from_str implementation now recognizes our new chain_id technique!

The updates to the from_str implementation for RunnerArg are well-executed:

  • The new match arm for "chain_id" is correctly added.
  • The error message is properly updated to include the new option.

These changes ensure that the chain_id option is fully integrated into the parsing logic.


192-194: Ohayo, sensei! The build_config function now masters the chain_id technique!

The addition of the RunnerArg::ChainId match arm in the build_config function is well-implemented:

  • It correctly calls the set_chain_id method when the ChainId argument is encountered.
  • The implementation maintains consistency with the handling of other configuration options.

This change ensures that the chain_id option is properly processed during configuration building.


Line range hint 1-205: Ohayo, sensei! Let's wrap up this kata with a final bow!

The implementation of the chain_id configuration option is excellently done. All necessary components have been added or updated consistently:

  • The Configuration struct
  • The RunnerArg enum
  • The from_str implementation
  • The build_config function

The changes are well-integrated with the existing code, maintaining the established patterns and style. Great job on this feature addition!

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

87-87: Ohayo again, sensei! The default implementation looks spot on!

The addition of chain_id: None to the Default implementation is perfect. It maintains backwards compatibility and follows the principle of least surprise. Well done!

Copy link

codecov bot commented Oct 18, 2024

Codecov Report

Attention: Patch coverage is 95.58824% with 3 lines in your changes missing coverage. Please review.

Project coverage is 69.59%. Comparing base (bdb8fb5) to head (2fac7c8).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
crates/katana/runner/macro/src/config.rs 87.50% 2 Missing ⚠️
crates/katana/runner/macro/src/entry.rs 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2554      +/-   ##
==========================================
+ Coverage   69.55%   69.59%   +0.03%     
==========================================
  Files         388      388              
  Lines       49964    50018      +54     
==========================================
+ Hits        34752    34809      +57     
+ Misses      15212    15209       -3     

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

🧹 Outside diff range and nitpick comments (4)
crates/katana/node-bindings/src/json.rs (1)

73-80: Ohayo, sensei! The new ChainId struct looks sharp!

The addition of the ChainId struct is well-implemented and consistent with the existing code style. It's properly documented and derives the necessary traits for JSON deserialization and debugging.

One small suggestion to consider:

You might want to add a Clone derive to the struct for easier copying if needed in the future. Here's how you could modify it:

-#[derive(Deserialize, Debug)]
+#[derive(Deserialize, Debug, Clone)]
 pub struct ChainId {
     pub chain: String,
 }

This change would make the struct more flexible for future use cases without affecting its current functionality.

crates/katana/primitives/src/chain.rs (1)

47-51: Ohayo, sensei! LGTM: Added Display trait implementation.

The new Display trait implementation for NamedChainId looks great! It provides a consistent way to display NamedChainId instances as strings, which is very useful for logging and debugging.

A small suggestion to make it even more awesome:

Consider using the write! macro instead of f.write_str() for potential future flexibility:

impl std::fmt::Display for NamedChainId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

This change allows for easier formatting if we need to add more complex logic in the future.

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

99-101: Ohayo, sensei! Nice addition of chain ID logging.

The new logging statement improves the observability of the node startup process. It's a good practice to log such important information.

Consider adding the node's version to this log message for even better diagnostics. For example:

info!(chain = %chain, version = env!("CARGO_PKG_VERSION"), "Starting node.");

Line range hint 102-120: Sugoi metrics implementation, sensei!

The addition of the Prometheus metrics server greatly enhances the node's observability. The conditional initialization and inclusion of database metrics (when available) are well thought out.

Consider adding error logging in case the metrics server fails to start. For example:

match prometheus_exporter::serve(
    addr,
    self.prometheus_handle.clone(),
    metrics_process::Collector::default(),
    reports,
).await {
    Ok(_) => info!(%addr, "Metrics endpoint started."),
    Err(e) => error!(%addr, error = %e, "Failed to start metrics endpoint."),
}

This will provide more visibility into potential issues during the metrics server initialization.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4e52a45 and ca2fadb.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • crates/katana/node-bindings/src/json.rs (1 hunks)
  • crates/katana/node-bindings/src/lib.rs (9 hunks)
  • crates/katana/node/src/lib.rs (1 hunks)
  • crates/katana/primitives/Cargo.toml (0 hunks)
  • crates/katana/primitives/src/chain.rs (2 hunks)
💤 Files with no reviewable changes (1)
  • crates/katana/primitives/Cargo.toml
🧰 Additional context used
🔇 Additional comments (7)
crates/katana/node-bindings/src/json.rs (1)

Line range hint 1-80: Excellent work integrating the new ChainId struct, sensei!

The addition of the ChainId struct seamlessly integrates with the existing codebase. It follows the established patterns and conventions used throughout the file, maintaining consistency and readability.

The new struct enhances the JSON parsing capabilities of the module, allowing for the parsing of chain ID information from log messages. This addition appears to be well-thought-out and implemented cleanly.

crates/katana/primitives/src/chain.rs (2)

7-7: Ohayo, sensei! LGTM: Removed derive macro for Display.

The removal of #[derive(Display)] is a good change as it paves the way for a custom Display trait implementation. This allows for more control over how NamedChainId is displayed as a string.


Line range hint 138-143: Ohayo, sensei! Verify compatibility with ChainId.

The changes to NamedChainId look compatible with the existing ChainId implementation. However, it's worth double-checking that the Display implementation for ChainId still works as expected with the new NamedChainId display logic.

Could you please run the following test to ensure everything is working correctly?

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

Line range hint 99-120: Dojo master level changes, sensei!

The additions to the launch method significantly enhance the node's observability. The chain ID logging and conditional Prometheus metrics server initialization are well-implemented and will greatly aid in monitoring and debugging.

A couple of minor suggestions were made to further improve the implementation:

  1. Consider adding the node's version to the initial log message.
  2. Add error logging for potential failures in metrics server initialization.

Overall, these changes are a valuable addition to the codebase. Excellent work!

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

633-648: Function parse_chain_id_log is well-implemented

The parse_chain_id_log function correctly parses the chain ID from log entries, handling both hexadecimal and Cairo short string formats effectively.


675-678: Test validates chain ID with JSON logging

The test starting on line 675 successfully verifies that the chain ID is correctly set and retrieved when JSON logging is enabled.


746-758: Test can_launch_katana_with_custom_chain_id confirms custom chain ID functionality

The added test function correctly ensures that a custom chain ID can be set for the Katana instance and that it matches the chain ID retrieved from the provider.

crates/katana/node-bindings/src/lib.rs Outdated Show resolved Hide resolved
crates/katana/node-bindings/src/lib.rs Show resolved Hide resolved
crates/katana/node-bindings/src/lib.rs Show resolved Hide resolved
crates/katana/node-bindings/src/lib.rs Show resolved Hide resolved
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/node-bindings/src/lib.rs (1)

149-149: Rephrase the doc comment for clarity

The doc comment can be improved for readability. Consider rephrasing it to:

/// The string indicator used to extract the chain ID from logs.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e2f5bd8 and 2fac7c8.

📒 Files selected for processing (1)
  • crates/katana/node-bindings/src/lib.rs (9 hunks)
🧰 Additional context used
🔇 Additional comments (7)
crates/katana/node-bindings/src/lib.rs (7)

18-18: Ohayo, sensei! Import looks good.

The cairo_short_string_to_felt function is correctly imported and will be useful for converting short strings to Felt.


522-522: Parsing logic is correctly implemented

The addition of the parsing condition for JsonLog<json::RpcAddr> appropriately handles JSON logging for RPC addresses.


529-539: Chain ID parsing from JSON logs is well-handled

The logic for extracting the chain ID from JSON logs effectively handles both hexadecimal and Cairo short string formats.


562-564: Properly parsing chain ID from standard logs

The added condition ensures that the chain ID is correctly parsed when JSON logging is disabled.


632-647: parse_chain_id_log function is implemented correctly

The function effectively cleans ANSI escape codes and parses the chain ID, handling both hex and short string formats appropriately.


674-677: Test for chain ID with JSON logging works as expected

The test accurately verifies that a custom chain ID is correctly set and retrieved when JSON logging is enabled.


747-757: Test for custom chain ID is successfully validating functionality

The asynchronous test ensures that setting a custom chain ID works correctly and that it can be retrieved from the provider.

@kariy kariy merged commit 3508fb9 into main Oct 18, 2024
15 checks passed
@kariy kariy deleted the katana/runner-chain-id branch October 18, 2024 13:26
@coderabbitai coderabbitai bot mentioned this pull request Oct 23, 2024
10 tasks
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