fix: prevent media upload OOM on Workers for large images (#262)

* fix: prevent media upload OOM on Workers via client thumbnails + server safety net

Large image uploads (5MB+) crash Cloudflare Workers (128MB limit) because
generatePlaceholder() decodes entire images to raw RGBA pixels. A 4000x3000
JPEG becomes ~48MB RGBA, exceeding the isolate memory budget.

Two-layer fix:
- Client-side: browser generates a 64px canvas thumbnail for oversized images
  and sends it alongside the upload. Server generates blurhash from the
  thumbnail (~16KB RGBA) instead of decoding the full image.
- Server-side: reads dimensions from image headers via image-size and skips
  placeholder generation when estimated decoded size exceeds 32MB. This covers
  API/CLI uploads that don't provide thumbnails.

* chore: add changeset for media upload OOM fix

* fix: clamp upload thumbnail to 64x64 box for extreme aspect ratios

Naive sizing (thumbW=64, thumbH=(h/w)*64) could produce an enormous canvas
for very tall or very wide images — e.g. a 100x840000 image would allocate
a 64x537600 canvas client-side, reintroducing the memory blowup this feature
exists to prevent.

Extract computeThumbnailSize() that fits the image within a 64x64 box by
scaling against max(width, height), wrap canvas allocation and drawImage
in try/catch with a no-thumbnail fallback, and add unit tests covering
extreme aspect ratios.

---------

Co-authored-by: Matt Kane <mkane@cloudflare.com>
This commit is contained in:
Benjamin Price
2026-04-06 16:14:39 +09:00
committed by GitHub
parent 73b71b4e59
commit 8c693b582d
8 changed files with 293 additions and 15 deletions

View File

@@ -0,0 +1,5 @@
---
"emdash": patch
---
Fix media upload OOM on Cloudflare Workers for large images by generating blurhash from client-provided thumbnails instead of decoding full-resolution images server-side