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): erc graphql image path & http ratelimiting #3032

Merged
merged 2 commits into from
Feb 14, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 14, 2025

Summary by CodeRabbit

  • New Features

    • Improved token image referencing to ensure images display accurately.
    • Streamlined the image retrieval process to enhance loading performance and format detection.
  • Chores

    • Updated retry configurations and error handling for content fetching, resulting in a more robust and reliable experience.

Copy link

coderabbitai bot commented Feb 14, 2025

Ohayo, sensei! Below is the breakdown of the changes:

Walkthrough

This PR introduces modifications across several modules. In the GraphQL component, the image path for ERC721 tokens is now generated using the token ID (with a colon replaced by a slash) instead of the contract address. In the server module, the image-fetching mechanism has been updated to use a new helper function, streamlining the HTTP fetching workflow and image format detection. Additionally, the SQLite modules now include a unified retry mechanism with exponential backoff, new static clients, and updated constant definitions for retry limits.

Changes

File(s) Change Summary
crates/torii/graphql/.../erc/erc_token.rs Updated image path construction for ERC721 tokens; now using id.replace(":", "/") instead of the contract_address in both the subscriptions method and metadata helper.
crates/torii/server/.../artifacts.rs Removed reqwest::Client import; updated image fetching to use new fetch_content_from_http helper; switched to image::load_from_memory_with_format for improved format detection.
crates/torii/sqlite/.../constants.rs Added new constant REQ_MAX_RETRIES set to 3; removed obsolete IPFS_CLIENT_MAX_RETRY constant.
crates/torii/sqlite/.../utils.rs Added static variables for HTTP_CLIENT and IPFS_CLIENT using once_cell::sync::Lazy; implemented fetch_content_from_http with exponential backoff; updated IPFS fetch retry logic.

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Artifacts as fetch_and_process_image
    participant HTTPFetch as fetch_content_from_http
    participant Server as HTTP Server

    App->>Artifacts: Request image processing
    Artifacts->>HTTPFetch: Fetch image using URL
    HTTPFetch->>Server: Send HTTP request
    alt On Failure
        Server-->>HTTPFetch: Return error
        HTTPFetch->>HTTPFetch: Apply exponential backoff and retry
    else On Success
        Server-->>HTTPFetch: Return image bytes
    end
    HTTPFetch-->>Artifacts: Return bytes / error after max retries
    Artifacts->>Artifacts: Load image with load_from_memory_with_format
    Artifacts-->>App: Return processed image or error
Loading

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

🔭 Outside diff range comments (1)
crates/torii/graphql/src/object/erc/erc_token.rs (1)

492-494: 🛠️ Refactor suggestion

Consider adding error handling for JSON parsing sensei.

The code assumes that metadata is always valid JSON with .expect("metadata is always json"). While this might be true for your current data, it's better to handle potential parsing errors gracefully.

Consider this safer approach:

-                let metadata: serde_json::Value =
-                    serde_json::from_str(&metadata_str).expect("metadata is always json");
+                let metadata: serde_json::Value = match serde_json::from_str(&metadata_str) {
+                    Ok(value) => value,
+                    Err(_) => return (metadata_str, None, None, None, String::new()),
+                };
🧹 Nitpick comments (3)
crates/torii/sqlite/src/utils.rs (2)

119-123: Credentials stored in code
Storing IPFS credentials in versioned source is risky. Consider moving them to environment variables or a secrets manager to strengthen security.


127-154: Ohayo sensei, exponential backoff logic
This retry mechanism is straightforward and robust. Adding a maximum cap to backoff can prevent excessively long waits during persistent failures.

crates/torii/graphql/src/object/erc/erc_token.rs (1)

479-480: Add bounds checking for token ID extraction sensei.

The code assumes the split operation will always yield at least two parts. While the format is enforced by the database schema, it's good practice to add bounds checking.

Consider this safer approach:

-            let token_id = id.split(':').collect::<Vec<&str>>()[1].to_string();
+            let token_id = id.split(':')
+                .nth(1)
+                .ok_or_else(|| sqlx::Error::RowNotFound)?
+                .to_string();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a186fa and 1e23b8b.

