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

refactor(torii-indexer): single fetch range but chunk block processing #2899

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Jan 13, 2025

Summary by CodeRabbit

  • Improvements

    • Enhanced functionality for handling multiple contract event ranges concurrently.
    • Streamlined data fetching and processing for improved efficiency.
  • Bug Fixes

    • Refined logic for fetching events to prioritize world events and handle results more effectively.
  • New Features

    • Introduced a new struct to encapsulate contract event ranges.
    • Added methods to determine event block ranges and fetch data more efficiently.

Copy link

coderabbitai bot commented Jan 13, 2025

Walkthrough

Ohayo, sensei! The changes in the engine.rs file introduce several modifications to the Engine struct, particularly enhancing the fetch_data method. A new struct, ContractRange, has been added to encapsulate block ranges for contract events. The fetch_data method's visibility has been changed, and its logic now retrieves contract event ranges using cursors and the latest block number. Additionally, the fetch_range method has been updated to process multiple contract ranges concurrently, while new methods for obtaining contract ranges and the first event block have been introduced.

Changes

File Change Summary
crates/torii/indexer/src/engine.rs - Added struct ContractRange { from: u64, to: u64 }
- Changed visibility of fetch_data method from public to private
- Updated fetch_range method to accept HashMap<Felt, ContractRange> instead of individual parameters
- Added method get_contract_ranges for retrieving contract ranges
- Added method get_first_event_block to determine the first event block for a contract

Sequence Diagram

sequenceDiagram
    participant Indexer as Engine
    participant BlockChain

    Indexer->>BlockChain: fetch_data(cursors)
    BlockChain-->>Indexer: Return latest block number
    Indexer->>Indexer: get_contract_ranges(cursors, latest_block)
    Indexer->>BlockChain: fetch_range(contract_ranges)
    BlockChain-->>Indexer: Return event data
    Indexer->>Indexer: Process event data
Loading

The sequence diagram illustrates the high-level flow of data fetching and processing within the indexer's engine, showcasing the interactions between the Engine and the blockchain.


🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

🧹 Nitpick comments (1)
crates/torii/indexer/src/engine.rs (1)

328-334: Ohayo sensei! Let's simplify the logging.

The log message contains redundant information by repeating the same values twice.

