Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ services:
- 8.8.8.8
stop_grace_period: 15s
healthcheck:
test: ["CMD", "/nodejs/bin/node", "-e", "fetch('http://127.0.0.1:3000/health').then((response) => process.exit(response.ok ? 0 : 1)).catch(() => process.exit(1))"]
test: ["CMD", "/nodejs/bin/node", "-e", "fetch('http://127.0.0.1:3000/health/ready').then((response) => process.exit(response.ok ? 0 : 1)).catch(() => process.exit(1))"]
interval: 30s
timeout: 3s
timeout: 5s
retries: 3
start_period: 10s
27 changes: 26 additions & 1 deletion docs/docker.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,32 @@ docker run -d \

<h2 id="health-checks">Health Checks & Monitoring</h2>

Codra exposes a `/health` endpoint that returns HTTP `200 OK`. The container includes an internal health check probe that monitors the server:
Codra exposes two health endpoints:

* `GET /health` is the liveness probe. It returns HTTP `200 OK` while the process is up and does not touch PostgreSQL or Redis.
* `GET /health/ready` is the readiness probe. It runs `SELECT 1` against PostgreSQL and reads a key from Redis (Workers KV on Cloudflare), each with a 2 second timeout. It returns `200` when both answer, and `503` with a JSON body when one does not:

```json
{
"status": "unhealthy",
"timestamp": "2026-11-17T16:30:00.000Z",
"checks": {
"database": { "status": "failed", "error": "unreachable" },
"kv": { "status": "ok" }
}
}
```

The `error` field is `timeout` or `unreachable`; the server log records only the error name and code, never the connection details. The `docker-compose.yml` health check calls `/health/ready`, so a container whose database or Redis is down is reported unhealthy. For Kubernetes, point the readiness probe at the same path:

```yaml
readinessProbe:
httpGet:
path: /health/ready
port: 3000
initialDelaySeconds: 10
periodSeconds: 15
Comment on lines +178 to +179

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Give the Kubernetes probe enough time to finish

When a healthy dependency responds in 1–2 seconds, this example fails readiness even though the handler ultimately returns 200: Kubernetes defaults an omitted timeoutSeconds to 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 as timeoutSeconds: 3.

Useful? React with 👍 / 👎.

```

```bash
# Inspect container health status
Expand Down
3 changes: 2 additions & 1 deletion docs/nodejs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,8 @@ curl -I http://localhost:3000/health
# HTTP/1.1 200 OK
```

* **Healthcheck**: Returns HTTP `200 OK` when the process is responsive.
* **Healthcheck**: Returns HTTP `200 OK` when the process is responsive. It does not touch PostgreSQL or Redis.
* **Readiness**: `GET /health/ready` runs `SELECT 1` on PostgreSQL and reads a key from Redis, and returns HTTP `503` with a JSON `checks` body when either does not answer within 2 seconds.
* **BullMQ Logging**: Worker lifecycle events (`completed`, `failed`) are automatically logged through the centralized `@codraoss/api` logger.
* **Automatic Model Registry**: An unreferenced background timer refreshes available model catalogs every hour with zero impact on database connection pools.

Expand Down
2 changes: 1 addition & 1 deletion docs/operations.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ If GitHub rejects inline comments with a validation error, Codra retries review

### Container health check failing (Docker)

- Ensure the internal service has completed startup and `/health` returns `200 OK`.
- Ensure the internal service has completed startup and `/health` returns `200 OK`. If `/health/ready` returns `503`, its `checks` body names the dependency (`database` or `kv`) that failed; the server log has the error name and code.
- Check database connectivity — the server will wait for initial database connection setup.
- If running under Docker Compose, ensure `dns: [1.1.1.1, 8.8.8.8]` is configured if your host network restricts DNS queries.

Expand Down
11 changes: 11 additions & 0 deletions packages/api/src/create-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bypass Hyperdrive caching when probing PostgreSQL

In Workers deployments with Hyperdrive query caching enabled, this constant SELECT 1 is cacheable. The Workers factory supplies the Hyperdrive binding here (apps/worker/src/api-deps.ts:12), so a previously successful probe can keep reporting the database as healthy after origin PostgreSQL becomes unreachable, until the cached result expires. The HTTP response's Cache-Control: no-store does not bypass Hyperdrive's SQL cache. Use an uncached database check so readiness actually tests the origin connection.

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__");
},
},
};
}
5 changes: 5 additions & 0 deletions packages/api/src/middleware/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ export const observability: MiddlewareHandler<ApiEnv> = async (c, next) => {
const requestId = c.req.header("x-request-id") || crypto.randomUUID();
c.set("requestId", requestId);

// Orchestrators probe /health every few seconds; logging each one would flood production logs.
if (c.req.path === "/health" || c.req.path.startsWith("/health/")) {
return next();
}

return logger.runWithContext(
{
requestId,
Expand Down
7 changes: 7 additions & 0 deletions packages/api/src/ports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,12 @@ export type QuotaResult =
| { allowed: true }
| { allowed: false; retryAfterSeconds?: number; reason?: string };

// Dependency probes for GET /health/ready. Each one rejects when its dependency is unreachable.
export interface HealthProbesPort {
database: () => Promise<void>;
kv: () => Promise<void>;
}

export interface ApiRouterDeps {
repositories: RepositoriesPort;
gitProvider: {
Expand All @@ -167,6 +173,7 @@ export interface ApiRouterDeps {
cloudflareAiEnabled?: boolean;
authz?: AuthzPort;
checkQuota?: (input: QuotaCheckInput) => Promise<QuotaResult>;
health?: HealthProbesPort;
}

export interface ApiEnv {
Expand Down
5 changes: 4 additions & 1 deletion packages/api/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { createReposRouter } from "./routes/api/repos";
import { createStatsRouter } from "./routes/api/stats";
import { createModelsRouter } from "./routes/api/models";
import { createSettingsRouter } from "./routes/api/settings";
import { createHealthRouter } from "./routes/health";

async function serveIndex(c: Context<ApiEnv>) {
// If the host platform passes an ASSETS binding via `c.env`, use it (e.g., Cloudflare Workers).
Expand Down Expand Up @@ -55,10 +56,12 @@ export function createApiRouter(options: ApiRouterOptions = {}) {
app.use("*", middleware);
}

// Machine health check — no session required
// Liveness: the process is up. Touches no dependency, no session required.
app.get("/health", (c) =>
c.json({ status: "ok", timestamp: new Date().toISOString() }),
);
// Readiness: PostgreSQL and the KV/Redis store answer. 503 when one does not.
app.route("/health", createHealthRouter());

app.use("/auth/logout", requireSession);
app.use("/auth/logout", requireCsrfHeader);
Expand Down
54 changes: 54 additions & 0 deletions packages/api/src/routes/health.ts
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound outstanding dependency operations after a timeout

During a Redis outage on Node, this race times out the HTTP waiter but does not stop the underlying GET. RedisKVAdapter.get() directly uses the shared ioredis client, which is configured with maxRetriesPerRequest: null in apps/node/src/index.ts:38–39, so commands can remain queued indefinitely after these responses return. Every subsequent readiness poll adds another command, causing unbounded retained work during a prolonged outage and a backlog on reconnection. Make probe operations fail fast without entering the offline queue, or bound/coalesce outstanding probes rather than only timing out their waiters.

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;
}
78 changes: 78 additions & 0 deletions test/health-ready.spec.ts
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();
});
});