forge
Explore
Log in

Don't you dare go Hollow

🏷️ echo the client's seq on exam-room saved and error frames

Browse files at this commit

9e25eac1eed3df51861e95339fd6a2391ca5ff45Ahmet Kaan GümüşParent: b50d48b
  • feat
    • 🏷️ echo the client's seq on exam-room saved and error frames
Show full message
feat: 🏷️ echo the client's seq on exam-room saved and error frames

`question_id` is not an identity. A student who saves q1, times out, and
saves q1 again has two sends outstanding for the same question, and the
first reply settles the second send β€” the badge read "Saved" for an
answer the server never accepted. That shipped.

The answer frame now takes an optional `seq`, echoed verbatim on both
the `saved` and the `error` reply. The server never reads it: uniqueness
and monotonicity are the client's problem, and a repeated value is
echoed as sent. Errors carry it even where `question_id` is not
attributable, which is exactly the case a client could not match before.

Omit it and every frame is byte-identical to before β€” the key is absent,
never null. `deny_unknown_fields` stays, since that is what made a
correlation id unsendable until now.
README.mdmodified+19 -5
@@ -1247,13 +1247,26 @@ frames:
1247 | direction | frame |1247 | direction | frame |
1248 |-----------|-------|1248 |-----------|-------|
1249 | server β†’ | `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |1249 | server β†’ | `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save |
1250-| client β†’ | `{"type":"answer", "question_id":"…", "selected":1}` or `{"type":"answer", "question_id":"…", "text":"…"}` |1250+| client β†’ | `{"type":"answer", "question_id":"…", "selected":1}` or `{"type":"answer", "question_id":"…", "text":"…"}`, optionally `+ "seq":7` |
1251-| server β†’ | `{"type":"saved", question_id, updated_at}` β€” the autosave ack |1251+| server β†’ | `{"type":"saved", question_id, updated_at, seq?}` β€” the autosave ack |
1252 | client β†’ | `{"type":"finish"}` β€” submit the attempt |1252 | client β†’ | `{"type":"finish"}` β€” submit the attempt |
1253 | server β†’ | `{"type":"finished", finished_at}`, then Close |1253 | server β†’ | `{"type":"finished", finished_at}`, then Close |
1254 | server β†’ | `{"type":"expired"}`, then Close β€” a tick noticed the deadline |1254 | server β†’ | `{"type":"expired"}`, then Close β€” a tick noticed the deadline |
1255 | client β†’ | `{"type":"ping"}` β†’ server `{"type":"pong"}` |1255 | client β†’ | `{"type":"ping"}` β†’ server `{"type":"pong"}` |
1256-| server β†’ | `{"type":"error", message}` β€” bad JSON, wrong kind, deadline, … |1256+| server β†’ | `{"type":"error", message, question_id?, seq?}` β€” bad JSON, wrong kind, deadline, … |
1257+
1258+An `answer` may carry a `seq`: any number the client picks, echoed verbatim on
1259+that message's `saved` or `error` and on nothing else. The server never reads
1260+it β€” no uniqueness, no ordering, no dedupe, all the client's business β€” and
1261+omits the key entirely when the request omitted it, so leaving it out keeps
1262+today's frames byte for byte. It exists because `question_id` is not an
1263+identity: save a question, time out, save it again, and two sends are
1264+outstanding for the same id β€” the first reply would settle the second and the
1265+UI would claim "Saved" for an answer the server never took. `question_id` on
1266+an `error` is the separate, orthogonal question: whether the failure belongs
1267+to that one question (payload or question) or to the room, in which case every
1268+save in flight is equally refused. An error can carry `seq` without
1269+`question_id`.
1257 1270
1258 Every tick and every save re-read the exam, so a mid-exam `ends_at` extension1271 Every tick and every save re-read the exam, so a mid-exam `ends_at` extension
1259 moves the room's countdown on the next tick, and no stale socket can write1272 moves the room's countdown on the next tick, and no stale socket can write
@@ -1281,10 +1294,11 @@ const ws = new WebSocket(`${BASE.replace("http", "ws")}/exams/${id}/attempt/ws`)
1281 ws.onmessage = (e) => {1294 ws.onmessage = (e) => {
1282 const m = JSON.parse(e.data);1295 const m = JSON.parse(e.data);
1283 if (m.type === "state") renderCountdown(m.remaining_ms, m.answered, m.question_count);1296 if (m.type === "state") renderCountdown(m.remaining_ms, m.answered, m.question_count);
1284- if (m.type === "saved") markSaved(m.question_id);1297+ if (m.type === "saved") settle(m.seq, m.question_id);
1285 };1298 };
1299+let seq = 0;
1286 const save = (question_id, selected) =>1300 const save = (question_id, selected) =>
1287- ws.send(JSON.stringify({ type: "answer", question_id, selected }));1301+ ws.send(JSON.stringify({ type: "answer", question_id, selected, seq: ++seq }));
1288 ```1302 ```
1289 1303
1290 The live monitor rides along: each roster row now carries `answered` and1304 The live monitor rides along: each roster row now carries `answered` and
src/web/exam_ws.rsmodified+48 -22
@@ -10,18 +10,25 @@
10 //! server β†’ client10 //! server β†’ client
11 //! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}`11 //! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}`
12 //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save12 //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save
13-//! - `{"type":"saved", question_id, updated_at}` β€” an answer landed13+//! - `{"type":"saved", question_id, updated_at, seq?}` β€” an answer landed
14 //! - `{"type":"pong"}`14 //! - `{"type":"pong"}`
15 //! - `{"type":"finished", finished_at}` then Close β€” submitted (here or elsewhere)15 //! - `{"type":"finished", finished_at}` then Close β€” submitted (here or elsewhere)
16 //! - `{"type":"expired"}` then Close β€” the deadline passed mid-session16 //! - `{"type":"expired"}` then Close β€” the deadline passed mid-session
17-//! - `{"type":"error", message, question_id?}` β€” bad JSON, unknown type,17+//! - `{"type":"error", message, question_id?, seq?}` β€” bad JSON, unknown type,
18 //! validation, deadline. `question_id` is present only when the failure18 //! validation, deadline. `question_id` is present only when the failure
19 //! belongs to that one `answer` (its payload or its question); absent means19 //! belongs to that one `answer` (its payload or its question); absent means
20 //! the failure is connection- or sitting-level, so every save in flight is20 //! the failure is connection- or sitting-level, so every save in flight is
21 //! equally refused21 //! equally refused
22 //!22 //!
23+//! `seq` on either reply is whatever the `answer` sent, echoed verbatim: the
24+//! server never reads it, never dedupes on it, and omits the key entirely when
25+//! the request omitted it. `question_id` cannot serve as the correlation id β€”
26+//! a re-save of the same question after a timeout leaves two sends
27+//! outstanding for it.
28+//!
23 //! client β†’ server29 //! client β†’ server
24-//! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id)30+//! - `{"type":"answer", question_id, selected? | text?, seq?}` (`selected` =
31+//! choice id, `seq` = the client's own correlation id)
25 //! - `{"type":"finish"}`32 //! - `{"type":"finish"}`
26 //! - `{"type":"ping"}`33 //! - `{"type":"ping"}`
27 //!34 //!
@@ -97,6 +104,13 @@ enum ClientMessage {
97 selected: Option<String>,104 selected: Option<String>,
98 #[serde(default)]105 #[serde(default)]
99 text: Option<String>,106 text: Option<String>,
107+ /// The client's own correlation id, echoed verbatim on this message's
108+ /// `saved` or `error` and never read by the server. `question_id` is
109+ /// not an identity β€” a re-save of the same question after a timeout
110+ /// has two sends outstanding, and the first reply would otherwise
111+ /// settle the second.
112+ #[serde(default)]
113+ seq: Option<u64>,
100 },114 },
101 Finish,115 Finish,
102 Ping,116 Ping,
@@ -365,10 +379,11 @@ async fn handle_message(
365 question_id,379 question_id,
366 selected,380 selected,
367 text,381 text,
382+ seq,
368 } => {383 } => {
369 // Cap the key before it can be echoed β€” see [`MAX_QUESTION_ID_LEN`].384 // Cap the key before it can be echoed β€” see [`MAX_QUESTION_ID_LEN`].
370 if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) {385 if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) {
371- let frame = error_frame(&AppError::Validation(err));386+ let frame = error_frame_for(&AppError::Validation(err), None, seq);
372 return send(socket, frame).await;387 return send(socket, frame).await;
373 }388 }
374 // Re-read the exam so the save is judged against the *current*389 // Re-read the exam so the save is judged against the *current*
@@ -396,15 +411,13 @@ async fn handle_message(
396 drop(guard);411 drop(guard);
397 match saved {412 match saved {
398 Ok(answer) => {413 Ok(answer) => {
399- send(414+ let mut frame = json!({
400- socket,415+ "type": "saved",
401- json!({416+ "question_id": answer.get_question().key(),
402- "type": "saved",417+ "updated_at": answer.get_updated_at().as_millis(),
403- "question_id": answer.get_question().key(),418+ });
404- "updated_at": answer.get_updated_at().as_millis(),419+ with_seq(&mut frame, seq);
405- }),420+ send(socket, frame).await?;
406- )
407- .await?;
408 // Progress changed β€” refresh the countdown/answered state421 // Progress changed β€” refresh the countdown/answered state
409 // right away rather than waiting out the tick.422 // right away rather than waiting out the tick.
410 push_state(socket, exam_id, attempt_id, db).await423 push_state(socket, exam_id, attempt_id, db).await
@@ -413,7 +426,7 @@ async fn handle_message(
413 let attributed = in_save && attributable(&err);426 let attributed = in_save && attributable(&err);
414 send(427 send(
415 socket,428 socket,
416- error_frame_for(&err, attributed.then_some(question_id.as_str())),429+ error_frame_for(&err, attributed.then_some(question_id.as_str()), seq),
417 )430 )
418 .await431 .await
419 }432 }
@@ -468,14 +481,25 @@ fn attributable(err: &AppError) -> bool {
468 /// The public words for an error β€” the same strings the HTTP layer would use,481 /// The public words for an error β€” the same strings the HTTP layer would use,
469 /// with internals logged, never sent.482 /// with internals logged, never sent.
470 fn error_frame(err: &AppError) -> Value {483 fn error_frame(err: &AppError) -> Value {
471- error_frame_for(err, None)484+ error_frame_for(err, None, None)
485+}
486+
487+/// Attach the request's correlation id, if it sent one. Omitted stays omitted
488+/// β€” never `null` β€” so a client that sends no `seq` sees byte-identical
489+/// frames.
490+fn with_seq(frame: &mut Value, seq: Option<u64>) {
491+ if let Some(seq) = seq {
492+ frame["seq"] = json!(seq);
493+ }
472 }494 }
473 495
474 /// [`error_frame`] plus the optional blame: `question_id` when the failure496 /// [`error_frame`] plus the optional blame: `question_id` when the failure
475-/// belongs to one `answer` message. Absent keeps its original meaning β€” an497+/// belongs to one `answer` message, and `seq` whenever the `answer` carried
476-/// unattributed failure β€” so a client that ignores the field behaves exactly498+/// one β€” the two are independent, so an unattributable failure is still
477-/// as before.499+/// matchable to the send that caused it. Absent keeps its original meaning β€”
478-fn error_frame_for(err: &AppError, question: Option<&str>) -> Value {500+/// an unattributed failure β€” so a client that ignores the fields behaves
501+/// exactly as before.
502+fn error_frame_for(err: &AppError, question: Option<&str>, seq: Option<u64>) -> Value {
479 let message = match err {503 let message = match err {
480 AppError::Validation(err) => err.to_string(),504 AppError::Validation(err) => err.to_string(),
481 AppError::NotFound => "not found".to_string(),505 AppError::NotFound => "not found".to_string(),
@@ -498,8 +522,10 @@ fn error_frame_for(err: &AppError, question: Option<&str>) -> Value {
498 "internal server error".to_string()522 "internal server error".to_string()
499 }523 }
500 };524 };
501- match question {525+ let mut frame = json!({ "type": "error", "message": message });
502- Some(question) => json!({ "type": "error", "message": message, "question_id": question }),526+ if let Some(question) = question {
503- None => json!({ "type": "error", "message": message }),527+ frame["question_id"] = json!(question);
504 }528 }
529+ with_seq(&mut frame, seq);
530+ frame
505 }531 }
tests/e2e.rsmodified+55 -0
@@ -688,9 +688,64 @@ async fn exam_room_websocket_round_trip() {
688 let saved = ws_frame_of_type(&mut ws, "saved").await;688 let saved = ws_frame_of_type(&mut ws, "saved").await;
689 assert_eq!(saved["question_id"], question_id.as_str());689 assert_eq!(saved["question_id"], question_id.as_str());
690 assert!(saved["updated_at"].as_i64().is_some());690 assert!(saved["updated_at"].as_i64().is_some());
691+ // No `seq` was sent, so no `seq` comes back β€” not even a null. Clients
692+ // that predate the field see exactly the frames they always saw.
693+ assert!(saved.get("seq").is_none(), "{saved}");
691 let state = ws_frame_of_type(&mut ws, "state").await;694 let state = ws_frame_of_type(&mut ws, "state").await;
692 assert_eq!(state["answered"], 1, "{state}");695 assert_eq!(state["answered"], 1, "{state}");
693 696
697+ // With a `seq`, the ack carries it back verbatim: `question_id` alone
698+ // cannot settle a send, since a re-save after a timeout leaves two of them
699+ // outstanding for the same question. The server assigns it no meaning β€”
700+ // a repeat of an already-used value is saved and echoed like any other.
701+ for _ in 0..2 {
702+ ws_send(
703+ &mut ws,
704+ json!({ "type": "answer", "question_id": question_id,
705+ "selected": room.choice_ids[1], "seq": 7 }),
706+ )
707+ .await;
708+ let saved = ws_frame_of_type(&mut ws, "saved").await;
709+ assert_eq!(saved["seq"], 7, "{saved}");
710+ assert_eq!(saved["question_id"], question_id.as_str());
711+ ws_frame_of_type(&mut ws, "state").await;
712+ }
713+
714+ // A failed save echoes it too β€” that is the whole point: the client can
715+ // fail the exact send, even when the error names no question.
716+ ws_send(
717+ &mut ws,
718+ json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x", "seq": 8 }),
719+ )
720+ .await;
721+ let error = ws_frame_of_type(&mut ws, "error").await;
722+ assert_eq!(error["seq"], 8, "{error}");
723+ assert!(error.get("question_id").is_none(), "{error}");
724+ // ... and `seq` rides alongside the blame when there is one.
725+ ws_send(
726+ &mut ws,
727+ json!({ "type": "answer", "question_id": question_id, "text": "4", "seq": 9 }),
728+ )
729+ .await;
730+ let error = ws_frame_of_type(&mut ws, "error").await;
731+ assert_eq!(error["seq"], 9, "{error}");
732+ assert_eq!(error["question_id"], question_id.as_str(), "{error}");
733+
734+ // `seq` is legal only because it is a declared field: everything else on
735+ // an `answer` is still refused outright.
736+ ws_send(
737+ &mut ws,
738+ json!({ "type": "answer", "question_id": question_id,
739+ "selected": room.choice_ids[1], "sequence": 10 }),
740+ )
741+ .await;
742+ let error = ws_frame_of_type(&mut ws, "error").await;
743+ assert!(
744+ error["message"].as_str().unwrap().contains("unrecognized"),
745+ "{error}"
746+ );
747+ assert!(error.get("seq").is_none(), "{error}");
748+
694 // A payload that doesn't fit the question is an error frame, not a close.749 // A payload that doesn't fit the question is an error frame, not a close.
695 ws_send(750 ws_send(
696 &mut ws,751 &mut ws,