Skip to content

Conversation

@adam-vessey
Copy link
Contributor

@adam-vessey adam-vessey commented Aug 20, 2025

Something of an odd case... wanting to say that this seems like an issue with some invalid media entities kicking around which are missing a value pointing at an image? Indeed, found evidence of "image" media lacking any related file being referenced.

Stacktrace
 [error]  AssertionError: Cannot load the "file" entity with NULL ID. in assert() (line 261 of /var/www/html/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php) #0 /var/www/html/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php(261): assert(false, 'Cannot load the...')
#1 /var/www/html/web/modules/contrib/dgi_image_discovery/src/Plugin/dgi_image_discovery/url_generator/UrlGenerationTrait.php(65): Drupal\Core\Entity\EntityStorageBase->load(NULL)
#2 /var/www/html/web/modules/contrib/dgi_image_discovery/src/Plugin/dgi_image_discovery/url_generator/PreGenerated.php(50): Drupal\dgi_image_discovery\Plugin\dgi_image_discovery\url_generator\PreGenerated->getGeneratedUrl(Object(Drupal\node\Entity\Node), Object(Drupal\dgi_i8_helper\Entity\ImageStyle))
#3 /var/www/html/web/modules/contrib/dgi_image_discovery/src/Plugin/search_api/processor/DgiImageDiscovery.php(130): Drupal\dgi_image_discovery\Plugin\dgi_image_discovery\url_generator\PreGenerated->generate(Object(Drupal\node\Entity\Node), Object(Drupal\dgi_i8_helper\Entity\ImageStyle))
#4 /var/www/html/web/modules/contrib/search_api/src/Item/Item.php(289): Drupal\dgi_image_discovery\Plugin\search_api\processor\DgiImageDiscovery->addFieldValues(Object(Drupal\search_api\Item\Item))
#5 /var/www/html/web/modules/contrib/search_api/src/Entity/Index.php(1026): Drupal\search_api\Item\Item->getFields()
[... of into search_api_fast / command bootstrap; snipping ...]

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling during image URL generation: when a media item lacks a file reference, the system now returns a proper not-found response instead of generating an invalid link.
    • Prevents broken image URLs and provides clearer feedback when an image asset is unavailable, while leaving normal image delivery unchanged.

@adam-vessey adam-vessey added the patch Backwards compatible bug fixes. label Aug 20, 2025
@coderabbitai
Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

Introduced a guard in UrlGenerationTrait::getGeneratedUrl to throw CacheableNotFoundHttpException when the resolved file_id is empty. All other URL generation logic remains unchanged, including file loading, missing image handling, and URL construction from the image URI.

Changes

Cohort / File(s) Summary of Changes
URL generation guard
src/Plugin/dgi_image_discovery/url_generator/UrlGenerationTrait.php
Added empty file_id check after retrieving from media source; throws CacheableNotFoundHttpException with context (media id, node id). Existing file load, missing image handling, and URL building remain unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Trait as UrlGenerationTrait
  participant MS as Media Source
  participant Media
  participant Files as File Storage

  Client->>Trait: getGeneratedUrl(node, media)
  Trait->>MS: resolve file_id from media source
  MS-->>Trait: file_id (may be empty)

  alt file_id is empty (new guard)
    Trait-->>Client: throw CacheableNotFoundHttpException\n"No file ID for discovered media (mid) for node (nid)"
  else file_id present
    Trait->>Files: load file by file_id
    alt file not found / missing image
      Trait-->>Client: existing handling (e.g., not found)
    else file found
      Trait->>Trait: build URL from image URI
      Trait-->>Client: return generated URL
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through URLs, quick and spry,
Sniffing file_ids as they flutter by—
If none appear, I thump: “Not today!”
Cacheable winds whisk woes away.
But when a path is clear and bright,
I bound the link into the light. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • JIRA integration encountered authorization issues. Please disconnect and reconnect the integration in the CodeRabbit UI.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/bad-media

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@adam-vessey adam-vessey marked this pull request as ready for review August 20, 2025 20:08
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)
src/Plugin/dgi_image_discovery/url_generator/UrlGenerationTrait.php (2)

62-69: Harden type validation and cast $file_id before loading.

Depending on media source implementations, getSourceFieldValue($media) can sometimes be non-scalar (e.g., array-like structures) or a non-integer string. Strengthen the check to ensure a positive integer and cast before load to avoid unexpected type errors.

Apply this diff:

     $media_source = $media->getSource();
     $file_id = $media_source->getSourceFieldValue($media);
-    if (empty($file_id)) {
-      throw new CacheableNotFoundHttpException($generated_url, "No file ID for discovered media ({$media->id()}) for node ({$node->id()}).");
-    }
+    // Ensure we have a positive integer file ID; reject non-scalar or non-numeric values.
+    if (!is_scalar($file_id) || !ctype_digit((string) $file_id) || (int) $file_id <= 0) {
+      throw new CacheableNotFoundHttpException(
+        $generated_url,
+        "No valid file ID for discovered media ({$media->id()}) for node ({$node->id()})."
+      );
+    }
+    $file_id = (int) $file_id;
     /** @var \Drupal\file\FileInterface|null $image */
     $image = $this->getEntityTypeManager()->getStorage('file')->load($file_id);

48-76: Add regression tests for “no media/file” scenarios

To ensure the behavior of UrlGenerationTrait remains locked and clearly documented, please add tests covering these cases:

• Test UrlGenerationTrait::getGeneratedUrl directly
– Stub a NodeInterface and ImageDiscoveryInterface so that
• getImage() returns an event with no media
• getImage() returns an event whose media’s source field value is empty
• getImage() returns an event whose media source yields a file ID that cannot be loaded
– In each scenario, assert that getGeneratedUrl throws a Drupal\Core\Http\Exception\CacheableNotFoundHttpException (as declared in UrlGenerationTrait) [see UrlGenerationTrait.php lines 55–71].

• Test PreGenerated::generate maps exceptions to null
– Call PreGenerated::generate(...) with the same stubbed failure scenarios above.
– Assert it returns null (confirming it catches NotFoundHttpException, including CacheableNotFoundHttpException) [see PreGenerated.php lines 49–53].

(Optional) If you rely on the deferred plugins (Redirect, Subrequest) elsewhere, consider an integration or functional test to verify that they propagate the exception as expected when resolving URLs.

By adding these tests, you’ll guard against regressions and clearly document the intended “no image” behavior for both indexers (via PreGenerated) and direct trait usage.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1f41fa9 and e085a01.

📒 Files selected for processing (1)
  • src/Plugin/dgi_image_discovery/url_generator/UrlGenerationTrait.php (1 hunks)
🔇 Additional comments (1)
src/Plugin/dgi_image_discovery/url_generator/UrlGenerationTrait.php (1)

64-66: Good guard to prevent fatal on NULL file IDs.

This early return via CacheableNotFoundHttpException avoids the prior assertion on load(NULL) and maintains consistent cacheability behavior with the other not-found branches. Looks correct and aligned with the intent of SEC-1647.

@jordandukart jordandukart merged commit b469bac into main Aug 21, 2025
2 checks passed
@jordandukart jordandukart deleted the fix/bad-media branch August 21, 2025 13:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

patch Backwards compatible bug fixes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants