Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(torii-erc): add avif support #3011

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

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 12, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an enhanced retry mechanism for fetching remote content, utilizing an automatic retry strategy with exponential backoff for improved reliability.
    • Added a new constant REQ_MAX_RETRIES to define maximum retry attempts for requests.
    • Updated the image dependency to include the new avif-native feature for enhanced configuration options.
  • Refactor

    • Streamlined network client initialization and error handling, enhancing efficiency when accessing external resources.
    • Updated image fetching logic to improve error handling and processing during image retrieval from URLs and IPFS.
    • Modified the construction of image_path for Erc721Token objects to ensure consistency in its derivation from the token's ID.

Copy link

coderabbitai bot commented Feb 12, 2025

Walkthrough

Ohayo, sensei! This pull request updates constant declarations, error handling, and client retry logic in the sqlite module. A new public constant REQ_MAX_RETRIES replaces the removed IPFS_CLIENT_MAX_RETRY constant. In the executor module, error handling calls are updated from .with_context() to .context(), and the HTTP metadata fetching logic is streamlined to use a dedicated fetching function. In the utils module, global static clients (HTTP_CLIENT and IPFS_CLIENT) are introduced with lazy initialization, and both HTTP and IPFS fetching now use an exponential backoff retry mechanism.

Changes

File(s) Change Summary
crates/torii/sqlite/src/constants.rs Added pub const REQ_MAX_RETRIES: u8 = 3; removed pub const IPFS_CLIENT_MAX_RETRY: u8 = 3.
crates/torii/sqlite/src/executor/erc.rs Replaced .with_context() with .context() in methods (apply_balance_diff, fetch_metadata, handle_erc721_token_metadata); streamlined HTTP client instantiation in fetch_metadata.
crates/torii/sqlite/src/utils.rs Introduced global static clients HTTP_CLIENT and IPFS_CLIENT using lazy initialization; added fetch_content_from_http with an exponential backoff retry mechanism; updated fetch_content_from_ipfs to use the new client and retry logic based on REQ_MAX_RETRIES.
Cargo.toml Updated image dependency from image = "0.25.2" to image = { version = "0.25.2", features = [ "avif-native" ] }.
crates/torii/server/src/artifacts.rs Modified fetch_and_process_image to use fetch_content_from_http for image fetching; updated image loading to use load_from_memory_with_format. Added debugging println! statements for image_uri and image_type.
crates/torii/graphql/src/object/erc/erc_token.rs Updated image_path construction for Erc721Token objects to use the token id instead of contract_address, ensuring consistency across methods.
.github/workflows/ci.yml Updated Docker image reference from ghcr.io/dojoengine/dojo-dev:v1.1.1 to ghcr.io/dojoengine/dojo-dev:dav1d; added step to install dav1d library using vcpkg in ensure-windows job.
.github/workflows/release.yml Added "Windows setup" step in release job to install dav1d library using vcpkg for Windows environment.

Possibly related PRs

Suggested labels

sozo


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a18e0ab and 2b99415.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml (7 hunks)
  • .github/workflows/release.yml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .github/workflows/ci.yml
🔇 Additional comments (1)
.github/workflows/release.yml (1)

106-110: Ohayo sensei! The Windows setup step looks good for AVIF support.

The step correctly installs the dav1d library using vcpkg, which is essential for AVIF image support on Windows builds. The conditional execution ensures it only runs for the Windows target.

Let's verify the vcpkg installation command:

✅ Verification successful

🌐 Web query:

What is the latest version of dav1d library available in vcpkg?

💡 Result:

The latest version of the dav1d library available in vcpkg is 1.5.0, as indicated by its official vcpkg package listing[4][7]. This version was marked as production-ready and includes support for all AV1 features with cross-platform decoding optimizations[4].

Key details:

  • Listed under "Available Versions" in vcpkg's dav1d package documentation[4]
  • Officially maintained by VideoLAN/FFmpeg communities and AOM[4][7]
  • Requires Meson build system for compilation[9]
  • Available for Windows x86/x64 architectures through vcpkg's triplet system[7]

The package can be installed via:

vcpkg install dav1d

This will automatically fetch the latest stable version (currently 1.5.0) from vcpkg's registry[4][7].

Citations:


Ohayo sensei! Windows Setup Step Verified

