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-artifacts): refetch image if the image uri changed #3053

Merged
merged 4 commits into from
Feb 22, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 20, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced image refresh logic now automatically verifies and retrieves updated images when changes are detected, ensuring that displayed visuals are always current and up-to-date.
  • Bug Fixes

    • Improved error management during image retrieval now provides more robust handling of unexpected issues, ensuring a smoother, more reliable user experience and consistent image delivery.

Copy link

coderabbitai bot commented Feb 20, 2025

Ohayo sensei! Here’s the detailed summary of your pull request:

Walkthrough

The pull request enhances image handling in the artifacts module by introducing a new asynchronous function, check_image_hash, which verifies if the image hash file exists and compares it with the current image URI stored in the database. Based on the comparison, the system decides whether to refetch the image. The process is integrated with the serve_static_file and fetch_and_process_image functions, with improved error handling and a streamlined process for storing the image hash.

Changes

File Path Change Summary
crates/torii/.../artifacts.rs - Introduced new async function check_image_hash for verifying image hash files.
- Updated serve_static_file to conditionally trigger image refetching based on hash checks.
- Modified fetch_and_process_image to write the image URI hash and simplified error handling.

Sequence Diagram(s)

sequenceDiagram
    participant S as serve_static_file
    participant CH as check_image_hash
    participant FP as fetch_and_process_image
    participant FS as File System
    participant DB as Database

    S ->> CH: Validate image hash
    alt Hash file missing or hash mismatch
        CH -->> S: Return false
        S ->> FP: Fetch & process image
        FP ->> FS: Save image & write image.hash
        FP -->> S: Return updated image
    else Valid hash
        CH -->> S: Return true
        S -->> S: Serve cached image
    end
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

🧹 Nitpick comments (2)
crates/torii/server/src/artifacts.rs (2)

213-213: Ohayo sensei! Thorough error message.
Adding context for missing "image" field in metadata helps quickly identify invalid or corrupted token metadata.


341-344: Ohayo sensei! Great step persisting the new image URI hash.
Storing the hash ensures subsequent requests can detect if the stored artifact is outdated. If you foresee large URIs or sensitive info, consider hashing or encrypting the URI before writing to disk for privacy.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f244197 and 7af68d5.

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

60-72: Ohayo sensei! Great fallback approach for refetching on error.
If there's an error checking the image hash or the directory doesn’t exist, defaulting to true for should_fetch ensures freshness of the artifact. This logic is straightforward and helps avoid stale images.


74-74: Ohayo sensei! Consider concurrency implications.
If multiple tasks hit should_fetch simultaneously, they could both attempt a refetch at the same time. Although this might be acceptable, you might want a lock or more granular concurrency control if collisions become an issue.


162-194: Ohayo sensei! Excellent implementation of hash-check logic.
This function cleanly determines whether the image URI has changed by comparing the stored hash against the current URI in the database. The fallback to Ok(true) ensures the image is fetched if there's no hash or an error reading the file. This is a robust approach to ensure artifact consistency.


207-207: Ohayo sensei! Good use of .context() here.
This additional context enhances debuggability by pinpointing the source of database fetching issues. Nice consistency with other lines.


215-215: Ohayo sensei! Solid validation on image field type.
This ensures the image field is indeed a string, preventing obscure runtime type errors further down the pipeline.

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/server/src/artifacts.rs (2)

162-194: Consider optimizing metadata handling, sensei!

The function works well but could be improved in a few areas:

  1. Consider caching parsed metadata to avoid repeated JSON parsing
  2. Add specific error messages for common failure cases

Here's a suggested optimization:

 async fn check_image_hash(
     token_image_dir: &Utf8PathBuf,
     token_id: &str,
     pool: &Pool<Sqlite>,
 ) -> Result<bool> {
     let hash_file = token_image_dir.join("image.hash");
 
     // Get current image URI from metadata
     let query = sqlx::query_as::<_, (String,)>(&format!(
         "SELECT metadata FROM {TOKENS_TABLE} WHERE id = ?"
     ))
     .bind(token_id)
     .fetch_one(pool)
     .await
-    .context("Failed to fetch metadata from database")?;
+    .context(format!("Failed to fetch metadata for token {}", token_id))?;
 
     let metadata: serde_json::Value =
         serde_json::from_str(&query.0).context("Failed to parse metadata")?;
     let current_uri = metadata
         .get("image")
-        .context("Image URL not found in metadata")?
+        .context(format!("Image URL not found in metadata for token {}", token_id))?
         .as_str()
-        .context("Image field not a string")?;
+        .context(format!("Image field not a string for token {}", token_id))?;

341-344: Consider atomic write for hash file, sensei!

The hash file storage is good, but consider using atomic write operations to prevent partial writes in case of system failures.

Here's a suggested approach using a temporary file:

-            // Before returning, store the image URI hash
-            let hash_file = dir_path.join("image.hash");
-            fs::write(&hash_file, &image_uri).await.context("Failed to write hash file")?;
+            // Store the image URI hash atomically
+            let hash_file = dir_path.join("image.hash");
+            let temp_hash_file = dir_path.join(".image.hash.tmp");
+            fs::write(&temp_hash_file, &image_uri).await.context("Failed to write temporary hash file")?;
+            fs::rename(&temp_hash_file, &hash_file).await.context("Failed to rename hash file")?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7af68d5 and 7d62bd4.

📒 Files selected for processing (1)
  • crates/torii/server/src/artifacts.rs (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: docs
  • GitHub Check: build
  • GitHub Check: clippy
🔇 Additional comments (1)
crates/torii/server/src/artifacts.rs (1)

60-74: Ohayo! Nice optimization for image refetching, sensei!

The new logic efficiently determines if an image needs to be refetched by checking the image hash. The error handling gracefully falls back to fetching when hash verification fails.

Copy link

codecov bot commented Feb 20, 2025

Codecov Report

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

Project coverage is 57.62%. Comparing base (f244197) to head (7d62bd4).
Report is 6 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/server/src/artifacts.rs 0.00% 42 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3053      +/-   ##
==========================================
- Coverage   57.65%   57.62%   -0.04%     
==========================================
  Files         439      439              
  Lines       59437    59470      +33     
==========================================
  Hits        34267    34267              
- Misses      25170    25203      +33     

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

@Larkooo Larkooo merged commit 9b93308 into dojoengine:main Feb 22, 2025
13 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