From 7065e184549b47ac041530de2c1d08a806f108fd Mon Sep 17 00:00:00 2001 From: Maurice Date: Mon, 23 Nov 2026 17:25:04 +0100 Subject: [PATCH] fix(memories): answer 503 while a large public copy is still being made A request now waits at most ten seconds for the location-free copy and is otherwise told to come back with Retry-After while the copy goes on being made, so a long video no longer holds the first request past a reverse proxy's timeout. Nothing but the copy is ever sent. --- .../nest/journey/journey-public.controller.ts | 13 +++++- .../nest/memories/photo-resolver.service.ts | 8 +++- .../src/nest/memories/public-media.service.ts | 45 ++++++++++++++++++- server/src/nest/platform/platform.routes.ts | 18 +++++++- .../unit/nest/journey.controller.test.ts | 20 ++++++++- .../memories/public-media.service.test.ts | 26 ++++++++++- .../unit/nest/photo-resolver.service.test.ts | 19 +++++++- .../unit/nest/platform.controller.test.ts | 24 +++++++++- 8 files changed, 161 insertions(+), 12 deletions(-) diff --git a/server/src/nest/journey/journey-public.controller.ts b/server/src/nest/journey/journey-public.controller.ts index 79805fc49..27ca82d28 100644 --- a/server/src/nest/journey/journey-public.controller.ts +++ b/server/src/nest/journey/journey-public.controller.ts @@ -4,7 +4,12 @@ import { RequireAddon } from '../addons/require-addon.decorator'; import { Public } from '../auth-core/public.decorator'; import { ResponseContract } from '../common/response-contract'; import { rowId } from '../common/row-id.pipe'; -import { PublicMediaService } from '../memories/public-media.service'; +import { + answerRenditionPending, + pendingOrNone, + PublicMediaService, + RENDITION_PENDING, +} from '../memories/public-media.service'; import { StorageService } from '../storage/storage.service'; import { JourneyService } from './journey.service'; import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common'; @@ -108,7 +113,11 @@ export class JourneyPublicController { } // The copy without GPS and place tags, never the stored original; a file // that cannot be cleaned is not served at all. - const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null); + const rendition = await this.publicMedia.renditionFor('journey', name).catch(pendingOrNone); + if (rendition === RENDITION_PENDING) { + answerRenditionPending(res); + return; + } if (!rendition) { throw new HttpException({ error: 'Not found' }, 404); } diff --git a/server/src/nest/memories/photo-resolver.service.ts b/server/src/nest/memories/photo-resolver.service.ts index 6ee1be88b..d84e68fae 100644 --- a/server/src/nest/memories/photo-resolver.service.ts +++ b/server/src/nest/memories/photo-resolver.service.ts @@ -5,7 +5,7 @@ import { StorageService } from '../storage/storage.service'; import { fail, success, type AssetInfo, type ServiceResult } from './memories.helpers'; import type { PhotoAssetRef } from './photo-provider'; import { PhotoProviderRegistry } from './photo-provider.registry'; -import { PublicMediaService } from './public-media.service'; +import { answerRenditionPending, pendingOrNone, PublicMediaService, RENDITION_PENDING } from './public-media.service'; import { ThumbnailService } from './thumbnail.service'; import { TrekPhotoCacheService } from './trek-photo-cache.service'; import { Injectable } from '@nestjs/common'; @@ -128,7 +128,11 @@ export class PhotoResolverService { if (!name || !(await this.storage.exists('journey', name).catch(() => false))) return false; let served = name; if (audience === 'public' && !name.startsWith('thumbs/')) { - const rendition = await this.publicMedia.renditionFor('journey', name).catch(() => null); + const rendition = await this.publicMedia.renditionFor('journey', name).catch(pendingOrNone); + if (rendition === RENDITION_PENDING) { + answerRenditionPending(res); + return true; + } if (!rendition) return false; served = rendition; } diff --git a/server/src/nest/memories/public-media.service.ts b/server/src/nest/memories/public-media.service.ts index 3288dd68a..95668c912 100644 --- a/server/src/nest/memories/public-media.service.ts +++ b/server/src/nest/memories/public-media.service.ts @@ -9,6 +9,7 @@ import { redactLocationInFile } from './media-redact'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; +import type { Response } from 'express'; import { Jimp } from 'jimp'; import crypto from 'node:crypto'; import fsPromises from 'node:fs/promises'; @@ -23,6 +24,45 @@ const RENDITION_CATEGORIES: readonly ServedCategory[] = ['avatars', 'covers', 'j /** Image types Jimp both decodes and writes; it writes no metadata, so a re-encoded copy carries no location. */ const REENCODABLE_EXTENSIONS = new Set(['.bmp', '.gif', '.jpeg', '.jpg', '.png', '.tif', '.tiff']); +/** + * How long a request waits for a copy being made. A large video takes longer + * than a reverse proxy waits for the first byte, so past this the request is + * told to come back while the copy goes on being made. + */ +const RENDITION_WAIT_MS = 10_000; + +/** The copy of a name is still being made; the request is answered with {@link answerRenditionPending}. */ +export class RenditionPendingError extends Error { + constructor() { + super('The public copy is still being made'); + } +} + +/** What {@link pendingOrNone} reads a copy still being made as. */ +export const RENDITION_PENDING = Symbol('rendition pending'); + +/** A refusal of `renditionFor` as a request reads it: RENDITION_PENDING while the copy is being made, else no copy. */ +export function pendingOrNone(err: unknown): typeof RENDITION_PENDING | null { + return err instanceof RenditionPendingError ? RENDITION_PENDING : null; +} + +/** Answers a request whose copy is still being made: 503, come back in a while, nothing cached. */ +export function answerRenditionPending(res: Response): void { + res.set('Retry-After', String(RENDITION_WAIT_MS / 1000)); + res.set('Cache-Control', 'no-store'); + res.status(503).json({ error: 'The file is being prepared, try again shortly' }); +} + +/** `pending` if it settles within RENDITION_WAIT_MS, else a RenditionPendingError while it goes on. */ +function withinWait(pending: Promise): Promise { + let timer: NodeJS.Timeout | undefined; + const late = new Promise((_, reject) => { + timer = setTimeout(() => reject(new RenditionPendingError()), RENDITION_WAIT_MS); + timer.unref(); + }); + return Promise.race([pending, late]).finally(() => clearTimeout(timer)); +} + /** How many copies the sweep checks at once, so a large instance does not open thousands of handles. */ const SWEEP_BATCH = 32; @@ -59,7 +99,8 @@ export class PublicMediaService { * can be made safely (a movie or format that can be neither cleaned nor * re-encoded): the caller then serves nothing rather than the original. A * missing source throws StorageNotFoundError, an invalid name - * StorageInvalidKeyError. + * StorageInvalidKeyError, and a copy not made within RENDITION_WAIT_MS + * RenditionPendingError (it is still made, for a later request). */ async renditionFor(category: ServedCategory, name: string): Promise { if (name.startsWith(RENDITION_PREFIX)) return null; @@ -77,7 +118,7 @@ export class PublicMediaService { pending = this.build(category, name, rendition).finally(() => this.inFlight.delete(key)); this.inFlight.set(key, pending); } - return pending; + return withinWait(pending); } /** diff --git a/server/src/nest/platform/platform.routes.ts b/server/src/nest/platform/platform.routes.ts index 53523dbda..2fd8a2400 100644 --- a/server/src/nest/platform/platform.routes.ts +++ b/server/src/nest/platform/platform.routes.ts @@ -9,7 +9,13 @@ import type { UserSessionsRepository } from '../../db/repositories/UserSessions. import type { UsersRepository } from '../../db/repositories/Users.repository'; import { verifyJwtAndLoadUser } from '../auth-core/jwt-verify'; import { withRequestContext } from '../database/request-context'; -import type { PublicMediaService } from '../memories/public-media.service'; +import { + answerRenditionPending, + pendingOrNone, + RENDITION_PENDING, + RenditionPendingError, + type PublicMediaService, +} from '../memories/public-media.service'; import { StorageService } from '../storage/storage.service'; import { StorageInvalidKeyError, StorageNotFoundError, type StorageCategory } from '../storage/storage.types'; import { precompressedStatic } from './precompressed-static'; @@ -116,6 +122,10 @@ export function storageStaticHandler( return resolveServedName(name, serving) .then((served) => (served === null ? next() : storage.sendToResponse(category, served, res))) .catch((err: unknown) => { + if (err instanceof RenditionPendingError) { + answerRenditionPending(res); + return; + } // MISS contract: unknown object, invalid key ('' at the mount root, // '..', dot segments, control chars) → Nest 404 envelope. if (err instanceof StorageNotFoundError || err instanceof StorageInvalidKeyError) { @@ -202,7 +212,11 @@ async function servePhoto( // A share link is no account: it gets the copy without the location, and a // photo that cannot be cleaned is not sent at all (fail closed, also when no // PublicMediaService was wired). - const rendition = publicMedia ? await publicMedia.renditionFor('photos', safeName).catch(() => null) : null; + const rendition = publicMedia ? await publicMedia.renditionFor('photos', safeName).catch(pendingOrNone) : null; + if (rendition === RENDITION_PENDING) { + answerRenditionPending(res); + return; + } if (!rendition) { res.status(404).send('Not found'); return; diff --git a/server/tests/unit/nest/journey.controller.test.ts b/server/tests/unit/nest/journey.controller.test.ts index d10bcb6cf..1c3420269 100644 --- a/server/tests/unit/nest/journey.controller.test.ts +++ b/server/tests/unit/nest/journey.controller.test.ts @@ -8,7 +8,7 @@ import type { JourneyPhotoLinksService } from '../../../src/nest/journey/journey import { JourneyPublicController } from '../../../src/nest/journey/journey-public.controller'; import { JourneyController } from '../../../src/nest/journey/journey.controller'; import type { JourneyService } from '../../../src/nest/journey/journey.service'; -import type { PublicMediaService } from '../../../src/nest/memories/public-media.service'; +import { RenditionPendingError, type PublicMediaService } from '../../../src/nest/memories/public-media.service'; import type { StorageReleaseService } from '../../../src/nest/storage/storage-release.service'; import type { StorageService } from '../../../src/nest/storage/storage.service'; import type { User } from '../../../src/types'; @@ -1345,6 +1345,24 @@ describe('JourneyPublicController', () => { expect(storageSendToResponse).toHaveBeenCalledWith('journey', 'public/photo.jpg', res); }); + it('legacy photo proxy: a local file whose copy is still being made is a 503 to come back to', async () => { + storageExists.mockResolvedValue(true); + renditionFor.mockRejectedValueOnce(new RenditionPendingError()); + const json = vi.fn(); + const res = { set: vi.fn(), status: vi.fn(() => ({ json })) } as unknown as Response; + const s = svc({ validateShareTokenForAsset: vi.fn().mockReturnValue({ ownerId: 5 }) } as Partial); + await new JourneyPublicController(s, storageStub, publicMediaStub).legacyPhoto( + 'tok', + 'local', + 'clip.mp4', + 'original', + res, + ); + expect(res.status).toHaveBeenCalledWith(503); + expect(res.set).toHaveBeenCalledWith('Retry-After', '10'); + expect(storageSendToResponse).not.toHaveBeenCalled(); + }); + it('legacy photo proxy: a local file that cannot be cleaned is a 404, not the original', async () => { storageExists.mockResolvedValue(true); renditionFor.mockResolvedValueOnce(null); diff --git a/server/tests/unit/nest/memories/public-media.service.test.ts b/server/tests/unit/nest/memories/public-media.service.test.ts index 05d1ddee0..92938a7f5 100644 --- a/server/tests/unit/nest/memories/public-media.service.test.ts +++ b/server/tests/unit/nest/memories/public-media.service.test.ts @@ -7,7 +7,7 @@ */ import { Journeys } from '../../../../src/db/entities/Journeys.entity'; import { TrekPhotos } from '../../../../src/db/entities/TrekPhotos.entity'; -import { PublicMediaService } from '../../../../src/nest/memories/public-media.service'; +import { PublicMediaService, RenditionPendingError } from '../../../../src/nest/memories/public-media.service'; import { StorageService } from '../../../../src/nest/storage/storage.service'; import { StorageNotFoundError } from '../../../../src/nest/storage/storage.types'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; @@ -115,6 +115,30 @@ describe('renditionFor', () => { expect(storage.put).toHaveBeenCalledTimes(1); }); + it('PMEDIA-006: a copy that takes longer than a request waits is refused as pending and finished for the next one', async () => { + write('journey', 'long.jpg', phonePhoto()); + let release = () => {}; + const held = new Promise((resolve) => (release = resolve)); + storage.withLocalFile.mockImplementationOnce(async (category, name, fn) => { + await held; + return fn(at(category, name)); + }); + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); + try { + const first = expect(service.renditionFor('journey', 'long.jpg')).rejects.toBeInstanceOf(RenditionPendingError); + await vi.advanceTimersByTimeAsync(10_000); + await first; + } finally { + vi.useRealTimers(); + } + expect(storage.put).not.toHaveBeenCalled(); + + release(); + expect(await service.renditionFor('journey', 'long.jpg')).toBe('public/long.jpg'); + expect(storage.put).toHaveBeenCalledTimes(1); + expect(await exifr.gps(fs.readFileSync(at('journey', 'public/long.jpg')))).toBeUndefined(); + }); + it('PMEDIA-003: refuses what it can neither clean nor re-encode, a copy by its own name, and a source that is gone', async () => { write('photos', 'c.bmp', Buffer.from(`BM${'x'.repeat(40)}`)); expect(await service.renditionFor('photos', 'c.bmp')).toBeNull(); diff --git a/server/tests/unit/nest/photo-resolver.service.test.ts b/server/tests/unit/nest/photo-resolver.service.test.ts index 0de48538d..2d44f0097 100644 --- a/server/tests/unit/nest/photo-resolver.service.test.ts +++ b/server/tests/unit/nest/photo-resolver.service.test.ts @@ -18,7 +18,7 @@ import { PhotoProviderRegistry } from '../../../src/nest/memories/photo-provider import { PhotoResolverService } from '../../../src/nest/memories/photo-resolver.service'; import { ImmichPhotoProvider } from '../../../src/nest/memories/providers/immich.provider'; import { SynologyPhotoProvider } from '../../../src/nest/memories/providers/synology.provider'; -import type { PublicMediaService } from '../../../src/nest/memories/public-media.service'; +import { RenditionPendingError, type PublicMediaService } from '../../../src/nest/memories/public-media.service'; import type { SynologyService } from '../../../src/nest/memories/synology.service'; import type { ThumbnailService } from '../../../src/nest/memories/thumbnail.service'; import type { TrekPhotoCacheService } from '../../../src/nest/memories/trek-photo-cache.service'; @@ -209,6 +209,23 @@ describe('streamPublicPhoto: what a share link gets', () => { expect(res.set).not.toHaveBeenCalled(); }); + it('RESOLVE-036: a copy still being made is a 503 to come back to, not the thumbnail or the stored file', async () => { + const id = await insertPhoto({ + provider: 'local', + file_path: 'journey/x.jpg', + thumbnail_path: 'journey/thumbs/h.jpg', + }); + storage.exists.mockResolvedValue(true); + publicMedia.renditionFor.mockRejectedValue(new RenditionPendingError()); + const res = makeRes(); + + await svc.streamPublicPhoto(res as never, 1, id, 'original'); + + expect(storage.sendToResponse).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(503); + expect(res.set).toHaveBeenCalledWith('Retry-After', '10'); + }); + it('RESOLVE-035: an immich original is asked for as the public rendition, and an owner still gets the original', async () => { const id = await insertPhoto({ provider: 'immich', asset_id: 'a1', owner_id: 5 }); const res = makeRes(); diff --git a/server/tests/unit/nest/platform.controller.test.ts b/server/tests/unit/nest/platform.controller.test.ts index 3f7dee995..ca4070514 100644 --- a/server/tests/unit/nest/platform.controller.test.ts +++ b/server/tests/unit/nest/platform.controller.test.ts @@ -1,6 +1,6 @@ import { Photos } from '../../../src/db/entities/Photos.entity'; import { ShareTokens } from '../../../src/db/entities/ShareTokens.entity'; -import type { PublicMediaService } from '../../../src/nest/memories/public-media.service'; +import { RenditionPendingError, type PublicMediaService } from '../../../src/nest/memories/public-media.service'; import { applyPlatformUploads, applyPlatformSpa, @@ -104,6 +104,10 @@ function makeRes() { this.headers[k] = v; return this; }), + set: vi.fn(function (this: typeof res, k: string, v: string) { + this.headers[k] = v; + return this; + }), }; return res; } @@ -398,6 +402,13 @@ describe('applyPlatformUploads', () => { const unwired = makeRes(); await photoHandler(null)(ask, unwired, next); expect(unwired.statusCode).toBe(404); + + renditionFor.mockRejectedValue(new RenditionPendingError()); + const pending = makeRes(); + await photoHandler()(ask, pending, next); + expect(pending.statusCode).toBe(503); + expect(pending.headers['Retry-After']).toBe('10'); + expect(h.sendToResponse).not.toHaveBeenCalledWith('photos', 'photo-unclean.jpg', pending); expect(h.sendToResponse).not.toHaveBeenCalled(); }); @@ -593,6 +604,17 @@ describe('applyPlatformUploads static mounts', () => { expect(renditionFor).toHaveBeenCalledTimes(1); }); + it('a copy still being made is a 503 to come back to, never the stored object', async () => { + renditionFor.mockRejectedValue(new RenditionPendingError()); + const next = vi.fn(); + const res = makeRes(); + await mount('/uploads/covers', publicMedia)({ method: 'GET', path: '/clip.mp4' }, res, next); + expect(res.statusCode).toBe(503); + expect(res.headers).toMatchObject({ 'Retry-After': '10', 'Cache-Control': 'no-store' }); + expect(next).not.toHaveBeenCalled(); + expect(h.sendToResponse).not.toHaveBeenCalled(); + }); + it('without PublicMediaService every mount serves nothing rather than the raw bytes', async () => { const mounts = ['/uploads/avatars', '/uploads/covers', '/uploads/journey', '/uploads/places']; const nexts = await Promise.all(