The Windows setup step in .github/workflows/release.yml correctly uses vcpkg install dav1d to install the dav1d library. Our web query confirms that vcpkg fetches the latest stable version (1.5.0), which is ideal for AVIF support on Windows. Everything checks out!


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

🧹 Nitpick comments (7)
crates/torii/sqlite/src/utils.rs (5)

133-133: Ohayo sensei, consider breaking this line up for readability.
The pipeline has flagged this line’s length as exceeding recommended limits. Splitting it into multiple shorter lines can make it easier to maintain.

🧰 Tools
🪛 GitHub Actions: ci

[warning] 133-133: Line exceeds the recommended length. Consider breaking it into multiple lines for better readability.


144-144: Add the URL to your debug log.
Incorporating the URL helps diagnose failures by clearly indicating which endpoint caused the error.

- debug!(error = %e, retry = retries, "Request failed, retrying after backoff");
+ debug!(error = %e, retry = retries, url = %url, "Request failed, retrying after backoff");

165-165: Include the IPFS CID in the debug statement.
This additional context makes troubleshooting easier when retries fail on a specific resource.

- debug!(error = %e, retry = retries, "Request failed, retrying after backoff");
+ debug!(error = %e, retry = retries, cid = %cid, "Request failed, retrying after backoff");

284-284: Sensei, the pipeline suggests splitting this line.
Excessively long lines hinder readability. Consider splitting or restructuring it.


310-310: Sensei, please shorten or split this line for improved clarity.
Following line-length guidelines makes the code more comfortable to maintain.

crates/torii/sqlite/src/executor/erc.rs (2)

278-279: Beware of logging full response data.
Large or sensitive payloads in logs can cause security or performance issues. Consider limiting the data size or omitting the raw bytes.

- .context(format!("Failed to parse metadata JSON from response: {:?}", bytes))?
+ .context(format!("Failed to parse metadata JSON (length: {})", bytes.len()))?

288-288: Likewise, consider limiting logged IPFS response data.
Full prints of the downloaded data might be too large and could risk leaking information.

- .context(format!("Failed to parse metadata JSON from IPFS: {:?}, data: {:?}", cid, bytes))
+ .context(format!("Failed to parse metadata JSON from IPFS: {}, data length: {}", cid, bytes.len()))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f0c1e0b and 7b8380e.

