80 lines
2.1 KiB
TypeScript
80 lines
2.1 KiB
TypeScript
export type ServiceHealthCategory = "core" | "integration";
|
|
export type ServiceHealthStatus = "operational" | "unavailable";
|
|
|
|
export type ServiceHealthProbe = {
|
|
id: string;
|
|
label: string;
|
|
category: ServiceHealthCategory;
|
|
check: () => Promise<boolean>;
|
|
};
|
|
|
|
export type ServiceHealthSnapshot = {
|
|
checkedAt: string;
|
|
services: {
|
|
id: string;
|
|
label: string;
|
|
category: ServiceHealthCategory;
|
|
status: ServiceHealthStatus;
|
|
}[];
|
|
};
|
|
|
|
async function checkWithTimeout(check: () => Promise<boolean>, timeoutMs: number) {
|
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
|
|
try {
|
|
return await Promise.race([
|
|
check(),
|
|
new Promise<boolean>((resolve) => {
|
|
timeout = setTimeout(() => resolve(false), timeoutMs);
|
|
}),
|
|
]);
|
|
} catch {
|
|
return false;
|
|
} finally {
|
|
if (timeout) clearTimeout(timeout);
|
|
}
|
|
}
|
|
|
|
export async function collectServiceHealth(
|
|
probes: ServiceHealthProbe[],
|
|
options: { timeoutMs?: number; now?: () => Date } = {},
|
|
): Promise<ServiceHealthSnapshot> {
|
|
const timeoutMs = options.timeoutMs ?? 5_000;
|
|
const checkedAt = (options.now ?? (() => new Date()))().toISOString();
|
|
const services = await Promise.all(
|
|
probes.map(async ({ id, label, category, check }) => ({
|
|
id,
|
|
label,
|
|
category,
|
|
status: (await checkWithTimeout(check, timeoutMs))
|
|
? ("operational" as const)
|
|
: ("unavailable" as const),
|
|
})),
|
|
);
|
|
|
|
return { checkedAt, services };
|
|
}
|
|
|
|
export function createCachedHealthReader(
|
|
load: () => Promise<ServiceHealthSnapshot>,
|
|
options: { ttlMs?: number; now?: () => number } = {},
|
|
) {
|
|
const ttlMs = options.ttlMs ?? 60_000;
|
|
const now = options.now ?? Date.now;
|
|
let cached:
|
|
| { expiresAt: number; value: Promise<ServiceHealthSnapshot> }
|
|
| undefined;
|
|
|
|
return () => {
|
|
const currentTime = now();
|
|
if (cached && currentTime < cached.expiresAt) return cached.value;
|
|
|
|
const value = load();
|
|
cached = { expiresAt: currentTime + ttlMs, value };
|
|
void value.catch(() => {
|
|
if (cached?.value === value) cached = undefined;
|
|
});
|
|
return value;
|
|
};
|
|
}
|