Live monitor pushes changes on a held-open stream
Browse files at this commit9aca0b4e7995a33245f575793b3ec6ea5ca7d312Parent: 3c6e9b9- test
- live monitor pushes changes on a held-open stream
1 changed file +161 -0
- tests/e2e.rs +161 -0
tests/e2e.rsmodified+161 -0
| @@ -501,6 +501,167 @@ async fn live_exam_stream_pushes_snapshots_over_http() { | |||
| 501 | assert!(body.contains("\"enrolled\":1"), "{body}"); | 501 | assert!(body.contains("\"enrolled\":1"), "{body}"); |
| 502 | } | 502 | } |
| 503 | 503 | ||
| 504 | +/// Read the open SSE stream `res` until a `snapshot` event whose parsed JSON | ||
| 505 | +/// satisfies `want`, and return that snapshot. `buf` carries bytes between | ||
| 506 | +/// calls, so a partial event at the end of one read completes in the next and | ||
| 507 | +/// events already buffered are drained before more are pulled. Panics if | ||
| 508 | +/// nothing matching arrives within `within`. | ||
| 509 | +async fn next_matching_snapshot( | ||
| 510 | + res: &mut reqwest::Response, | ||
| 511 | + buf: &mut String, | ||
| 512 | + within: std::time::Duration, | ||
| 513 | + want: impl Fn(&Value) -> bool, | ||
| 514 | +) -> Value { | ||
| 515 | + let deadline = tokio::time::Instant::now() + within; | ||
| 516 | + loop { | ||
| 517 | + // Drain every complete event (`\n\n`-terminated) already buffered | ||
| 518 | + // before pulling more bytes — keep-alive comments and non-snapshot | ||
| 519 | + // frames are skipped, non-matching snapshots consumed and dropped. | ||
| 520 | + while let Some(end) = buf.find("\n\n") { | ||
| 521 | + let event: String = buf.drain(..end + 2).collect(); | ||
| 522 | + if !event.contains("event: snapshot") { | ||
| 523 | + continue; | ||
| 524 | + } | ||
| 525 | + let data = event | ||
| 526 | + .lines() | ||
| 527 | + .find_map(|line| line.strip_prefix("data:")) | ||
| 528 | + .expect("a snapshot event carries a data line") | ||
| 529 | + .trim(); | ||
| 530 | + let snapshot: Value = serde_json::from_str(data).expect("snapshot is json"); | ||
| 531 | + if want(&snapshot) { | ||
| 532 | + return snapshot; | ||
| 533 | + } | ||
| 534 | + } | ||
| 535 | + let chunk = tokio::time::timeout_at(deadline, res.chunk()) | ||
| 536 | + .await | ||
| 537 | + .expect("an SSE event before the deadline") | ||
| 538 | + .expect("stream stays open") | ||
| 539 | + .expect("stream yields data"); | ||
| 540 | + buf.push_str(&String::from_utf8_lossy(&chunk)); | ||
| 541 | + } | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +/// The teacher's monitor updates *live* on one held-open connection: after the | ||
| 545 | +/// first snapshot lands, a student's submission must surface in a *later* event | ||
| 546 | +/// on the *same* stream, no reconnect. Guards against a monitor that replays a | ||
| 547 | +/// cached first snapshot or stops re-reading the exam each tick — the split | ||
| 548 | +/// coverage (one-shot `/live` correctness + a single streamed event) would miss | ||
| 549 | +/// that. | ||
| 550 | +#[tokio::test] | ||
| 551 | +async fn live_stream_reflects_a_status_change_on_the_open_connection() { | ||
| 552 | + let (base, db) = spawn_server().await; | ||
| 553 | + let teacher = client(); | ||
| 554 | + register(&teacher, &base, "hoca").await; | ||
| 555 | + promote(&db, "hoca", "teacher").await; | ||
| 556 | + login(&teacher, &base, "hoca").await; | ||
| 557 | + | ||
| 558 | + let student = client(); | ||
| 559 | + register(&student, &base, "veli").await; | ||
| 560 | + login(&student, &base, "veli").await; | ||
| 561 | + let student_id: Value = student | ||
| 562 | + .get(format!("{base}/auth/me")) | ||
| 563 | + .send() | ||
| 564 | + .await | ||
| 565 | + .unwrap() | ||
| 566 | + .json() | ||
| 567 | + .await | ||
| 568 | + .unwrap(); | ||
| 569 | + let student_id = student_id["id"].as_str().unwrap().to_string(); | ||
| 570 | + | ||
| 571 | + let now: Value = teacher | ||
| 572 | + .get(format!("{base}/time")) | ||
| 573 | + .send() | ||
| 574 | + .await | ||
| 575 | + .unwrap() | ||
| 576 | + .json() | ||
| 577 | + .await | ||
| 578 | + .unwrap(); | ||
| 579 | + let now = now["now"].as_i64().unwrap(); | ||
| 580 | + | ||
| 581 | + let course: Value = teacher | ||
| 582 | + .post(format!("{base}/courses")) | ||
| 583 | + .json(&json!({ "title": "algebra" })) | ||
| 584 | + .send() | ||
| 585 | + .await | ||
| 586 | + .unwrap() | ||
| 587 | + .json() | ||
| 588 | + .await | ||
| 589 | + .unwrap(); | ||
| 590 | + let course_id = course["id"].as_str().unwrap(); | ||
| 591 | + let res = teacher | ||
| 592 | + .post(format!("{base}/courses/{course_id}/enrollments")) | ||
| 593 | + .json(&json!({ "user_id": student_id })) | ||
| 594 | + .send() | ||
| 595 | + .await | ||
| 596 | + .unwrap(); | ||
| 597 | + assert_eq!(res.status(), StatusCode::OK); | ||
| 598 | + let exam: Value = teacher | ||
| 599 | + .post(format!("{base}/courses/{course_id}/exams")) | ||
| 600 | + .json(&json!({ | ||
| 601 | + "title": "final", "kind": "final", | ||
| 602 | + "mode": "sync", "starts_at": now - 1_000, "ends_at": now + 600_000, | ||
| 603 | + })) | ||
| 604 | + .send() | ||
| 605 | + .await | ||
| 606 | + .unwrap() | ||
| 607 | + .json() | ||
| 608 | + .await | ||
| 609 | + .unwrap(); | ||
| 610 | + let exam_id = exam["id"].as_str().unwrap(); | ||
| 611 | + | ||
| 612 | + // The student sits down — in progress, nothing submitted. | ||
| 613 | + let res = student | ||
| 614 | + .post(format!("{base}/exams/{exam_id}/attempt")) | ||
| 615 | + .send() | ||
| 616 | + .await | ||
| 617 | + .unwrap(); | ||
| 618 | + assert_eq!(res.status(), StatusCode::CREATED); | ||
| 619 | + | ||
| 620 | + // The teacher opens the live stream and reads the first snapshot. | ||
| 621 | + let mut res = teacher | ||
| 622 | + .get(format!("{base}/exams/{exam_id}/live/stream")) | ||
| 623 | + .send() | ||
| 624 | + .await | ||
| 625 | + .unwrap(); | ||
| 626 | + assert_eq!(res.status(), StatusCode::OK); | ||
| 627 | + assert!( | ||
| 628 | + res.headers() | ||
| 629 | + .get("content-type") | ||
| 630 | + .expect("content-type") | ||
| 631 | + .to_str() | ||
| 632 | + .unwrap() | ||
| 633 | + .starts_with("text/event-stream") | ||
| 634 | + ); | ||
| 635 | + | ||
| 636 | + let mut buf = String::new(); | ||
| 637 | + let first = | ||
| 638 | + next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(5), |s| { | ||
| 639 | + s["counts"]["in_progress"].as_i64() == Some(1) | ||
| 640 | + }) | ||
| 641 | + .await; | ||
| 642 | + assert_eq!(first["counts"]["submitted"], 0, "{first}"); | ||
| 643 | + assert_eq!(first["students"][0]["user"]["username"], "veli"); | ||
| 644 | + assert_eq!(first["students"][0]["status"], "in_progress", "{first}"); | ||
| 645 | + | ||
| 646 | + // The student submits while the teacher's stream stays open. | ||
| 647 | + let res_finish = student | ||
| 648 | + .post(format!("{base}/exams/{exam_id}/attempt/finish")) | ||
| 649 | + .send() | ||
| 650 | + .await | ||
| 651 | + .unwrap(); | ||
| 652 | + assert_eq!(res_finish.status(), StatusCode::OK); | ||
| 653 | + | ||
| 654 | + // A later event on the same connection must carry the change — the monitor | ||
| 655 | + // re-reads and recomputes each tick, it does not replay the first snapshot. | ||
| 656 | + let later = | ||
| 657 | + next_matching_snapshot(&mut res, &mut buf, std::time::Duration::from_secs(8), |s| { | ||
| 658 | + s["counts"]["submitted"].as_i64() == Some(1) | ||
| 659 | + }) | ||
| 660 | + .await; | ||
| 661 | + assert_eq!(later["counts"]["in_progress"], 0, "{later}"); | ||
| 662 | + assert_eq!(later["students"][0]["status"], "submitted", "{later}"); | ||
| 663 | +} | ||
| 664 | + | ||
| 504 | /// Log in without a cookie jar and hand back the raw `session=<token>` pair — | 665 | /// Log in without a cookie jar and hand back the raw `session=<token>` pair — |
| 505 | /// the exact header value the WebSocket handshake needs (tungstenite carries | 666 | /// the exact header value the WebSocket handshake needs (tungstenite carries |
| 506 | /// no jar of its own). | 667 | /// no jar of its own). |