diff --git a/README.md b/README.md index a8af348..747a004 100644 --- a/README.md +++ b/README.md @@ -1247,13 +1247,26 @@ frames: | direction | frame | |-----------|-------| | server → | `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}` on connect, every ~2 s, and after each save | -| client → | `{"type":"answer", "question_id":"…", "selected":1}` or `{"type":"answer", "question_id":"…", "text":"…"}` | -| server → | `{"type":"saved", question_id, updated_at}` — the autosave ack | +| client → | `{"type":"answer", "question_id":"…", "selected":1}` or `{"type":"answer", "question_id":"…", "text":"…"}`, optionally `+ "seq":7` | +| server → | `{"type":"saved", question_id, updated_at, seq?}` — the autosave ack | | client → | `{"type":"finish"}` — submit the attempt | | server → | `{"type":"finished", finished_at}`, then Close | | server → | `{"type":"expired"}`, then Close — a tick noticed the deadline | | client → | `{"type":"ping"}` → server `{"type":"pong"}` | -| server → | `{"type":"error", message}` — bad JSON, wrong kind, deadline, … | +| server → | `{"type":"error", message, question_id?, seq?}` — bad JSON, wrong kind, deadline, … | + +An `answer` may carry a `seq`: any number the client picks, echoed verbatim on +that message's `saved` or `error` and on nothing else. The server never reads +it — no uniqueness, no ordering, no dedupe, all the client's business — and +omits the key entirely when the request omitted it, so leaving it out keeps +today's frames byte for byte. It exists because `question_id` is not an +identity: save a question, time out, save it again, and two sends are +outstanding for the same id — the first reply would settle the second and the +UI would claim "Saved" for an answer the server never took. `question_id` on +an `error` is the separate, orthogonal question: whether the failure belongs +to that one question (payload or question) or to the room, in which case every +save in flight is equally refused. An error can carry `seq` without +`question_id`. Every tick and every save re-read the exam, so a mid-exam `ends_at` extension 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`) ws.onmessage = (e) => { const m = JSON.parse(e.data); if (m.type === "state") renderCountdown(m.remaining_ms, m.answered, m.question_count); - if (m.type === "saved") markSaved(m.question_id); + if (m.type === "saved") settle(m.seq, m.question_id); }; +let seq = 0; const save = (question_id, selected) => - ws.send(JSON.stringify({ type: "answer", question_id, selected })); + ws.send(JSON.stringify({ type: "answer", question_id, selected, seq: ++seq })); ``` The live monitor rides along: each roster row now carries `answered` and diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 25bbca4..a30f741 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -10,18 +10,25 @@ //! server → client //! - `{"type":"state", status, attempt, deadline, remaining_ms, now, answered, question_count}` //! on connect, every [`EXAM_WS_TICK_SECS`], and after each save -//! - `{"type":"saved", question_id, updated_at}` — an answer landed +//! - `{"type":"saved", question_id, updated_at, seq?}` — an answer landed //! - `{"type":"pong"}` //! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) //! - `{"type":"expired"}` then Close — the deadline passed mid-session -//! - `{"type":"error", message, question_id?}` — bad JSON, unknown type, +//! - `{"type":"error", message, question_id?, seq?}` — bad JSON, unknown type, //! validation, deadline. `question_id` is present only when the failure //! belongs to that one `answer` (its payload or its question); absent means //! the failure is connection- or sitting-level, so every save in flight is //! equally refused //! +//! `seq` on either reply is whatever the `answer` sent, echoed verbatim: the +//! server never reads it, never dedupes on it, and omits the key entirely when +//! the request omitted it. `question_id` cannot serve as the correlation id — +//! a re-save of the same question after a timeout leaves two sends +//! outstanding for it. +//! //! client → server -//! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id) +//! - `{"type":"answer", question_id, selected? | text?, seq?}` (`selected` = +//! choice id, `seq` = the client's own correlation id) //! - `{"type":"finish"}` //! - `{"type":"ping"}` //! @@ -97,6 +104,13 @@ enum ClientMessage { selected: Option, #[serde(default)] text: Option, + /// The client's own correlation id, echoed verbatim on this message's + /// `saved` or `error` and never read by the server. `question_id` is + /// not an identity — a re-save of the same question after a timeout + /// has two sends outstanding, and the first reply would otherwise + /// settle the second. + #[serde(default)] + seq: Option, }, Finish, Ping, @@ -365,10 +379,11 @@ async fn handle_message( question_id, selected, text, + seq, } => { // Cap the key before it can be echoed — see [`MAX_QUESTION_ID_LEN`]. if let Err(err) = validate_required("question_id", &question_id, MAX_QUESTION_ID_LEN) { - let frame = error_frame(&AppError::Validation(err)); + let frame = error_frame_for(&AppError::Validation(err), None, seq); return send(socket, frame).await; } // Re-read the exam so the save is judged against the *current* @@ -396,15 +411,13 @@ async fn handle_message( drop(guard); match saved { Ok(answer) => { - send( - socket, - json!({ - "type": "saved", - "question_id": answer.get_question().key(), - "updated_at": answer.get_updated_at().as_millis(), - }), - ) - .await?; + let mut frame = json!({ + "type": "saved", + "question_id": answer.get_question().key(), + "updated_at": answer.get_updated_at().as_millis(), + }); + with_seq(&mut frame, seq); + send(socket, frame).await?; // Progress changed — refresh the countdown/answered state // right away rather than waiting out the tick. push_state(socket, exam_id, attempt_id, db).await @@ -413,7 +426,7 @@ async fn handle_message( let attributed = in_save && attributable(&err); send( socket, - error_frame_for(&err, attributed.then_some(question_id.as_str())), + error_frame_for(&err, attributed.then_some(question_id.as_str()), seq), ) .await } @@ -468,14 +481,25 @@ fn attributable(err: &AppError) -> bool { /// The public words for an error — the same strings the HTTP layer would use, /// with internals logged, never sent. fn error_frame(err: &AppError) -> Value { - error_frame_for(err, None) + error_frame_for(err, None, None) +} + +/// Attach the request's correlation id, if it sent one. Omitted stays omitted +/// — never `null` — so a client that sends no `seq` sees byte-identical +/// frames. +fn with_seq(frame: &mut Value, seq: Option) { + if let Some(seq) = seq { + frame["seq"] = json!(seq); + } } /// [`error_frame`] plus the optional blame: `question_id` when the failure -/// belongs to one `answer` message. Absent keeps its original meaning — an -/// unattributed failure — so a client that ignores the field behaves exactly -/// as before. -fn error_frame_for(err: &AppError, question: Option<&str>) -> Value { +/// belongs to one `answer` message, and `seq` whenever the `answer` carried +/// one — the two are independent, so an unattributable failure is still +/// matchable to the send that caused it. Absent keeps its original meaning — +/// an unattributed failure — so a client that ignores the fields behaves +/// exactly as before. +fn error_frame_for(err: &AppError, question: Option<&str>, seq: Option) -> Value { let message = match err { AppError::Validation(err) => err.to_string(), AppError::NotFound => "not found".to_string(), @@ -498,8 +522,10 @@ fn error_frame_for(err: &AppError, question: Option<&str>) -> Value { "internal server error".to_string() } }; - match question { - Some(question) => json!({ "type": "error", "message": message, "question_id": question }), - None => json!({ "type": "error", "message": message }), + let mut frame = json!({ "type": "error", "message": message }); + if let Some(question) = question { + frame["question_id"] = json!(question); } + with_seq(&mut frame, seq); + frame } diff --git a/tests/e2e.rs b/tests/e2e.rs index b6dd060..2e2848e 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -688,9 +688,64 @@ async fn exam_room_websocket_round_trip() { let saved = ws_frame_of_type(&mut ws, "saved").await; assert_eq!(saved["question_id"], question_id.as_str()); assert!(saved["updated_at"].as_i64().is_some()); + // No `seq` was sent, so no `seq` comes back — not even a null. Clients + // that predate the field see exactly the frames they always saw. + assert!(saved.get("seq").is_none(), "{saved}"); let state = ws_frame_of_type(&mut ws, "state").await; assert_eq!(state["answered"], 1, "{state}"); + // With a `seq`, the ack carries it back verbatim: `question_id` alone + // cannot settle a send, since a re-save after a timeout leaves two of them + // outstanding for the same question. The server assigns it no meaning — + // a repeat of an already-used value is saved and echoed like any other. + for _ in 0..2 { + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, + "selected": room.choice_ids[1], "seq": 7 }), + ) + .await; + let saved = ws_frame_of_type(&mut ws, "saved").await; + assert_eq!(saved["seq"], 7, "{saved}"); + assert_eq!(saved["question_id"], question_id.as_str()); + ws_frame_of_type(&mut ws, "state").await; + } + + // A failed save echoes it too — that is the whole point: the client can + // fail the exact send, even when the error names no question. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x", "seq": 8 }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert_eq!(error["seq"], 8, "{error}"); + assert!(error.get("question_id").is_none(), "{error}"); + // ... and `seq` rides alongside the blame when there is one. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, "text": "4", "seq": 9 }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert_eq!(error["seq"], 9, "{error}"); + assert_eq!(error["question_id"], question_id.as_str(), "{error}"); + + // `seq` is legal only because it is a declared field: everything else on + // an `answer` is still refused outright. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": question_id, + "selected": room.choice_ids[1], "sequence": 10 }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert!( + error["message"].as_str().unwrap().contains("unrecognized"), + "{error}" + ); + assert!(error.get("seq").is_none(), "{error}"); + // A payload that doesn't fit the question is an error frame, not a close. ws_send( &mut ws,