Files
0pt/tests/lib/health-checks.test.ts
T
Claude 0062edbec3
CI (SIAX Cloud) / integration (push) Skipped
masterplan-lock / check (push) Successful in 6s
CI (SIAX Cloud) / security (push) Successful in 15s
masterplan-lock / check (pull_request) Successful in 4s
Security Scan (SIAX Cloud) / security (push) Successful in 27s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / quality (push) Successful in 45s
CI (SIAX Cloud) / integration (pull_request) Successful in 31s
CI (SIAX Cloud) / quality (pull_request) Successful in 40s
fix(readiness): /api/ready svarade 200 med en död motor i produktion
Mätt live 2026-09-25 mot produktionsdeployen (0pt.app / api.0pt.app,
container shxd6lepxuxfsjsp0ath3z1g-172514162615 på server6, uppe 17,9 h,
Docker-status "healthy" hela tiden):

    GET /api/health -> HTTP/1.1 200 OK
      {"ok":false,"service":"0pt-web","db":"ok","queue":"not_configured",
       "engine":"error","stripe":"not_configured",
       "detail":{"engine":"This operation was aborted"}}

    GET /api/ready  -> HTTP/1.1 200 OK
      {"ready":true,"service":"0pt-web","db":"ok","engine":"error",...}

ENGINE_URL pekade på http://0pt-engine:8000. Mätt inifrån containern:
`getent hosts 0pt-engine` ger ingen post, och det finns ingen sådan
container på någon av server5-11. Ett direktanrop mot motorn misslyckas
efter ~5 s (DNS). Datamotorn — 0pt:s hela produkt — var alltså BORTA, och
samtliga signaler ovanför den var gröna: Docker healthy, /api/health 200,
/api/ready 200.

`ok:false` i en 200-kropp är ingen signal. Ingenting i kedjan läser
kroppar; allt läser statuskoder och exitkoder.

isReady skilde tidigare bara på "db ok". Den skillnad som saknades är inte
konfigurerad-vs-ej-konfigurerad utan FRÅNVARANDE-vs-TRASIG:

  * not_configured / not_integrated -> fortsatt ready. 0pt är byggt för att
    kunna köra utan motor, Stripe och kö (se .env.example).
  * error -> INTE ready. Statusen "error" betyder att någon medvetet
    konfigurerade beroendet och att en riktig round trip mot det just
    misslyckades. Det är inte längre en valfri integration.

Ändrar ingenting i driften i dag: container-HEALTHCHECK pekar på
/api/health (liveness) och Dockerfilen säger uttryckligen att en
readiness-probe inte ska peka dit. Den här ändringen gör bara att den
ärliga ytan faktiskt blir ärlig, så en yttre övervakning kan använda den.

Regressionstest tillagt; verifierat att det FALLER mot den gamla isReady
(1 failed | 18 passed) och passerar mot den nya (24 passed över
health-checks/ready/health).

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-25 13:34:42 +02:00

210 lines
7.4 KiB
TypeScript