-        info!(target: LOG_TARGET,
-            from = %cursors.head.unwrap_or(self.config.world_block),
-            to = %latest_block.block_number,
-            "Fetching data from {} to {}",
-            cursors.head.unwrap_or(self.config.world_block),
-            latest_block.block_number
-        );
+        info!(target: LOG_TARGET,
+            from = %cursors.head.unwrap_or(self.config.world_block),
+            to = %latest_block.block_number,
+            "Fetching data"
+        );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a5377ac and f2113b1.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/engine.rs (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/indexer/src/engine.rs

[warning] 337-337: Formatting issue: Line needs to be split into multiple lines for better readability


[warning] 344-344: Formatting issue: Line needs to be split into multiple lines for better readability


[warning] 555-555: Formatting issue: Extra whitespace needs to be removed


[warning] 562-562: Formatting issue: Extra whitespace needs to be removed


[warning] 603-603: Formatting issue: Line needs to be split into multiple lines for better readability

🔇 Additional comments (3)
crates/torii/indexer/src/engine.rs (3)

337-353: LGTM! Clean and well-structured fetch logic.

The implementation handles edge cases appropriately and includes helpful debug timing information.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 337-337: Formatting issue: Line needs to be split into multiple lines for better readability


[warning] 344-344: Formatting issue: Line needs to be split into multiple lines for better readability


555-604: Excellent chunked processing implementation, sensei!

The chunked processing with proper block tracking and transaction handling looks solid.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 555-555: Formatting issue: Extra whitespace needs to be removed


[warning] 562-562: Formatting issue: Extra whitespace needs to be removed


[warning] 603-603: Formatting issue: Line needs to be split into multiple lines for better readability


563-563: Consider validating the chunk size.

The chunk size should be validated to ensure it's greater than zero to prevent potential infinite loops.

Add validation in the EngineConfig implementation:

impl EngineConfig {
    pub fn new(blocks_chunk_size: u64) -> Result<Self> {
        if blocks_chunk_size == 0 {
            return Err(anyhow!("blocks_chunk_size must be greater than zero"));
        }
        Ok(Self {
            blocks_chunk_size,
            ..Default::default()
        })
    }
}

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

🧹 Nitpick comments (2)
crates/torii/indexer/src/engine.rs (2)

327-347: Ohayo sensei! Fix formatting issues in fetch_data method.

The logic looks good, but there are some formatting issues to address:

  1. Remove extra whitespace at line 327
  2. Split long lines at 331-332 and 337-338 for better readability
- info!(target: LOG_TARGET, from = %from, to = %latest_block.block_number, "Retrieving block events.");
+ info!(
+     target: LOG_TARGET,
+     from = %from,
+     to = %latest_block.block_number,
+     "Retrieving block events."
+ );

- info!(target: LOG_TARGET, latest_block_number = %latest_block.block_number, "Retrieving pending block.");
+ info!(
+     target: LOG_TARGET,
+     latest_block_number = %latest_block.block_number,
+     "Retrieving pending block."
+ );
🧰 Tools
🪛 GitHub Actions: ci

[warning] 331-332: Line too long, needs to be split across multiple lines for better formatting


[warning] 337-338: Line too long, needs to be split across multiple lines for better formatting


549-598: Fix formatting issues in process_range method.

Please address the following formatting issues:

  1. Remove extra whitespace at lines 549 and 556
  2. Split the long line at 597-598
- current_block = chunk_end + 1;
+ current_block = chunk_end + 1;
🧰 Tools
🪛 GitHub Actions: ci

[warning] 549-549: Extra whitespace line detected


[warning] 556-556: Extra whitespace line detected


[warning] 597-598: Line too long, needs to be split across multiple lines for better formatting

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2113b1 and 5cb5e26.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/engine.rs (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/indexer/src/engine.rs

[warning] 324-324: Extra whitespace line detected


[warning] 331-332: Line too long, needs to be split across multiple lines for better formatting


[warning] 337-338: Line too long, needs to be split across multiple lines for better formatting


[warning] 549-549: Extra whitespace line detected


[warning] 556-556: Extra whitespace line detected


[warning] 597-598: Line too long, needs to be split across multiple lines for better formatting

🔇 Additional comments (2)
crates/torii/indexer/src/engine.rs (2)

549-598: Excellent chunking implementation for block processing!

The refactoring to process transactions in chunks based on block numbers is a great optimization. It provides better control over memory usage and allows for more efficient processing of large block ranges.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 549-549: Extra whitespace line detected


[warning] 556-556: Extra whitespace line detected


[warning] 597-598: Line too long, needs to be split across multiple lines for better formatting


Line range hint 327-600: Ohayo sensei! Overall excellent refactoring work!

The changes demonstrate a thoughtful approach to improving the indexer's performance:

  1. Better control over block processing through chunking
  2. Comprehensive logging for debugging
  3. Well-implemented parallelization
  4. Proper error handling throughout

Keep up the great work! 🚀

🧰 Tools
🪛 GitHub Actions: ci

[warning] 549-549: Extra whitespace line detected


[warning] 556-556: Extra whitespace line detected


[warning] 597-598: Line too long, needs to be split across multiple lines for better formatting

Copy link

codecov bot commented Jan 13, 2025

Codecov Report

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

Project coverage is 55.85%. Comparing base (4371331) to head (01fee71).
Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/indexer/src/engine.rs 0.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2899      +/-   ##
==========================================
+ Coverage   55.82%   55.85%   +0.03%     
==========================================
  Files         449      449              
  Lines       57693    57732      +39     
==========================================
+ Hits        32206    32246      +40     
+ Misses      25487    25486       -1     

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

🧹 Nitpick comments (3)
crates/torii/indexer/src/engine.rs (3)

368-391: Consider parallelizing first event block retrieval.

The method currently processes contracts sequentially. For better performance, consider using futures::stream::iter(self.contracts.iter()).map().buffer_unordered() to parallelize the first event block retrieval.

 async fn get_contract_ranges(
     &self,
     cursors: &Cursors,
     latest_block: u64,
 ) -> Result<HashMap<Felt, ContractRange>> {
     let mut ranges = HashMap::new();
     let base_from = cursors.head.unwrap_or(self.config.world_block);
-
-    for (contract_address, _) in self.contracts.iter() {
+    use futures::stream::{StreamExt, TryStreamExt};
+    let contract_ranges = futures::stream::iter(self.contracts.iter())
+        .map(|(contract_address, _)| async move {
+            let first_event_block =
+                self.get_first_event_block(base_from, latest_block, *contract_address).await?;
+            Ok::<_, anyhow::Error>((*contract_address, first_event_block))
+        })
+        .buffer_unordered(10)
+        .try_collect::<Vec<_>>()
+        .await?;
+
+    for (contract_address, first_event_block) in contract_ranges {
         // First fetch a single chunk to find the first event block
-        let first_event_block =
-            self.get_first_event_block(base_from, latest_block, *contract_address).await?;
-
         if let Some(first_block) = first_event_block {
             let from = if first_block == 0 { first_block } else { first_block + 1 };
             let total_remaining = latest_block - from;
             let blocks_to_process = total_remaining.min(self.config.blocks_chunk_size);
             let to = from + blocks_to_process;

-            ranges.insert(*contract_address, ContractRange { from, to });
+            ranges.insert(contract_address, ContractRange { from, to });
         }
     }

     Ok(ranges)

Line range hint 413-486: Add context to errors for better debugging.

While the concurrent processing is well-implemented, consider adding more context to errors using anyhow::Context. This will help in debugging issues across multiple contract ranges.

 async fn fetch_range(
     &mut self,
     contract_ranges: HashMap<Felt, ContractRange>,
 ) -> Result<FetchRangeResult> {
     let mut fetch_all_events_tasks = VecDeque::new();

     for (contract_address, range) in contract_ranges.iter() {
-        if let Some(contract_type) = self.contracts.get(contract_address) {
+        if let Some(contract_type) = self.contracts.get(contract_address).with_context(|| format!("Contract {:#x} not found", contract_address))? {
             let events_filter = EventFilter {
                 from_block: Some(BlockId::Number(range.from)),
                 to_block: Some(BlockId::Number(range.to)),
                 address: Some(*contract_address),
                 keys: None,
             };

             let token_events_pages =
-                get_all_events(&self.provider, events_filter, self.config.events_chunk_size);
+                get_all_events(&self.provider, events_filter, self.config.events_chunk_size)
+                    .with_context(|| format!("Failed to fetch events for contract {:#x}", contract_address));

Line range hint 574-611: Enhance observability with structured logging.

Consider adding more structured logging to track the progress of range processing, especially for large ranges.

 async fn process_range(&mut self, data: FetchRangeResult) -> Result<()> {
+    debug!(
+        target: LOG_TARGET,
+        total_transactions = data.transactions.len(),
+        "Starting range processing"
+    );
     let mut processed_blocks = HashSet::new();
     let mut cursor_map = HashMap::new();

     for ((block_number, transaction_hash), events) in data.transactions {
-        debug!("Processing transaction hash: {:#x}", transaction_hash);
+        debug!(
+            target: LOG_TARGET,
+            %block_number,
+            %transaction_hash,
+            events_count = events.len(),
+            "Processing transaction"
+        );
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e5f3db7 and 78b4802.

📒 Files selected for processing (1)
  • crates/torii/indexer/src/engine.rs (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: ensure-wasm
  • GitHub Check: build
  • GitHub Check: clippy
  • GitHub Check: docs
🔇 Additional comments (3)
crates/torii/indexer/src/engine.rs (3)

210-214: LGTM! Clean and focused struct definition.

The ContractRange struct is well-designed for its purpose of representing block ranges for contract events.


330-366: Ohayo, sensei! Nice refactor of the fetch_data method!

The changes improve efficiency by introducing chunked processing and better separation of concerns between range and pending block handling.


394-411: Efficient implementation of first event block retrieval!

The method is well-optimized by using a limit of 1 event and properly handling the case when no events are found.

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