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
30 changes: 29 additions & 1 deletion apps/node/src/api-deps.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
import { createSharedApiDeps } from "@codraoss/api";
import { createSharedApiDeps, type HealthProbesPort } from "@codraoss/api";
import { getOrFetchRawDiffForCompletedJob } from "@codraoss/core";
import { queryRows } from "@codraoss/db/client";
import type { NodeAppBindings } from "./env";
import { logger } from "@codraoss/api/logger";
import { createReviewRuntime } from "./runtime";

const nodeHealthProbes = new WeakMap<NodeAppBindings, HealthProbesPort>();

function getNodeHealthProbes(env: NodeAppBindings): HealthProbesPort {
const existing = nodeHealthProbes.get(env);
if (existing) {
return existing;
}

const db = {
HYPERDRIVE: env.DATABASE_CONFIG,
APP_KV: env.APP_KV,
workerMode: false as const,
};
const probes: HealthProbesPort = {
database: async () => {
await queryRows(db, "SELECT 1");
},
kv: () =>
env.PING_REDIS
? env.PING_REDIS()
: env.APP_KV.get("__health_check__").then(() => undefined),
};
nodeHealthProbes.set(env, probes);
return probes;
}

export function createNodeApiDeps(env: NodeAppBindings) {
return createSharedApiDeps({
sessionStore: env.SESSION_STORE,
Expand Down Expand Up @@ -55,5 +82,6 @@ export function createNodeApiDeps(env: NodeAppBindings) {
githubAppId: env.GITHUB_APP_ID,
githubAppWebhookSecret: env.GITHUB_APP_WEBHOOK_SECRET,
llmConfigEncryptionKey: env.LLM_CONFIG_ENCRYPTION_KEY,
health: getNodeHealthProbes(env),
});
}
2 changes: 2 additions & 0 deletions apps/node/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface NodeAppBindings {
SESSION_STORE: SessionStore;
IDENTITY_PROVIDER?: IdentityProvider;
APP_KV: KeyValueStore;
PING_REDIS?: () => Promise<void>;
REVIEW_QUEUE: QueueProducer<ReviewJobMessage>;
REVIEW_ORCHESTRATOR?: JobOrchestrator;

Expand All @@ -35,6 +36,7 @@ export interface NodeAppBindings {
export function createNodeEnv(stubs: {
SESSION_STORE: SessionStore;
APP_KV: KeyValueStore;
PING_REDIS?: () => Promise<void>;
REVIEW_QUEUE: QueueProducer<ReviewJobMessage>;
REVIEW_ORCHESTRATOR?: JobOrchestrator;
}): NodeAppBindings {
Expand Down
7 changes: 7 additions & 0 deletions apps/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,13 @@ const reviewQueue = new Queue("codra-reviews", { connection: redisClient });
const stubs = {
SESSION_STORE: new RedisSessionStore(redisClient),
APP_KV: new RedisKVAdapter(redisClient),
PING_REDIS: async () => {
// Fail fast when disconnected instead of queueing commands on ioredis's offlineQueue.
if (redisClient.status !== "ready") {
throw new Error(`Redis client not ready (${redisClient.status})`);
}
await redisClient.ping();
},
REVIEW_QUEUE: new RedisQueueAdapter(reviewQueue),
REVIEW_ORCHESTRATOR: undefined as NodeOrchestrator | undefined,
};
Expand Down
14 changes: 13 additions & 1 deletion apps/worker/src/api-deps.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import { createSharedApiDeps } from "@codraoss/api";
import { queryRows } from "@codraoss/db/client";
import type { AppBindings } from "./env";
import { CloudflareSessionStore } from "./sessions";
import { createReviewRuntime } from "./adapters";
import { logger } from "./core/logger";
import { getOrFetchRawDiffForCompletedJob } from "./core/review";

export function createApiRouterDeps(env: AppBindings, _ctx: ExecutionContext) {
const db = { HYPERDRIVE: env.HYPERDRIVE, APP_KV: env.APP_KV, workerMode: true };
return createSharedApiDeps({
sessionStore: new CloudflareSessionStore(env.APP_KV),
kv: env.APP_KV,
db: { HYPERDRIVE: env.HYPERDRIVE, APP_KV: env.APP_KV, workerMode: true },
db,
identityProvider: env.IDENTITY_PROVIDER,
enqueueReviewJob: async (input) => await env.REVIEW_QUEUE.send(input),
terminateJobWorkflow: async (job) => {
Expand Down Expand Up @@ -56,5 +58,15 @@ export function createApiRouterDeps(env: AppBindings, _ctx: ExecutionContext) {
llmConfigEncryptionKey: env.LLM_CONFIG_ENCRYPTION_KEY,
cfApiToken: env.CF_API_TOKEN,
cfAccountId: env.CF_ACCOUNT_ID,
health: {
// clock_timestamp() is VOLATILE, so Hyperdrive cannot serve a cached result during an origin outage.
// Closures stay per-request on Workers so I/O promises are never shared across request contexts.
database: async () => {
await queryRows(db, "SELECT clock_timestamp()");
},
kv: async () => {
await env.APP_KV.get("__health_check__");
},
},
});
}
12 changes: 10 additions & 2 deletions docs/docker.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ docker run -d \
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:
* `GET /health/ready` is the readiness probe. It runs `SELECT 1` on Node (`SELECT clock_timestamp()` on Workers Hyperdrive to bypass edge SQL caching) against PostgreSQL and `PING` on Redis (a `get` of `__health_check__` on Workers KV), each with a 2 second timeout. It returns `200` when both answer, and `503` with a JSON body when one does not:

```json
{
Expand All @@ -168,15 +168,23 @@ Codra exposes two health endpoints:
}
```

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:
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 (keep in mind that auto-restart supervisors acting on Docker health will restart the container during an external dependency outage). For Kubernetes, keep `livenessProbe` on `/health` and point `readinessProbe` at `/health/ready` with `timeoutSeconds` greater than the 2 second probe deadline:

```yaml
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 10
periodSeconds: 30
timeoutSeconds: 3
readinessProbe:
httpGet:
path: /health/ready
port: 3000
initialDelaySeconds: 10
periodSeconds: 15
timeoutSeconds: 3
```

```bash
Expand Down
2 changes: 1 addition & 1 deletion docs/nodejs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ curl -I http://localhost:3000/health
```

* **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.
* **Readiness**: `GET /health/ready` runs `SELECT 1` on PostgreSQL and `PING` on 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
7 changes: 4 additions & 3 deletions packages/api/src/create-deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface PlatformDeps {
cfAccountId?: string;
checkQuota?: ((input: QuotaCheckInput) => Promise<QuotaResult>) | null;
authz?: AuthzPort;
health?: HealthProbesPort;
}

import type {
Expand All @@ -46,6 +47,7 @@ import type {
QuotaCheckInput,
QuotaResult,
AuthzPort,
HealthProbesPort,
} from "./ports";
import type {
SessionStore,
Expand Down Expand Up @@ -201,12 +203,11 @@ export function createSharedApiDeps(p: PlatformDeps): ApiRouterDeps {
? createDefaultQuotaChecker(p.kv)
: undefined,
authz: p.authz,
health: {
health: p.health ?? {
database: async () => {
await queryRows(p.db, "SELECT 1");
},
// 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.
// A missing key resolves to null; only an unreachable store throws.
kv: async () => {
await p.kv.get("__health_check__");
},
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export type {
AuthorizeResult,
QuotaCheckInput,
QuotaResult,
HealthProbesPort,
} from "./ports";
// Exported so an app embedding this router can reuse the same guards on its own routes.
export { requirePermission, requireQuota } from "./middleware/authorize";
Expand Down
14 changes: 10 additions & 4 deletions packages/api/src/middleware/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +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();
}
// Orchestrators probe /health and /health/ready every few seconds; skip info access logs while
// keeping AsyncLocalStorage request context active so probe failure warnings keep requestId.
const isHealthProbe =
(c.req.method === "GET" || c.req.method === "HEAD") &&
(c.req.path === "/health" || c.req.path === "/health/ready");

return logger.runWithContext(
{
Expand All @@ -18,6 +19,11 @@ export const observability: MiddlewareHandler<ApiEnv> = async (c, next) => {
path: c.req.path,
},
async () => {
if (isHealthProbe) {
await next();
return;
}

logger.info(`Incoming request: ${c.req.method} ${c.req.path}`);

const start = Date.now();
Expand Down
41 changes: 37 additions & 4 deletions packages/api/src/routes/health.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,58 @@ const PROBE_TIMEOUT_MS = 2000;

type CheckResult = { status: "ok" } | { status: "failed"; error: string };

class ProbeTimeoutError extends Error {
constructor() {
super("timeout");
this.name = "ProbeTimeoutError";
}
}

// Coalesce concurrent/hanging calls per probe function so repeated readiness polls during an outage
// do not stack queries on the DB pool or Redis client while an earlier call is still pending.
const activeProbes = new WeakMap<() => Promise<void>, Promise<void>>();

function getOrStartProbe(run: () => Promise<void>): Promise<void> {
const existing = activeProbes.get(run);
if (existing) {
return existing;
}

const op = Promise.resolve().then(() => run());
op.catch(() => {});
const tracked = op.finally(() => {
if (activeProbes.get(run) === tracked) {
activeProbes.delete(run);
}
});
// Silence unhandled rejections if the underlying probe fails after the request timed out.
tracked.catch(() => {});
activeProbes.set(run, tracked);
return tracked;
}

async function probe(name: string, run: () => Promise<void>): Promise<CheckResult> {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
run(),
getOrStartProbe(run),
new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error("timeout")), PROBE_TIMEOUT_MS);
timer = setTimeout(() => reject(new ProbeTimeoutError()), PROBE_TIMEOUT_MS);
(timer as unknown as { unref?: () => void }).unref?.();
}),
]);
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" };
return {
status: "failed",
error: error instanceof ProbeTimeoutError ? "timeout" : "unreachable",
};
} finally {
clearTimeout(timer);
}
Expand Down
Loading