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
+295 -26

No files matched your search

+157 -26
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);
}
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 {
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<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"),