diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index fb8e2d0..7e10b52 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -274,6 +274,29 @@ points = isCorrect ? Math.max(1, Math.ceil(10 * (1 - elapsedMs / limitMs))) : 0 reached the server. A correct answer scores 10 down to 1 across the time limit. Wrong answers score nothing. +#### ws-server metrics + +The ws-server serves Prometheus text format at `GET /metrics` on a separate +listener (port `9090` by default, configurable with `METRICS_PORT`). It binds +to `127.0.0.1` by default (`METRICS_HOST`); Docker Compose binds it to the +container network, but does not publish that port in production. In the +development Compose setup it is published only on host loopback: +`http://127.0.0.1:9090/metrics`. In production, scrape +`http://ws-server:9090/metrics` from an authorized container on the private +Compose network; do not proxy or publish this listener publicly. + +Exposed metrics are aggregate, with no session or participant labels: +`rexial_ws_connections_open`, `rexial_ws_sessions_in_progress`, +`rexial_ws_answers_submitted_total`, `rexial_ws_answers_persisted_total`, +`rexial_ws_answer_queue_flush_failures_total`, +`rexial_ws_answer_queue_transaction_errors_total`, and the histogram +`rexial_ws_question_close_latency_seconds`. Submitted counts answers accepted +into the in-memory queue; persisted counts rows returned as inserted by the +database. Their difference is the current process-lifetime gap, and a rising +flush-failure or transaction-error counter indicates why it is growing. +Question-close latency covers timer-expired questions, from the timer deadline +to the results broadcast. + ### genAI — AI question generation FastAPI, isolated from the Node services so the Python AI dependency tree diff --git a/apps/ws-server/src/index.ts b/apps/ws-server/src/index.ts index 36389cb..223af16 100644 --- a/apps/ws-server/src/index.ts +++ b/apps/ws-server/src/index.ts @@ -2,16 +2,31 @@ import { configDotenv } from 'dotenv'; configDotenv(); import WebSocket, { WebSocketServer } from 'ws'; -import { clients, unindexClient } from './clients/index.js'; +import { clients, sessionTimers, unindexClient } from './clients/index.js'; import { handleMessage } from './utils/handleMessages.js'; import { startSessionSubscriber } from './utils/broadcastTosession.js'; import { invalidateParticipants } from './utils/cache.js'; import { drainAll } from './utils/answerQueue.js'; - +import { createMetricsServer } from './utils/metrics.js'; const wss = new WebSocketServer({ port: 8080 }); +const metricsPort = Number(process.env.METRICS_PORT ?? 9090); +if (!Number.isInteger(metricsPort) || metricsPort < 1 || metricsPort > 65535) { + throw new Error('METRICS_PORT must be an integer between 1 and 65535'); +} +const metricsHost = process.env.METRICS_HOST ?? '127.0.0.1'; +const metricsServer = createMetricsServer(() => ({ + openConnections: clients.size, + sessionsInProgress: sessionTimers.size, +})); +metricsServer.on('error', (err) => { + console.error('[metrics] server failed', err); +}); +metricsServer.listen(metricsPort, metricsHost, () => { + console.log(`[metrics] listening on ${metricsHost}:${metricsPort}`); +}); @@ -70,6 +85,7 @@ for (const signal of ['SIGTERM', 'SIGINT'] as const) { console.error('[shutdown] flush failed', err); } + metricsServer.close(); wss.close(() => process.exit(0)); // Do not hang on a socket that will not close. setTimeout(() => process.exit(0), 5_000).unref(); diff --git a/apps/ws-server/src/utils/answerQueue.metrics.test.ts b/apps/ws-server/src/utils/answerQueue.metrics.test.ts new file mode 100644 index 0000000..3b2e100 --- /dev/null +++ b/apps/ws-server/src/utils/answerQueue.metrics.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + createManyAndReturn: vi.fn(), + transaction: vi.fn(), + updateMany: vi.fn(), +})); + +vi.mock("@repo/db", () => ({ + prisma: { + participantAnswer: { createManyAndReturn: mocks.createManyAndReturn }, + participant: { updateMany: mocks.updateMany }, + $transaction: mocks.transaction, + }, +})); + +import { enqueueAnswer, flushSession } from "./answerQueue.js"; +import { renderMetrics } from "./metrics.js"; + +function metricValue(name: string): number { + const line = renderMetrics(0, 0).split("\n").find((entry) => entry.startsWith(`${name} `)); + if (!line) throw new Error(`Missing metric ${name}`); + return Number(line.slice(name.length + 1)); +} + +function answer(participantId = "participant-1") { + return { + participantId, + questionId: "question-1", + answerId: "answer-1", + timeMs: 100, + isCorrect: true, + points: 5, + }; +} + +beforeEach(() => { + mocks.createManyAndReturn.mockReset(); + mocks.transaction.mockReset().mockResolvedValue([]); + mocks.updateMany.mockReset().mockResolvedValue({ count: 1 }); +}); + +describe("answer queue metrics", () => { + it("counts accepted submissions and only rows returned as inserted", async () => { + const submittedBefore = metricValue("rexial_ws_answers_submitted_total"); + const persistedBefore = metricValue("rexial_ws_answers_persisted_total"); + mocks.createManyAndReturn.mockResolvedValue([{ participantId: "participant-1", points: 5 }]); + + expect(enqueueAnswer("metrics-success", answer())).toBe(true); + expect(enqueueAnswer("metrics-success", answer())).toBe(false); + await flushSession("metrics-success"); + + expect(metricValue("rexial_ws_answers_submitted_total")).toBe(submittedBefore + 1); + expect(metricValue("rexial_ws_answers_persisted_total")).toBe(persistedBefore + 1); + }); + + it("counts a failed flush and persists a requeued answer only once", async () => { + const submittedBefore = metricValue("rexial_ws_answers_submitted_total"); + const persistedBefore = metricValue("rexial_ws_answers_persisted_total"); + const failuresBefore = metricValue("rexial_ws_answer_queue_flush_failures_total"); + mocks.createManyAndReturn + .mockRejectedValueOnce(new Error("database unavailable")) + .mockResolvedValueOnce([{ participantId: "participant-2", points: 5 }]); + + enqueueAnswer("metrics-retry", answer("participant-2")); + await expect(flushSession("metrics-retry")).rejects.toThrow("database unavailable"); + await flushSession("metrics-retry"); + + expect(metricValue("rexial_ws_answers_submitted_total")).toBe(submittedBefore + 1); + expect(metricValue("rexial_ws_answers_persisted_total")).toBe(persistedBefore + 1); + expect(metricValue("rexial_ws_answer_queue_flush_failures_total")).toBe(failuresBefore + 1); + }); + + it("counts score transaction errors separately from flush failures", async () => { + const persistedBefore = metricValue("rexial_ws_answers_persisted_total"); + const failuresBefore = metricValue("rexial_ws_answer_queue_flush_failures_total"); + const transactionErrorsBefore = metricValue("rexial_ws_answer_queue_transaction_errors_total"); + mocks.createManyAndReturn + .mockResolvedValueOnce([{ participantId: "participant-3", points: 5 }]) + .mockResolvedValueOnce([]); + mocks.transaction.mockRejectedValueOnce(new Error("transaction timed out")); + + enqueueAnswer("metrics-transaction", answer("participant-3")); + await expect(flushSession("metrics-transaction")).rejects.toThrow("transaction timed out"); + await flushSession("metrics-transaction"); + + expect(metricValue("rexial_ws_answers_persisted_total")).toBe(persistedBefore + 1); + expect(metricValue("rexial_ws_answer_queue_flush_failures_total")).toBe(failuresBefore + 1); + expect(metricValue("rexial_ws_answer_queue_transaction_errors_total")).toBe(transactionErrorsBefore + 1); + }); +}); diff --git a/apps/ws-server/src/utils/answerQueue.ts b/apps/ws-server/src/utils/answerQueue.ts index 67b525b..db37d4b 100644 --- a/apps/ws-server/src/utils/answerQueue.ts +++ b/apps/ws-server/src/utils/answerQueue.ts @@ -1,4 +1,10 @@ import { prisma } from "@repo/db"; +import { + recordAnswerQueueFlushFailure, + recordAnswerQueueTransactionError, + recordAnswerSubmitted, + recordAnswersPersisted, +} from "./metrics.js"; /** * Buffered writer for answer submissions. @@ -76,6 +82,7 @@ export function enqueueAnswer(sessionId: string, answer: PendingAnswer): boolean } buffer.set(key, answer); + recordAnswerSubmitted(); let seen = questionsBySession.get(sessionId); if (!seen) { @@ -197,6 +204,7 @@ export async function flushSession(sessionId: string): Promise { skipDuplicates: true, select: { participantId: true, points: true }, }); + recordAnswersPersisted(inserted.length); // Remember who is now written, so countAnswered can work from memory // rather than querying once per submission. @@ -213,16 +221,22 @@ export async function flushSession(sessionId: string): Promise { } if (byPoints.size > 0) { - await prisma.$transaction( - [...byPoints.entries()].map(([points, ids]) => - prisma.participant.updateMany({ - where: { id: { in: ids } }, - data: { score: { increment: points } }, - }), - ), - ); + try { + await prisma.$transaction( + [...byPoints.entries()].map(([points, ids]) => + prisma.participant.updateMany({ + where: { id: { in: ids } }, + data: { score: { increment: points } }, + }), + ), + ); + } catch (err) { + recordAnswerQueueTransactionError(); + throw err; + } } } catch (err) { + recordAnswerQueueFlushFailure(); // Put the batch back so the next flush retries it, rather than losing // answers people have already given. Entries that arrived meanwhile // win, since they are newer. diff --git a/apps/ws-server/src/utils/metrics.test.ts b/apps/ws-server/src/utils/metrics.test.ts new file mode 100644 index 0000000..5392e13 --- /dev/null +++ b/apps/ws-server/src/utils/metrics.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { createMetricsServer, renderMetrics } from "./metrics.js"; + +describe("Prometheus metrics endpoint", () => { + let server: ReturnType | undefined; + + afterEach(async () => { + if (!server?.listening) return; + await new Promise((resolve, reject) => { + server?.close((error) => error ? reject(error) : resolve()); + }); + server = undefined; + }); + + it("serves bounded aggregate metrics in Prometheus text format", async () => { + const metrics = renderMetrics(3, 2); + + expect(metrics).toContain("rexial_ws_connections_open 3"); + expect(metrics).toContain("rexial_ws_sessions_in_progress 2"); + expect(metrics).toContain("# TYPE rexial_ws_answers_submitted_total counter"); + expect(metrics).toContain('rexial_ws_question_close_latency_seconds_bucket{le="+Inf"}'); + expect(metrics).not.toContain("sessionId"); + expect(metrics.endsWith("\n")).toBe(true); + }); + + it("only serves GET /metrics", async () => { + server = createMetricsServer(() => ({ openConnections: 0, sessionsInProgress: 0 })); + await new Promise((resolve) => server?.listen(0, "127.0.0.1", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Metrics listener has no TCP address"); + const baseUrl = `http://127.0.0.1:${address.port}`; + + const metricsResponse = await fetch(`${baseUrl}/metrics`); + expect(metricsResponse.status).toBe(200); + expect(metricsResponse.headers.get("content-type")).toContain("text/plain"); + expect(await metricsResponse.text()).toContain("rexial_ws_answers_persisted_total"); + + expect((await fetch(`${baseUrl}/`)).status).toBe(404); + expect((await fetch(`${baseUrl}/metrics`, { method: "POST" })).status).toBe(405); + }); +}); diff --git a/apps/ws-server/src/utils/metrics.ts b/apps/ws-server/src/utils/metrics.ts new file mode 100644 index 0000000..338db18 --- /dev/null +++ b/apps/ws-server/src/utils/metrics.ts @@ -0,0 +1,104 @@ +import { createServer } from "node:http"; + +const questionCloseLatencyBuckets = [ + 0.01, + 0.025, + 0.05, + 0.1, + 0.25, + 0.5, + 1, + 2.5, + 5, +].map((upperBound) => ({ upperBound, count: 0 })); + +let answersSubmitted = 0; +let answersPersisted = 0; +let answerQueueFlushFailures = 0; +let answerQueueTransactionErrors = 0; +let questionCloseLatencyCount = 0; +let questionCloseLatencySum = 0; + +export function recordAnswerSubmitted() { + answersSubmitted++; +} + +export function recordAnswersPersisted(count: number) { + answersPersisted += count; +} + +export function recordAnswerQueueFlushFailure() { + answerQueueFlushFailures++; +} + +export function recordAnswerQueueTransactionError() { + answerQueueTransactionErrors++; +} + +export function observeQuestionCloseLatency(seconds: number) { + questionCloseLatencyCount++; + questionCloseLatencySum += seconds; + for (const bucket of questionCloseLatencyBuckets) { + if (seconds <= bucket.upperBound) bucket.count++; + } +} + +export function renderMetrics(openConnections: number, sessionsInProgress: number): string { + const lines = [ + "# HELP rexial_ws_connections_open Current open WebSocket connections.", + "# TYPE rexial_ws_connections_open gauge", + `rexial_ws_connections_open ${openConnections}`, + "# HELP rexial_ws_sessions_in_progress Sessions with a running question timer on this instance.", + "# TYPE rexial_ws_sessions_in_progress gauge", + `rexial_ws_sessions_in_progress ${sessionsInProgress}`, + "# HELP rexial_ws_answers_submitted_total Answers accepted into the in-memory queue.", + "# TYPE rexial_ws_answers_submitted_total counter", + `rexial_ws_answers_submitted_total ${answersSubmitted}`, + "# HELP rexial_ws_answers_persisted_total Answers inserted into the database.", + "# TYPE rexial_ws_answers_persisted_total counter", + `rexial_ws_answers_persisted_total ${answersPersisted}`, + "# HELP rexial_ws_answer_queue_flush_failures_total Answer queue flush attempts that failed.", + "# TYPE rexial_ws_answer_queue_flush_failures_total counter", + `rexial_ws_answer_queue_flush_failures_total ${answerQueueFlushFailures}`, + "# HELP rexial_ws_answer_queue_transaction_errors_total Answer score transactions that failed.", + "# TYPE rexial_ws_answer_queue_transaction_errors_total counter", + `rexial_ws_answer_queue_transaction_errors_total ${answerQueueTransactionErrors}`, + "# HELP rexial_ws_question_close_latency_seconds Time from the question deadline to results broadcast.", + "# TYPE rexial_ws_question_close_latency_seconds histogram", + ]; + + questionCloseLatencyBuckets.forEach(({ upperBound, count }) => { + lines.push( + `rexial_ws_question_close_latency_seconds_bucket{le="${upperBound}"} ${count}`, + ); + }); + lines.push( + `rexial_ws_question_close_latency_seconds_bucket{le="+Inf"} ${questionCloseLatencyCount}`, + `rexial_ws_question_close_latency_seconds_sum ${questionCloseLatencySum}`, + `rexial_ws_question_close_latency_seconds_count ${questionCloseLatencyCount}`, + ); + + return `${lines.join("\n")}\n`; +} + +export function createMetricsServer(getGauges: () => { + openConnections: number; + sessionsInProgress: number; +}) { + return createServer((request, response) => { + if (request.url?.split("?")[0] !== "/metrics") { + response.writeHead(404).end(); + return; + } + if (request.method !== "GET") { + response.writeHead(405, { Allow: "GET" }).end(); + return; + } + + const { openConnections, sessionsInProgress } = getGauges(); + response.writeHead(200, { + "Content-Type": "text/plain; version=0.0.4; charset=utf-8", + }); + response.end(renderMetrics(openConnections, sessionsInProgress)); + }); +} diff --git a/apps/ws-server/src/utils/timeManager.ts b/apps/ws-server/src/utils/timeManager.ts index b42fce5..796af7b 100644 --- a/apps/ws-server/src/utils/timeManager.ts +++ b/apps/ws-server/src/utils/timeManager.ts @@ -6,6 +6,7 @@ import { getCachedQuestions, getCachedLeaderboard, import { broadcastToSession } from './broadcastTosession.js'; import { sessionTimers } from '../clients/index.js'; import { flushSession } from './answerQueue.js'; +import { observeQuestionCloseLatency } from './metrics.js'; // Redis key that marks "a timer is already running for this question" const timerLockKey = (sessionId: string, questionIndex: number) => @@ -49,6 +50,7 @@ async function finishQuestion( * ticking into negative numbers with results that never came. */ byCountdown = false, + timerEndedAt?: number, ) { const lockKey = timerLockKey(sessionId, questionIndex); @@ -105,6 +107,9 @@ async function finishQuestion( .filter((a: any) => a.isCorrect) .map((a: any) => a.id), }); + if (timerEndedAt !== undefined) { + observeQuestionCloseLatency((Date.now() - timerEndedAt) / 1_000); + } setTimeout(() => { broadcastToSession(sessionId, 'quiz:leaderboard', { leaderboard }); @@ -223,7 +228,7 @@ export async function startQuestionTimer( // error in here has to be caught on the spot. Left alone it is an // unhandled rejection, and on Node 22 that takes down the whole // process and every quiz running on it. - finishQuestion(sessionId, questionIndex, true).catch((err) => + finishQuestion(sessionId, questionIndex, true, endsAt).catch((err) => console.error('[timer] countdown finish failed', { sessionId, questionIndex }, err), ); } diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 6ffcc43..e51a265 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -73,6 +73,9 @@ services: restart: always env_file: - .env.prod + environment: + - METRICS_HOST=0.0.0.0 + - METRICS_PORT=9090 networks: - rexial-network extra_hosts: diff --git a/docker-compose.yml b/docker-compose.yml index 47d50e2..4606879 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,6 +22,7 @@ services: container_name: RexialWsServer ports: - "8080:8080" + - "127.0.0.1:9090:9090" volumes: - .:/app - rexial_node_modules:/app/node_modules @@ -36,6 +37,8 @@ services: - REDIS_HOST=redis - REDIS_PORT=6379 - REDIS_PASSWORD=thisistheredisPassword + - METRICS_HOST=0.0.0.0 + - METRICS_PORT=9090 command: sh -c "pnpm --filter @repo/db run db:generate && pnpm run dev" depends_on: db: