Drop the live-monitor SSE stream for poll-only
Browse files at this commitbacd9ede1cd7b3ea7770587716e06840837aa970Parent: 24dba16- feat
- drop the live-monitor SSE stream for poll-only
6 changed files +9 -418
- README.md +5 -12
- src/constant.rs +0 -3
- src/web/exam_ws.rs +2 -2
- src/web/exams.rs +2 -77
- tests/e2e.rs +0 -270
- tests/integration.rs +0 -54
README.mdmodified+5 -12
| @@ -311,7 +311,7 @@ course enrollments. | |||
| 311 | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | | 311 | | Answer questions inside **own** attempt (REST autosave or the exam-room WebSocket) | student | **Students only**; attempt must be `in_progress`; deadline judged by the server clock; blocked after leaving the room while `allow_rejoin` is off | |
| 312 | | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt | | 312 | | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt | |
| 313 | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | | 313 | | Read a question list (with `correct`) or a student's answer sheet | teacher | Course-management rights — one teacher can't read another's answer key | |
| 314 | -| Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | | 314 | +| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights | |
| 315 | | Create courses | teacher | The creator manages the course, and owns it for good | | 315 | | Create courses | teacher | The creator manages the course, and owns it for good | |
| 316 | | Assign / unassign a course's teachers | manager | Staffing is the office's call — a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ | | 316 | | Assign / unassign a course's teachers | manager | Staffing is the office's call — a course's own creator cannot hand rights to peers; the assignee must be `teacher`+ | |
| 317 | | Delete a course | teacher | Only the **creator**, or a `manager`+ — an assigned teacher runs the course but doesn't own it | | 317 | | Delete a course | teacher | Only the **creator**, or a `manager`+ — an assigned teacher runs the course but doesn't own it | |
| @@ -528,8 +528,7 @@ their existing shapes: the student exam-room reads | |||
| 528 | | DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) | | 528 | | DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) | |
| 529 | | GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) | | 529 | | GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) | |
| 530 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | | 530 | | GET | `/exams/{id}/attempt/ws` | student | **WebSocket** exam room (students only): state ticks, autosave, finish; entering clears `left_at`, leaving stamps it (see "Taking an exam") | |
| 531 | -| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager) | | 531 | +| GET | `/exams/{id}/live` | teacher | Live monitor snapshot: roster × latest attempts × marks + per-student progress/`left_at`/`attempts_used` + counts; no-shows turn `absent` once the window closes (course manager); poll to keep a monitor current | |
| 532 | -| GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | | ||
| 533 | | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) | | 532 | | POST | `/courses/{id}/homework` | teacher | `{title, description?, subject_id, due_at, assigned?}` — assign homework tagged with a course subject, due in the future; `assigned` names an enrolled-student subset, ≤ 200 (omit/`[]` = the whole course) (course manager) | |
| 534 | | GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) · paged | | 533 | | GET | `/courses/{id}/homework` | student | List the course's homework, newest first (enrolled, creator, assigned teacher, or manager+; students see only what they're assigned) · paged | |
| 535 | | GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) · paged | | 534 | | GET | `/homework` | student | The caller's cross-course homework: their courses' (manager+: all; students only what they're assigned) · paged | |
| @@ -1019,15 +1018,9 @@ latest sitting) plus summary counts, all judged at a single `now`. Once the | |||
| 1019 | window closes, `not_started` hardens into `absent` — the no-shows, flagged | 1018 | window closes, `not_started` hardens into `absent` — the no-shows, flagged |
| 1020 | right in the roster (open exams have no window, so never an `absent`). The | 1019 | right in the roster (open exams have no window, so never an `absent`). The |
| 1021 | flag is informational: an absent student still has no mark until the teacher | 1020 | flag is informational: an absent student still has no mark until the teacher |
| 1022 | -records one through `POST /exams/{id}/results`. | 1021 | +records one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to |
| 1023 | -`GET /exams/{id}/live/stream` is the same JSON as Server-Sent Events: a | 1022 | +keep a monitor current — attendance, ticking clocks, submissions, and marks all |
| 1024 | -`snapshot` event immediately on connect, then every ~2 s — attendance, ticking | 1023 | +ride in each snapshot. |
| 1025 | -clocks, submissions, and marks land without polling: | ||
| 1026 | - | ||
| 1027 | -```js | ||
| 1028 | -const es = new EventSource(`${BASE}/exams/${id}/live/stream`, { withCredentials: true }); | ||
| 1029 | -es.addEventListener("snapshot", (e) => render(JSON.parse(e.data))); | ||
| 1030 | -``` | ||
| 1031 | 1024 | ||
| 1032 | Deleting an exam (or its course) cascades attempts, questions, answers, and | 1025 | Deleting an exam (or its course) cascades attempts, questions, answers, and |
| 1033 | question + answer images (blobs included) along with results; unenrolling mid-exam | 1026 | question + answer images (blobs included) along with results; unenrolling mid-exam |
src/constant.rsmodified+0 -3
| @@ -176,9 +176,6 @@ pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000; | |||
| 176 | pub const MAX_EXAM_ATTEMPTS: i64 = 100; | 176 | pub const MAX_EXAM_ATTEMPTS: i64 = 100; |
| 177 | pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; | 177 | pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; |
| 178 | 178 | ||
| 179 | -/// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). | ||
| 180 | -pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; | ||
| 181 | - | ||
| 182 | /// Cadence of the background keepalive query on the database WebSocket. The | 179 | /// Cadence of the background keepalive query on the database WebSocket. The |
| 183 | /// traffic keeps the connection from being dropped as idle; when it does drop, | 180 | /// traffic keeps the connection from being dropped as idle; when it does drop, |
| 184 | /// the ping also makes the SDK notice and reconnect long before the next real | 181 | /// the ping also makes the SDK notice and reconnect long before the next real |
src/web/exam_ws.rsmodified+2 -2
| @@ -2,8 +2,8 @@ | |||
| 2 | //! | 2 | //! |
| 3 | //! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the | 3 | //! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the |
| 4 | //! socket exists so a sitting student gets autosave acks and a live, | 4 | //! socket exists so a sitting student gets autosave acks and a live, |
| 5 | -//! server-judged countdown without polling. The teacher monitor deliberately | 5 | +//! server-judged countdown without polling. The teacher monitor polls the |
| 6 | -//! stays on SSE (`/exams/{id}/live/stream`) — it only ever flows one way. | 6 | +//! one-shot snapshot (`GET /exams/{id}/live`) instead. |
| 7 | //! | 7 | //! |
| 8 | //! Wire protocol (JSON text frames): | 8 | //! Wire protocol (JSON text frames): |
| 9 | //! | 9 | //! |
src/web/exams.rsmodified+2 -77
| @@ -1,21 +1,15 @@ | |||
| 1 | use std::collections::HashMap; | 1 | use std::collections::HashMap; |
| 2 | -use std::time::Duration; | ||
| 3 | 2 | ||
| 4 | use axum::Json; | 3 | use axum::Json; |
| 5 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; | 4 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; |
| 6 | use axum::http::StatusCode; | 5 | use axum::http::StatusCode; |
| 7 | use axum::response::Response; | 6 | use axum::response::Response; |
| 8 | -use axum::response::sse::{Event, KeepAlive, Sse}; | ||
| 9 | use serde::{Deserialize, Serialize}; | 7 | use serde::{Deserialize, Serialize}; |
| 10 | -use tokio_stream::wrappers::IntervalStream; | ||
| 11 | -use tokio_stream::{Stream, StreamExt}; | ||
| 12 | use utoipa::ToSchema; | 8 | use utoipa::ToSchema; |
| 13 | use utoipa_axum::router::OpenApiRouter; | 9 | use utoipa_axum::router::OpenApiRouter; |
| 14 | use utoipa_axum::routes; | 10 | use utoipa_axum::routes; |
| 15 | 11 | ||
| 16 | -use crate::constant::{ | 12 | +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 17 | - EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES, | ||
| 18 | -}; | ||
| 19 | use crate::database::Database; | 13 | use crate::database::Database; |
| 20 | use crate::domain::answer_image::AnswerImage; | 14 | use crate::domain::answer_image::AnswerImage; |
| 21 | use crate::domain::course::Course; | 15 | use crate::domain::course::Course; |
| @@ -80,7 +74,6 @@ pub fn routes() -> OpenApiRouter<AppState> { | |||
| 80 | .routes(routes!(start_attempt, my_attempt)) | 74 | .routes(routes!(start_attempt, my_attempt)) |
| 81 | .routes(routes!(finish_attempt)) | 75 | .routes(routes!(finish_attempt)) |
| 82 | .routes(routes!(exam_live)) | 76 | .routes(routes!(exam_live)) |
| 83 | - .routes(routes!(exam_live_stream)) | ||
| 84 | .routes(routes!(create_question, list_questions)) | 77 | .routes(routes!(create_question, list_questions)) |
| 85 | .routes(routes!(update_question, delete_question)) | 78 | .routes(routes!(update_question, delete_question)) |
| 86 | .routes(routes!(attempt_questions)) | 79 | .routes(routes!(attempt_questions)) |
| @@ -1238,8 +1231,7 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result<ExamLiveResponse, A | |||
| 1238 | /// on which sitting), who walked out of the room (`left_at`), who never | 1231 | /// on which sitting), who walked out of the room (`left_at`), who never |
| 1239 | /// showed at all (`absent`, once the window is over), time each student has | 1232 | /// showed at all (`absent`, once the window is over), time each student has |
| 1240 | /// left, and marks as they land. Requires teacher+ and management rights | 1233 | /// left, and marks as they land. Requires teacher+ and management rights |
| 1241 | -/// over the exam's course. For a self-updating feed of the same shape, see | 1234 | +/// over the exam's course. Poll it to keep a monitor up to date. |
| 1242 | -/// `GET /exams/{id}/live/stream`. | ||
| 1243 | #[utoipa::path( | 1235 | #[utoipa::path( |
| 1244 | get, | 1236 | get, |
| 1245 | path = "/{id}/live", | 1237 | path = "/{id}/live", |
| @@ -1270,73 +1262,6 @@ async fn exam_live( | |||
| 1270 | Ok(Json(live_snapshot(&exam, &st.db).await?)) | 1262 | Ok(Json(live_snapshot(&exam, &st.db).await?)) |
| 1271 | } | 1263 | } |
| 1272 | 1264 | ||
| 1273 | -/// The live snapshot as a Server-Sent-Events stream: one `snapshot` event | ||
| 1274 | -/// (the `ExamLiveResponse` JSON) immediately on connect and then every couple | ||
| 1275 | -/// of seconds, so attendance, remaining time, submissions, and marks update | ||
| 1276 | -/// without polling. Requires teacher+ and management rights over the exam's | ||
| 1277 | -/// course. Consume with `EventSource` (cookies ride along on same-site / | ||
| 1278 | -/// credentialed requests). If the exam disappears mid-stream an `error` event | ||
| 1279 | -/// is sent instead. | ||
| 1280 | -#[utoipa::path( | ||
| 1281 | - get, | ||
| 1282 | - path = "/{id}/live/stream", | ||
| 1283 | - tag = "exams", | ||
| 1284 | - security(("session_cookie" = [])), | ||
| 1285 | - params(("id" = String, Path, description = "Exam id")), | ||
| 1286 | - responses( | ||
| 1287 | - (status = 200, description = "SSE feed of `snapshot` events (`ExamLiveResponse` as JSON)", content_type = "text/event-stream"), | ||
| 1288 | - (status = 401, description = "Not authenticated", body = ErrorResponse), | ||
| 1289 | - (status = 403, description = "Not the course creator or an assigned teacher (and not a manager/admin)", body = ErrorResponse), | ||
| 1290 | - (status = 404, description = "Exam not found", body = ErrorResponse), | ||
| 1291 | - ), | ||
| 1292 | -)] | ||
| 1293 | -async fn exam_live_stream( | ||
| 1294 | - State(st): State<AppState>, | ||
| 1295 | - RequireTeacher(user): RequireTeacher, | ||
| 1296 | - Path(id): Path<String>, | ||
| 1297 | -) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> { | ||
| 1298 | - let exam_id = ExamId::from_key(&id); | ||
| 1299 | - // A missing exam is a 404 up front; after this the response is a stream. | ||
| 1300 | - let exam = Exam::read(&exam_id, &st.db) | ||
| 1301 | - .await? | ||
| 1302 | - .ok_or(AppError::NotFound)?; | ||
| 1303 | - let course = course_of(&exam, &st.db).await?; | ||
| 1304 | - if !can_manage_course(&course, &user) { | ||
| 1305 | - return Err(AppError::Forbidden( | ||
| 1306 | - "only the course creator, an assigned teacher, or a manager/admin can monitor this exam", | ||
| 1307 | - )); | ||
| 1308 | - } | ||
| 1309 | - | ||
| 1310 | - // First tick fires immediately, so the monitor paints on connect. The | ||
| 1311 | - // exam is re-read every tick: schedule edits (deadline extensions) show | ||
| 1312 | - // up mid-stream. | ||
| 1313 | - let interval = tokio::time::interval(Duration::from_secs(EXAM_LIVE_STREAM_INTERVAL_SECS)); | ||
| 1314 | - let stream = IntervalStream::new(interval).then(move |_| { | ||
| 1315 | - let db = st.db.clone(); | ||
| 1316 | - let exam_id = exam_id.clone(); | ||
| 1317 | - async move { | ||
| 1318 | - let snapshot = match Exam::read(&exam_id, &db).await { | ||
| 1319 | - Ok(Some(exam)) => live_snapshot(&exam, &db).await, | ||
| 1320 | - Ok(None) => Err(AppError::NotFound), | ||
| 1321 | - Err(err) => Err(err), | ||
| 1322 | - }; | ||
| 1323 | - match snapshot { | ||
| 1324 | - Ok(snapshot) => Event::default().event("snapshot").json_data(&snapshot), | ||
| 1325 | - // Exam deleted mid-stream or a db hiccup: say so without | ||
| 1326 | - // leaking internals and keep the stream alive — the client | ||
| 1327 | - // decides whether to hang on or close. | ||
| 1328 | - Err(err) => { | ||
| 1329 | - tracing::warn!("live exam stream snapshot failed: {err}"); | ||
| 1330 | - Event::default() | ||
| 1331 | - .event("error") | ||
| 1332 | - .json_data(serde_json::json!({ "error": "live snapshot unavailable" })) | ||
| 1333 | - } | ||
| 1334 | - } | ||
| 1335 | - } | ||
| 1336 | - }); | ||
| 1337 | - Ok(Sse::new(stream).keep_alive(KeepAlive::default())) | ||
| 1338 | -} | ||
| 1339 | - | ||
| 1340 | // ---- questions -------------------------------------------------------------- | 1265 | // ---- questions -------------------------------------------------------------- |
| 1341 | // Teachers author the question list before the exam runs; it freezes the | 1266 | // Teachers author the question list before the exam runs; it freezes the |
| 1342 | // moment anyone starts an attempt, so every student sits the same exam. | 1267 | // moment anyone starts an attempt, so every student sits the same exam. |
tests/e2e.rsmodified+0 -270
| @@ -403,276 +403,6 @@ async fn attendance_rollup_across_users() { | |||
| 403 | assert_eq!(res.status(), StatusCode::UNAUTHORIZED); | 403 | assert_eq!(res.status(), StatusCode::UNAUTHORIZED); |
| 404 | } | 404 | } |
| 405 | 405 | ||
| 406 | -/// The live exam monitor over a real TCP connection: an `EventSource`-style | ||
| 407 | -/// GET must yield a `snapshot` event carrying the roster within the first | ||
| 408 | -/// ticks (the first one fires immediately on connect). | ||
| 409 | -#[tokio::test] | ||
| 410 | -async fn live_exam_stream_pushes_snapshots_over_http() { | ||
| 411 | - let (base, db) = spawn_server().await; | ||
| 412 | - let teacher = client(); | ||
| 413 | - register(&teacher, &base, "hoca").await; | ||
| 414 | - promote(&db, "hoca", "teacher").await; | ||
| 415 | - login(&teacher, &base, "hoca").await; | ||
| 416 | - | ||
| 417 | - let student = client(); | ||
| 418 | - register(&student, &base, "veli").await; | ||
| 419 | - login(&student, &base, "veli").await; | ||
| 420 | - let student_id: Value = student | ||
| 421 | - .get(format!("{base}/auth/me")) | ||
| 422 | - .send() | ||
| 423 | - .await | ||
| 424 | - .unwrap() | ||
| 425 | - .json() | ||
| 426 | - .await | ||
| 427 | - .unwrap(); | ||
| 428 | - let student_id = student_id["id"].as_str().unwrap().to_string(); | ||
| 429 | - | ||
| 430 | - // Course + enrolled student + a sync exam whose window is open now | ||
| 431 | - // (window times judged by the server clock, fetched from `/time`). | ||
| 432 | - let now: Value = teacher | ||
| 433 | - .get(format!("{base}/time")) | ||
| 434 | - .send() | ||
| 435 | - .await | ||
| 436 | - .unwrap() | ||
| 437 | - .json() | ||
| 438 | - .await | ||
| 439 | - .unwrap(); | ||
| 440 | - let now = now["now"].as_i64().unwrap(); | ||
| 441 | - | ||
| 442 | - let course: Value = teacher | ||
| 443 | - .post(format!("{base}/courses")) | ||
| 444 | - .json(&json!({ "title": "algebra" })) | ||
| 445 | - .send() | ||
| 446 | - .await | ||
| 447 | - .unwrap() | ||
| 448 | - .json() | ||
| 449 | - .await | ||
| 450 | - .unwrap(); | ||
| 451 | - let course_id = course["id"].as_str().unwrap(); | ||
| 452 | - let res = teacher | ||
| 453 | - .post(format!("{base}/courses/{course_id}/enrollments")) | ||
| 454 | - .json(&json!({ "user_id": student_id })) | ||
| 455 | - .send() | ||
| 456 | - .await | ||
| 457 | - .unwrap(); | ||
| 458 | - assert_eq!(res.status(), StatusCode::OK); | ||
| 459 | - let exam: Value = teacher | ||
| 460 | - .post(format!("{base}/courses/{course_id}/exams")) | ||
| 461 | - .json(&json!({ | ||
| 462 | - "title": "final", "kind": "final", | ||
| 463 | - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, | ||
| 464 | - })) | ||
| 465 | - .send() | ||
| 466 | - .await | ||
| 467 | - .unwrap() | ||
| 468 | - .json() | ||
| 469 | - .await | ||
| 470 | - .unwrap(); | ||
| 471 | - let exam_id = exam["id"].as_str().unwrap(); | ||
| 472 | - | ||
| 473 | - // The student sits down — that's the live-attendance signal. | ||
| 474 | - let res = student | ||
| 475 | - .post(format!("{base}/exams/{exam_id}/attempt")) | ||
| 476 | - .send() | ||
| 477 | - .await | ||
| 478 | - .unwrap(); | ||
| 479 | - assert_eq!(res.status(), StatusCode::CREATED); | ||
| 480 | - | ||
| 481 | - // Open the stream and read until one full snapshot event has arrived. | ||
| 482 | - let mut res = teacher | ||
| 483 | - .get(format!("{base}/exams/{exam_id}/live/stream")) | ||
| 484 | - .send() | ||
| 485 | - .await | ||
| 486 | - .unwrap(); | ||
| 487 | - assert_eq!(res.status(), StatusCode::OK); | ||
| 488 | - let content_type = res | ||
| 489 | - .headers() | ||
| 490 | - .get("content-type") | ||
| 491 | - .expect("content-type") | ||
| 492 | - .to_str() | ||
| 493 | - .unwrap() | ||
| 494 | - .to_string(); | ||
| 495 | - assert!( | ||
| 496 | - content_type.starts_with("text/event-stream"), | ||
| 497 | - "{content_type}" | ||
| 498 | - ); | ||
| 499 | - | ||
| 500 | - let mut body = String::new(); | ||
| 501 | - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); | ||
| 502 | - while !(body.contains("event: snapshot") && body.contains("\n\n")) { | ||
| 503 | - let chunk = tokio::time::timeout_at(deadline, res.chunk()) | ||
| 504 | - .await | ||
| 505 | - .expect("a snapshot event within 5s") | ||
| 506 | - .expect("stream stays open") | ||
| 507 | - .expect("stream yields data"); | ||
| 508 | - body.push_str(&String::from_utf8_lossy(&chunk)); | ||
| 509 | - } | ||
| 510 | - assert!(body.contains("\"in_progress\""), "{body}"); | ||
| 511 | - assert!(body.contains("veli"), "{body}"); | ||
| 512 | - assert!(body.contains("\"enrolled\":1"), "{body}"); | ||
| 513 | -} | ||
| 514 | - | ||
| 515 | -/// Read the open SSE stream `res` until a `snapshot` event whose parsed JSON | ||
| 516 | -/// satisfies `want`, and return that snapshot. `buf` carries bytes between | ||
| 517 | -/// calls, so a partial event at the end of one read completes in the next and | ||
| 518 | -/// events already buffered are drained before more are pulled. Panics if | ||
| 519 | -/// nothing matching arrives within `within`. | ||
| 520 | -async fn next_matching_snapshot( | ||
| 521 | - res: &mut reqwest::Response, | ||
| 522 | - buf: &mut String, | ||
| 523 | - within: std::time::Duration, | ||
| 524 | - want: impl Fn(&Value) -> bool, | ||
| 525 | -) -> Value { | ||
| 526 | - let deadline = tokio::time::Instant::now() + within; | ||
| 527 | - loop { | ||
| 528 | - // Drain every complete event (`\n\n`-terminated) already buffered | ||
| 529 | - // before pulling more bytes — keep-alive comments and non-snapshot | ||
| 530 | - // frames are skipped, non-matching snapshots consumed and dropped. | ||
| 531 | - while let Some(end) = buf.find("\n\n") { | ||
| 532 | - let event: String = buf.drain(..end + 2).collect(); | ||
| 533 | - if !event.contains("event: snapshot") { | ||
| 534 | - continue; | ||
| 535 | - } | ||
| 536 | - let data = event | ||
| 537 | - .lines() | ||
| 538 | - .find_map(|line| line.strip_prefix("data:")) | ||
| 539 | - .expect("a snapshot event carries a data line") | ||
| 540 | - .trim(); | ||
| 541 | - let snapshot: Value = serde_json::from_str(data).expect("snapshot is json"); | ||
| 542 | - if want(&snapshot) { | ||
| 543 | - return snapshot; | ||
| 544 | - } | ||
| 545 | - } | ||
| 546 | - let chunk = tokio::time::timeout_at(deadline, res.chunk()) | ||
| 547 | - .await | ||
| 548 | - .expect("an SSE event before the deadline") | ||
| 549 | - .expect("stream stays open") | ||
| 550 | - .expect("stream yields data"); | ||
| 551 | - buf.push_str(&String::from_utf8_lossy(&chunk)); | ||
| 552 | - } | ||
| 553 | -} | ||
| 554 | - | ||
| 555 | -/// The teacher's monitor updates *live* on one held-open connection: after the | ||
| 556 | -/// first snapshot lands, a student's submission must surface in a *later* event | ||
| 557 | -/// on the *same* stream, no reconnect. Guards against a monitor that replays a | ||
| 558 | -/// cached first snapshot or stops re-reading the exam each tick — the split | ||
| 559 | -/// coverage (one-shot `/live` correctness + a single streamed event) would miss | ||
| 560 | -/// that. | ||
| 561 | -#[tokio::test] | ||
| 562 | -async fn live_stream_reflects_a_status_change_on_the_open_connection() { | ||
| 563 | - let (base, db) = spawn_server().await; | ||
| 564 | - let teacher = client(); | ||
| 565 | - register(&teacher, &base, "hoca").await; | ||
| 566 | - promote(&db, "hoca", "teacher").await; | ||
| 567 | - login(&teacher, &base, "hoca").await; | ||
| 568 | - | ||
| 569 | - let student = client(); | ||
| 570 | - register(&student, &base, "veli").await; | ||
| 571 | - login(&student, &base, "veli").await; | ||
| 572 | - let student_id: Value = student | ||
| 573 | - .get(format!("{base}/auth/me")) | ||
| 574 | - .send() | ||
| 575 | - .await | ||
| 576 | - .unwrap() | ||
| 577 | - .json() | ||
| 578 | - .await | ||
| 579 | - .unwrap(); | ||
| 580 | - let student_id = student_id["id"].as_str().unwrap().to_string(); | ||
| 581 | - | ||
| 582 | - let now: Value = teacher | ||
| 583 | - .get(format!("{base}/time")) | ||
| 584 | - .send() | ||
| 585 | - .await | ||
| 586 | - .unwrap() | ||
| 587 | - .json() | ||
| 588 | - .await | ||
| 589 | - .unwrap(); | ||
| 590 | - let now = now["now"].as_i64().unwrap(); | ||
| 591 | - | ||
| 592 | - let course: Value = teacher | ||
| 593 | - .post(format!("{base}/courses")) | ||
| 594 | - .json(&json!({ "title": "algebra" })) | ||
| 595 | - .send() | ||
| 596 | - .await | ||
| 597 | - .unwrap() | ||
| 598 | - .json() | ||
| 599 | - .await | ||
| 600 | - .unwrap(); | ||
| 601 | - let course_id = course["id"].as_str().unwrap(); | ||
| 602 | - let res = teacher | ||
| 603 | - .post(format!("{base}/courses/{course_id}/enrollments")) | ||
| 604 | - .json(&json!({ "user_id": student_id })) | ||
| 605 | - .send() | ||
| 606 | - .await | ||
| 607 | - .unwrap(); | ||
| 608 | - assert_eq!(res.status(), StatusCode::OK); | ||
| 609 | - let exam: Value = teacher | ||
| 610 | - .post(format!("{base}/courses/{course_id}/exams")) | ||
| 611 | - .json(&json!({ | ||
| 612 | - "title": "final", "kind": "final", | ||
| 613 | - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, | ||
| 614 | - })) | ||
| 615 | - .send() | ||
| 616 | - .await | ||
| 617 | - .unwrap() | ||
| 618 | - .json() | ||
| 619 | - .await | ||
| 620 | - .unwrap(); | ||
| 621 | - let exam_id = exam["id"].as_str().unwrap(); | ||
| 622 | - | ||
| 623 | - // The student sits down — in progress, nothing submitted. | ||
| 624 | - let res = student | ||
| 625 | - .post(format!("{base}/exams/{exam_id}/attempt")) | ||
| 626 | - .send() | ||
| 627 | - .await | ||
| 628 | - .unwrap(); | ||
| 629 | - assert_eq!(res.status(), StatusCode::CREATED); | ||
| 630 | - | ||
| 631 | - // The teacher opens the live stream and reads the first snapshot. | ||
| 632 | - let mut res = teacher | ||
| 633 | - .get(format!("{base}/exams/{exam_id}/live/stream")) | ||
| 634 | - .send() | ||
| 635 | - .await | ||
| 636 | - .unwrap(); | ||
| 637 | - assert_eq!(res.status(), StatusCode::OK); | ||
| 638 | - assert!( | ||
| 639 | - res.headers() | ||
| 640 | - .get("content-type") | ||
| 641 | - .expect("content-type") | ||
| 642 | - .to_str() | ||
| 643 | - .unwrap() | ||
| 644 | - .starts_with("text/event-stream") | ||
| 645 | - ); | ||
| 646 | - | ||
| 647 | - let mut buf = String::new(); | ||
| 648 | - let first = | ||
| 649 | - next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(5), |s| { | ||
| 650 | - s["counts"]["in_progress"].as_i64() == Some(1) | ||
| 651 | - }) | ||
| 652 | - .await; | ||
| 653 | - assert_eq!(first["counts"]["submitted"], 0, "{first}"); | ||
| 654 | - assert_eq!(first["students"][0]["user"]["username"], "veli"); | ||
| 655 | - assert_eq!(first["students"][0]["status"], "in_progress", "{first}"); | ||
| 656 | - | ||
| 657 | - // The student submits while the teacher's stream stays open. | ||
| 658 | - let res_finish = student | ||
| 659 | - .post(format!("{base}/exams/{exam_id}/attempt/finish")) | ||
| 660 | - .send() | ||
| 661 | - .await | ||
| 662 | - .unwrap(); | ||
| 663 | - assert_eq!(res_finish.status(), StatusCode::OK); | ||
| 664 | - | ||
| 665 | - // A later event on the same connection must carry the change — the monitor | ||
| 666 | - // re-reads and recomputes each tick, it does not replay the first snapshot. | ||
| 667 | - let later = | ||
| 668 | - next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(8), |s| { | ||
| 669 | - s["counts"]["submitted"].as_i64() == Some(1) | ||
| 670 | - }) | ||
| 671 | - .await; | ||
| 672 | - assert_eq!(later["counts"]["in_progress"], 0, "{later}"); | ||
| 673 | - assert_eq!(later["students"][0]["status"], "submitted", "{later}"); | ||
| 674 | -} | ||
| 675 | - | ||
| 676 | /// Log in without a cookie jar and hand back the raw `session=<token>` pair — | 406 | /// Log in without a cookie jar and hand back the raw `session=<token>` pair — |
| 677 | /// the exact header value the WebSocket handshake needs (tungstenite carries | 407 | /// the exact header value the WebSocket handshake needs (tungstenite carries |
| 678 | /// no jar of its own). | 408 | /// no jar of its own). |
tests/integration.rsmodified+0 -54
| @@ -203,7 +203,6 @@ async fn protected_routes_require_session() { | |||
| 203 | ("GET", "/exams/x/attempt"), | 203 | ("GET", "/exams/x/attempt"), |
| 204 | ("POST", "/exams/x/attempt/finish"), | 204 | ("POST", "/exams/x/attempt/finish"), |
| 205 | ("GET", "/exams/x/live"), | 205 | ("GET", "/exams/x/live"), |
| 206 | - ("GET", "/exams/x/live/stream"), | ||
| 207 | ("POST", "/exams/x/questions"), | 206 | ("POST", "/exams/x/questions"), |
| 208 | ("GET", "/exams/x/questions"), | 207 | ("GET", "/exams/x/questions"), |
| 209 | ("PATCH", "/exams/x/questions/y"), | 208 | ("PATCH", "/exams/x/questions/y"), |
| @@ -3258,7 +3257,6 @@ async fn course_data_is_walled_off_from_other_teachers() { | |||
| 3258 | format!("/exams/{exam_id}/results"), | 3257 | format!("/exams/{exam_id}/results"), |
| 3259 | format!("/exams/{exam_id}/statistics"), | 3258 | format!("/exams/{exam_id}/statistics"), |
| 3260 | format!("/exams/{exam_id}/live"), | 3259 | format!("/exams/{exam_id}/live"), |
| 3261 | - format!("/exams/{exam_id}/live/stream"), | ||
| 3262 | format!("/exams/{exam_id}/questions"), | 3260 | format!("/exams/{exam_id}/questions"), |
| 3263 | format!("/exams/{exam_id}/attempts/{alice_id}/answers"), | 3261 | format!("/exams/{exam_id}/attempts/{alice_id}/answers"), |
| 3264 | ] { | 3262 | ] { |
| @@ -6903,58 +6901,6 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() { | |||
| 6903 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); | 6901 | assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); |
| 6904 | } | 6902 | } |
| 6905 | 6903 | ||
| 6906 | -#[tokio::test] | ||
| 6907 | -async fn live_stream_is_sse_and_teacher_scoped() { | ||
| 6908 | - let (app, db) = app_and_db().await; | ||
| 6909 | - let teacher = login_as(&app, &db, "sse_t", "teacher").await; | ||
| 6910 | - let student = login(&app, "selin").await; | ||
| 6911 | - let course = create_course(&app, &teacher, "geo").await; | ||
| 6912 | - let now = Timestamp::now().as_millis(); | ||
| 6913 | - let exam = scheduled_exam( | ||
| 6914 | - &app, | ||
| 6915 | - &teacher, | ||
| 6916 | - &course, | ||
| 6917 | - json!({ "title": "final", "kind": "final", | ||
| 6918 | - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), | ||
| 6919 | - ) | ||
| 6920 | - .await; | ||
| 6921 | - | ||
| 6922 | - // Teacher: 200 with SSE headers. The body is an endless stream, so only | ||
| 6923 | - // the head of the response is inspected (common::send would hang). | ||
| 6924 | - let request = Request::builder() | ||
| 6925 | - .method("GET") | ||
| 6926 | - .uri(format!("/exams/{exam}/live/stream")) | ||
| 6927 | - .header("cookie", &teacher) | ||
| 6928 | - .body(Body::empty()) | ||
| 6929 | - .unwrap(); | ||
| 6930 | - let response = app.clone().oneshot(request).await.unwrap(); | ||
| 6931 | - assert_eq!(response.status(), StatusCode::OK); | ||
| 6932 | - let content_type = response | ||
| 6933 | - .headers() | ||
| 6934 | - .get("content-type") | ||
| 6935 | - .expect("content-type") | ||
| 6936 | - .to_str() | ||
| 6937 | - .unwrap(); | ||
| 6938 | - assert!( | ||
| 6939 | - content_type.starts_with("text/event-stream"), | ||
| 6940 | - "{content_type}" | ||
| 6941 | - ); | ||
| 6942 | - drop(response); | ||
| 6943 | - | ||
| 6944 | - // Students can't watch the monitor; a missing exam is a 404 up front. | ||
| 6945 | - let res = send( | ||
| 6946 | - &app, | ||
| 6947 | - "GET", | ||
| 6948 | - &format!("/exams/{exam}/live/stream"), | ||
| 6949 | - Some(&student), | ||
| 6950 | - None, | ||
| 6951 | - ) | ||
| 6952 | - .await; | ||
| 6953 | - assert_eq!(res.status, StatusCode::FORBIDDEN); | ||
| 6954 | - let res = send(&app, "GET", "/exams/nope/live/stream", Some(&teacher), None).await; | ||
| 6955 | - assert_eq!(res.status, StatusCode::NOT_FOUND); | ||
| 6956 | -} | ||
| 6957 | - | ||
| 6958 | // --- subjects --------------------------------------------------------------- | 6904 | // --- subjects --------------------------------------------------------------- |
| 6959 | 6905 | ||
| 6960 | #[tokio::test] | 6906 | #[tokio::test] |