Files
0pt/lib/health-checks.ts
T
admin a88ad04867
Security Scan (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / security (push) Successful in 21s
CI (SIAX Cloud) / quality (push) Successful in 41s
CI (SIAX Cloud) / security (pull_request) Successful in 22s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 21s
CI (SIAX Cloud) / quality (pull_request) Successful in 41s
fix(health): report real per-dependency status instead of hardcoded ok:true
BACKLOG P0-3: /api/health only ever checked *presence* of DATABASE_URL/
REDIS_URL and always returned ok:true regardless of whether anything was
reachable -- ARCHITECTURE.md's own words, "an uptime monitor watching HTTP
200 would show green for a dying instance".

lib/health-checks.ts adds real dependency probes:
  - db: a live `select 1` round trip (not just DATABASE_URL presence)
  - engine: a real HTTP call to the FastAPI engine's own GET /health
  - stripe: Stripe's documented lightweight balance.retrieve() liveness call
  - queue: honestly reports "not_integrated" when REDIS_URL is set but
    unused -- no Redis client is wired anywhere in this repo, so reporting
    "ok" would fabricate a check that doesn't exist

/api/health stays a liveness check (always 200 while the process can
respond; the body's `ok` field is the honest signal). New GET /api/ready
fails closed with 503 when the load-bearing dependency (db) isn't both
configured and reachable -- the "no /ready route" gap.

contracts/openapi.yaml, docs/architecture/ARCHITECTURE.md, and docs/slo.md
updated to match. 17 new unit tests (dependency-injected fakes, no real
network/DB) + 5 route-level tests.
2026-08-11 13:49:23 +02:00

175 lines
6.8 KiB
TypeScript

// Dependency health probes shared by GET /api/health (liveness) and
// GET /api/ready (readiness). See docs/architecture/ARCHITECTURE.md
// "Hälsokontroll" and BACKLOG P0-3 for the finding this fixes: the old
// /api/health handler only ever checked *presence* of an env var and
// hardcoded `ok: true` regardless of whether anything was actually
// reachable -- "an uptime monitor watching HTTP 200 would show green for a
// dying instance". Each check below returns one of four honest states:
//
// "ok" -- configured AND a live round trip succeeded.
// "error" -- configured but the round trip failed (bad creds,
// host unreachable, timeout, ...). detail carries the
// underlying error message.
// "not_configured" -- no env var set. Not a failure by itself (0pt is
// designed to build/boot with everything unset).
// "not_integrated" -- env var IS set, but no client code in this repo
// actually uses it (currently only REDIS_URL/queue --
// see .env.example). Reporting "ok" here would be a
// fabricated check; reporting "not_configured" would
// hide that a value was provided. This is its own
// honest state rather than either of those two.
import { dbUrl, getSql } from "./db";
import { getStripe } from "./stripe";
import { hasEngine } from "./engine";
export type DepStatus = "ok" | "error" | "not_configured" | "not_integrated";
export interface DepResult {
status: DepStatus;
detail?: string;
latencyMs?: number;
}
export const DEFAULT_TIMEOUT_MS = 2000;
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
promise.then(
(v) => {
clearTimeout(timer);
resolve(v);
},
(e) => {
clearTimeout(timer);
reject(e);
},
);
});
}
// Minimal shape of the one call site needs from the postgres client --
// matches `postgres`'s tagged-template callable, but kept narrow so tests
// can inject a fake without constructing a real `postgres.Sql`.
export type SqlPing = (strings: TemplateStringsArray, ...values: unknown[]) => Promise<unknown>;
/**
* Postgres reachability. `select 1` is the standard zero-cost liveness query
* -- it never touches application tables, so it can't fail on schema drift.
*/
export async function checkDatabase(
sqlClient: SqlPing | null = getSql() as unknown as SqlPing | null,
timeoutMs: number = DEFAULT_TIMEOUT_MS,
): Promise<DepResult> {
if (!dbUrl() || !sqlClient) return { status: "not_configured" };
const start = Date.now();
try {
await withTimeout(sqlClient`select 1`, timeoutMs, "database ping");
return { status: "ok", latencyMs: Date.now() - start };
} catch (err) {
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
}
}
/**
* FastAPI data engine (services/api) reachability via its own `GET /health`
* (services/api/orchestrator/main.py). Uses a real HTTP round trip, not just
* `hasEngine()` presence -- ENGINE_URL pointing at a dead host used to read
* as healthy.
*/
export async function checkEngine(
fetchImpl: typeof fetch = fetch,
timeoutMs: number = DEFAULT_TIMEOUT_MS,
): Promise<DepResult> {
if (!hasEngine()) return { status: "not_configured" };
const base = process.env.ENGINE_URL as string;
const start = Date.now();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetchImpl(`${base}/health`, {
signal: controller.signal,
cache: "no-store",
headers: { "X-Internal-Token": process.env.INTERNAL_TOKEN ?? "" },
});
if (!res.ok) {
return { status: "error", detail: `HTTP ${res.status}`, latencyMs: Date.now() - start };
}
return { status: "ok", latencyMs: Date.now() - start };
} catch (err) {
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
} finally {
clearTimeout(timer);
}
}
// Minimal shape of the one Stripe call this needs -- matches
// `Stripe#balance.retrieve`, kept narrow so tests can inject a fake instead
// of constructing a real Stripe client.
export interface StripeBalanceClient {
balance: { retrieve(): Promise<unknown> };
}
/**
* Stripe reachability. `balance.retrieve()` is Stripe's documented
* lightweight "is this key valid and can I reach the API" call -- it makes
* one real API round trip (catching e.g. a revoked/placeholder key) without
* mutating anything or touching a specific resource.
*/
export async function checkStripe(
client: StripeBalanceClient | null = getStripe() as unknown as StripeBalanceClient | null,
timeoutMs: number = DEFAULT_TIMEOUT_MS,
): Promise<DepResult> {
if (!client) return { status: "not_configured" };
const start = Date.now();
try {
await withTimeout(client.balance.retrieve(), timeoutMs, "stripe balance.retrieve");
return { status: "ok", latencyMs: Date.now() - start };
} catch (err) {
return { status: "error", detail: errMessage(err), latencyMs: Date.now() - start };
}
}
/**
* Redis/queue: presence-only, honestly. No queue client library is a
* dependency of this package (grep-verified against package.json) and no
* code path in this repo reads REDIS_URL to open a connection -- so there is
* no real check to run. Reporting "ok" would fabricate a probe that doesn't
* exist; this reports "not_integrated" instead of silently upgrading to a
* pretend pass.
*/
export function checkQueue(): DepResult {
return { status: process.env.REDIS_URL ? "not_integrated" : "not_configured" };
}
export interface DependencyResults {
db: DepResult;
engine: DepResult;
stripe: DepResult;
queue: DepResult;
}
export async function checkAllDependencies(): Promise<DependencyResults> {
const [db, engine, stripe] = await Promise.all([checkDatabase(), checkEngine(), checkStripe()]);
return { db, engine, stripe, queue: checkQueue() };
}
/** True when any dependency that IS configured/integrated is broken. */
export function hasDegradedDependency(deps: DependencyResults): boolean {
return Object.values(deps).some((d) => d.status === "error");
}
/**
* Readiness (unlike liveness) treats "not configured" for the deps this app
* cannot serve real traffic without as not-ready too. Only `db` is load-bearing
* today -- engine/stripe/queue are optional integrations the app is designed
* to run without (see .env.example).
*/
export function isReady(deps: DependencyResults): boolean {
return deps.db.status === "ok";
}