fix: manage immich request lifecycles

This commit is contained in:
Leon Tonhäuser committed 2026-08-09 21:45:59 +02:00
1 parent a5973bfaf1
commit 653e5ca050
2 files changed
+291 -22

No files matched your search

+138
View File
@@ -18,6 +18,14 @@ beforeEach(() => server.listen({ onUnhandledRequest: "error" }));
afterEach(() => server.resetHandlers());
afterEach(() => server.close());
function wait(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function albumsResponse(body: ReadableStream<Uint8Array> | 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<Uint8Array> | undefined;
let requestAborts = 0;
const streamingClient = createImmichClient({
baseUrl,
apiKey,
timeoutMs: 5,
fetch: async (_input, init) => {
const body = new ReadableStream<Uint8Array>({
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<Uint8Array>();
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(
+153 -22
View File
@@ -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<ImmichErrorCode, "IMMICH_ABORTED" | "IMMICH_TIMEOUT"> | 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<typeof setTimeout> | 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<Response> {
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);
}
return response;
return { response, lifecycle };
} catch (error) {
lifecycle.cleanup();
if (error instanceof ImmichClientError) {
throw error;
}
throw failureError(lifecycle);
}
}
async function requestJson<T>(
@@ -150,23 +201,103 @@ export function createImmichClient({
schema: z.ZodType<T>,
signal?: AbortSignal,
): Promise<T> {
const response = await request(path, init, signal);
const { response, lifecycle } = await request(path, init, signal);
try {
return schema.parse(await response.json());
} catch {
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<ImmichBinary> {
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<Uint8Array>({
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"),