From 653e5ca050b9aef06e4367663e03174507156ed9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Sun, 9 Aug 2026 21:45:59 +0200 Subject: [PATCH] fix: manage immich request lifecycles --- src/modules/immich/client.test.ts | 138 ++++++++++++++++++++++ src/modules/immich/client.ts | 183 +++++++++++++++++++++++++----- 2 files changed, 295 insertions(+), 26 deletions(-) diff --git a/src/modules/immich/client.test.ts b/src/modules/immich/client.test.ts index c21de7b..b76e3cc 100644 --- a/src/modules/immich/client.test.ts +++ b/src/modules/immich/client.test.ts @@ -18,6 +18,14 @@ beforeEach(() => server.listen({ onUnhandledRequest: "error" })); afterEach(() => server.resetHandlers()); afterEach(() => server.close()); +function wait(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); +} + +function albumsResponse(body: ReadableStream | string): Response { + return new Response(body, { headers: { "content-type": "application/json" } }); +} + test("lists albums through the documented API with server-side authentication", async () => { server.use( http.get(`${baseUrl}/api/albums`, ({ request }) => { @@ -109,6 +117,136 @@ test("maps an aborted timeout signal to IMMICH_TIMEOUT", async () => { await expect(timedOutClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_TIMEOUT" }); }); +test("cleans up the request timeout after a successful JSON response", async () => { + let requestSignal: AbortSignal | undefined; + const fastClient = createImmichClient({ + baseUrl, + apiKey, + timeoutMs: 5, + fetch: async (_input, init) => { + requestSignal = init?.signal ?? undefined; + return albumsResponse(JSON.stringify([immichAlbum])); + }, + }); + + await expect(fastClient.listAlbums()).resolves.toEqual([immichAlbum]); + await wait(20); + expect(requestSignal?.aborted).toBe(false); +}); + +test("clears the request timeout after binary headers so a long stream continues", async () => { + let sourceController: ReadableStreamDefaultController | undefined; + let requestAborts = 0; + const streamingClient = createImmichClient({ + baseUrl, + apiKey, + timeoutMs: 5, + fetch: async (_input, init) => { + const body = new ReadableStream({ + start(controller) { + sourceController = controller; + init?.signal?.addEventListener("abort", () => { + requestAborts += 1; + controller.error(init.signal?.reason); + }); + }, + }); + return new Response(body, { headers: { "content-type": "image/jpeg" } }); + }, + }); + + const original = await streamingClient.getOriginal("asset-1"); + await wait(20); + sourceController?.enqueue(new Uint8Array([1, 2, 3])); + sourceController?.close(); + + await expect(new Response(original.body).arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer); + expect(requestAborts).toBe(0); +}); + +test("maps a caller abort during a binary stream to IMMICH_ABORTED", async () => { + const caller = new AbortController(); + const streamingClient = createImmichClient({ + baseUrl, + apiKey, + fetch: async () => { + const body = new ReadableStream(); + return new Response(body, { headers: { "content-type": "image/jpeg" } }); + }, + }); + + const original = await streamingClient.getOriginal("asset-1", caller.signal); + const read = original.body.getReader().read(); + caller.abort(); + + await expect(read).rejects.toMatchObject({ code: "IMMICH_ABORTED" }); +}); + +test("preserves abort, timeout, and network failures while reading JSON bodies", async () => { + const caller = new AbortController(); + const abortedClient = createImmichClient({ + baseUrl, + apiKey, + fetch: async (_input, init) => + albumsResponse( + new ReadableStream({ + start(controller) { + init?.signal?.addEventListener("abort", () => controller.error(init.signal?.reason)); + }, + }), + ), + }); + const aborted = abortedClient.listAlbums(caller.signal); + await Promise.resolve(); + caller.abort(); + await expect(aborted).rejects.toMatchObject({ code: "IMMICH_ABORTED" }); + + const timedOutClient = createImmichClient({ + baseUrl, + apiKey, + timeoutMs: 5, + fetch: async (_input, init) => + albumsResponse( + new ReadableStream({ + start(controller) { + init?.signal?.addEventListener("abort", () => controller.error(init.signal?.reason)); + }, + }), + ), + }); + await expect(timedOutClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_TIMEOUT" }); + + const unavailableClient = createImmichClient({ + baseUrl, + apiKey, + fetch: async () => + albumsResponse( + new ReadableStream({ + start(controller) { + queueMicrotask(() => controller.error(new TypeError("connection lost"))); + }, + }), + ), + }); + await expect(unavailableClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_UNAVAILABLE" }); +}); + +test("maps malformed JSON and schema failures to IMMICH_INVALID_RESPONSE", async () => { + const malformedJsonClient = createImmichClient({ + baseUrl, + apiKey, + fetch: async () => albumsResponse("{"), + }); + await expect(malformedJsonClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_INVALID_RESPONSE" }); + + const malformedSchemaClient = createImmichClient({ + baseUrl, + apiKey, + fetch: async () => albumsResponse(JSON.stringify([{ id: "missing-required-fields" }])), + }); + await expect(malformedSchemaClient.listAlbums()).rejects.toMatchObject({ code: "IMMICH_INVALID_RESPONSE" }); +}); + test("streams binary endpoints without buffering and preserves safe response metadata", async () => { const bytes = new Uint8Array([1, 2, 3]); server.use( diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts index 50a182f..58628c1 100644 --- a/src/modules/immich/client.ts +++ b/src/modules/immich/client.ts @@ -8,7 +8,6 @@ import { ImmichClientError, type ImmichErrorCode } from "./errors"; import type { ImmichAlbum, ImmichAlbumSummary, - ImmichAsset, ImmichBinary, ImmichClient, ImmichSearchPage, @@ -57,6 +56,13 @@ const metadataSearchSchema = z type FetchLike = typeof globalThis.fetch; +type RequestLifecycle = { + signal: AbortSignal; + cleanup(): void; + clearTimeout(): void; + failureCode(): Extract | undefined; +}; + export type CreateImmichClientOptions = { baseUrl?: string; apiKey?: string; @@ -105,6 +111,51 @@ function contentLength(response: Response): number | null { return Number.isSafeInteger(length) ? length : null; } +function createRequestLifecycle(callerSignal: AbortSignal | undefined, timeoutMs: number): RequestLifecycle { + const controller = new AbortController(); + let timedOut = false; + let timeoutId: ReturnType | undefined = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + + const abortFromCaller = () => controller.abort(); + if (callerSignal?.aborted) { + abortFromCaller(); + } else { + callerSignal?.addEventListener("abort", abortFromCaller, { once: true }); + } + + function clearTimeout() { + if (timeoutId !== undefined) { + globalThis.clearTimeout(timeoutId); + timeoutId = undefined; + } + } + + return { + signal: controller.signal, + cleanup() { + clearTimeout(); + callerSignal?.removeEventListener("abort", abortFromCaller); + }, + clearTimeout, + failureCode() { + if (timedOut) { + return "IMMICH_TIMEOUT"; + } + if (callerSignal?.aborted) { + return "IMMICH_ABORTED"; + } + return undefined; + }, + }; +} + +function failureError(lifecycle: RequestLifecycle): ImmichClientError { + return new ImmichClientError(lifecycle.failureCode() ?? "IMMICH_UNAVAILABLE"); +} + export function createImmichClient({ baseUrl = env.IMMICH_BASE_URL, apiKey = env.IMMICH_API_KEY, @@ -113,35 +164,35 @@ export function createImmichClient({ }: CreateImmichClientOptions = {}): ImmichClient { const apiBaseUrl = `${baseUrl.replace(/\/+$/, "")}/api`; - async function request(path: string, init: RequestInit, signal?: AbortSignal): Promise { - const timeoutSignal = AbortSignal.timeout(timeoutMs); - const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal; + async function request( + path: string, + init: RequestInit, + signal?: AbortSignal, + ): Promise<{ response: Response; lifecycle: RequestLifecycle }> { + const lifecycle = createRequestLifecycle(signal, timeoutMs); - let response: Response; try { - response = await (fetchImpl ?? globalThis.fetch)(`${apiBaseUrl}${path}`, { + const response = await (fetchImpl ?? globalThis.fetch)(`${apiBaseUrl}${path}`, { ...init, headers: { "x-api-key": apiKey, ...init.headers, }, - signal: requestSignal, + signal: lifecycle.signal, }); - } catch { - if (timeoutSignal.aborted) { - throw new ImmichClientError("IMMICH_TIMEOUT"); - } - if (signal?.aborted) { - throw new ImmichClientError("IMMICH_ABORTED"); - } - throw new ImmichClientError("IMMICH_UNAVAILABLE"); - } - if (!response.ok) { - throw errorForStatus(response.status); - } + if (!response.ok) { + throw errorForStatus(response.status); + } - return response; + return { response, lifecycle }; + } catch (error) { + lifecycle.cleanup(); + if (error instanceof ImmichClientError) { + throw error; + } + throw failureError(lifecycle); + } } async function requestJson( @@ -150,23 +201,103 @@ export function createImmichClient({ schema: z.ZodType, signal?: AbortSignal, ): Promise { - const response = await request(path, init, signal); + const { response, lifecycle } = await request(path, init, signal); try { - return schema.parse(await response.json()); - } catch { - throw new ImmichClientError("IMMICH_INVALID_RESPONSE"); + let body: unknown; + try { + body = await response.json(); + } catch (error) { + const code = lifecycle.failureCode(); + if (code) { + throw new ImmichClientError(code); + } + if (error instanceof SyntaxError) { + throw new ImmichClientError("IMMICH_INVALID_RESPONSE"); + } + throw new ImmichClientError("IMMICH_UNAVAILABLE"); + } + + try { + return schema.parse(body); + } catch (error) { + if (error instanceof z.ZodError) { + throw new ImmichClientError("IMMICH_INVALID_RESPONSE"); + } + throw error; + } + } finally { + lifecycle.cleanup(); } } async function requestBinary(path: string, signal?: AbortSignal): Promise { - const response = await request(path, { method: "GET" }, signal); + const { response, lifecycle } = await request(path, { method: "GET" }, signal); if (!response.body) { + lifecycle.cleanup(); throw new ImmichClientError("IMMICH_INVALID_RESPONSE"); } + lifecycle.clearTimeout(); + const reader = response.body.getReader(); + let completed = false; + let abortStream: (() => void) | undefined; + const finish = () => { + if (completed) { + return; + } + completed = true; + if (abortStream) { + lifecycle.signal.removeEventListener("abort", abortStream); + } + lifecycle.cleanup(); + }; + + const body = new ReadableStream({ + start(controller) { + abortStream = () => { + if (completed) { + return; + } + const error = failureError(lifecycle); + finish(); + void reader.cancel(error); + controller.error(error); + }; + lifecycle.signal.addEventListener("abort", abortStream, { once: true }); + if (lifecycle.signal.aborted) { + abortStream(); + } + }, + async pull(controller) { + if (completed) { + return; + } + try { + const { done, value } = await reader.read(); + if (done) { + finish(); + controller.close(); + return; + } + controller.enqueue(value); + } catch { + if (completed) { + return; + } + const error = failureError(lifecycle); + finish(); + controller.error(error); + } + }, + cancel(reason) { + finish(); + return reader.cancel(reason); + }, + }); + return { - body: response.body, + body, contentType: response.headers.get("content-type") ?? "application/octet-stream", contentLength: contentLength(response), filename: responseFilename(response, "asset"),