Repository navigation
feat: cache media files in the route cache - #4911
Conversation
Store whole image files and /_image variants for one year under emdash:media:<storageKey>, purge the tag on replace and on deletes that remove the stored file (admin, MCP, trusted and sandboxed plugins), and redirect non-canonical /_image queries to Astro's parameter order.
Skip caching media whose storage key could split its Cache-Tag, cap media responses at 10 MB in memoryCache(), purge deletes from the media picker and the hourly cleanup, and purge sandbox bridge deletes only when the stored file was removed.
Read the route cache provider after all integrations ran, describe the total memoryCache() bound, back the Cloudflare bridge test with a real SQLite table, and cover purge failures, disabled caches, missing items, failed Cloudflare transforms and the cleanup invalidator wiring.
Cover the route cache provider name reaching the config virtual module and ctx.media.delete() purging through the request cache in trusted plugin routes. Document that /_image also redirects differently encoded queries and that memoryCache() hits can skip the redirect.
🦋 Changeset detectedLatest commit: 589cf2f The changes in this PR will be included in the next version bump. This PR includes changesets to release 12 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
@emdash-cms/admin
@emdash-cms/auth
@emdash-cms/auth-atproto
@emdash-cms/blocks
@emdash-cms/cloudflare
@emdash-cms/contentful-to-portable-text
emdash
create-emdash
@emdash-cms/gutenberg-to-portable-text
@emdash-cms/plugin-cli
@emdash-cms/plugin-test
@emdash-cms/plugin-types
@emdash-cms/registry-client
@emdash-cms/registry-lexicons
@emdash-cms/registry-loader
@emdash-cms/registry-moderation
@emdash-cms/registry-verification
upgrade-emdash
@emdash-cms/sandbox-workerd
@emdash-cms/x402
@emdash-cms/plugin-ai-moderation
@emdash-cms/plugin-ai-search
@emdash-cms/plugin-atproto
@emdash-cms/plugin-audit-log
@emdash-cms/plugin-color
@emdash-cms/plugin-embeds
@emdash-cms/plugin-field-kit
@emdash-cms/plugin-forms
@emdash-cms/plugin-webhook-notifier
commit: |
There was a problem hiding this comment.
The approach is right and follows the accepted plan (proposals/media-route-cache.md). Media responses get route-cache intent with a per-storage-key tag, replace and delete purge that tag, /_image URLs are canonicalized, and the existing invalidateRouteCache and plugin content-action plumbing is reused. One reviewer found no actionable issues and approved. The other raised one needs_fixing finding and two suggestions, and all three are kept here. The needs_fixing item is a design-record mismatch: replace purges even when the metadata update fails, which contradicts the accepted plan. The suggestions are wasted purges for media that was never cacheable and uncapped cache entries on the file route. Both reviews were static; neither ran tests or builds.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.
| return handleError(error, "Failed to replace media", "MEDIA_REPLACE_ERROR"); | ||
| } | ||
| // The stored bytes changed even if the metadata update below fails. | ||
| await invalidateRouteCache(cache, [mediaCacheTag(media.storageKey)]); |
There was a problem hiding this comment.
[needs fixing] The purge runs as soon as the storage upload succeeds, before handleMediaReplaceMetadata. A replace whose metadata update fails therefore still purges, and the new test purges even when the metadata update fails after the bytes changed pins that behavior.
The accepted plan's Verification section says the opposite: "Replace: a successful replace invalidates the tag; a failed upload or metadata update does not." Purging here is probably correct, because the bytes under the key have already changed. But it is a silent change to the accepted design, and the PR description's "Details beyond the plan" does not mention it.
Please amend proposals/media-route-cache.md so the design record matches what ships. The same amendment could cover:
- the 10 MB
memoryCache()cap - not caching unsafe storage keys
- deferring sandboxed purges to the invocation flush
- purging from cleanup
(The other reviewer approved with no findings and did not raise this.)
| ) { | ||
| return apiError("MEDIA_DELETE_ERROR", "Failed to delete media", 500); | ||
| } | ||
| if (result.data.storageDeleted) { |
There was a problem hiding this comment.
[suggestion] This purges emdash:media:<storageKey> for every delete that removed the stored file. That includes PDFs, audio, video and keys that fail isSafeTransformKey, none of which cacheMediaResponse ever stores.
On Cloudflare, each purge counts against the account-wide Workers Cache limit (5 per minute, burst of 25). Bulk-deleting documents can rate-limit later content purges and leave pages stale, while buying nothing. runSystemCleanup already filters with isSafeTransformKey.
Consider purging only when the deleted item could have been cached: an image/* MIME type and a safe key. media.mimeType is already loaded above. The same applies to the media-picker route and the MCP media_delete tool. The docs' line that deleting a media item whose stored file was removed costs one purge request would then also be accurate for non-images.
| if (body) unusedBody = undefined; | ||
| // Only images: memoryCache() ignores Range, so a cached video or audio | ||
| // file would answer a player's seek with the whole file. | ||
| if (!range && result.contentType.startsWith("image/")) { |
There was a problem hiding this comment.
[suggestion] The file route caches the whole response whatever the request's query string. Each distinct ?x=1, ?x=2… becomes its own route-cache entry under the same tag. With memoryCache(), an anonymous visitor could fill the 1,000-entry limit with copies of one 10 MB image. That needs no transform work, unlike the /_image variant flood the docs describe, and it evicts cached pages.
The plan's goal of one cache entry per URL is enforced only for /_image. Consider calling cacheMediaResponse only when the query is empty or contains only the admin's _emdash_media cache-buster. Alternatively, redirect other query strings the way /_image does.
Skip the route-cache purge when a deleted file was never cacheable (non-image types and unsafe keys), cache media file responses only for an empty query or the admin preview parameter, and record the shipped behavior in the proposal.
Approval statusThe current revision does not meet the approval requirements yet.
This comment updates as reviews arrive. See MAINTAINING.md and the proposal process for the rules. |
There was a problem hiding this comment.
The approach is sound and matches the accepted plan in proposals/media-route-cache.md. Image responses get route-cache intent under a per-storage-key tag. Replace and delete purge that tag. /_image URLs are redirected to one canonical form. The existing invalidateRouteCache and plugin content-action plumbing is reused. Both reviewers approved with no new findings. Both found the earlier findings fixed: the proposal now records that replace purges even when the metadata update fails, purges are skipped for media that was never cacheable, and the file route caches only an empty query or the _emdash_media parameter. Both reviews were static; neither ran tests or builds.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol.
|
I maintain the rapier-jxl encoder and the JPEG XL Image Optimizer plugin for EmDash. The plugin answers
On The fix is likely a separate URL for JPEG XL, the way AVIF already has one through |
A static import pulled the image endpoint into the Worker's startup modules and pushed the starter template past the 30-module limit.
danielmlr
left a comment
There was a problem hiding this comment.
Found 3 things worth a look:
- I think the
/_imageredirect should only kick in for Astro's own image service. From the code, a site with a custom local service that adds its own param ingetURLnow gets a 301 to the URL without it, like thesize=thumbnailcase @khoinguyenpham04 hit. Browsers keep that 301, so it sticks even after a fix. MaybecanonicalTransformSearchcould run, and the variant get cached, only whenimageConfig.service.entrypointis Astro's built-in one? - I'd go with @khoinguyenpham04's idea of leaving media caching off under
memoryCache()for now. A site that setsquery.includefor its pages dropshreffrom the key, so every image shares one cache entry. And with several processes, a delete or replace only purges the one that handled it, so the others can keep serving the old image for up to a year. - #4889 changes the same paragraph and Node list in
route-caching.mdx, so whichever goes in second will clash there. Once both are in, hooks, cron jobs and the hourly cleanup on Node do purge, so the two "not purged" bullets would be wrong. Could whichever goes in second update them?
There was a problem hiding this comment.
The approach remains sound: cache eligible image responses by storage-key tag and purge them when stored bytes change. This follow-up appropriately narrows provider and image-service compatibility, with corresponding amendments to the proposal, guide, and changeset.
I reviewed the changes since the previously approved head, including the memoryCache() exclusion, source-URL eligibility, tag-length limits, and invocation-scoped Cloudflare media deletion. The added tests cover observable response behavior, storage deletion, capability checks, and RPC isolation. Earlier findings remain resolved; I found no new issues to fix.
Review was static; I did not run tests or builds. Deployed Cloudflare timeout guarantees remain unverified and are explicitly documented as a limitation.
Follow-up review by openai/gpt-6.1-sol, scoped to the changes since the last review.
|
Thanks @danielmlr and @khoinguyenpham04, your findings are addressed in the latest push. Automatic media caching is disabled entirely under I've also noted the overlap with #4889 in the PR description. Whichever lands second will need to reconcile the Node purge documentation and verify the combined behavior. |
There was a problem hiding this comment.
The approach is sound. Eligible image responses are cached under a per-storage-key tag (emdash:media:<storageKey>), and that tag is purged when the stored bytes change. The narrowed scope (stock image services only, plain local sources, original-file URLs without a query string, no automatic entries under memoryCache()) is recorded in the proposal, guide and changeset. Both reviewers approved with no open findings. They agree that the earlier query-string finding, the purge-filtering finding and the design-record finding about purging on a failed metadata update are resolved at this head. Review was static, so tests and builds were not run. Deployed Cloudflare purge behavior, purges after a sandbox timeout, and whether providers skip storing HEAD responses remain unverified. The first two are documented as limitations.
Reviewed by anthropic/claude-opus-5-5 and openai/gpt-6.1-sol. The change since the last review (1116 lines) was too large for a scoped follow-up, so this is a full review.
What does this PR do?
Implements the accepted media route-cache feature plan. I encountered repeated storage reads and image transforms on my EmDash site.
Closes #4498
On sites with a compatible route-cache provider, such as
cacheCloudflare(), EmDash caches whole image responses for one year underemdash:media:<storageKey>. Replacing an image, or deleting its stored file, purges the original and its cached variants. Browser cache headers and validators remain unchanged._emdash_mediapreview parameter. Audio, video, partial responses, conditional304responses and errors are not automatically cached.@astrojs/cloudflare/image-service-workerdon Cloudflare. Custom image services retain their parameters and existing handling. Stock-service redirects also apply without a cache provider.hrefmust be exactly the internal media path or that path prefixed with the request's origin. Nested queries, fragments, foreign origins and alternate path spellings retain existing image handling but receive no automatic cache entries. Relative and same-origin absolute sources can occupy separate entries.memoryCache()receives no automatic media entries. Its query filtering can collapse different images onto one cache key, and warm hits do not preserve the endpoint's conditional responses. Page caching remains available. Other providers must preserve distinct image inputs and conditional-request behavior..,_and-, and are at most 1,011 characters long so the full tag fits Cloudflare's 1,024-character purge limit. Longer keys remain valid for serving existing media.Invalidation covers media API routes, the media picker, MCP
media_delete, trusted and sandboxed plugin routes, and Cloudflare cleanup of objects left behind by failed deletes. Replace purges after storage succeeds even if the later metadata update fails. Deletes purge only after storage removal and only for potentially cached media.Cloudflare sandbox deletion uses an invocation-bound RPC target so the host callback survives cross-isolate routing. Purges are queued for host-side execution. A late deletion after a plugin timeout can still miss its purge if the host invocation ends; a grace timer is not a deployed lifetime guarantee. Direct bucket changes, failed purges and overlapping cache fills have the limitations documented in the route-caching guide.
The proposal records these scope amendments.
Integration note: #4889 changes Node background invalidation and the same route-caching documentation. Whichever PR merges second must reconcile the documentation and test media purges from Node hooks, cron tasks and hourly cleanup with the combined implementation. The current Node limitations describe this branch without that still-open change.
Type of change
Your connection to this change
Checklist
pnpm typecheckpassespnpm lintpassespnpm testpasses (or targeted tests for my change)pnpm formathas been runmessages.pochanges except in translation PRs — a workflow extracts catalogs on merge tomain.AI assistance disclosure
Screenshots / test output
Not applicable (no UI changes or new admin strings).
Validated the merge with upstream
6d0551bdec7f776d3f77233f095342f3aefeb1ac, candidate treee5b5c7db7054c64ea38f001cc9b7b7c9c0c34565:pnpm format,pnpm build,pnpm lint:quick, type-awarelint:json(zero diagnostics, pipeline failures checked), andpnpm typecheckpassed.pnpm testpassed. Admin: 5,357 passed; core: 11,752 passed, 24 skipped; Cloudflare: 624 passed, 2 skipped; workerd: 277 passed.One full-suite attempt hit a 275 ms Save-click timeout in the admin media-repeater test. The unchanged test passed in isolation and the subsequent full suite passed. An earlier run interrupted by a concurrent rebuild is not counted. Typechecking used the installed native compiler's directory on PATH because its workspace binary link was missing.
An independent full static review covered all 46 changed files against the integrated upstream base and found no confirmed code defect. Its publication finding was that the previous PR description was stale; this description corrects those claims. Review is evidence, not human approval.
Regression coverage exercises the real Astro memory provider and Sharp transforms, custom-service parameters, source-query exclusions, and invocation-bound sandbox deletion. The local workerd RPC tests check D1/R2 deletion and callback isolation, not a deployed Workers Cache purge.
Earlier deployed Cloudflare MISS/HIT and replace/delete measurements belong to a previous revision. Earlier Node memory-cache HIT and size-limit measurements are superseded by the exclusion of automatic media caching.
Not verified on this candidate: PostgreSQL (
EMDASH_TEST_PGunavailable), D1 query snapshots, deployed Cloudflare cache behavior, and host lifetime after sandbox timeout. The dedicated core workerd run covers the two relevant media test files, not that entire suite.