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
23 changes: 23 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 18 additions & 2 deletions apps/ws-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
});



Expand Down Expand Up @@ -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();
Expand Down
91 changes: 91 additions & 0 deletions apps/ws-server/src/utils/answerQueue.metrics.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
30 changes: 22 additions & 8 deletions apps/ws-server/src/utils/answerQueue.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { prisma } from "@repo/db";
import {
recordAnswerQueueFlushFailure,
recordAnswerQueueTransactionError,
recordAnswerSubmitted,
recordAnswersPersisted,
} from "./metrics.js";

/**
* Buffered writer for answer submissions.
Expand Down Expand Up @@ -76,6 +82,7 @@ export function enqueueAnswer(sessionId: string, answer: PendingAnswer): boolean
}

buffer.set(key, answer);
recordAnswerSubmitted();

let seen = questionsBySession.get(sessionId);
if (!seen) {
Expand Down Expand Up @@ -197,6 +204,7 @@ export async function flushSession(sessionId: string): Promise<void> {
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.
Expand All @@ -213,16 +221,22 @@ export async function flushSession(sessionId: string): Promise<void> {
}

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.
Expand Down
41 changes: 41 additions & 0 deletions apps/ws-server/src/utils/metrics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it } from "vitest";
import { createMetricsServer, renderMetrics } from "./metrics.js";

describe("Prometheus metrics endpoint", () => {
let server: ReturnType<typeof createMetricsServer> | undefined;

afterEach(async () => {
if (!server?.listening) return;
await new Promise<void>((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<void>((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);
});
});
104 changes: 104 additions & 0 deletions apps/ws-server/src/utils/metrics.ts
Original file line number Diff line number Diff line change
@@ -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));
});
}
Loading
Loading