π·οΈ settle exam-room saves by client_seq, not by guesswork
Browse files at this commitb5d89d99bba3816af55e5ea58a5b785c9b955932Parent: 5d93c16- fix
- π·οΈ settle exam-room saves by client_seq, not by guesswork
3 changed files +112 -197
- src/components/exams/exam-room-ws.tsx +21 -14
- src/lib/create-ack-waiter.test.ts +46 -90
- src/lib/create-ack-waiter.ts +45 -93
src/components/exams/exam-room-ws.tsxmodified+21 -14
| @@ -32,12 +32,14 @@ const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => | |||
| 32 | type WsState = "connecting" | "connected" | "disconnected"; | 32 | type WsState = "connecting" | "connected" | "disconnected"; |
| 33 | type WsMessage = | 33 | type WsMessage = |
| 34 | | { type: "state"; status: string; deadline: number | null; remaining_ms: number | null; now: number; answered: number; question_count: number } | 34 | | { type: "state"; status: string; deadline: number | null; remaining_ms: number | null; now: number; answered: number; question_count: number } |
| 35 | - | { type: "saved"; question_id: string; updated_at: number } | 35 | + // `client_seq` is the value we minted on the `answer` frame this replies to, |
| 36 | + // echoed back verbatim β the only exact link between a send and its outcome. | ||
| 37 | + | { type: "saved"; question_id: string; updated_at: number; client_seq?: number } | ||
| 36 | | { type: "finished"; finished_at: number } | 38 | | { type: "finished"; finished_at: number } |
| 37 | | { type: "expired" } | 39 | | { type: "expired" } |
| 38 | | { type: "pong" } | 40 | | { type: "pong" } |
| 39 | // `question_id` is present only when the server could blame one save. | 41 | // `question_id` is present only when the server could blame one save. |
| 40 | - | { type: "error"; message: string; question_id?: string }; | 42 | + | { type: "error"; message: string; question_id?: string; client_seq?: number }; |
| 41 | 43 | ||
| 42 | function formatRemaining(ms: number | null): string { | 44 | function formatRemaining(ms: number | null): string { |
| 43 | if (ms == null) return "β"; | 45 | if (ms == null) return "β"; |
| @@ -99,6 +101,9 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 99 | // A `send()` is not a save. Every WS answer waits for the server's matching | 101 | // A `send()` is not a save. Every WS answer waits for the server's matching |
| 100 | // `saved` frame before the student is told anything was stored. | 102 | // `saved` frame before the student is told anything was stored. |
| 101 | const acks = createAckWaiter(); | 103 | const acks = createAckWaiter(); |
| 104 | + // Stamped on every `answer` frame and echoed back on its reply. The server | ||
| 105 | + // treats it as opaque, so it only has to be unique while this room lives. | ||
| 106 | + let clientSeq = 0; | ||
| 102 | // Auto-reconnect a socket that drops mid-sitting: a transient network blip | 107 | // Auto-reconnect a socket that drops mid-sitting: a transient network blip |
| 103 | // shouldn't freeze the live countdown/state at "disconnected". Rejoining also | 108 | // shouldn't freeze the live countdown/state at "disconnected". Rejoining also |
| 104 | // clears the backend's `left_at` (which any socket close stamps) β so on an | 109 | // clears the backend's `left_at` (which any socket close stamps) β so on an |
| @@ -147,7 +152,7 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 147 | ws.onerror = null; | 152 | ws.onerror = null; |
| 148 | ws.onmessage = null; | 153 | ws.onmessage = null; |
| 149 | ws.close(); | 154 | ws.close(); |
| 150 | - acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); | 155 | + acks.failAll(new Error(t("attempt.saveDisconnected"))); |
| 151 | } | 156 | } |
| 152 | setWsState("connecting"); | 157 | setWsState("connecting"); |
| 153 | const socket = new WebSocket(wsUrl()); | 158 | const socket = new WebSocket(wsUrl()); |
| @@ -161,7 +166,7 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 161 | setWsState("disconnected"); | 166 | setWsState("disconnected"); |
| 162 | ws = null; | 167 | ws = null; |
| 163 | // Anything still waiting for a `saved` frame will never get one. | 168 | // Anything still waiting for a `saved` frame will never get one. |
| 164 | - acks.failAll(new Error(t("attempt.saveDisconnected")), "socket-closed"); | 169 | + acks.failAll(new Error(t("attempt.saveDisconnected"))); |
| 165 | scheduleReconnect(); | 170 | scheduleReconnect(); |
| 166 | }; | 171 | }; |
| 167 | socket.onclose = dropped; | 172 | socket.onclose = dropped; |
| @@ -189,7 +194,9 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 189 | break; | 194 | break; |
| 190 | } | 195 | } |
| 191 | case "saved": { | 196 | case "saved": { |
| 192 | - acks.ack(msg.question_id); | 197 | + // No echo means we cannot tell which send this confirms (an older |
| 198 | + // server): confirm nobody and let the send time out as unsaved. | ||
| 199 | + if (msg.client_seq != null) acks.ack(msg.client_seq); | ||
| 193 | setQuestions((prev) => | 200 | setQuestions((prev) => |
| 194 | prev.map((q) => | 201 | prev.map((q) => |
| 195 | q.id === msg.question_id | 202 | q.id === msg.question_id |
| @@ -215,13 +222,12 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 215 | case "error": { | 222 | case "error": { |
| 216 | const message = formatApiErrorMessage(msg.message, locale()); | 223 | const message = formatApiErrorMessage(msg.message, locale()); |
| 217 | setError(message); | 224 | setError(message); |
| 218 | - // A frame that names a question refused that one save; anything else is | 225 | + // A frame that echoes our `client_seq` refused that one send; anything |
| 219 | - // room-level (bad frame, sitting over, unenrolled, internal error), so | 226 | + // else is room-level (bad frame, sitting over, unenrolled, internal |
| 220 | - // everything in flight is treated as rejected β never as saved. The | 227 | + // error) or from an older server, so everything in flight is treated as |
| 221 | - // socket stays open on this path, so each rejected send is still owed a | 228 | + // rejected β never as saved. |
| 222 | - // frame of its own: `error-frame` keeps that debt instead of wiping it. | 229 | + if (msg.client_seq != null) acks.fail(msg.client_seq, new Error(message)); |
| 223 | - if (msg.question_id) acks.fail(msg.question_id, new Error(message)); | 230 | + else acks.failAll(new Error(message)); |
| 224 | - else acks.failAll(new Error(message), "error-frame"); | ||
| 225 | break; | 231 | break; |
| 226 | } | 232 | } |
| 227 | } | 233 | } |
| @@ -271,13 +277,14 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 271 | const saveAnswer = async (question: AttemptQuestion, value: string): Promise<boolean> => { | 277 | const saveAnswer = async (question: AttemptQuestion, value: string): Promise<boolean> => { |
| 272 | setError(""); | 278 | setError(""); |
| 273 | if (ws && ws.readyState === WebSocket.OPEN) { | 279 | if (ws && ws.readyState === WebSocket.OPEN) { |
| 274 | - const payload: Record<string, unknown> = { type: "answer", question_id: question.id }; | 280 | + const seq = (clientSeq += 1); |
| 281 | + const payload: Record<string, unknown> = { type: "answer", question_id: question.id, client_seq: seq }; | ||
| 275 | if (question.kind === "choice") { | 282 | if (question.kind === "choice") { |
| 276 | payload.selected = value; // choice id, not a position | 283 | payload.selected = value; // choice id, not a position |
| 277 | } else { | 284 | } else { |
| 278 | payload.text = value; | 285 | payload.text = value; |
| 279 | } | 286 | } |
| 280 | - const acked = acks.wait(question.id); | 287 | + const acked = acks.wait(seq, question.id); |
| 281 | sendWs(payload); | 288 | sendWs(payload); |
| 282 | let result; | 289 | let result; |
| 283 | try { | 290 | try { |
src/lib/create-ack-waiter.test.tsmodified+46 -90
| @@ -2,12 +2,12 @@ import { describe, expect, it, vi } from "vitest"; | |||
| 2 | import { createAckWaiter } from "./create-ack-waiter"; | 2 | import { createAckWaiter } from "./create-ack-waiter"; |
| 3 | 3 | ||
| 4 | describe("createAckWaiter", () => { | 4 | describe("createAckWaiter", () => { |
| 5 | - it("resolves ok only when the matching ack arrives", async () => { | 5 | + it("resolves ok only when the ack for that client_seq arrives", async () => { |
| 6 | const w = createAckWaiter(1000); | 6 | const w = createAckWaiter(1000); |
| 7 | - const p = w.wait("q1"); | 7 | + const p = w.wait(1, "q1"); |
| 8 | - w.ack("q2"); // another question's ack must not confirm this one | 8 | + w.ack(2); // another send's ack must not confirm this one |
| 9 | expect(w.size).toBe(1); | 9 | expect(w.size).toBe(1); |
| 10 | - w.ack("q1"); | 10 | + w.ack(1); |
| 11 | await expect(p).resolves.toBe("ok"); | 11 | await expect(p).resolves.toBe("ok"); |
| 12 | expect(w.size).toBe(0); | 12 | expect(w.size).toBe(0); |
| 13 | }); | 13 | }); |
| @@ -15,7 +15,7 @@ describe("createAckWaiter", () => { | |||
| 15 | it("rejects when no ack ever comes back", async () => { | 15 | it("rejects when no ack ever comes back", async () => { |
| 16 | vi.useFakeTimers(); | 16 | vi.useFakeTimers(); |
| 17 | const w = createAckWaiter(8000); | 17 | const w = createAckWaiter(8000); |
| 18 | - const p = w.wait("q1"); | 18 | + const p = w.wait(1, "q1"); |
| 19 | const assertion = expect(p).rejects.toThrow("ack timeout"); | 19 | const assertion = expect(p).rejects.toThrow("ack timeout"); |
| 20 | await vi.advanceTimersByTimeAsync(8000); | 20 | await vi.advanceTimersByTimeAsync(8000); |
| 21 | await assertion; | 21 | await assertion; |
| @@ -23,152 +23,108 @@ describe("createAckWaiter", () => { | |||
| 23 | vi.useRealTimers(); | 23 | vi.useRealTimers(); |
| 24 | }); | 24 | }); |
| 25 | 25 | ||
| 26 | - it("rejects every pending wait on failAll (error frame / socket drop)", async () => { | 26 | + it("rejects every pending wait on failAll (unattributable frame / socket drop)", async () => { |
| 27 | const w = createAckWaiter(1000); | 27 | const w = createAckWaiter(1000); |
| 28 | - const a = w.wait("q1"); | 28 | + const a = w.wait(1, "q1"); |
| 29 | - const b = w.wait("q2"); | 29 | + const b = w.wait(2, "q2"); |
| 30 | - w.failAll(new Error("disconnected"), "socket-closed"); | 30 | + w.failAll(new Error("disconnected")); |
| 31 | await expect(a).rejects.toThrow("disconnected"); | 31 | await expect(a).rejects.toThrow("disconnected"); |
| 32 | await expect(b).rejects.toThrow("disconnected"); | 32 | await expect(b).rejects.toThrow("disconnected"); |
| 33 | expect(w.size).toBe(0); | 33 | expect(w.size).toBe(0); |
| 34 | }); | 34 | }); |
| 35 | 35 | ||
| 36 | - // Regression (defect 1): an unattributed error frame does NOT close the socket | 36 | + it("fails only the named send when the error frame echoes its client_seq", async () => { |
| 37 | - // (`exam_ws.rs:496` keeps serving), so the frames owed to the sends it rejected | ||
| 38 | - // are still on their way. One of them must not confirm the student's retry. | ||
| 39 | - it("does not let an in-flight ack confirm the retry after an unattributed error frame", async () => { | ||
| 40 | const w = createAckWaiter(1000); | 37 | const w = createAckWaiter(1000); |
| 41 | - const first = w.wait("q1"); | 38 | + const a = w.wait(1, "q1"); |
| 42 | - const firstAssertion = expect(first).rejects.toThrow("state unavailable"); | 39 | + const b = w.wait(2, "q2"); |
| 43 | - w.failAll(new Error("state unavailable"), "error-frame"); // socket stays open | 40 | + w.fail(1, new Error("a choice question takes selected")); |
| 44 | - await firstAssertion; | ||
| 45 | - | ||
| 46 | - const retry = w.wait("q1"); | ||
| 47 | - let outcome: string | undefined; | ||
| 48 | - void retry.then( | ||
| 49 | - (r) => { outcome = `resolved:${r}`; }, | ||
| 50 | - (e: Error) => { outcome = `rejected:${e.message}`; }, | ||
| 51 | - ); | ||
| 52 | - w.ack("q1"); // the FIRST send's `saved` frame, still in flight | ||
| 53 | - await Promise.resolve(); | ||
| 54 | - expect(outcome).toBeUndefined(); // must NOT claim the retry was saved | ||
| 55 | - | ||
| 56 | - w.ack("q1"); // now the retry's own frame | ||
| 57 | - await expect(retry).resolves.toBe("ok"); | ||
| 58 | - }); | ||
| 59 | - | ||
| 60 | - // A genuine socket close means nothing is coming: the debt must not survive | ||
| 61 | - // into the reconnect, or the next save on that question would eat its own ack. | ||
| 62 | - it("clears owed frames when the socket actually closes", async () => { | ||
| 63 | - const w = createAckWaiter(1000); | ||
| 64 | - const first = w.wait("q1"); | ||
| 65 | - const firstAssertion = expect(first).rejects.toThrow("state unavailable"); | ||
| 66 | - w.failAll(new Error("state unavailable"), "error-frame"); | ||
| 67 | - await firstAssertion; | ||
| 68 | - | ||
| 69 | - w.failAll(new Error("disconnected"), "socket-closed"); // socket drops, reconnect | ||
| 70 | - const afterReconnect = w.wait("q1"); | ||
| 71 | - w.ack("q1"); | ||
| 72 | - await expect(afterReconnect).resolves.toBe("ok"); | ||
| 73 | - }); | ||
| 74 | - | ||
| 75 | - it("fails only the named save when the error frame blames one question", async () => { | ||
| 76 | - const w = createAckWaiter(1000); | ||
| 77 | - const a = w.wait("q1"); | ||
| 78 | - const b = w.wait("q2"); | ||
| 79 | - w.fail("q1", new Error("a choice question takes selected")); | ||
| 80 | await expect(a).rejects.toThrow("a choice question takes selected"); | 41 | await expect(a).rejects.toThrow("a choice question takes selected"); |
| 81 | expect(w.size).toBe(1); // q2 is still waiting for its own answer | 42 | expect(w.size).toBe(1); // q2 is still waiting for its own answer |
| 82 | - w.ack("q2"); | 43 | + w.ack(2); |
| 83 | await expect(b).resolves.toBe("ok"); | 44 | await expect(b).resolves.toBe("ok"); |
| 84 | }); | 45 | }); |
| 85 | 46 | ||
| 86 | - it("ignores a fail for a question with nothing in flight", () => { | 47 | + it("ignores a fail for a client_seq with nothing in flight", () => { |
| 87 | const w = createAckWaiter(1000); | 48 | const w = createAckWaiter(1000); |
| 88 | - void w.wait("q1").catch(() => {}); | 49 | + void w.wait(1, "q1").catch(() => {}); |
| 89 | - w.fail("q2", new Error("boom")); // late/unknown blame must not touch q1 | 50 | + w.fail(2, new Error("boom")); // late/unknown blame must not touch send #1 |
| 90 | expect(w.size).toBe(1); | 51 | expect(w.size).toBe(1); |
| 91 | - w.failAll(new Error("cleanup"), "socket-closed"); | 52 | + w.failAll(new Error("cleanup")); |
| 92 | }); | 53 | }); |
| 93 | 54 | ||
| 94 | it("marks an overtaken save superseded and lets its own ack settle nobody", async () => { | 55 | it("marks an overtaken save superseded and lets its own ack settle nobody", async () => { |
| 95 | const w = createAckWaiter(1000); | 56 | const w = createAckWaiter(1000); |
| 96 | - const first = w.wait("q1"); | 57 | + const first = w.wait(1, "q1"); |
| 97 | - const second = w.wait("q1"); | 58 | + const second = w.wait(2, "q1"); |
| 98 | await expect(first).resolves.toBe("superseded"); | 59 | await expect(first).resolves.toBe("superseded"); |
| 99 | expect(w.size).toBe(1); | 60 | expect(w.size).toBe(1); |
| 100 | - w.ack("q1"); // the first send's ack β the second is still unconfirmed | 61 | + w.ack(1); // the first send's ack β it owns nobody now |
| 101 | expect(w.size).toBe(1); | 62 | expect(w.size).toBe(1); |
| 102 | - w.ack("q1"); // now the second send's own ack | 63 | + w.ack(2); |
| 103 | await expect(second).resolves.toBe("ok"); | 64 | await expect(second).resolves.toBe("ok"); |
| 104 | expect(w.size).toBe(0); | 65 | expect(w.size).toBe(0); |
| 105 | }); | 66 | }); |
| 106 | 67 | ||
| 107 | // Regression: a `saved` frame for a send that already timed out must never | 68 | // Regression: a `saved` frame for a send that already timed out must never |
| 108 | // confirm the retry that replaced it β that told students "Saved" for an | 69 | // confirm the retry that replaced it β that told students "Saved" for an |
| 109 | - // answer the server had refused. | 70 | + // answer the server had refused. With exact correlation the late frame simply |
| 71 | + // names a send nobody waits on, and it no longer poisons the retry either. | ||
| 110 | it("does not let a timed-out send's late ack confirm the retry", async () => { | 72 | it("does not let a timed-out send's late ack confirm the retry", async () => { |
| 111 | vi.useFakeTimers(); | 73 | vi.useFakeTimers(); |
| 112 | const w = createAckWaiter(8000); | 74 | const w = createAckWaiter(8000); |
| 113 | - const first = w.wait("q1"); // student saves "A" | 75 | + const first = w.wait(1, "q1"); // student saves "A" |
| 114 | const firstAssertion = expect(first).rejects.toThrow("ack timeout"); | 76 | const firstAssertion = expect(first).rejects.toThrow("ack timeout"); |
| 115 | await vi.advanceTimersByTimeAsync(8000); | 77 | await vi.advanceTimersByTimeAsync(8000); |
| 116 | await firstAssertion; | 78 | await firstAssertion; |
| 117 | 79 | ||
| 118 | - const retry = w.wait("q1"); // student presses save again with "B" | 80 | + const retry = w.wait(2, "q1"); // student presses save again with "B" |
| 119 | let outcome: string | undefined; | 81 | let outcome: string | undefined; |
| 120 | void retry.then( | 82 | void retry.then( |
| 121 | (r) => { outcome = `resolved:${r}`; }, | 83 | (r) => { outcome = `resolved:${r}`; }, |
| 122 | (e: Error) => { outcome = `rejected:${e.message}`; }, | 84 | (e: Error) => { outcome = `rejected:${e.message}`; }, |
| 123 | ); | 85 | ); |
| 124 | 86 | ||
| 125 | - w.ack("q1"); // the FIRST send's late `saved` frame finally lands | 87 | + w.ack(1); // the FIRST send's late `saved` frame finally lands |
| 126 | await vi.advanceTimersByTimeAsync(0); | 88 | await vi.advanceTimersByTimeAsync(0); |
| 127 | expect(outcome).toBeUndefined(); // must NOT claim the retry was saved | 89 | expect(outcome).toBeUndefined(); // must NOT claim the retry was saved |
| 128 | 90 | ||
| 129 | - w.fail("q1", new Error("a choice question takes selected")); // the retry's own error frame | 91 | + w.ack(2); // the retry's own frame β no debt swallowed it |
| 130 | await vi.advanceTimersByTimeAsync(0); | 92 | await vi.advanceTimersByTimeAsync(0); |
| 131 | - expect(outcome).toBe("rejected:a choice question takes selected"); | 93 | + expect(outcome).toBe("resolved:ok"); |
| 132 | vi.useRealTimers(); | 94 | vi.useRealTimers(); |
| 133 | }); | 95 | }); |
| 134 | 96 | ||
| 135 | - // Regression (defect 2): the old tombstone was dropped by a timer after one | 97 | + // The unattributable-error path keeps the socket open, so the frames owed to |
| 136 | - // more timeout window, so a frame arriving after that settled the NEXT live | 98 | + // the sends it rejected are still on their way. They name their own client_seq |
| 137 | - // send "ok". Debt has no expiry β it is only ever paid off by a frame. | 99 | + // and settle nobody; the retry is confirmed by its own frame, not by theirs. |
| 138 | - it("does not let a very late ack confirm a newer send once the tombstone window would have lapsed", async () => { | 100 | + it("does not let an in-flight ack confirm the retry after an unattributable error frame", async () => { |
| 139 | - vi.useFakeTimers(); | 101 | + const w = createAckWaiter(1000); |
| 140 | - const w = createAckWaiter(8000); | 102 | + const first = w.wait(1, "q1"); |
| 141 | - const first = w.wait("q1"); // t=0, send #1 | 103 | + const firstAssertion = expect(first).rejects.toThrow("state unavailable"); |
| 142 | - const firstAssertion = expect(first).rejects.toThrow("ack timeout"); | 104 | + w.failAll(new Error("state unavailable")); // socket stays open |
| 143 | - await vi.advanceTimersByTimeAsync(8000); // t=8s, send #1 times out | ||
| 144 | await firstAssertion; | 105 | await firstAssertion; |
| 145 | 106 | ||
| 146 | - await vi.advanceTimersByTimeAsync(1000); // t=9s | 107 | + const retry = w.wait(2, "q1"); |
| 147 | - const second = w.wait("q1"); // send #2, live | ||
| 148 | let outcome: string | undefined; | 108 | let outcome: string | undefined; |
| 149 | - void second.then( | 109 | + void retry.then( |
| 150 | (r) => { outcome = `resolved:${r}`; }, | 110 | (r) => { outcome = `resolved:${r}`; }, |
| 151 | (e: Error) => { outcome = `rejected:${e.message}`; }, | 111 | (e: Error) => { outcome = `rejected:${e.message}`; }, |
| 152 | ); | 112 | ); |
| 113 | + w.ack(1); // the FIRST send's `saved` frame, still in flight | ||
| 114 | + await Promise.resolve(); | ||
| 115 | + expect(outcome).toBeUndefined(); // must NOT claim the retry was saved | ||
| 153 | 116 | ||
| 154 | - await vi.advanceTimersByTimeAsync(7000); // t=16s, old tombstone expiry moment | 117 | + w.ack(2); |
| 155 | - w.ack("q1"); // send #1's frame lands at last | 118 | + await expect(retry).resolves.toBe("ok"); |
| 156 | - await vi.advanceTimersByTimeAsync(0); | ||
| 157 | - expect(outcome).toBeUndefined(); // must NOT confirm send #2 | ||
| 158 | - | ||
| 159 | - w.ack("q1"); // send #2's own frame | ||
| 160 | - await vi.advanceTimersByTimeAsync(0); | ||
| 161 | - expect(outcome).toBe("resolved:ok"); | ||
| 162 | - vi.useRealTimers(); | ||
| 163 | }); | 119 | }); |
| 164 | 120 | ||
| 165 | it("does not confirm after a timeout has already fired", async () => { | 121 | it("does not confirm after a timeout has already fired", async () => { |
| 166 | vi.useFakeTimers(); | 122 | vi.useFakeTimers(); |
| 167 | const w = createAckWaiter(100); | 123 | const w = createAckWaiter(100); |
| 168 | - const p = w.wait("q1"); | 124 | + const p = w.wait(1, "q1"); |
| 169 | const assertion = expect(p).rejects.toThrow("ack timeout"); | 125 | const assertion = expect(p).rejects.toThrow("ack timeout"); |
| 170 | await vi.advanceTimersByTimeAsync(100); | 126 | await vi.advanceTimersByTimeAsync(100); |
| 171 | - w.ack("q1"); // late ack: nothing to settle, must not throw | 127 | + w.ack(1); // late ack: nothing to settle, must not throw |
| 172 | await assertion; | 128 | await assertion; |
| 173 | vi.useRealTimers(); | 129 | vi.useRealTimers(); |
| 174 | }); | 130 | }); |
src/lib/create-ack-waiter.tsmodified+45 -93
| @@ -3,30 +3,19 @@ | |||
| 3 | * | 3 | * |
| 4 | * A WebSocket `send()` only means "handed to the OS" β it is not a save. The | 4 | * A WebSocket `send()` only means "handed to the OS" β it is not a save. The |
| 5 | * exam room waits for the server's `{"type":"saved", question_id}` frame before | 5 | * exam room waits for the server's `{"type":"saved", question_id}` frame before |
| 6 | - * it may tell a student their answer is stored. `wait(key)` hands back a promise | 6 | + * it may tell a student their answer is stored. `wait(seq, key)` hands back a |
| 7 | - * that settles on `ack(key)`, rejects on `fail(key)` (an error frame that names | 7 | + * promise that settles on `ack(seq)`, rejects on `fail(seq)` (an error frame |
| 8 | - * the question it refused), rejects on `failAll()` (a socket drop, or an | 8 | + * that names the send it refused), rejects on `failAll()` (a socket drop, or a |
| 9 | - * unattributed error frame) and rejects on its own timeout when nothing ever | 9 | + * frame that identifies no send at all) and rejects on its own timeout when |
| 10 | - * comes back. | 10 | + * nothing ever comes back. |
| 11 | * | 11 | * |
| 12 | - * **Acks are matched per send, not per question.** The server answers every | 12 | + * **Acks are matched per send, not per question.** Every `answer` frame carries |
| 13 | - * `answer` frame with exactly one `saved`/`error` frame, in order | 13 | + * a `client_seq` the caller mints, and the server echoes it on the one |
| 14 | - * (`exam_ws.rs:396,410`), so each key keeps a FIFO queue of the sends that still | 14 | + * `saved`/`error` frame that answers it β so a reply names its send exactly. |
| 15 | - * own a promise, plus `owed`: a count of frames the server still has to send for | 15 | + * Nothing is ever inferred from arrival order: a send that timed out or was |
| 16 | - * sends that no longer own anybody's promise (they timed out, a newer save | 16 | + * overtaken is simply gone, and its late frame finds no entry and settles |
| 17 | - * overtook them, or an unattributed error frame rejected them while the socket | 17 | + * nobody. The `client_seq` is opaque to the server (no dedupe, no ordering); |
| 18 | - * stayed open). Those dead sends are always older than any live one, so an | 18 | + * uniqueness within a socket's lifetime is the caller's job. |
| 19 | - * incoming frame pays off `owed` first and is discarded; only once the debt is | ||
| 20 | - * clear does a frame settle the oldest live send. That is exact and timer-free β | ||
| 21 | - * nothing can expire into the wrong match, and send #1's late `saved` can never | ||
| 22 | - * confirm send #2. | ||
| 23 | - * | ||
| 24 | - * Trade-off: if the server truly never answers a send, its debt sits there and | ||
| 25 | - * swallows one later legitimate frame, so that question's next save reads "not | ||
| 26 | - * saved" and the student presses save again. Wrong in the safe direction β the | ||
| 27 | - * badge never claims "Saved" for a payload the server did not accept. The debt | ||
| 28 | - * is not permanent: a socket close clears it (`failAll(..., "socket-closed")`), | ||
| 29 | - * so a reconnect always starts from zero. | ||
| 30 | * | 19 | * |
| 31 | * A second `wait()` for the same key means the student saved again: the older | 20 | * A second `wait()` for the same key means the student saved again: the older |
| 32 | * promise resolves `"superseded"` so its caller stays quiet and the newer save | 21 | * promise resolves `"superseded"` so its caller stays quiet and the newer save |
| @@ -38,101 +27,64 @@ export type AckResult = "ok" | "superseded"; | |||
| 38 | export const ACK_TIMEOUT = "ack timeout"; | 27 | export const ACK_TIMEOUT = "ack timeout"; |
| 39 | 28 | ||
| 40 | type Entry = { | 29 | type Entry = { |
| 30 | + /** Question this send belongs to β only used to supersede its older sends. */ | ||
| 31 | + key: string; | ||
| 41 | settle: (result: AckResult) => void; | 32 | settle: (result: AckResult) => void; |
| 42 | fail: (reason: Error) => void; | 33 | fail: (reason: Error) => void; |
| 43 | timer: ReturnType<typeof setTimeout>; | 34 | timer: ReturnType<typeof setTimeout>; |
| 44 | }; | 35 | }; |
| 45 | 36 | ||
| 46 | -/** | ||
| 47 | - * Why every pending save is being rejected at once: | ||
| 48 | - * - `socket-closed` β the socket dropped or we replaced it. Nothing is coming, | ||
| 49 | - * ever, so both the queue and the debt are wiped. | ||
| 50 | - * - `error-frame` β the server refused something it could not attribute to one | ||
| 51 | - * question and **kept the socket open** (`exam_ws.rs:496` sends | ||
| 52 | - * `error_frame_for(err, None)` and keeps serving). Each in-flight send is | ||
| 53 | - * still owed its own frame, so rejecting them turns them into debt. | ||
| 54 | - */ | ||
| 55 | -export type FailAllCause = "socket-closed" | "error-frame"; | ||
| 56 | - | ||
| 57 | export function createAckWaiter(timeoutMs = 8000) { | 37 | export function createAckWaiter(timeoutMs = 8000) { |
| 58 | - const queues = new Map<string, Entry[]>(); | 38 | + /** client_seq β the send still waiting on its reply. */ |
| 59 | - /** key β frames the server still owes for sends nobody is waiting on anymore. */ | 39 | + const pending = new Map<number, Entry>(); |
| 60 | - const owed = new Map<string, number>(); | ||
| 61 | 40 | ||
| 62 | - /** This send lost its owner but the server will still answer it: bank the debt. */ | 41 | + const take = (seq: number) => { |
| 63 | - const disown = (key: string, entry: Entry) => { | 42 | + const entry = pending.get(seq); |
| 64 | - clearTimeout(entry.timer); | 43 | + if (!entry) return undefined; |
| 65 | - const queue = queues.get(key); | 44 | + pending.delete(seq); |
| 66 | - const at = queue?.indexOf(entry) ?? -1; | ||
| 67 | - if (queue && at >= 0) queue.splice(at, 1); | ||
| 68 | - if (queue && queue.length === 0) queues.delete(key); | ||
| 69 | - owed.set(key, (owed.get(key) ?? 0) + 1); | ||
| 70 | - }; | ||
| 71 | - | ||
| 72 | - /** | ||
| 73 | - * Pop the send an incoming frame belongs to, or `undefined` when the frame | ||
| 74 | - * pays off an older dead send instead (debt is always older than live sends). | ||
| 75 | - */ | ||
| 76 | - const takeOldest = (key: string) => { | ||
| 77 | - const debt = owed.get(key) ?? 0; | ||
| 78 | - if (debt > 0) { | ||
| 79 | - if (debt === 1) owed.delete(key); | ||
| 80 | - else owed.set(key, debt - 1); | ||
| 81 | - return undefined; | ||
| 82 | - } | ||
| 83 | - const queue = queues.get(key); | ||
| 84 | - if (!queue || queue.length === 0) return undefined; | ||
| 85 | - const entry = queue.shift()!; | ||
| 86 | - if (queue.length === 0) queues.delete(key); | ||
| 87 | clearTimeout(entry.timer); | 45 | clearTimeout(entry.timer); |
| 88 | return entry; | 46 | return entry; |
| 89 | }; | 47 | }; |
| 90 | 48 | ||
| 91 | return { | 49 | return { |
| 92 | - wait(key: string): Promise<AckResult> { | 50 | + wait(seq: number, key: string): Promise<AckResult> { |
| 93 | - // Disowning the last live entry drops the queue, so re-seat it afterwards. | 51 | + for (const [at, entry] of [...pending]) { |
| 94 | - for (const entry of [...(queues.get(key) ?? [])]) { | 52 | + if (entry.key !== key) continue; |
| 53 | + pending.delete(at); | ||
| 54 | + clearTimeout(entry.timer); | ||
| 95 | entry.settle("superseded"); | 55 | entry.settle("superseded"); |
| 96 | - disown(key, entry); | ||
| 97 | } | 56 | } |
| 98 | - const queue = queues.get(key) ?? []; | ||
| 99 | - queues.set(key, queue); | ||
| 100 | return new Promise<AckResult>((resolve, reject) => { | 57 | return new Promise<AckResult>((resolve, reject) => { |
| 101 | - const entry: Entry = { | 58 | + pending.set(seq, { |
| 59 | + key, | ||
| 102 | settle: resolve, | 60 | settle: resolve, |
| 103 | fail: reject, | 61 | fail: reject, |
| 104 | timer: setTimeout(() => { | 62 | timer: setTimeout(() => { |
| 105 | - entry.fail(new Error(ACK_TIMEOUT)); | 63 | + pending.delete(seq); |
| 106 | - disown(key, entry); | 64 | + reject(new Error(ACK_TIMEOUT)); |
| 107 | }, timeoutMs), | 65 | }, timeoutMs), |
| 108 | - }; | 66 | + }); |
| 109 | - queue.push(entry); | ||
| 110 | }); | 67 | }); |
| 111 | }, | 68 | }, |
| 112 | - ack(key: string) { | 69 | + ack(seq: number) { |
| 113 | - takeOldest(key)?.settle("ok"); | 70 | + take(seq)?.settle("ok"); |
| 114 | }, | 71 | }, |
| 115 | - /** Reject one save β the server blamed this question and no other. */ | 72 | + /** Reject one save β the server blamed this send and no other. */ |
| 116 | - fail(key: string, reason: Error) { | 73 | + fail(seq: number, reason: Error) { |
| 117 | - takeOldest(key)?.fail(reason); | 74 | + take(seq)?.fail(reason); |
| 118 | }, | 75 | }, |
| 119 | - failAll(reason: Error, cause: FailAllCause) { | 76 | + /** |
| 120 | - for (const [key, queue] of [...queues]) { | 77 | + * Reject everything in flight: the socket dropped, or a frame arrived that |
| 121 | - for (const entry of [...queue]) { | 78 | + * named no send (a room-level error, or an older server that echoes no |
| 122 | - entry.fail(reason); | 79 | + * `client_seq`). Refusing them all is the safe read β a badge must never |
| 123 | - if (cause === "error-frame") disown(key, entry); | 80 | + * say "Saved" for a payload the server did not confirm. |
| 124 | - else clearTimeout(entry.timer); | 81 | + */ |
| 125 | - } | 82 | + failAll(reason: Error) { |
| 126 | - if (cause === "socket-closed") queues.delete(key); | 83 | + for (const [seq] of [...pending]) take(seq)?.fail(reason); |
| 127 | - } | ||
| 128 | - // A dead socket answers nothing: the reconnect must not inherit old debt. | ||
| 129 | - if (cause === "socket-closed") owed.clear(); | ||
| 130 | }, | 84 | }, |
| 131 | - /** Sends still waiting for an outcome β banked debt doesn't count. */ | 85 | + /** Sends still waiting for an outcome. */ |
| 132 | get size() { | 86 | get size() { |
| 133 | - let n = 0; | 87 | + return pending.size; |
| 134 | - for (const queue of queues.values()) n += queue.length; | ||
| 135 | - return n; | ||
| 136 | }, | 88 | }, |
| 137 | }; | 89 | }; |
| 138 | } | 90 | } |