diff --git a/src/components/exams/exam-room-ws.tsx b/src/components/exams/exam-room-ws.tsx index 84b1160..e1f08f1 100644 --- a/src/components/exams/exam-room-ws.tsx +++ b/src/components/exams/exam-room-ws.tsx @@ -32,12 +32,14 @@ const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => type WsState = "connecting" | "connected" | "disconnected"; type WsMessage = | { type: "state"; status: string; deadline: number | null; remaining_ms: number | null; now: number; answered: number; question_count: number } - | { type: "saved"; question_id: string; updated_at: number } + // `client_seq` is the value we minted on the `answer` frame this replies to, + // echoed back verbatim — the only exact link between a send and its outcome. + | { type: "saved"; question_id: string; updated_at: number; client_seq?: number } | { type: "finished"; finished_at: number } | { type: "expired" } | { type: "pong" } // `question_id` is present only when the server could blame one save. - | { type: "error"; message: string; question_id?: string }; + | { type: "error"; message: string; question_id?: string; client_seq?: number }; function formatRemaining(ms: number | null): string { if (ms == null) return "—"; @@ -99,6 +101,9 @@ export function ExamRoomWS(props: { exam: Exam }) { // A `send()` is not a save. Every WS answer waits for the server's matching // `saved` frame before the student is told anything was stored. const acks = createAckWaiter(); + // Stamped on every `answer` frame and echoed back on its reply. The server + // treats it as opaque, so it only has to be unique while this room lives. + let clientSeq = 0; // Auto-reconnect a socket that drops mid-sitting: a transient network blip // shouldn't freeze the live countdown/state at "disconnected". Rejoining also // clears the backend's `left_at` (which any socket close stamps) — so on an @@ -147,7 +152,7 @@ export function ExamRoomWS(props: { exam: Exam }) { ws.onerror = null; ws.onmessage = null; ws.close(); - acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); + acks.failAll(new Error(t("attempt.saveDisconnected"))); } setWsState("connecting"); const socket = new WebSocket(wsUrl()); @@ -161,7 +166,7 @@ export function ExamRoomWS(props: { exam: Exam }) { setWsState("disconnected"); ws = null; // Anything still waiting for a `saved` frame will never get one. - acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); + acks.failAll(new Error(t("attempt.saveDisconnected"))); scheduleReconnect(); }; socket.onclose = dropped; @@ -189,7 +194,9 @@ export function ExamRoomWS(props: { exam: Exam }) { break; } case "saved": { - acks.ack(msg.question_id); + // No echo means we cannot tell which send this confirms (an older + // server): confirm nobody and let the send time out as unsaved. + if (msg.client_seq != null) acks.ack(msg.client_seq); setQuestions((prev) => prev.map((q) => q.id === msg.question_id @@ -215,13 +222,12 @@ export function ExamRoomWS(props: { exam: Exam }) { case "error": { const message = formatApiErrorMessage(msg.message, locale()); setError(message); - // A frame that names a question refused that one save; anything else is - // room-level (bad frame, sitting over, unenrolled, internal error), so - // everything in flight is treated as rejected — never as saved. The - // socket stays open on this path, so each rejected send is still owed a - // frame of its own: `error-frame` keeps that debt instead of wiping it. - if (msg.question_id) acks.fail(msg.question_id, new Error(message)); - else acks.failAll(new Error(message), "error-frame"); + // A frame that echoes our `client_seq` refused that one send; anything + // else is room-level (bad frame, sitting over, unenrolled, internal + // error) or from an older server, so everything in flight is treated as + // rejected — never as saved. + if (msg.client_seq != null) acks.fail(msg.client_seq, new Error(message)); + else acks.failAll(new Error(message)); break; } } @@ -271,13 +277,14 @@ export function ExamRoomWS(props: { exam: Exam }) { const saveAnswer = async (question: AttemptQuestion, value: string): Promise => { setError(""); if (ws && ws.readyState === WebSocket.OPEN) { - const payload: Record = { type: "answer", question_id: question.id }; + const seq = (clientSeq += 1); + const payload: Record = { type: "answer", question_id: question.id, client_seq: seq }; if (question.kind === "choice") { payload.selected = value; // choice id, not a position } else { payload.text = value; } - const acked = acks.wait(question.id); + const acked = acks.wait(seq, question.id); sendWs(payload); let result; try { diff --git a/src/lib/create-ack-waiter.test.ts b/src/lib/create-ack-waiter.test.ts index e1c59b1..0b72de4 100644 --- a/src/lib/create-ack-waiter.test.ts +++ b/src/lib/create-ack-waiter.test.ts @@ -2,12 +2,12 @@ import { describe, expect, it, vi } from "vitest"; import { createAckWaiter } from "./create-ack-waiter"; describe("createAckWaiter", () => { - it("resolves ok only when the matching ack arrives", async () => { + it("resolves ok only when the ack for that client_seq arrives", async () => { const w = createAckWaiter(1000); - const p = w.wait("q1"); - w.ack("q2"); // another question's ack must not confirm this one + const p = w.wait(1, "q1"); + w.ack(2); // another send's ack must not confirm this one expect(w.size).toBe(1); - w.ack("q1"); + w.ack(1); await expect(p).resolves.toBe("ok"); expect(w.size).toBe(0); }); @@ -15,7 +15,7 @@ describe("createAckWaiter", () => { it("rejects when no ack ever comes back", async () => { vi.useFakeTimers(); const w = createAckWaiter(8000); - const p = w.wait("q1"); + const p = w.wait(1, "q1"); const assertion = expect(p).rejects.toThrow("ack timeout"); await vi.advanceTimersByTimeAsync(8000); await assertion; @@ -23,152 +23,108 @@ describe("createAckWaiter", () => { vi.useRealTimers(); }); - it("rejects every pending wait on failAll (error frame / socket drop)", async () => { + it("rejects every pending wait on failAll (unattributable frame / socket drop)", async () => { const w = createAckWaiter(1000); - const a = w.wait("q1"); - const b = w.wait("q2"); - w.failAll(new Error("disconnected"), "socket-closed"); + const a = w.wait(1, "q1"); + const b = w.wait(2, "q2"); + w.failAll(new Error("disconnected")); await expect(a).rejects.toThrow("disconnected"); await expect(b).rejects.toThrow("disconnected"); expect(w.size).toBe(0); }); - // Regression (defect 1): an unattributed error frame does NOT close the socket - // (`exam_ws.rs:496` keeps serving), so the frames owed to the sends it rejected - // are still on their way. One of them must not confirm the student's retry. - it("does not let an in-flight ack confirm the retry after an unattributed error frame", async () => { + it("fails only the named send when the error frame echoes its client_seq", async () => { const w = createAckWaiter(1000); - const first = w.wait("q1"); - const firstAssertion = expect(first).rejects.toThrow("state unavailable"); - w.failAll(new Error("state unavailable"), "error-frame"); // socket stays open - await firstAssertion; - - const retry = w.wait("q1"); - let outcome: string | undefined; - void retry.then( - (r) => { outcome = `resolved:${r}`; }, - (e: Error) => { outcome = `rejected:${e.message}`; }, - ); - w.ack("q1"); // the FIRST send's `saved` frame, still in flight - await Promise.resolve(); - expect(outcome).toBeUndefined(); // must NOT claim the retry was saved - - w.ack("q1"); // now the retry's own frame - await expect(retry).resolves.toBe("ok"); - }); - - // A genuine socket close means nothing is coming: the debt must not survive - // into the reconnect, or the next save on that question would eat its own ack. - it("clears owed frames when the socket actually closes", async () => { - const w = createAckWaiter(1000); - const first = w.wait("q1"); - const firstAssertion = expect(first).rejects.toThrow("state unavailable"); - w.failAll(new Error("state unavailable"), "error-frame"); - await firstAssertion; - - w.failAll(new Error("disconnected"), "socket-closed"); // socket drops, reconnect - const afterReconnect = w.wait("q1"); - w.ack("q1"); - await expect(afterReconnect).resolves.toBe("ok"); - }); - - it("fails only the named save when the error frame blames one question", async () => { - const w = createAckWaiter(1000); - const a = w.wait("q1"); - const b = w.wait("q2"); - w.fail("q1", new Error("a choice question takes selected")); + const a = w.wait(1, "q1"); + const b = w.wait(2, "q2"); + w.fail(1, new Error("a choice question takes selected")); await expect(a).rejects.toThrow("a choice question takes selected"); expect(w.size).toBe(1); // q2 is still waiting for its own answer - w.ack("q2"); + w.ack(2); await expect(b).resolves.toBe("ok"); }); - it("ignores a fail for a question with nothing in flight", () => { + it("ignores a fail for a client_seq with nothing in flight", () => { const w = createAckWaiter(1000); - void w.wait("q1").catch(() => {}); - w.fail("q2", new Error("boom")); // late/unknown blame must not touch q1 + void w.wait(1, "q1").catch(() => {}); + w.fail(2, new Error("boom")); // late/unknown blame must not touch send #1 expect(w.size).toBe(1); - w.failAll(new Error("cleanup"), "socket-closed"); + w.failAll(new Error("cleanup")); }); it("marks an overtaken save superseded and lets its own ack settle nobody", async () => { const w = createAckWaiter(1000); - const first = w.wait("q1"); - const second = w.wait("q1"); + const first = w.wait(1, "q1"); + const second = w.wait(2, "q1"); await expect(first).resolves.toBe("superseded"); expect(w.size).toBe(1); - w.ack("q1"); // the first send's ack — the second is still unconfirmed + w.ack(1); // the first send's ack — it owns nobody now expect(w.size).toBe(1); - w.ack("q1"); // now the second send's own ack + w.ack(2); await expect(second).resolves.toBe("ok"); expect(w.size).toBe(0); }); // Regression: a `saved` frame for a send that already timed out must never // confirm the retry that replaced it — that told students "Saved" for an - // answer the server had refused. + // answer the server had refused. With exact correlation the late frame simply + // names a send nobody waits on, and it no longer poisons the retry either. it("does not let a timed-out send's late ack confirm the retry", async () => { vi.useFakeTimers(); const w = createAckWaiter(8000); - const first = w.wait("q1"); // student saves "A" + const first = w.wait(1, "q1"); // student saves "A" const firstAssertion = expect(first).rejects.toThrow("ack timeout"); await vi.advanceTimersByTimeAsync(8000); await firstAssertion; - const retry = w.wait("q1"); // student presses save again with "B" + const retry = w.wait(2, "q1"); // student presses save again with "B" let outcome: string | undefined; void retry.then( (r) => { outcome = `resolved:${r}`; }, (e: Error) => { outcome = `rejected:${e.message}`; }, ); - w.ack("q1"); // the FIRST send's late `saved` frame finally lands + w.ack(1); // the FIRST send's late `saved` frame finally lands await vi.advanceTimersByTimeAsync(0); expect(outcome).toBeUndefined(); // must NOT claim the retry was saved - w.fail("q1", new Error("a choice question takes selected")); // the retry's own error frame + w.ack(2); // the retry's own frame — no debt swallowed it await vi.advanceTimersByTimeAsync(0); - expect(outcome).toBe("rejected:a choice question takes selected"); + expect(outcome).toBe("resolved:ok"); vi.useRealTimers(); }); - // Regression (defect 2): the old tombstone was dropped by a timer after one - // more timeout window, so a frame arriving after that settled the NEXT live - // send "ok". Debt has no expiry — it is only ever paid off by a frame. - it("does not let a very late ack confirm a newer send once the tombstone window would have lapsed", async () => { - vi.useFakeTimers(); - const w = createAckWaiter(8000); - const first = w.wait("q1"); // t=0, send #1 - const firstAssertion = expect(first).rejects.toThrow("ack timeout"); - await vi.advanceTimersByTimeAsync(8000); // t=8s, send #1 times out + // The unattributable-error path keeps the socket open, so the frames owed to + // the sends it rejected are still on their way. They name their own client_seq + // and settle nobody; the retry is confirmed by its own frame, not by theirs. + it("does not let an in-flight ack confirm the retry after an unattributable error frame", async () => { + const w = createAckWaiter(1000); + const first = w.wait(1, "q1"); + const firstAssertion = expect(first).rejects.toThrow("state unavailable"); + w.failAll(new Error("state unavailable")); // socket stays open await firstAssertion; - await vi.advanceTimersByTimeAsync(1000); // t=9s - const second = w.wait("q1"); // send #2, live + const retry = w.wait(2, "q1"); let outcome: string | undefined; - void second.then( + void retry.then( (r) => { outcome = `resolved:${r}`; }, (e: Error) => { outcome = `rejected:${e.message}`; }, ); + w.ack(1); // the FIRST send's `saved` frame, still in flight + await Promise.resolve(); + expect(outcome).toBeUndefined(); // must NOT claim the retry was saved - await vi.advanceTimersByTimeAsync(7000); // t=16s, old tombstone expiry moment - w.ack("q1"); // send #1's frame lands at last - await vi.advanceTimersByTimeAsync(0); - expect(outcome).toBeUndefined(); // must NOT confirm send #2 - - w.ack("q1"); // send #2's own frame - await vi.advanceTimersByTimeAsync(0); - expect(outcome).toBe("resolved:ok"); - vi.useRealTimers(); + w.ack(2); + await expect(retry).resolves.toBe("ok"); }); it("does not confirm after a timeout has already fired", async () => { vi.useFakeTimers(); const w = createAckWaiter(100); - const p = w.wait("q1"); + const p = w.wait(1, "q1"); const assertion = expect(p).rejects.toThrow("ack timeout"); await vi.advanceTimersByTimeAsync(100); - w.ack("q1"); // late ack: nothing to settle, must not throw + w.ack(1); // late ack: nothing to settle, must not throw await assertion; vi.useRealTimers(); }); diff --git a/src/lib/create-ack-waiter.ts b/src/lib/create-ack-waiter.ts index ff2d2b1..ee38d72 100644 --- a/src/lib/create-ack-waiter.ts +++ b/src/lib/create-ack-waiter.ts @@ -3,30 +3,19 @@ * * A WebSocket `send()` only means "handed to the OS" — it is not a save. The * exam room waits for the server's `{"type":"saved", question_id}` frame before - * it may tell a student their answer is stored. `wait(key)` hands back a promise - * that settles on `ack(key)`, rejects on `fail(key)` (an error frame that names - * the question it refused), rejects on `failAll()` (a socket drop, or an - * unattributed error frame) and rejects on its own timeout when nothing ever - * comes back. + * it may tell a student their answer is stored. `wait(seq, key)` hands back a + * promise that settles on `ack(seq)`, rejects on `fail(seq)` (an error frame + * that names the send it refused), rejects on `failAll()` (a socket drop, or a + * frame that identifies no send at all) and rejects on its own timeout when + * nothing ever comes back. * - * **Acks are matched per send, not per question.** The server answers every - * `answer` frame with exactly one `saved`/`error` frame, in order - * (`exam_ws.rs:396,410`), so each key keeps a FIFO queue of the sends that still - * own a promise, plus `owed`: a count of frames the server still has to send for - * sends that no longer own anybody's promise (they timed out, a newer save - * overtook them, or an unattributed error frame rejected them while the socket - * stayed open). Those dead sends are always older than any live one, so an - * incoming frame pays off `owed` first and is discarded; only once the debt is - * clear does a frame settle the oldest live send. That is exact and timer-free — - * nothing can expire into the wrong match, and send #1's late `saved` can never - * confirm send #2. - * - * Trade-off: if the server truly never answers a send, its debt sits there and - * swallows one later legitimate frame, so that question's next save reads "not - * saved" and the student presses save again. Wrong in the safe direction — the - * badge never claims "Saved" for a payload the server did not accept. The debt - * is not permanent: a socket close clears it (`failAll(..., "socket-closed")`), - * so a reconnect always starts from zero. + * **Acks are matched per send, not per question.** Every `answer` frame carries + * a `client_seq` the caller mints, and the server echoes it on the one + * `saved`/`error` frame that answers it — so a reply names its send exactly. + * Nothing is ever inferred from arrival order: a send that timed out or was + * overtaken is simply gone, and its late frame finds no entry and settles + * nobody. The `client_seq` is opaque to the server (no dedupe, no ordering); + * uniqueness within a socket's lifetime is the caller's job. * * A second `wait()` for the same key means the student saved again: the older * promise resolves `"superseded"` so its caller stays quiet and the newer save @@ -38,101 +27,64 @@ export type AckResult = "ok" | "superseded"; export const ACK_TIMEOUT = "ack timeout"; type Entry = { + /** Question this send belongs to — only used to supersede its older sends. */ + key: string; settle: (result: AckResult) => void; fail: (reason: Error) => void; timer: ReturnType; }; -/** - * Why every pending save is being rejected at once: - * - `socket-closed` — the socket dropped or we replaced it. Nothing is coming, - * ever, so both the queue and the debt are wiped. - * - `error-frame` — the server refused something it could not attribute to one - * question and **kept the socket open** (`exam_ws.rs:496` sends - * `error_frame_for(err, None)` and keeps serving). Each in-flight send is - * still owed its own frame, so rejecting them turns them into debt. - */ -export type FailAllCause = "socket-closed" | "error-frame"; - export function createAckWaiter(timeoutMs = 8000) { - const queues = new Map(); - /** key → frames the server still owes for sends nobody is waiting on anymore. */ - const owed = new Map(); + /** client_seq → the send still waiting on its reply. */ + const pending = new Map(); - /** This send lost its owner but the server will still answer it: bank the debt. */ - const disown = (key: string, entry: Entry) => { - clearTimeout(entry.timer); - const queue = queues.get(key); - const at = queue?.indexOf(entry) ?? -1; - if (queue && at >= 0) queue.splice(at, 1); - if (queue && queue.length === 0) queues.delete(key); - owed.set(key, (owed.get(key) ?? 0) + 1); - }; - - /** - * Pop the send an incoming frame belongs to, or `undefined` when the frame - * pays off an older dead send instead (debt is always older than live sends). - */ - const takeOldest = (key: string) => { - const debt = owed.get(key) ?? 0; - if (debt > 0) { - if (debt === 1) owed.delete(key); - else owed.set(key, debt - 1); - return undefined; - } - const queue = queues.get(key); - if (!queue || queue.length === 0) return undefined; - const entry = queue.shift()!; - if (queue.length === 0) queues.delete(key); + const take = (seq: number) => { + const entry = pending.get(seq); + if (!entry) return undefined; + pending.delete(seq); clearTimeout(entry.timer); return entry; }; return { - wait(key: string): Promise { - // Disowning the last live entry drops the queue, so re-seat it afterwards. - for (const entry of [...(queues.get(key) ?? [])]) { + wait(seq: number, key: string): Promise { + for (const [at, entry] of [...pending]) { + if (entry.key !== key) continue; + pending.delete(at); + clearTimeout(entry.timer); entry.settle("superseded"); - disown(key, entry); } - const queue = queues.get(key) ?? []; - queues.set(key, queue); return new Promise((resolve, reject) => { - const entry: Entry = { + pending.set(seq, { + key, settle: resolve, fail: reject, timer: setTimeout(() => { - entry.fail(new Error(ACK_TIMEOUT)); - disown(key, entry); + pending.delete(seq); + reject(new Error(ACK_TIMEOUT)); }, timeoutMs), - }; - queue.push(entry); + }); }); }, - ack(key: string) { - takeOldest(key)?.settle("ok"); + ack(seq: number) { + take(seq)?.settle("ok"); }, - /** Reject one save — the server blamed this question and no other. */ - fail(key: string, reason: Error) { - takeOldest(key)?.fail(reason); + /** Reject one save — the server blamed this send and no other. */ + fail(seq: number, reason: Error) { + take(seq)?.fail(reason); }, - failAll(reason: Error, cause: FailAllCause) { - for (const [key, queue] of [...queues]) { - for (const entry of [...queue]) { - entry.fail(reason); - if (cause === "error-frame") disown(key, entry); - else clearTimeout(entry.timer); - } - if (cause === "socket-closed") queues.delete(key); - } - // A dead socket answers nothing: the reconnect must not inherit old debt. - if (cause === "socket-closed") owed.clear(); + /** + * Reject everything in flight: the socket dropped, or a frame arrived that + * named no send (a room-level error, or an older server that echoes no + * `client_seq`). Refusing them all is the safe read — a badge must never + * say "Saved" for a payload the server did not confirm. + */ + failAll(reason: Error) { + for (const [seq] of [...pending]) take(seq)?.fail(reason); }, - /** Sends still waiting for an outcome — banked debt doesn't count. */ + /** Sends still waiting for an outcome. */ get size() { - let n = 0; - for (const queue of queues.values()) n += queue.length; - return n; + return pending.size; }, }; }