/**
* Unit tests for the dependency probes behind GET /api/health + GET
* /api/ready (BACKLOG P0-3). Each check is exercised via dependency
* injection (fake sql/fetch/stripe clients) rather than real network I/O,
* matching the fake-over-mock-global convention used elsewhere in this repo
* (e.g. tests/p0/document-intelligence-adapter.test.ts).
*/
import { describe, it, expect, afterEach } from "vitest";
import {
checkDatabase,
checkEngine,
checkStripe,
checkQueue,
hasDegradedDependency,
isReady,
type DependencyResults,
type SqlPing,
} from "@/lib/health-checks";
function jsonResponse(body: unknown, status = 200): Response {
return {
ok: status < 400,
status,
json: async () => body,
} as unknown as Response;
}
describe("checkDatabase", () => {
const saved = process.env.DATABASE_URL;
afterEach(() => {
if (saved === undefined) delete process.env.DATABASE_URL;
else process.env.DATABASE_URL = saved;
});
it("reports not_configured when DATABASE_URL is unset, without calling the client", async () => {
delete process.env.DATABASE_URL;
let called = false;
const fakeSql: SqlPing = async () => {
called = true;
return [{ "?column?": 1 }];
};
const result = await checkDatabase(fakeSql);
expect(result.status).toBe("not_configured");
expect(called).toBe(false);
});
it("reports ok when the ping round trip succeeds", async () => {
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
const fakeSql: SqlPing = async () => [{ "?column?": 1 }];
const result = await checkDatabase(fakeSql);
expect(result.status).toBe("ok");
expect(typeof result.latencyMs).toBe("number");
});
it("reports error with the driver message when the ping fails", async () => {
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
const fakeSql: SqlPing = async () => {
throw new Error("ECONNREFUSED 127.0.0.1:5432");
};
const result = await checkDatabase(fakeSql);
expect(result.status).toBe("error");
expect(result.detail).toContain("ECONNREFUSED");
});
it("reports error on timeout rather than hanging", async () => {
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
const fakeSql: SqlPing = () => new Promise(() => {}); // never resolves
const result = await checkDatabase(fakeSql, 20);
expect(result.status).toBe("error");
expect(result.detail).toContain("timed out");
});
it("reports not_configured when DATABASE_URL is set but no client is available", async () => {
process.env.DATABASE_URL = "postgres://user:pass@localhost:5432/opt";
const result = await checkDatabase(null);
expect(result.status).toBe("not_configured");
});
});
describe("checkEngine", () => {
const saved = process.env.ENGINE_URL;
afterEach(() => {
if (saved === undefined) delete process.env.ENGINE_URL;
else process.env.ENGINE_URL = saved;
});
it("reports not_configured when ENGINE_URL is unset", async () => {
delete process.env.ENGINE_URL;
const result = await checkEngine(async () => jsonResponse({ ok: true }));
expect(result.status).toBe("not_configured");
});
it("reports ok when the engine's /health responds 2xx", async () => {
process.env.ENGINE_URL = "http://engine.local:8000";
const fetchMock = (async (url: string) => {
expect(url).toBe("http://engine.local:8000/health");
return jsonResponse({ ok: true });
}) as unknown as typeof fetch;
const result = await checkEngine(fetchMock);
expect(result.status).toBe("ok");
});
it("reports error when the engine responds non-2xx", async () => {
process.env.ENGINE_URL = "http://engine.local:8000";
const result = await checkEngine(async () => jsonResponse({}, 500));
expect(result.status).toBe("error");
expect(result.detail).toContain("500");
});
it("reports error when the fetch throws (host unreachable)", async () => {
process.env.ENGINE_URL = "http://engine.local:8000";
const result = await checkEngine(async () => {
throw new Error("fetch failed");
});
expect(result.status).toBe("error");
});
});
describe("checkStripe", () => {
it("reports not_configured when no client is available (no STRIPE_SECRET_KEY)", async () => {
const result = await checkStripe(null);
expect(result.status).toBe("not_configured");
});
it("reports ok when balance.retrieve() succeeds", async () => {
const result = await checkStripe({ balance: { retrieve: async () => ({ available: [] }) } });
expect(result.status).toBe("ok");
});
it("reports error when balance.retrieve() rejects (e.g. revoked key)", async () => {
const result = await checkStripe({
balance: {
retrieve: async () => {
throw new Error("Invalid API Key provided");
},
},
});
expect(result.status).toBe("error");
expect(result.detail).toContain("Invalid API Key");
});
});
describe("checkQueue", () => {
const saved = process.env.REDIS_URL;
afterEach(() => {
if (saved === undefined) delete process.env.REDIS_URL;
else process.env.REDIS_URL = saved;
});
it("never claims ok — only not_configured or not_integrated (no Redis client wired in this repo)", () => {
delete process.env.REDIS_URL;
expect(checkQueue().status).toBe("not_configured");
process.env.REDIS_URL = "redis://localhost:6379";
expect(checkQueue().status).toBe("not_integrated");
});
});
describe("hasDegradedDependency / isReady", () => {
function deps(overrides: Partial<DependencyResults> = {}): DependencyResults {
return {
db: { status: "not_configured" },
engine: { status: "not_configured" },
stripe: { status: "not_configured" },
queue: { status: "not_configured" },
...overrides,
};
}
it("hasDegradedDependency is false when nothing is configured", () => {
expect(hasDegradedDependency(deps())).toBe(false);
});
it("hasDegradedDependency is true when any dependency errored", () => {
expect(hasDegradedDependency(deps({ engine: { status: "error", detail: "boom" } }))).toBe(true);
});
it("isReady is false when db is not ok, even if nothing else is broken", () => {
expect(isReady(deps())).toBe(false);
expect(isReady(deps({ db: { status: "error" } }))).toBe(false);
});
it("isReady is true once db is ok and no configured integration is failing", () => {
expect(isReady(deps({ db: { status: "ok" } }))).toBe(true);
});
it("isReady stays true for integrations that are merely absent (0pt boots without them)", () => {
expect(
isReady(
deps({
db: { status: "ok" },
engine: { status: "not_configured" },
stripe: { status: "not_configured" },
queue: { status: "not_integrated" },
}),
),
).toBe(true);
});
it("REGRESSION: isReady is false when a CONFIGURED integration is failing its live round trip", () => {
// Mätt i prod 2026-09-25: ENGINE_URL pekade på 0pt-engine:8000, en värd
// utan DNS-post någonstans i flottan, och /api/ready svarade ändå
// {"ready":true,...,"engine":"error"}. En konfigurerad-men-död motor är
// inte "valfri" -- någon har bett om den och den svarar inte.
expect(isReady(deps({ db: { status: "ok" }, engine: { status: "error", detail: "fetch failed" } }))).toBe(
false,
);
expect(isReady(deps({ db: { status: "ok" }, stripe: { status: "error", detail: "bad key" } }))).toBe(false);
});
});