📒 Files selected for processing (4)
  • crates/torii/graphql/src/object/erc/erc_token.rs (2 hunks)
  • crates/torii/server/src/artifacts.rs (6 hunks)
  • crates/torii/sqlite/src/constants.rs (1 hunks)
  • crates/torii/sqlite/src/utils.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: clippy
  • GitHub Check: build
  • GitHub Check: docs
🔇 Additional comments (13)
crates/torii/sqlite/src/utils.rs (5)

10-11: Ohayo sensei! Dependency import looks good
Introducing Lazy from once_cell and reqwest::Client is a sound approach to reduce overhead and avoid re-initialization in every request.


18-18: Unified reference to REQ_MAX_RETRIES
The consolidation of constants ensures consistent retry behavior across HTTP and IPFS.


110-117: Ohayo sensei, global static HTTP client
Reusing a single reqwest::Client across the application is typically more efficient than recreating it per request.


125-125: Initial backoff of 100ms
Starting with 100ms may or may not be sufficient, depending on rate-limiting constraints. Please verify this value against your service usage patterns.


156-175: Consistent IPFS retry logic
Synchronizing the IPFS fetching logic with the HTTP retry strategy promotes uniform error handling across different data sources.

crates/torii/sqlite/src/constants.rs (1)

7-7: Ohayo sensei, nicely introduced REQ_MAX_RETRIES
Centralizing retry attempts under a single constant helps maintain consistency and clarity in retry-related configurations.

crates/torii/server/src/artifacts.rs (6)

18-18: Importing fetch utilities
The explicit import of fetch_content_from_http and fetch_content_from_ipfs clarifies responsibilities and avoids code duplication.


61-61: Conditional fetch logic
Falling back to fetch_and_process_image when no local directory exists is a neat approach to on-demand artifact generation.


176-177: HTTP fetch refactor
Forwarding all external requests through fetch_content_from_http centralizes both error handling and retry logic.


187-188: Ohayo sensei, image format detection
Utilizing load_from_memory_with_format is a solid upgrade to accurately determine the image type.


210-211: Improved IPFS image load
Harmonizes the IPFS image-loading flow with the same format detection improvements made for HTTP.


232-232: Consistent data URI handling
Applying image::load_from_memory_with_format ensures data URIs receive the same robust detection and loading approach.

crates/torii/graphql/src/object/erc/erc_token.rs (1)

425-426:

❓ Verification inconclusive

Ohayo sensei! The image path construction looks good but let's verify the token ID format.

The change to use token ID for image path construction is consistent across both locations. However, we should verify that the token ID format assumption (containing a colon) is always valid.

Let's verify the token ID format in the database:

Also applies to: 502-502


🏁 Script executed:

#!/bin/bash
# Description: Check if all token IDs in the database follow the expected format (containing a colon)
# Expected: All token IDs should contain a colon

echo "Checking token ID format in the database..."
sqlite3 torii.db "SELECT id FROM tokens WHERE contract_type='erc721' AND id NOT LIKE '%:%';"

Length of output: 301


Ohayo sensei! The image path changes look consistent across the board, but please manually verify the underlying assumption regarding token ID formats.

  • The update at lines 425-426 (and similarly at line 502) correctly constructs the image path by replacing a colon with a slash.
  • However, because our automated check failed to run (due to the missing sqlite3 command), we need you to manually confirm that all ERC721 token IDs indeed include a colon.
  • If there’s a possibility that any token ID might not follow the expected format, consider adding additional validation or tests to safeguard against potential edge cases.

Copy link

codecov bot commented Feb 14, 2025

Codecov Report

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

Project coverage is 56.27%. Comparing base (ac52ea6) to head (1e23b8b).
Report is 16 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/sqlite/src/utils.rs 0.00% 43 Missing ⚠️
crates/torii/server/src/artifacts.rs 0.00% 6 Missing ⚠️
crates/torii/graphql/src/object/erc/erc_token.rs 0.00% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3032      +/-   ##
==========================================
+ Coverage   56.24%   56.27%   +0.03%     
==========================================
  Files         436      437       +1     
  Lines       58829    58966     +137     
==========================================
+ Hits        33087    33184      +97     
- Misses      25742    25782      +40     

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

@Larkooo Larkooo enabled auto-merge (squash) February 14, 2025 04:55
@Larkooo Larkooo merged commit de7eddd into dojoengine:main Feb 14, 2025
14 of 15 checks passed
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.

2 participants