📒 Files selected for processing (3)
  • crates/torii/sqlite/src/constants.rs (1 hunks)
  • crates/torii/sqlite/src/executor/erc.rs (8 hunks)
  • crates/torii/sqlite/src/utils.rs (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/sqlite/src/executor/erc.rs

[warning] 17-17: Line exceeds the recommended length. Consider breaking it into multiple lines for better readability.


[warning] 284-284: Line exceeds the recommended length. Consider breaking it into multiple lines for better readability.


[warning] 310-310: Line exceeds the recommended length. Consider breaking it into multiple lines for better readability.

crates/torii/sqlite/src/utils.rs

[warning] 133-133: Line exceeds the recommended length. Consider breaking it into multiple lines for better readability.

🔇 Additional comments (6)
crates/torii/sqlite/src/utils.rs (1)

111-117: Ohayo sensei! Great job introducing a global HTTP client.
Centralizing the client configuration helps ensure consistent timeouts while reducing repeated instantiations.

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

7-7: Ohayo sensei, consolidating retry logic is awesome!
Defining a single retry constant (REQ_MAX_RETRIES) simplifies updates and promotes consistency.

crates/torii/sqlite/src/executor/erc.rs (4)

77-77: Ohayo sensei, nice usage of .context(...) for error propagation.
Replacing .with_context() with .context(...) is consistent and concise, making your error handling cleaner.

Also applies to: 96-96, 144-144, 343-343


256-256: Including token_uri in the warning log is helpful.
Thanks for adding extra context when metadata fails to fetch.


273-279: Nice re-use of fetch_content_from_http.
This centralization reduces code repetition and ensures uniform error handling.


314-317: Ohayo sensei, the data URI parsing looks thorough!
Your error context is clear and should help identify bugs in metadata quickly.

Comment on lines +119 to +123
static IPFS_CLIENT: Lazy<IpfsClient> = Lazy::new(|| {
IpfsClient::from_str(IPFS_CLIENT_URL)
.expect("Failed to create IPFS client")
.with_credentials(IPFS_CLIENT_USERNAME, IPFS_CLIENT_PASSWORD)
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ohayo sensei, storing credentials as constants is risky.
Hardcoding credentials can lead to accidental exposure and security vulnerabilities. Consider moving these credentials to environment variables or another secure store.

-static IPFS_CLIENT: Lazy<IpfsClient> = Lazy::new(|| {
-    IpfsClient::from_str(IPFS_CLIENT_URL)
-        .expect("Failed to create IPFS client")
-        .with_credentials(IPFS_CLIENT_USERNAME, IPFS_CLIENT_PASSWORD)
-});
+// Example approach using environment variables
+static IPFS_CLIENT: Lazy<IpfsClient> = Lazy::new(|| {
+    let url = std::env::var("IPFS_CLIENT_URL").expect("Missing IPFS_CLIENT_URL env var");
+    let username = std::env::var("IPFS_CLIENT_USERNAME").unwrap_or_default();
+    let password = std::env::var("IPFS_CLIENT_PASSWORD").unwrap_or_default();
+
+    IpfsClient::from_str(&url)
+        .expect("Failed to create IPFS client")
+        .with_credentials(&username, &password)
+});
📝 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.

Suggested change
static IPFS_CLIENT: Lazy<IpfsClient> = Lazy::new(|| {
IpfsClient::from_str(IPFS_CLIENT_URL)
.expect("Failed to create IPFS client")
.with_credentials(IPFS_CLIENT_USERNAME, IPFS_CLIENT_PASSWORD)
});
// Example approach using environment variables
static IPFS_CLIENT: Lazy<IpfsClient> = Lazy::new(|| {
let url = std::env::var("IPFS_CLIENT_URL").expect("Missing IPFS_CLIENT_URL env var");
let username = std::env::var("IPFS_CLIENT_USERNAME").unwrap_or_default();
let password = std::env::var("IPFS_CLIENT_PASSWORD").unwrap_or_default();
IpfsClient::from_str(&url)
.expect("Failed to create IPFS client")
.with_credentials(&username, &password)
});

@Larkooo Larkooo changed the title fix(torii): http metadata ratelimiting & image static fix(torii): http metadata ratelimiting & add avif support Feb 12, 2025
@Larkooo Larkooo changed the title fix(torii): http metadata ratelimiting & add avif support fix(torii): add avif support & http ratelimiting handling Feb 12, 2025
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b8380e and 4417c10.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • Cargo.toml (1 hunks)
  • crates/torii/server/src/artifacts.rs (4 hunks)
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/server/src/artifacts.rs

[warning] 58-58: Code formatting issue: Await should be on the same line as the function call.


[warning] 177-177: Code formatting issue: Await should be on the same line as the function call.

🔇 Additional comments (4)
crates/torii/server/src/artifacts.rs (3)

18-18: LGTM! Clean import refactoring.

Ohayo! The import changes nicely consolidate the HTTP and IPFS fetching utilities.


180-182: LGTM! Improved HTTP fetching with retries.

The HTTP fetching logic is now more robust with built-in retry mechanism.


215-215: LGTM! More explicit image format handling.

Using load_from_memory_with_format is safer as it ensures the correct format is used for loading the image.

Cargo.toml (1)

187-187: LGTM! Added AVIF image support.

Ohayo sensei! Adding the avif-native feature is great as AVIF offers superior compression while maintaining high image quality.

@@ -173,19 +171,15 @@ async fn fetch_and_process_image(
.with_context(|| format!("Image field not a string for token_id: {}", token_id))?
.to_string();

println!("image_uri: {}", image_uri);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove debug print statements.

Ohayo sensei! These debug print statements should be replaced with proper logging using the tracing crate that's already imported.

-    println!("image_uri: {}", image_uri);
+    debug!(image_uri = %image_uri, "Processing image URI");

-    println!("image_type: {:?}", image_type);
+    debug!(image_type = ?image_type, "Determined image type");

Also applies to: 247-247

@Larkooo
Copy link
Collaborator Author

Larkooo commented Feb 14, 2025

#3028 addresses this also i think

@Larkooo Larkooo changed the title fix(torii): add avif support & http ratelimiting handling feat(torii-erc): add avif support Feb 14, 2025
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