diff --git a/README.md b/README.md index 557d6f7..5243be1 100644 --- a/README.md +++ b/README.md @@ -311,7 +311,7 @@ course enrollments. | 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 | | Author an exam's questions (add/edit/delete, incl. question + option images) | teacher | Course-management rights; frozen once anyone has an attempt | | 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 | -| Watch an exam's live monitor (snapshot or SSE stream) | teacher | Course-management rights | +| Watch an exam's live monitor (poll the snapshot) | teacher | Course-management rights | | Create courses | teacher | The creator manages the course, and owns it for good | | 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`+ | | 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 | DELETE | `/exams/{id}/attempt/answers/{qid}/image` | student | Clear the caller's own drawn answer (own in-progress attempt) | | GET | `/exams/{id}/attempts/{user}/answers/{qid}/image` | teacher | A student's drawn-answer bytes, inline, for the grader (course manager) | | 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") | -| 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) | -| GET | `/exams/{id}/live/stream` | teacher | The same snapshot as SSE `snapshot` events every ~2s (course manager) | +| 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 | | 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) | | 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 | | 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 window closes, `not_started` hardens into `absent` — the no-shows, flagged right in the roster (open exams have no window, so never an `absent`). The flag is informational: an absent student still has no mark until the teacher -records one through `POST /exams/{id}/results`. -`GET /exams/{id}/live/stream` is the same JSON as Server-Sent Events: a -`snapshot` event immediately on connect, then every ~2 s — attendance, ticking -clocks, submissions, and marks land without polling: - -```js -const es = new EventSource(`${BASE}/exams/${id}/live/stream`, { withCredentials: true }); -es.addEventListener("snapshot", (e) => render(JSON.parse(e.data))); -``` +records one through `POST /exams/{id}/results`. Poll `GET /exams/{id}/live` to +keep a monitor current — attendance, ticking clocks, submissions, and marks all +ride in each snapshot. Deleting an exam (or its course) cascades attempts, questions, answers, and question + answer images (blobs included) along with results; unenrolling mid-exam diff --git a/src/constant.rs b/src/constant.rs index 8490705..824f4c7 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -176,9 +176,6 @@ pub const MAX_EXAM_DURATION_MS: i64 = 24 * 60 * 60 * 1000; pub const MAX_EXAM_ATTEMPTS: i64 = 100; pub const UNLIMITED_EXAM_ATTEMPTS: i64 = 0; -/// Cadence of the live exam-monitor SSE stream (`GET /exams/{id}/live/stream`). -pub const EXAM_LIVE_STREAM_INTERVAL_SECS: u64 = 2; - /// Cadence of the background keepalive query on the database WebSocket. The /// traffic keeps the connection from being dropped as idle; when it does drop, /// the ping also makes the SDK notice and reconnect long before the next real diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index ae8da8c..fa5780f 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -2,8 +2,8 @@ //! //! REST remains the fallback (`POST /exams/{id}/attempt/answers` etc.); the //! socket exists so a sitting student gets autosave acks and a live, -//! server-judged countdown without polling. The teacher monitor deliberately -//! stays on SSE (`/exams/{id}/live/stream`) — it only ever flows one way. +//! server-judged countdown without polling. The teacher monitor polls the +//! one-shot snapshot (`GET /exams/{id}/live`) instead. //! //! Wire protocol (JSON text frames): //! diff --git a/src/web/exams.rs b/src/web/exams.rs index c089edd..11dd0c7 100644 --- a/src/web/exams.rs +++ b/src/web/exams.rs @@ -1,21 +1,15 @@ use std::collections::HashMap; -use std::time::Duration; use axum::Json; use axum::extract::{DefaultBodyLimit, Multipart, Path, Query, State}; use axum::http::StatusCode; use axum::response::Response; -use axum::response::sse::{Event, KeepAlive, Sse}; use serde::{Deserialize, Serialize}; -use tokio_stream::wrappers::IntervalStream; -use tokio_stream::{Stream, StreamExt}; use utoipa::ToSchema; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{ - EXAM_LIVE_STREAM_INTERVAL_SECS, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES, -}; +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; use crate::domain::course::Course; @@ -80,7 +74,6 @@ pub fn routes() -> OpenApiRouter { .routes(routes!(start_attempt, my_attempt)) .routes(routes!(finish_attempt)) .routes(routes!(exam_live)) - .routes(routes!(exam_live_stream)) .routes(routes!(create_question, list_questions)) .routes(routes!(update_question, delete_question)) .routes(routes!(attempt_questions)) @@ -1238,8 +1231,7 @@ async fn live_snapshot(exam: &Exam, db: &Database) -> Result, - RequireTeacher(user): RequireTeacher, - Path(id): Path, -) -> Result>>, AppError> { - let exam_id = ExamId::from_key(&id); - // A missing exam is a 404 up front; after this the response is a stream. - let exam = Exam::read(&exam_id, &st.db) - .await? - .ok_or(AppError::NotFound)?; - let course = course_of(&exam, &st.db).await?; - if !can_manage_course(&course, &user) { - return Err(AppError::Forbidden( - "only the course creator, an assigned teacher, or a manager/admin can monitor this exam", - )); - } - - // First tick fires immediately, so the monitor paints on connect. The - // exam is re-read every tick: schedule edits (deadline extensions) show - // up mid-stream. - let interval = tokio::time::interval(Duration::from_secs(EXAM_LIVE_STREAM_INTERVAL_SECS)); - let stream = IntervalStream::new(interval).then(move |_| { - let db = st.db.clone(); - let exam_id = exam_id.clone(); - async move { - let snapshot = match Exam::read(&exam_id, &db).await { - Ok(Some(exam)) => live_snapshot(&exam, &db).await, - Ok(None) => Err(AppError::NotFound), - Err(err) => Err(err), - }; - match snapshot { - Ok(snapshot) => Event::default().event("snapshot").json_data(&snapshot), - // Exam deleted mid-stream or a db hiccup: say so without - // leaking internals and keep the stream alive — the client - // decides whether to hang on or close. - Err(err) => { - tracing::warn!("live exam stream snapshot failed: {err}"); - Event::default() - .event("error") - .json_data(serde_json::json!({ "error": "live snapshot unavailable" })) - } - } - } - }); - Ok(Sse::new(stream).keep_alive(KeepAlive::default())) -} - // ---- questions -------------------------------------------------------------- // Teachers author the question list before the exam runs; it freezes the // moment anyone starts an attempt, so every student sits the same exam. diff --git a/tests/e2e.rs b/tests/e2e.rs index 7487cd2..33b90a2 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -403,276 +403,6 @@ async fn attendance_rollup_across_users() { assert_eq!(res.status(), StatusCode::UNAUTHORIZED); } -/// The live exam monitor over a real TCP connection: an `EventSource`-style -/// GET must yield a `snapshot` event carrying the roster within the first -/// ticks (the first one fires immediately on connect). -#[tokio::test] -async fn live_exam_stream_pushes_snapshots_over_http() { - let (base, db) = spawn_server().await; - let teacher = client(); - register(&teacher, &base, "hoca").await; - promote(&db, "hoca", "teacher").await; - login(&teacher, &base, "hoca").await; - - let student = client(); - register(&student, &base, "veli").await; - login(&student, &base, "veli").await; - let student_id: Value = student - .get(format!("{base}/auth/me")) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let student_id = student_id["id"].as_str().unwrap().to_string(); - - // Course + enrolled student + a sync exam whose window is open now - // (window times judged by the server clock, fetched from `/time`). - let now: Value = teacher - .get(format!("{base}/time")) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let now = now["now"].as_i64().unwrap(); - - let course: Value = teacher - .post(format!("{base}/courses")) - .json(&json!({ "title": "algebra" })) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let course_id = course["id"].as_str().unwrap(); - let res = teacher - .post(format!("{base}/courses/{course_id}/enrollments")) - .json(&json!({ "user_id": student_id })) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::OK); - let exam: Value = teacher - .post(format!("{base}/courses/{course_id}/exams")) - .json(&json!({ - "title": "final", "kind": "final", - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, - })) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let exam_id = exam["id"].as_str().unwrap(); - - // The student sits down — that's the live-attendance signal. - let res = student - .post(format!("{base}/exams/{exam_id}/attempt")) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::CREATED); - - // Open the stream and read until one full snapshot event has arrived. - let mut res = teacher - .get(format!("{base}/exams/{exam_id}/live/stream")) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::OK); - let content_type = res - .headers() - .get("content-type") - .expect("content-type") - .to_str() - .unwrap() - .to_string(); - assert!( - content_type.starts_with("text/event-stream"), - "{content_type}" - ); - - let mut body = String::new(); - let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5); - while !(body.contains("event: snapshot") && body.contains("\n\n")) { - let chunk = tokio::time::timeout_at(deadline, res.chunk()) - .await - .expect("a snapshot event within 5s") - .expect("stream stays open") - .expect("stream yields data"); - body.push_str(&String::from_utf8_lossy(&chunk)); - } - assert!(body.contains("\"in_progress\""), "{body}"); - assert!(body.contains("veli"), "{body}"); - assert!(body.contains("\"enrolled\":1"), "{body}"); -} - -/// Read the open SSE stream `res` until a `snapshot` event whose parsed JSON -/// satisfies `want`, and return that snapshot. `buf` carries bytes between -/// calls, so a partial event at the end of one read completes in the next and -/// events already buffered are drained before more are pulled. Panics if -/// nothing matching arrives within `within`. -async fn next_matching_snapshot( - res: &mut reqwest::Response, - buf: &mut String, - within: std::time::Duration, - want: impl Fn(&Value) -> bool, -) -> Value { - let deadline = tokio::time::Instant::now() + within; - loop { - // Drain every complete event (`\n\n`-terminated) already buffered - // before pulling more bytes — keep-alive comments and non-snapshot - // frames are skipped, non-matching snapshots consumed and dropped. - while let Some(end) = buf.find("\n\n") { - let event: String = buf.drain(..end + 2).collect(); - if !event.contains("event: snapshot") { - continue; - } - let data = event - .lines() - .find_map(|line| line.strip_prefix("data:")) - .expect("a snapshot event carries a data line") - .trim(); - let snapshot: Value = serde_json::from_str(data).expect("snapshot is json"); - if want(&snapshot) { - return snapshot; - } - } - let chunk = tokio::time::timeout_at(deadline, res.chunk()) - .await - .expect("an SSE event before the deadline") - .expect("stream stays open") - .expect("stream yields data"); - buf.push_str(&String::from_utf8_lossy(&chunk)); - } -} - -/// The teacher's monitor updates *live* on one held-open connection: after the -/// first snapshot lands, a student's submission must surface in a *later* event -/// on the *same* stream, no reconnect. Guards against a monitor that replays a -/// cached first snapshot or stops re-reading the exam each tick — the split -/// coverage (one-shot `/live` correctness + a single streamed event) would miss -/// that. -#[tokio::test] -async fn live_stream_reflects_a_status_change_on_the_open_connection() { - let (base, db) = spawn_server().await; - let teacher = client(); - register(&teacher, &base, "hoca").await; - promote(&db, "hoca", "teacher").await; - login(&teacher, &base, "hoca").await; - - let student = client(); - register(&student, &base, "veli").await; - login(&student, &base, "veli").await; - let student_id: Value = student - .get(format!("{base}/auth/me")) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let student_id = student_id["id"].as_str().unwrap().to_string(); - - let now: Value = teacher - .get(format!("{base}/time")) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let now = now["now"].as_i64().unwrap(); - - let course: Value = teacher - .post(format!("{base}/courses")) - .json(&json!({ "title": "algebra" })) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let course_id = course["id"].as_str().unwrap(); - let res = teacher - .post(format!("{base}/courses/{course_id}/enrollments")) - .json(&json!({ "user_id": student_id })) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::OK); - let exam: Value = teacher - .post(format!("{base}/courses/{course_id}/exams")) - .json(&json!({ - "title": "final", "kind": "final", - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, - })) - .send() - .await - .unwrap() - .json() - .await - .unwrap(); - let exam_id = exam["id"].as_str().unwrap(); - - // The student sits down — in progress, nothing submitted. - let res = student - .post(format!("{base}/exams/{exam_id}/attempt")) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::CREATED); - - // The teacher opens the live stream and reads the first snapshot. - let mut res = teacher - .get(format!("{base}/exams/{exam_id}/live/stream")) - .send() - .await - .unwrap(); - assert_eq!(res.status(), StatusCode::OK); - assert!( - res.headers() - .get("content-type") - .expect("content-type") - .to_str() - .unwrap() - .starts_with("text/event-stream") - ); - - let mut buf = String::new(); - let first = - next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(5), |s| { - s["counts"]["in_progress"].as_i64() == Some(1) - }) - .await; - assert_eq!(first["counts"]["submitted"], 0, "{first}"); - assert_eq!(first["students"][0]["user"]["username"], "veli"); - assert_eq!(first["students"][0]["status"], "in_progress", "{first}"); - - // The student submits while the teacher's stream stays open. - let res_finish = student - .post(format!("{base}/exams/{exam_id}/attempt/finish")) - .send() - .await - .unwrap(); - assert_eq!(res_finish.status(), StatusCode::OK); - - // A later event on the same connection must carry the change — the monitor - // re-reads and recomputes each tick, it does not replay the first snapshot. - let later = - next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(8), |s| { - s["counts"]["submitted"].as_i64() == Some(1) - }) - .await; - assert_eq!(later["counts"]["in_progress"], 0, "{later}"); - assert_eq!(later["students"][0]["status"], "submitted", "{later}"); -} - /// Log in without a cookie jar and hand back the raw `session=` pair — /// the exact header value the WebSocket handshake needs (tungstenite carries /// no jar of its own). diff --git a/tests/integration.rs b/tests/integration.rs index 0d468e5..a487ca3 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -203,7 +203,6 @@ async fn protected_routes_require_session() { ("GET", "/exams/x/attempt"), ("POST", "/exams/x/attempt/finish"), ("GET", "/exams/x/live"), - ("GET", "/exams/x/live/stream"), ("POST", "/exams/x/questions"), ("GET", "/exams/x/questions"), ("PATCH", "/exams/x/questions/y"), @@ -3258,7 +3257,6 @@ async fn course_data_is_walled_off_from_other_teachers() { format!("/exams/{exam_id}/results"), format!("/exams/{exam_id}/statistics"), format!("/exams/{exam_id}/live"), - format!("/exams/{exam_id}/live/stream"), format!("/exams/{exam_id}/questions"), format!("/exams/{exam_id}/attempts/{alice_id}/answers"), ] { @@ -6903,58 +6901,6 @@ async fn open_duration_and_sync_retakes_shape_the_deadline_and_monitor() { assert_eq!(res.status, StatusCode::CONFLICT, "{}", res.body); } -#[tokio::test] -async fn live_stream_is_sse_and_teacher_scoped() { - let (app, db) = app_and_db().await; - let teacher = login_as(&app, &db, "sse_t", "teacher").await; - let student = login(&app, "selin").await; - let course = create_course(&app, &teacher, "geo").await; - let now = Timestamp::now().as_millis(); - let exam = scheduled_exam( - &app, - &teacher, - &course, - json!({ "title": "final", "kind": "final", - "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000 }), - ) - .await; - - // Teacher: 200 with SSE headers. The body is an endless stream, so only - // the head of the response is inspected (common::send would hang). - let request = Request::builder() - .method("GET") - .uri(format!("/exams/{exam}/live/stream")) - .header("cookie", &teacher) - .body(Body::empty()) - .unwrap(); - let response = app.clone().oneshot(request).await.unwrap(); - assert_eq!(response.status(), StatusCode::OK); - let content_type = response - .headers() - .get("content-type") - .expect("content-type") - .to_str() - .unwrap(); - assert!( - content_type.starts_with("text/event-stream"), - "{content_type}" - ); - drop(response); - - // Students can't watch the monitor; a missing exam is a 404 up front. - let res = send( - &app, - "GET", - &format!("/exams/{exam}/live/stream"), - Some(&student), - None, - ) - .await; - assert_eq!(res.status, StatusCode::FORBIDDEN); - let res = send(&app, "GET", "/exams/nope/live/stream", Some(&teacher), None).await; - assert_eq!(res.status, StatusCode::NOT_FOUND); -} - // --- subjects --------------------------------------------------------------- #[tokio::test]