Repository navigation
feat(api): add GET /health/ready readiness probe for PostgreSQL and KV/Redis #202
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -55,6 +55,7 @@ import type { | |
| import type { KvCompat } from "./platform/config"; | ||
| import type { DbEnv } from "@codraoss/db/env"; | ||
|
|
||
| import { queryRows } from "@codraoss/db/client"; | ||
| import * as dbAccounts from "@codraoss/db/accounts"; | ||
| import * as dbJobs from "@codraoss/db/jobs"; | ||
| import * as dbFileReviews from "@codraoss/db/file-reviews"; | ||
|
|
@@ -200,5 +201,15 @@ export function createSharedApiDeps(p: PlatformDeps): ApiRouterDeps { | |
| ? createDefaultQuotaChecker(p.kv) | ||
| : undefined, | ||
| authz: p.authz, | ||
| health: { | ||
| database: async () => { | ||
| await queryRows(p.db, "SELECT 1"); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In Workers deployments with Hyperdrive query caching enabled, this constant Useful? React with 👍 / 👎. |
||
| }, | ||
| // A missing key resolves to null; only an unreachable store throws. Redis (Node) answers a GET | ||
| // like a PING, and a Workers KV read of an absent key is cheap. | ||
| kv: async () => { | ||
| await p.kv.get("__health_check__"); | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { Hono } from "hono"; | ||
| import type { ApiEnv } from "../ports"; | ||
| import { logger } from "../logger"; | ||
|
|
||
| const PROBE_TIMEOUT_MS = 2000; | ||
|
|
||
| type CheckResult = { status: "ok" } | { status: "failed"; error: string }; | ||
|
|
||
| async function probe(name: string, run: () => Promise<void>): Promise<CheckResult> { | ||
| let timer: ReturnType<typeof setTimeout> | undefined; | ||
| try { | ||
| await Promise.race([ | ||
| run(), | ||
| new Promise<never>((_, reject) => { | ||
| timer = setTimeout(() => reject(new Error("timeout")), PROBE_TIMEOUT_MS); | ||
| }), | ||
|
Comment on lines
+12
to
+16
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
During a Redis outage on Node, this race times out the HTTP waiter but does not stop the underlying GET. Useful? React with 👍 / 👎. |
||
| ]); | ||
| return { status: "ok" }; | ||
| } catch (error) { | ||
| // The raw message can carry a host name or connection string, so neither the body nor the log gets it. | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| const code = (error as { code?: unknown } | null)?.code; | ||
| logger.warn(`Readiness probe failed: ${name}`, { | ||
| error: error instanceof Error ? error.name : "unknown", | ||
| ...(typeof code === "string" ? { code } : {}), | ||
| }); | ||
| return { status: "failed", error: message === "timeout" ? "timeout" : "unreachable" }; | ||
| } finally { | ||
| clearTimeout(timer); | ||
| } | ||
| } | ||
|
|
||
| export function createHealthRouter() { | ||
| const app = new Hono<ApiEnv>(); | ||
|
|
||
| app.get("/ready", async (c) => { | ||
| const probes = c.env.deps?.health; | ||
| const [database, kv] = probes | ||
| ? await Promise.all([probe("database", probes.database), probe("kv", probes.kv)]) | ||
| : [{ status: "failed", error: "unreachable" } as CheckResult, { status: "failed", error: "unreachable" } as CheckResult]; | ||
| const healthy = database.status === "ok" && kv.status === "ok"; | ||
| c.header("Cache-Control", "no-store"); | ||
| return c.json( | ||
| { | ||
| status: healthy ? "ok" : "unhealthy", | ||
| timestamp: new Date().toISOString(), | ||
| checks: { database, kv }, | ||
| }, | ||
| healthy ? 200 : 503, | ||
| ); | ||
| }); | ||
|
|
||
| return app; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { createApiRouter } from "@codraoss/api"; | ||
|
|
||
| const ok = async () => {}; | ||
|
|
||
| function request(health?: { database: () => Promise<void>; kv: () => Promise<void> }) { | ||
| const app = createApiRouter(); | ||
| return app.request("/health/ready", {}, { deps: { health } } as any); | ||
| } | ||
|
|
||
| describe("GET /health/ready", () => { | ||
| it("returns 200 when the database and the KV store answer", async () => { | ||
| const res = await request({ database: ok, kv: ok }); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ | ||
| status: "ok", | ||
| checks: { database: { status: "ok" }, kv: { status: "ok" } }, | ||
| }); | ||
| }); | ||
|
|
||
| it("returns 503 and names the failed dependency when one is down", async () => { | ||
| const res = await request({ | ||
| database: async () => { | ||
| throw new Error("connect ECONNREFUSED postgres://user:secret@db.internal:5432/codra"); | ||
| }, | ||
| kv: ok, | ||
| }); | ||
| expect(res.status).toBe(503); | ||
| const text = await res.text(); | ||
| const body = JSON.parse(text); | ||
| expect(body.status).toBe("unhealthy"); | ||
| expect(body.checks.database).toEqual({ status: "failed", error: "unreachable" }); | ||
| expect(body.checks.kv).toEqual({ status: "ok" }); | ||
| expect(text).not.toContain("secret"); | ||
| expect(text).not.toContain("db.internal"); | ||
| }); | ||
|
|
||
| it("returns 503 with both checks failed when everything is down", async () => { | ||
| const down = async () => { | ||
| throw new Error("down"); | ||
| }; | ||
| const res = await request({ database: down, kv: down }); | ||
| expect(res.status).toBe(503); | ||
| const body = (await res.json()) as any; | ||
| expect(body.checks.database.status).toBe("failed"); | ||
| expect(body.checks.kv.status).toBe("failed"); | ||
| }); | ||
|
|
||
| it("reports a probe that hangs as a timeout", async () => { | ||
| vi.useFakeTimers(); | ||
| try { | ||
| const pending = request({ database: () => new Promise<void>(() => {}), kv: ok }); | ||
| await vi.advanceTimersByTimeAsync(2100); | ||
| const res = await pending; | ||
| expect(res.status).toBe(503); | ||
| expect(((await res.json()) as any).checks.database).toEqual({ status: "failed", error: "timeout" }); | ||
| } finally { | ||
| vi.useRealTimers(); | ||
| } | ||
| }); | ||
|
|
||
| it("returns 503 when no probes are wired", async () => { | ||
| expect((await request(undefined)).status).toBe(503); | ||
| }); | ||
| }); | ||
|
|
||
| describe("GET /health (liveness)", () => { | ||
| it("stays 200 without touching any dependency", async () => { | ||
| const database = vi.fn(ok); | ||
| const kv = vi.fn(ok); | ||
| const app = createApiRouter(); | ||
| const res = await app.request("/health", {}, { deps: { health: { database, kv } } } as any); | ||
| expect(res.status).toBe(200); | ||
| expect(await res.json()).toMatchObject({ status: "ok" }); | ||
| expect(database).not.toHaveBeenCalled(); | ||
| expect(kv).not.toHaveBeenCalled(); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When a healthy dependency responds in 1–2 seconds, this example fails readiness even though the handler ultimately returns 200: Kubernetes defaults an omitted
timeoutSecondsto 1, while the endpoint allows each check two seconds. Users copying this configuration can therefore keep healthy pods unready. Set an explicit probe timeout above the handler's two-second deadline, such astimeoutSeconds: 3.Useful? React with 👍 / 👎.