From 0b54752b6f5b9547369ef60399c0855d314aeeb5 Mon Sep 17 00:00:00 2001 From: mahmood Date: Thu, 26 Nov 2026 14:16:38 +0330 Subject: [PATCH] fix(uploads): downscale huge-dimension files and give thumbnails a fallback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A flat 8000x8000 PNG can weigh 13 KB, so the byte-size shortcut skipped compression and every thumbnail render had to decode 64 MP first — on a small server that outlived nginx's timeout, leaving the card broken until the variant finished while the original (/uploads) opened fine. Files over 2000 px on their long side are now converted even when they are small on disk. ant-design-vue paints the upload tile as name with no error handling, so any failed resize showed the grey box with just the file name. The tile now falls back to the stored original. Co-Authored-By: Claude Haiku 5.5 --- .../components/upload/ImageUploadInput.vue | 20 ++++++++++++++- .../image-variants.service.spec.ts | 18 ++++++++++++- .../admin-uploads/image-variants.service.ts | 25 ++++++++++++++++--- 3 files changed, 58 insertions(+), 5 deletions(-) diff --git a/apps/admin-panel/src/components/upload/ImageUploadInput.vue b/apps/admin-panel/src/components/upload/ImageUploadInput.vue index 815af745..fbc3ed9c 100644 --- a/apps/admin-panel/src/components/upload/ImageUploadInput.vue +++ b/apps/admin-panel/src/components/upload/ImageUploadInput.vue @@ -10,7 +10,7 @@ The bound value is the stored file's URL, which is what the schema keeps. --> -
+
props.placeholder); +/** + * ant-design-vue paints the tile as `name` + * with no error handling of its own, so a failed resize (a 404/504 from + * /api/img, or a variant still rendering) left the card grey with only the + * file name — which is what an admin saw right after uploading. Swap the + * thumbnail for the stored original, which the eye preview already loads. + * Capture phase: `error` on an does not bubble. + */ +function onThumbError(e: Event) { + const img = e.target as HTMLImageElement | null; + const original = fileList.value[0]?.url; + if (!img || img.tagName !== 'IMG' || !original) return; + // Compare paths, not the whole URL: the browser resolves src absolutely. + if (new URL(img.src, window.location.origin).pathname !== original) { + img.src = original; + } +} + function beforeUpload(file: File) { const problem = checkImageFile(file); if (problem) { diff --git a/apps/api/src/modules/admin-uploads/image-variants.service.spec.ts b/apps/api/src/modules/admin-uploads/image-variants.service.spec.ts index d1ea3279..dc263eee 100644 --- a/apps/api/src/modules/admin-uploads/image-variants.service.spec.ts +++ b/apps/api/src/modules/admin-uploads/image-variants.service.spec.ts @@ -63,7 +63,11 @@ describe('ImageVariantService', () => { const big = Buffer.alloc(3000 * KB); /** A sharp stand-in whose output size depends on the requested quality and side. */ - function fakeSharp(svc: ImageVariantService, sizeFor: (side: number, quality: number) => number) { + function fakeSharp( + svc: ImageVariantService, + sizeFor: (side: number, quality: number) => number, + dims: { width: number; height: number } = { width: 1600, height: 1200 }, + ) { const calls: Array<{ side: number; quality: number }> = []; (svc as unknown as { sharp: unknown }).sharp = () => { let side = 0; @@ -72,6 +76,7 @@ describe('ImageVariantService', () => { rotate: () => p, resize: (o: { width: number }) => ((side = o.width), p), webp: (o: { quality: number }) => ((quality = o.quality), p), + metadata: async () => dims, toFile: jest.fn(), toBuffer: async () => { calls.push({ side, quality }); @@ -135,6 +140,17 @@ describe('ImageVariantService', () => { const heic = await svc.compressUpload(Buffer.alloc(20 * KB), 'image/heic', 'photo.heic'); expect(heic).toMatchObject({ ext: '.webp' }); }); + + it('downscales a small file with huge dimensions', async () => { + const svc = new ImageVariantService(); + // 13 KB on disk, 6400×6400 when decoded: every thumbnail render would + // have to decode 41 MP first. + const calls = fakeSharp(svc, () => 40 * KB, { width: 6400, height: 6400 }); + + const out = await svc.compressUpload(Buffer.alloc(13 * KB), 'image/png', 'flat.png'); + expect(calls.length).toBeGreaterThan(0); + expect(out).toMatchObject({ ext: '.webp' }); + }); }); it('falls back to the original when a render fails', async () => { diff --git a/apps/api/src/modules/admin-uploads/image-variants.service.ts b/apps/api/src/modules/admin-uploads/image-variants.service.ts index 481a1cf5..c792f7b7 100644 --- a/apps/api/src/modules/admin-uploads/image-variants.service.ts +++ b/apps/api/src/modules/admin-uploads/image-variants.service.ts @@ -63,6 +63,7 @@ interface SharpPipeline { withoutEnlargement: boolean; }): SharpPipeline; webp(opts: { quality: number }): SharpPipeline; + metadata(): Promise<{ width?: number; height?: number }>; toFile(path: string): Promise; toBuffer(): Promise; } @@ -146,10 +147,26 @@ export class ImageVariantService { // Small uploads are kept as sent — except formats browsers cannot paint, // which are always converted so the card thumbnail is never broken. const mustConvert = BROWSER_UNSAFE_MIME.has(mimeType); - if (buffer.length <= ORIGINAL_TARGET_BYTES && !mustConvert) return null; const sharp = this.loadSharp(); if (!sharp) return null; + let oversized = false; + if (!mustConvert && buffer.length <= ORIGINAL_TARGET_BYTES) { + // Bytes are not size: a flat 8000×8000 PNG can be 13 KB. Keeping one + // means every thumbnail render has to decode 64 MP first, which on a + // small server outlives nginx's timeout — the card showed a broken + // image until the variant finally finished. Downscale those too. + try { + const meta = await sharp(buffer, { failOn: 'none', limitInputPixels: MAX_INPUT_PIXELS }).metadata(); + const side = Math.max(meta.width ?? 0, meta.height ?? 0); + if (side <= ORIGINAL_ATTEMPTS[0].side) return null; + oversized = true; + } catch (err) { + this.logger.warn(`metadata failed for ${filename}: ${(err as Error).message}`); + return null; + } + } + let smallest: Buffer | null = null; try { for (const { side, quality } of ORIGINAL_ATTEMPTS) { @@ -167,8 +184,10 @@ export class ImageVariantService { } if (!smallest) return null; - // A conversion is mandatory for browser-unsafe formats even if larger. - if (!mustConvert && smallest.length >= buffer.length) return null; + // A conversion is mandatory for browser-unsafe formats even if larger, and + // a huge-dimension source is worth a few extra KB: every later resize of + // it stays cheap. + if (!mustConvert && !oversized && smallest.length >= buffer.length) return null; if (smallest.length > ORIGINAL_CEILING_BYTES) { this.logger.warn(`${filename} is still ${smallest.length} bytes after compression`); }