forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

e2e.rs4381 lines, 151.9 KiBHistoryRawDownload
1//! End-to-end tests: boot the real server on an ephemeral TCP port and drive it
2//! with `reqwest` over HTTP, using its cookie jar exactly like a browser client.
3
4use hezarfen_backend::database::Database;
5use hezarfen_backend::rate_limit::RateLimitConfig;
6use hezarfen_backend::state::AppState;
7use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId};
8use hezarfen_backend::{build_router, database};
9mod common;
10
11use reqwest::{Client, StatusCode};
12use serde_json::{Value, json};
13use uuid::Uuid;
14
15/// Start the server on a random port. Returns its base URL (e.g.
16/// `http://127.0.0.1:54321`) plus a handle to its database, so a test can grant
17/// roles the same out-of-band way production does.
18async fn spawn_server() -> (String, Database) {
19 spawn_server_with_ai(None).await
20}
21
22/// [`spawn_server`], with the AI bridge the chatbot relays through wired in.
23async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) {
24 let tenants = database::init_test_tenants().await;
25 let db = tenants
26 .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
27 .await
28 .expect("the demo school");
29 // The deployment's operator, seeded exactly as `main` does from
30 // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable
31 // over real TCP here too.
32 hezarfen_backend::service::builder::ensure(
33 tenants.control(),
34 hezarfen_backend::domain::user::Username::try_new("operator").unwrap(),
35 hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(),
36 )
37 .await
38 .expect("seed the builder");
39 let app = build_router(AppState {
40 db: tenants.control().clone(),
41 tenants,
42 // Kept (not auto-deleted) so the directory outlives this helper;
43 // it's under the OS temp dir, reclaimed like any other temp file.
44 files_path: tempfile::tempdir().expect("files dir").keep(),
45 cookie_secure: false,
46 // Every request here comes from 127.0.0.1, so per-IP limits would
47 // meter the whole suite as one client. Off; `rate_limit.rs` covers it.
48 rate_limit: RateLimitConfig::unlimited(),
49 chatbot_limit: Default::default(),
50 rag_limit: Default::default(),
51 exam_presence: Default::default(),
52 board_hub: Default::default(),
53 ai,
54 metrics: hezarfen_backend::telemetry::Metrics::noop(),
55 });
56 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
57 let addr = listener.local_addr().unwrap();
58 tokio::spawn(async move {
59 // Mirror `main`: expose peer addresses so the limiter key path in
60 // production is the same one exercised end-to-end.
61 axum::serve(
62 listener,
63 app.into_make_service_with_connect_info::<std::net::SocketAddr>(),
64 )
65 .await
66 .unwrap();
67 });
68 (format!("http://{addr}"), db)
69}
70
71/// Grant `user` a role directly (the manual bootstrap path).
72async fn promote(db: &Database, user: &str, role: &str) {
73 sqlx::query("UPDATE app_user SET role = $1 WHERE username = $2")
74 .bind(role)
75 .bind(user)
76 .execute(db)
77 .await
78 .unwrap();
79}
80
81/// A reqwest client with its own cookie jar (one per simulated user).
82fn client() -> Client {
83 Client::builder().cookie_store(true).build().unwrap()
84}
85
86async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response {
87 client
88 .post(format!("{base}/auth/register"))
89 .json(&json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": user, "password": "secret1" }))
90 .send()
91 .await
92 .unwrap()
93}
94
95async fn login(client: &Client, base: &str, user: &str) {
96 let res = client
97 .post(format!("{base}/auth/login"))
98 .json(&json!({ "username": user, "password": "secret1" }))
99 .send()
100 .await
101 .unwrap();
102 assert_eq!(res.status(), StatusCode::OK, "login {user}");
103}
104
105#[tokio::test]
106async fn full_user_journey() {
107 let (base, db) = spawn_server().await;
108 let ali = client();
109 let veli = client();
110
111 // --- signup + auth ---------------------------------------------------
112 assert_eq!(
113 register(&ali, &base, "ali").await.status(),
114 StatusCode::CREATED
115 );
116 assert_eq!(
117 register(&veli, &base, "veli").await.status(),
118 StatusCode::CREATED
119 );
120 // ali runs the class: give her the teacher role. veli stays a student.
121 promote(&db, "ali", "teacher").await;
122
123 // me before login -> 401
124 let res = ali.get(format!("{base}/auth/me")).send().await.unwrap();
125 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
126
127 login(&ali, &base, "ali").await;
128 login(&veli, &base, "veli").await;
129
130 let me: Value = ali
131 .get(format!("{base}/auth/me"))
132 .send()
133 .await
134 .unwrap()
135 .json()
136 .await
137 .unwrap();
138 assert_eq!(me["username"], "ali");
139
140 let veli_id = veli
141 .get(format!("{base}/auth/me"))
142 .send()
143 .await
144 .unwrap()
145 .json::<Value>()
146 .await
147 .unwrap()["id"]
148 .as_str()
149 .unwrap()
150 .to_string();
151
152 // --- notes -----------------------------------------------------------
153 let note: Value = ali
154 .post(format!("{base}/notes"))
155 .json(&json!({ "title": "first", "content": "hello" }))
156 .send()
157 .await
158 .unwrap()
159 .json()
160 .await
161 .unwrap();
162 let note_id = note["id"].as_str().unwrap().to_string();
163 assert_eq!(note["title"], "first");
164
165 // veli cannot read ali's note
166 let res = veli
167 .get(format!("{base}/notes/{note_id}"))
168 .send()
169 .await
170 .unwrap();
171 assert_eq!(res.status(), StatusCode::NOT_FOUND);
172
173 // --- events + attendance --------------------------------------------
174 let event: Value = ali
175 .post(format!("{base}/events"))
176 .json(&json!({ "title": "standup" }))
177 .send()
178 .await
179 .unwrap()
180 .json()
181 .await
182 .unwrap();
183 let event_id = event["id"].as_str().unwrap().to_string();
184
185 // ali marks veli present
186 let res = ali
187 .post(format!("{base}/events/{event_id}/attendance"))
188 .json(&json!({ "status": "present", "user_id": veli_id }))
189 .send()
190 .await
191 .unwrap();
192 assert_eq!(res.status(), StatusCode::OK);
193
194 // The roster is a teacher+ view — veli (a student) is refused …
195 let res = veli
196 .get(format!("{base}/events/{event_id}/attendance"))
197 .send()
198 .await
199 .unwrap();
200 assert_eq!(res.status(), StatusCode::FORBIDDEN);
201
202 // … while ali (the teacher) reads it in full.
203 let roster: Value = ali
204 .get(format!("{base}/events/{event_id}/attendance"))
205 .send()
206 .await
207 .unwrap()
208 .json()
209 .await
210 .unwrap();
211 assert_eq!(roster["items"].as_array().unwrap().len(), 1);
212 // People come back as refs — id plus something a human can read.
213 assert_eq!(roster["items"][0]["user"]["id"], veli_id);
214 assert_eq!(roster["items"][0]["user"]["username"], "veli");
215 assert_eq!(roster["items"][0]["marked_by"]["username"], "ali");
216 assert_eq!(roster["items"][0]["status"], "present");
217
218 // --- user search (for the pickers) -----------------------------------
219 // Teacher+ finds people by fragment; the refs carry no contact details.
220 let found: Value = ali
221 .get(format!("{base}/users/search?q=vel"))
222 .send()
223 .await
224 .unwrap()
225 .json()
226 .await
227 .unwrap();
228 assert_eq!(found["items"][0]["username"], "veli");
229 assert!(found["items"][0].get("email").is_none());
230
231 // Role filter narrows: veli is a student, so she matches `role=student`
232 // but vanishes under `role=teacher`. An unknown role is a 400.
233 let found: Value = ali
234 .get(format!("{base}/users/search?q=vel&role=student"))
235 .send()
236 .await
237 .unwrap()
238 .json()
239 .await
240 .unwrap();
241 assert_eq!(found["items"].as_array().unwrap().len(), 1);
242 assert_eq!(found["items"][0]["username"], "veli");
243
244 let found: Value = ali
245 .get(format!("{base}/users/search?q=vel&role=teacher"))
246 .send()
247 .await
248 .unwrap()
249 .json()
250 .await
251 .unwrap();
252 assert!(found["items"].as_array().unwrap().is_empty());
253
254 let res = ali
255 .get(format!("{base}/users/search?q=vel&role=wizard"))
256 .send()
257 .await
258 .unwrap();
259 assert_eq!(res.status(), StatusCode::BAD_REQUEST);
260
261 // The filter also *includes* on non-student roles: ali is the teacher.
262 let found: Value = ali
263 .get(format!("{base}/users/search?q=al&role=teacher"))
264 .send()
265 .await
266 .unwrap()
267 .json()
268 .await
269 .unwrap();
270 assert_eq!(found["items"].as_array().unwrap().len(), 1);
271 assert_eq!(found["items"][0]["username"], "ali");
272
273 // Search matches profile names too, and the role filter applies to those
274 // hits as well: "lic" only exists in ali's freshly set name, not in any
275 // username, so it appears under `role=teacher` and not `role=student`.
276 let res = ali
277 .patch(format!("{base}/users/me"))
278 .json(&json!({ "name": "Alice" }))
279 .send()
280 .await
281 .unwrap();
282 assert_eq!(res.status(), StatusCode::OK);
283
284 let found: Value = ali
285 .get(format!("{base}/users/search?q=lic&role=teacher"))
286 .send()
287 .await
288 .unwrap()
289 .json()
290 .await
291 .unwrap();
292 assert_eq!(found["items"].as_array().unwrap().len(), 1);
293 assert_eq!(found["items"][0]["username"], "ali");
294 assert_eq!(found["items"][0]["display_name"], "Alice");
295
296 let found: Value = ali
297 .get(format!("{base}/users/search?q=lic&role=student"))
298 .send()
299 .await
300 .unwrap()
301 .json()
302 .await
303 .unwrap();
304 assert!(found["items"].as_array().unwrap().is_empty());
305
306 // A student may search since #24 — and sees staff only: ali the teacher
307 // comes back, another student never would.
308 let found: Value = veli
309 .get(format!("{base}/users/search?q=ali"))
310 .send()
311 .await
312 .unwrap()
313 .json()
314 .await
315 .unwrap();
316 assert_eq!(found["items"].as_array().unwrap().len(), 1);
317 assert_eq!(found["items"][0]["username"], "ali");
318 let res = veli
319 .get(format!("{base}/users/search?q=vel&role=student"))
320 .send()
321 .await
322 .unwrap();
323 assert_eq!(res.status(), StatusCode::FORBIDDEN);
324
325 // veli is only a student, so she cannot create events.
326 let res = veli
327 .post(format!("{base}/events"))
328 .json(&json!({ "title": "nope" }))
329 .send()
330 .await
331 .unwrap();
332 assert_eq!(res.status(), StatusCode::FORBIDDEN);
333
334 // --- logout invalidates the session ---------------------------------
335 let res = ali
336 .post(format!("{base}/auth/logout"))
337 .send()
338 .await
339 .unwrap();
340 assert_eq!(res.status(), StatusCode::NO_CONTENT);
341
342 let res = ali.get(format!("{base}/auth/me")).send().await.unwrap();
343 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
344}
345
346#[tokio::test]
347async fn attendance_rollup_across_users() {
348 let (base, db) = spawn_server().await;
349 let host = client();
350 let a = client();
351 let b = client();
352
353 for (c, name) in [(&host, "host"), (&a, "amy"), (&b, "ben")] {
354 assert_eq!(register(c, &base, name).await.status(), StatusCode::CREATED);
355 login(c, &base, name).await;
356 }
357 // The host runs the event and records everyone, which is a teacher+ action.
358 promote(&db, "host", "teacher").await;
359
360 let id_of = |v: &Value| v["id"].as_str().unwrap().to_string();
361 let amy_id = id_of(
362 &a.get(format!("{base}/auth/me"))
363 .send()
364 .await
365 .unwrap()
366 .json::<Value>()
367 .await
368 .unwrap(),
369 );
370 let ben_id = id_of(
371 &b.get(format!("{base}/auth/me"))
372 .send()
373 .await
374 .unwrap()
375 .json::<Value>()
376 .await
377 .unwrap(),
378 );
379
380 // Host creates an event and records everyone.
381 let event_id = id_of(
382 &host
383 .post(format!("{base}/events"))
384 .json(&json!({ "title": "all-hands" }))
385 .send()
386 .await
387 .unwrap()
388 .json::<Value>()
389 .await
390 .unwrap(),
391 );
392
393 for (uid, status) in [(&amy_id, "present"), (&ben_id, "late")] {
394 let res = host
395 .post(format!("{base}/events/{event_id}/attendance"))
396 .json(&json!({ "status": status, "user_id": uid }))
397 .send()
398 .await
399 .unwrap();
400 assert_eq!(res.status(), StatusCode::OK);
401 }
402 // Host marks self too.
403 host.post(format!("{base}/events/{event_id}/attendance"))
404 .json(&json!({ "status": "present" }))
405 .send()
406 .await
407 .unwrap();
408
409 // The roster is a teacher+ view: an attendee sees only their own tallies
410 // (`/attendance/me`), so ben is refused …
411 let res = b
412 .get(format!("{base}/events/{event_id}/attendance"))
413 .send()
414 .await
415 .unwrap();
416 assert_eq!(res.status(), StatusCode::FORBIDDEN);
417
418 // … while the host reads the full roster (3 people).
419 let roster: Value = host
420 .get(format!("{base}/events/{event_id}/attendance"))
421 .send()
422 .await
423 .unwrap()
424 .json()
425 .await
426 .unwrap();
427 assert_eq!(roster["items"].as_array().unwrap().len(), 3);
428
429 // Unauthenticated client is refused.
430 let res = client()
431 .get(format!("{base}/events/{event_id}/attendance"))
432 .send()
433 .await
434 .unwrap();
435 assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
436}
437
438/// Log in without a cookie jar and hand back the raw `session=<token>` pair —
439/// the exact header value the WebSocket handshake needs (tungstenite carries
440/// no jar of its own).
441async fn raw_session_cookie(base: &str, user: &str) -> String {
442 let res = Client::new()
443 .post(format!("{base}/auth/login"))
444 .json(&json!({ "username": user, "password": "secret1" }))
445 .send()
446 .await
447 .unwrap();
448 assert_eq!(res.status(), StatusCode::OK, "login {user}");
449 res.headers()
450 .get("set-cookie")
451 .expect("session cookie set on login")
452 .to_str()
453 .unwrap()
454 .split(';')
455 .next()
456 .unwrap()
457 .to_string()
458}
459
460// ---- the exam room (WebSocket) ---------------------------------------------
461
462use futures_util::{SinkExt, StreamExt};
463use tokio_tungstenite::tungstenite::client::IntoClientRequest;
464use tokio_tungstenite::tungstenite::protocol::Message;
465use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, connect_async};
466
467type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
468
469/// Open the exam room, optionally authenticated. `Ok` is the upgraded socket;
470/// `Err` is the HTTP status a pre-upgrade gate refused with.
471async fn ws_open(base: &str, exam_id: &str, cookie: Option<&str>) -> Result<WsStream, u16> {
472 let url = format!(
473 "{}/exams/{exam_id}/attempt/ws",
474 base.replace("http://", "ws://")
475 );
476 let mut request = url.into_client_request().unwrap();
477 if let Some(cookie) = cookie {
478 request
479 .headers_mut()
480 .insert("cookie", cookie.parse().unwrap());
481 }
482 match connect_async(request).await {
483 Ok((ws, _)) => Ok(ws),
484 Err(tokio_tungstenite::tungstenite::Error::Http(response)) => {
485 Err(response.status().as_u16())
486 }
487 Err(other) => panic!("unexpected handshake failure: {other}"),
488 }
489}
490
491async fn ws_send(ws: &mut WsStream, frame: Value) {
492 ws.send(Message::Text(frame.to_string().into()))
493 .await
494 .unwrap();
495}
496
497/// The next JSON text frame, within a deadline; `None` once the server closes.
498/// 6 s covers the room's 2 s tick with room to spare on a loaded machine.
499async fn ws_next_frame(ws: &mut WsStream) -> Option<Value> {
500 loop {
501 let message = tokio::time::timeout(std::time::Duration::from_secs(6), ws.next())
502 .await
503 .expect("a frame within 6s")?
504 .expect("stream stays healthy");
505 match message {
506 Message::Text(text) => {
507 return Some(serde_json::from_str(text.as_str()).expect("JSON frame"));
508 }
509 Message::Close(_) => return None,
510 _ => continue,
511 }
512 }
513}
514
515/// Skip periodic `state` ticks until a frame of `kind` arrives.
516async fn ws_frame_of_type(ws: &mut WsStream, kind: &str) -> Value {
517 loop {
518 let frame = ws_next_frame(ws)
519 .await
520 .unwrap_or_else(|| panic!("room closed while waiting for a {kind:?} frame"));
521 if frame["type"] == kind {
522 return frame;
523 }
524 assert_eq!(frame["type"], "state", "unexpected frame: {frame}");
525 }
526}
527
528/// A booted server with teacher `hoca`, enrolled student `veli` (jar client +
529/// raw cookie for the handshake), and an open sync exam holding one choice
530/// question — the spine of every exam-room test. The window closes
531/// `window_ms` from now.
532struct ExamRoom {
533 base: String,
534 db: Database,
535 teacher: Client,
536 student: Client,
537 student_id: String,
538 cookie: String,
539 subject_id: String,
540 /// The instance the şube teaches the course as — the academic anchor every
541 /// roster, exam and karne keys on since the K12 remodel.
542 instance_id: String,
543 /// The dönem the exams written here are filed under.
544 term: String,
545 exam_id: String,
546 question_id: String,
547 /// The fixture question's minted choice ids, in list order — what the
548 /// tests below used to write as the indexes 0 and 1.
549 choice_ids: Vec<String>,
550}
551
552impl ExamRoom {
553 /// Write one more exam into the fixture's instance as the teacher, through
554 /// the shipped shape: it hangs off `/instances/{id}/exams` and must carry
555 /// the dönem it counts into. `extra` overlays the scheduling fields.
556 async fn an_exam(&self, title: &str, extra: Value) -> Value {
557 let mut body = json!({ "title": title, "kind": "yazili", "term": self.term });
558 if let Some(map) = body.as_object_mut() {
559 map.extend(extra.as_object().cloned().unwrap_or_default());
560 }
561 self.teacher
562 .post(format!(
563 "{}/instances/{}/exams",
564 self.base, self.instance_id
565 ))
566 .json(&body)
567 .send()
568 .await
569 .unwrap()
570 .json()
571 .await
572 .unwrap()
573 }
574}
575
576async fn exam_room_fixture(window_ms: i64) -> ExamRoom {
577 let (base, db) = spawn_server().await;
578 let teacher = client();
579 register(&teacher, &base, "hoca").await;
580 promote(&db, "hoca", "teacher").await;
581 login(&teacher, &base, "hoca").await;
582 let teacher_id: Value = teacher
583 .get(format!("{base}/auth/me"))
584 .send()
585 .await
586 .unwrap()
587 .json()
588 .await
589 .unwrap();
590 let teacher_id = teacher_id["id"].as_str().unwrap().to_string();
591
592 // A şube is school structure, so a manager mints the calendar, the section
593 // and the instance every exam in this fixture hangs off.
594 let manager = client();
595 register(&manager, &base, "mudur").await;
596 promote(&db, "mudur", "manager").await;
597 login(&manager, &base, "mudur").await;
598
599 let student = client();
600 register(&student, &base, "veli").await;
601 login(&student, &base, "veli").await;
602 let me: Value = student
603 .get(format!("{base}/auth/me"))
604 .send()
605 .await
606 .unwrap()
607 .json()
608 .await
609 .unwrap();
610 let student_id = me["id"].as_str().unwrap().to_string();
611
612 let now: Value = teacher
613 .get(format!("{base}/time"))
614 .send()
615 .await
616 .unwrap()
617 .json()
618 .await
619 .unwrap();
620 let now = now["now"].as_i64().unwrap();
621
622 let year: Value = manager
623 .post(format!("{base}/academic-years"))
624 .json(&json!({
625 "name": "2026-2027",
626 "starts_at": 1_750_000_000_000_i64,
627 "ends_at": 1_800_000_000_000_i64,
628 }))
629 .send()
630 .await
631 .unwrap()
632 .json()
633 .await
634 .unwrap();
635 let year = year["id"].as_str().unwrap().to_string();
636 let term: Value = manager
637 .post(format!("{base}/terms"))
638 .json(&json!({
639 "name": "1. Dönem",
640 "year": year,
641 "starts_at": 1_750_000_000_000_i64,
642 "ends_at": 1_800_000_000_000_i64,
643 }))
644 .send()
645 .await
646 .unwrap()
647 .json()
648 .await
649 .unwrap();
650 let term = term["id"].as_str().unwrap().to_string();
651
652 let course: Value = teacher
653 .post(format!("{base}/courses"))
654 .json(&json!({ "title": "algebra" }))
655 .send()
656 .await
657 .unwrap()
658 .json()
659 .await
660 .unwrap();
661 let course_id = course["id"].as_str().unwrap().to_string();
662 let subject: Value = teacher
663 .post(format!("{base}/courses/{course_id}/subjects"))
664 .json(&json!({ "name": "arithmetic" }))
665 .send()
666 .await
667 .unwrap()
668 .json()
669 .await
670 .unwrap();
671 let subject_id = subject["id"].as_str().unwrap().to_string();
672
673 // 9-A teaches it, with `hoca` as its homeroom teacher — which is what lets
674 // a plain teacher run the instance's roster and write its exams.
675 let class: Value = manager
676 .post(format!("{base}/classes"))
677 .json(&json!({ "name": "9-A", "grade_level": 9, "year": year, "teacher_id": teacher_id }))
678 .send()
679 .await
680 .unwrap()
681 .json()
682 .await
683 .unwrap();
684 let class_id = class["class"]["id"].as_str().unwrap().to_string();
685 let instance: Value = manager
686 .post(format!("{base}/classes/{class_id}/instances"))
687 .json(&json!({ "course_id": course_id }))
688 .send()
689 .await
690 .unwrap()
691 .json()
692 .await
693 .unwrap();
694 let instance_id = instance["id"].as_str().unwrap().to_string();
695
696 // The attach auto-minted the grade-level offering with an empty syllabus;
697 // the manager selects the fresh topic onto it, because a question may
698 // only name a subject the section teaches.
699 let offering: Value = manager
700 .get(format!("{base}/instances/{instance_id}"))
701 .send()
702 .await
703 .unwrap()
704 .json()
705 .await
706 .unwrap();
707 let offering_id = offering["offering"].as_str().unwrap().to_string();
708 let res = manager
709 .post(format!("{base}/offerings/{offering_id}/subjects"))
710 .json(&json!({ "subject": subject_id }))
711 .send()
712 .await
713 .unwrap();
714 assert_eq!(res.status(), StatusCode::CREATED);
715
716 let res = teacher
717 .post(format!("{base}/instances/{instance_id}/enrollments"))
718 .json(&json!({ "user_id": student_id }))
719 .send()
720 .await
721 .unwrap();
722 assert_eq!(res.status(), StatusCode::OK);
723 let exam: Value = teacher
724 .post(format!("{base}/instances/{instance_id}/exams"))
725 .json(&json!({
726 "title": "final", "kind": "yazili", "term": term,
727 "mode": "sync", "starts_at": now - 1_000, "ends_at": now + window_ms,
728 }))
729 .send()
730 .await
731 .unwrap()
732 .json()
733 .await
734 .unwrap();
735 let exam_id = exam["id"].as_str().unwrap().to_string();
736 let question: Value = teacher
737 .post(format!("{base}/exams/{exam_id}/questions"))
738 .json(
739 &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",
740 "points": 10, "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}], "correct": "b" }),
741 )
742 .send()
743 .await
744 .unwrap()
745 .json()
746 .await
747 .unwrap();
748 let question_id = question["id"].as_str().unwrap().to_string();
749 let choice_ids = choice_ids(&question);
750 let cookie = raw_session_cookie(&base, "veli").await;
751 ExamRoom {
752 base,
753 db,
754 teacher,
755 student,
756 student_id,
757 cookie,
758 subject_id,
759 instance_id,
760 term,
761 exam_id,
762 question_id,
763 choice_ids,
764 }
765}
766
767/// The minted ids of a question response's options, in list order.
768fn choice_ids(question: &Value) -> Vec<String> {
769 question["choices"]
770 .as_array()
771 .unwrap()
772 .iter()
773 .map(|choice| choice["id"].as_str().unwrap().to_string())
774 .collect()
775}
776
777/// The student exam room over a real TCP WebSocket: connect with the session
778/// cookie, get the state frame, autosave an answer, survive junk input,
779/// finish, and watch the server close the room — with the result visible to
780/// the teacher over REST.
781#[tokio::test]
782async fn exam_room_websocket_round_trip() {
783 let room = exam_room_fixture(600_000).await;
784 let ExamRoom {
785 base,
786 teacher,
787 student,
788 student_id,
789 cookie,
790 exam_id,
791 question_id,
792 ..
793 } = &room;
794 // A second question so progress counts have something to be partial over.
795 let res = teacher
796 .post(format!("{base}/exams/{exam_id}/questions"))
797 .json(&json!({ "subject_id": room.subject_id, "text": "Explain.",
798 "kind": "text", "points": 20 }))
799 .send()
800 .await
801 .unwrap();
802 assert_eq!(res.status(), StatusCode::CREATED);
803
804 // The room requires an attempt — the gate rejects at HTTP time (404),
805 // before any upgrade.
806 assert_eq!(
807 ws_open(base, exam_id, Some(cookie)).await.err(),
808 Some(404),
809 "start the attempt first"
810 );
811
812 let res = student
813 .post(format!("{base}/exams/{exam_id}/attempt"))
814 .send()
815 .await
816 .unwrap();
817 assert_eq!(res.status(), StatusCode::CREATED);
818
819 let mut ws = ws_open(base, exam_id, Some(cookie)).await.expect("upgrade");
820
821 // Connect-time state: in progress, nothing answered yet, server clock in.
822 let state = ws_next_frame(&mut ws).await.expect("connect state");
823 assert_eq!(state["type"], "state", "{state}");
824 assert_eq!(state["status"], "in_progress");
825 assert_eq!(state["answered"], 0);
826 assert_eq!(state["question_count"], 2);
827 assert!(state["remaining_ms"].as_i64().unwrap() > 0);
828 assert!(state["now"].as_i64().is_some());
829
830 // Ping/pong keeps the client's clock honest between ticks.
831 ws_send(&mut ws, json!({ "type": "ping" })).await;
832 ws_frame_of_type(&mut ws, "pong").await;
833
834 // Autosave: answer -> saved ack -> a state showing the progress.
835 ws_send(
836 &mut ws,
837 json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }),
838 )
839 .await;
840 let saved = ws_frame_of_type(&mut ws, "saved").await;
841 assert_eq!(saved["question_id"], question_id.as_str());
842 assert!(saved["updated_at"].as_i64().is_some());
843 // No `client_seq` was sent, so no `client_seq` comes back — not even a null. Clients
844 // that predate the field see exactly the frames they always saw.
845 assert!(saved.get("client_seq").is_none(), "{saved}");
846 let state = ws_frame_of_type(&mut ws, "state").await;
847 assert_eq!(state["answered"], 1, "{state}");
848
849 // With a `client_seq`, the ack carries it back verbatim: `question_id` alone
850 // cannot settle a send, since a re-save after a timeout leaves two of them
851 // outstanding for the same question. The server assigns it no meaning —
852 // a repeat of an already-used value is saved and echoed like any other.
853 for _ in 0..2 {
854 ws_send(
855 &mut ws,
856 json!({ "type": "answer", "question_id": question_id,
857 "selected": room.choice_ids[1], "client_seq": 7 }),
858 )
859 .await;
860 let saved = ws_frame_of_type(&mut ws, "saved").await;
861 assert_eq!(saved["client_seq"], 7, "{saved}");
862 assert_eq!(saved["question_id"], question_id.as_str());
863 ws_frame_of_type(&mut ws, "state").await;
864 }
865
866 // A failed save echoes it too — that is the whole point: the client can
867 // fail the exact send, even when the error names no question.
868 ws_send(
869 &mut ws,
870 json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x", "client_seq": 8 }),
871 )
872 .await;
873 let error = ws_frame_of_type(&mut ws, "error").await;
874 assert_eq!(error["client_seq"], 8, "{error}");
875 assert!(error.get("question_id").is_none(), "{error}");
876 // ... and `client_seq` rides alongside the blame when there is one.
877 ws_send(
878 &mut ws,
879 json!({ "type": "answer", "question_id": question_id, "text": "4", "client_seq": 9 }),
880 )
881 .await;
882 let error = ws_frame_of_type(&mut ws, "error").await;
883 assert_eq!(error["client_seq"], 9, "{error}");
884 assert_eq!(error["question_id"], question_id.as_str(), "{error}");
885
886 // `client_seq` is legal only because it is a declared field: everything else on
887 // an `answer` is still refused outright.
888 ws_send(
889 &mut ws,
890 json!({ "type": "answer", "question_id": question_id,
891 "selected": room.choice_ids[1], "sequence": 10 }),
892 )
893 .await;
894 let error = ws_frame_of_type(&mut ws, "error").await;
895 assert!(
896 error["message"].as_str().unwrap().contains("unrecognized"),
897 "{error}"
898 );
899 assert!(error.get("client_seq").is_none(), "{error}");
900
901 // A payload that doesn't fit the question is an error frame, not a close.
902 ws_send(
903 &mut ws,
904 json!({ "type": "answer", "question_id": question_id, "text": "4" }),
905 )
906 .await;
907 let error = ws_frame_of_type(&mut ws, "error").await;
908 assert!(
909 error["message"].as_str().unwrap().contains("selected"),
910 "{error}"
911 );
912 // ... and it names the question it belongs to, so a client with several
913 // saves in flight fails only this one.
914 assert_eq!(error["question_id"], question_id.as_str(), "{error}");
915
916 // A question that isn't in this exam is attributable too — that one save
917 // is doomed, the others aren't.
918 ws_send(
919 &mut ws,
920 json!({ "type": "answer", "question_id": "nosuchquestion", "text": "x" }),
921 )
922 .await;
923 let error = ws_frame_of_type(&mut ws, "error").await;
924 assert_eq!(error["question_id"], "nosuchquestion", "{error}");
925
926 // An over-long `question_id` dies at the door and is *not* reflected. The
927 // error frame echoes the field it blames, and axum accepts frames up to
928 // 64 MiB, so an uncapped echo is a self-inflicted amplifier — uncapped,
929 // this arrives back with all 70 000 characters attached.
930 ws_send(
931 &mut ws,
932 json!({ "type": "answer", "question_id": "x".repeat(70_000), "text": "x" }),
933 )
934 .await;
935 let error = ws_frame_of_type(&mut ws, "error").await;
936 let message = error["message"].as_str().unwrap();
937 assert!(message.contains("question_id"), "{error}");
938 assert!(message.len() < 200, "the id itself is never quoted back");
939 assert!(error.get("question_id").is_none(), "{error}");
940
941 // Junk and unknown message types too — the room shrugs and stays up.
942 // These are frame-level, not save-level: no question to blame, so the
943 // client keeps failing everything in flight.
944 ws.send(Message::Text("not json".into())).await.unwrap();
945 let error = ws_frame_of_type(&mut ws, "error").await;
946 assert!(
947 error["message"].as_str().unwrap().contains("unrecognized"),
948 "{error}"
949 );
950 assert!(error.get("question_id").is_none(), "{error}");
951 ws_send(&mut ws, json!({ "type": "selfdestruct" })).await;
952 let error = ws_frame_of_type(&mut ws, "error").await;
953 assert!(
954 error["message"].as_str().unwrap().contains("unrecognized"),
955 "{error}"
956 );
957 assert!(error.get("question_id").is_none(), "{error}");
958 ws_send(&mut ws, json!({ "type": "ping" })).await;
959 ws_frame_of_type(&mut ws, "pong").await;
960
961 // Finish: acknowledged, then the server closes the room.
962 ws_send(&mut ws, json!({ "type": "finish" })).await;
963 let finished = ws_frame_of_type(&mut ws, "finished").await;
964 assert!(finished["finished_at"].as_i64().is_some(), "{finished}");
965 loop {
966 match ws_next_frame(&mut ws).await {
967 None => break, // closed — as promised
968 Some(frame) => assert_eq!(frame["type"], "state", "{frame}"),
969 }
970 }
971
972 // The submission and the saved answer are visible over REST.
973 let attempt: Value = student
974 .get(format!("{base}/exams/{exam_id}/attempt"))
975 .send()
976 .await
977 .unwrap()
978 .json()
979 .await
980 .unwrap();
981 assert_eq!(attempt["status"], "submitted");
982 assert_eq!(attempt["answered"], 1);
983
984 let sheet: Value = teacher
985 .get(format!(
986 "{base}/exams/{exam_id}/attempts/{student_id}/answers"
987 ))
988 .send()
989 .await
990 .unwrap()
991 .json()
992 .await
993 .unwrap();
994 assert_eq!(sheet["answers"][0]["is_correct"], true);
995 assert_eq!(sheet["auto_score"]["earned"], 10);
996 assert_eq!(sheet["auto_score"]["possible"], 10);
997}
998
999/// Every pre-upgrade gate answers with a proper HTTP status, so a rejected
1000/// client sees *why* instead of an instant close.
1001#[tokio::test]
1002async fn exam_room_rejects_bad_handshakes() {
1003 let room = exam_room_fixture(600_000).await;
1004
1005 // No session cookie: 401 before anything else.
1006 assert_eq!(
1007 ws_open(&room.base, &room.exam_id, None).await.err(),
1008 Some(401)
1009 );
1010
1011 // Unknown exam: 404.
1012 assert_eq!(
1013 ws_open(&room.base, "does-not-exist", Some(&room.cookie))
1014 .await
1015 .err(),
1016 Some(404)
1017 );
1018
1019 // An unscheduled exam has no room to join: 409.
1020 let unscheduled = room.an_exam("homework", json!({})).await;
1021 let unscheduled_id = unscheduled["id"].as_str().unwrap();
1022 assert_eq!(
1023 ws_open(&room.base, unscheduled_id, Some(&room.cookie))
1024 .await
1025 .err(),
1026 Some(409)
1027 );
1028
1029 // Not enrolled: 403, even on a scheduled, open exam.
1030 let outsider = client();
1031 register(&outsider, &room.base, "omer").await;
1032 let outsider_cookie = raw_session_cookie(&room.base, "omer").await;
1033 assert_eq!(
1034 ws_open(&room.base, &room.exam_id, Some(&outsider_cookie))
1035 .await
1036 .err(),
1037 Some(403)
1038 );
1039
1040 // A submitted attempt has nothing left to write: 409.
1041 let res = room
1042 .student
1043 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1044 .send()
1045 .await
1046 .unwrap();
1047 assert_eq!(res.status(), StatusCode::CREATED);
1048 let res = room
1049 .student
1050 .post(format!(
1051 "{}/exams/{}/attempt/finish",
1052 room.base, room.exam_id
1053 ))
1054 .send()
1055 .await
1056 .unwrap();
1057 assert_eq!(res.status(), StatusCode::OK);
1058 assert_eq!(
1059 ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1060 .await
1061 .err(),
1062 Some(409)
1063 );
1064}
1065
1066/// A promotion out of `student` mid-exam closes the open room's answer sheet
1067/// on the very next save: the role wall is re-judged per save against the
1068/// live row — like the enrollment wall — so the door check is never the last
1069/// word for a socket that outlives the role. A demotion back reopens the
1070/// sheet on the same socket: it is a live check, not a latch.
1071#[tokio::test]
1072async fn exam_room_promotion_mid_exam_closes_the_sheet() {
1073 let room = exam_room_fixture(600_000).await;
1074 let ExamRoom {
1075 base,
1076 db,
1077 teacher,
1078 student,
1079 student_id,
1080 cookie,
1081 exam_id,
1082 question_id,
1083 ..
1084 } = &room;
1085 let res = student
1086 .post(format!("{base}/exams/{exam_id}/attempt"))
1087 .send()
1088 .await
1089 .unwrap();
1090 assert_eq!(res.status(), StatusCode::CREATED);
1091 let mut ws = ws_open(base, exam_id, Some(cookie)).await.expect("upgrade");
1092
1093 // While the sitter is a student the sheet is open — save one answer.
1094 ws_send(
1095 &mut ws,
1096 json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[1] }),
1097 )
1098 .await;
1099 ws_frame_of_type(&mut ws, "saved").await;
1100
1101 // Mid-exam, with the socket still open, the sitter stops being a student.
1102 promote(db, "veli", "teacher").await;
1103
1104 // The very next save is refused over the same socket...
1105 ws_send(
1106 &mut ws,
1107 json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }),
1108 )
1109 .await;
1110 let error = ws_frame_of_type(&mut ws, "error").await;
1111 assert!(
1112 error["message"].as_str().unwrap().contains("only students"),
1113 "{error}"
1114 );
1115 // Sitter-level, not question-level: the sheet is closed for every question,
1116 // so the frame blames none of them and the client fails everything.
1117 assert!(error.get("question_id").is_none(), "{error}");
1118
1119 // ... and over REST — the two paths share the wall.
1120 let res = student
1121 .post(format!("{base}/exams/{exam_id}/attempt/answers"))
1122 .json(&json!({ "question_id": question_id, "selected": room.choice_ids[0] }))
1123 .send()
1124 .await
1125 .unwrap();
1126 assert_eq!(res.status(), StatusCode::FORBIDDEN);
1127
1128 // The refused writes left no trace: the sheet still holds the original.
1129 let sheet: Value = teacher
1130 .get(format!(
1131 "{base}/exams/{exam_id}/attempts/{student_id}/answers"
1132 ))
1133 .send()
1134 .await
1135 .unwrap()
1136 .json()
1137 .await
1138 .unwrap();
1139 assert_eq!(sheet["answers"].as_array().unwrap().len(), 1);
1140 assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]);
1141
1142 // Demoted back, the same socket writes again — no reconnect required.
1143 promote(db, "veli", "student").await;
1144 ws_send(
1145 &mut ws,
1146 json!({ "type": "answer", "question_id": question_id, "selected": room.choice_ids[0] }),
1147 )
1148 .await;
1149 ws_frame_of_type(&mut ws, "saved").await;
1150}
1151
1152/// A teacher extending `ends_at` mid-exam moves the open room's countdown on
1153/// the next tick — the deadline is re-read, never cached in the socket.
1154#[tokio::test]
1155async fn exam_room_deadline_moves_with_a_live_extension() {
1156 let room = exam_room_fixture(600_000).await;
1157 let res = room
1158 .student
1159 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1160 .send()
1161 .await
1162 .unwrap();
1163 assert_eq!(res.status(), StatusCode::CREATED);
1164
1165 let mut ws = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1166 .await
1167 .expect("upgrade");
1168 let state = ws_next_frame(&mut ws).await.expect("connect state");
1169 let deadline = state["deadline"].as_i64().expect("deadline");
1170
1171 let extended = deadline + 300_000;
1172 let res = room
1173 .teacher
1174 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1175 .json(&json!({ "ends_at": extended }))
1176 .send()
1177 .await
1178 .unwrap();
1179 assert_eq!(res.status(), StatusCode::OK);
1180
1181 // Within a couple of ticks the room follows.
1182 let mut moved = false;
1183 for _ in 0..5 {
1184 let state = ws_frame_of_type(&mut ws, "state").await;
1185 if state["deadline"].as_i64() == Some(extended) {
1186 assert!(state["remaining_ms"].as_i64().unwrap() > 300_000);
1187 moved = true;
1188 break;
1189 }
1190 }
1191 assert!(moved, "the extension reaches the open room");
1192}
1193
1194/// When the deadline passes mid-session, a tick notices: the room announces
1195/// `expired`, closes, and everything saved in time survives for grading.
1196#[tokio::test]
1197async fn exam_room_expires_mid_session() {
1198 // A generous window while the room is set up. Keying the deadline off
1199 // *fixture* time (this used to ask for 2.6 s) made the whole fixture race
1200 // it — five HTTP calls plus a `raw_session_cookie` login, and argon2 is
1201 // deliberately expensive, so on a loaded run the setup alone outran the
1202 // window and the attempt POST below hit an already-closed exam (409).
1203 // Nothing here cares *when* the window closes, only that it closes with the
1204 // room open — so close it deliberately, further down, once it is.
1205 let room = exam_room_fixture(600_000).await;
1206 let res = room
1207 .student
1208 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1209 .send()
1210 .await
1211 .unwrap();
1212 assert_eq!(res.status(), StatusCode::CREATED);
1213
1214 let mut ws = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1215 .await
1216 .expect("upgrade");
1217 let state = ws_next_frame(&mut ws).await.expect("connect state");
1218 assert_eq!(state["status"], "in_progress", "{state}");
1219
1220 // One answer lands inside the window.
1221 ws_send(
1222 &mut ws,
1223 json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }),
1224 )
1225 .await;
1226 ws_frame_of_type(&mut ws, "saved").await;
1227
1228 // Now bring the deadline in, from a *fresh* server clock — the room re-reads
1229 // the schedule every tick, the same live-schedule path
1230 // `exam_room_deadline_moves_with_a_live_extension` covers, in the other
1231 // direction. Setup latency is behind us, so the only wait left is one tick.
1232 let now: Value = room
1233 .teacher
1234 .get(format!("{}/time", room.base))
1235 .send()
1236 .await
1237 .unwrap()
1238 .json()
1239 .await
1240 .unwrap();
1241 let res = room
1242 .teacher
1243 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1244 .json(&json!({ "ends_at": now["now"].as_i64().unwrap() + 1_000 }))
1245 .send()
1246 .await
1247 .unwrap();
1248 assert_eq!(res.status(), StatusCode::OK);
1249
1250 // A tick notices the deadline: `expired`, then the room closes.
1251 ws_frame_of_type(&mut ws, "expired").await;
1252 assert!(
1253 ws_next_frame(&mut ws).await.is_none(),
1254 "room closes after expiring"
1255 );
1256
1257 // The server agrees over REST: no more writes, the attempt is expired,
1258 // and the in-time answer is still there for the grader.
1259 let res = room
1260 .student
1261 .post(format!(
1262 "{}/exams/{}/attempt/answers",
1263 room.base, room.exam_id
1264 ))
1265 .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
1266 .send()
1267 .await
1268 .unwrap();
1269 assert_eq!(res.status(), StatusCode::CONFLICT);
1270 let attempt: Value = room
1271 .student
1272 .get(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1273 .send()
1274 .await
1275 .unwrap()
1276 .json()
1277 .await
1278 .unwrap();
1279 assert_eq!(attempt["status"], "expired");
1280 assert_eq!(attempt["answered"], 1);
1281 let sheet: Value = room
1282 .teacher
1283 .get(format!(
1284 "{}/exams/{}/attempts/{}/answers",
1285 room.base, room.exam_id, room.student_id
1286 ))
1287 .send()
1288 .await
1289 .unwrap()
1290 .json()
1291 .await
1292 .unwrap();
1293 assert_eq!(sheet["answers"][0]["selected"], room.choice_ids[1]);
1294 assert_eq!(sheet["auto_score"]["earned"], 10);
1295}
1296
1297/// The student's latest attempt as their own REST view sees it.
1298async fn my_attempt(room: &ExamRoom) -> Value {
1299 room.student
1300 .get(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1301 .send()
1302 .await
1303 .unwrap()
1304 .json()
1305 .await
1306 .unwrap()
1307}
1308
1309/// Wait (bounded) for the room teardown to stamp `left_at` — the socket close
1310/// and the server's stamp race, so poll the REST view briefly.
1311async fn wait_for_left_at(room: &ExamRoom) -> i64 {
1312 for _ in 0..50 {
1313 let attempt = my_attempt(room).await;
1314 if let Some(left_at) = attempt["left_at"].as_i64() {
1315 return left_at;
1316 }
1317 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1318 }
1319 panic!("left_at was never stamped after the socket closed");
1320}
1321
1322/// The rejoin door: with `allow_rejoin` off, walking out of the room stamps
1323/// `left_at` and locks re-entry and further saves (REST included) — finish
1324/// stays possible — until the teacher flips the door back open, which lets
1325/// the student reconnect (clearing `left_at`) and keep answering.
1326#[tokio::test]
1327async fn exam_room_rejoin_door_is_the_teachers_call() {
1328 let room = exam_room_fixture(600_000).await;
1329
1330 // Close the door before anyone sits.
1331 let res = room
1332 .teacher
1333 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1334 .json(&json!({ "allow_rejoin": false }))
1335 .send()
1336 .await
1337 .unwrap();
1338 assert_eq!(res.status(), StatusCode::OK);
1339
1340 let res = room
1341 .student
1342 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1343 .send()
1344 .await
1345 .unwrap();
1346 assert_eq!(res.status(), StatusCode::CREATED);
1347
1348 // First entry is fine — the door only matters after a walk-out.
1349 let mut ws = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1350 .await
1351 .expect("first entry");
1352 let state = ws_next_frame(&mut ws).await.expect("connect state");
1353 assert_eq!(state["status"], "in_progress", "{state}");
1354 assert_eq!(state["attempt"], 1, "{state}");
1355 ws.close(None).await.unwrap();
1356 let left_at = wait_for_left_at(&room).await;
1357 assert!(left_at > 0);
1358
1359 // Locked out: no REST saves, no re-entry.
1360 let res = room
1361 .student
1362 .post(format!(
1363 "{}/exams/{}/attempt/answers",
1364 room.base, room.exam_id
1365 ))
1366 .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] }))
1367 .send()
1368 .await
1369 .unwrap();
1370 assert_eq!(res.status(), StatusCode::CONFLICT);
1371 assert_eq!(
1372 ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1373 .await
1374 .expect_err("rejoin is closed"),
1375 409
1376 );
1377
1378 // The teacher reopens the door live; the student walks back in, which
1379 // clears the stamp, and answering works again.
1380 let res = room
1381 .teacher
1382 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1383 .json(&json!({ "allow_rejoin": true }))
1384 .send()
1385 .await
1386 .unwrap();
1387 assert_eq!(res.status(), StatusCode::OK);
1388 let mut ws = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1389 .await
1390 .expect("rejoin after the teacher reopened");
1391 ws_next_frame(&mut ws).await.expect("state after rejoin");
1392 let attempt = my_attempt(&room).await;
1393 assert!(
1394 attempt["left_at"].is_null(),
1395 "re-entry clears left_at: {attempt}"
1396 );
1397 ws_send(
1398 &mut ws,
1399 json!({ "type": "answer", "question_id": room.question_id, "selected": room.choice_ids[1] }),
1400 )
1401 .await;
1402 ws_frame_of_type(&mut ws, "saved").await;
1403
1404 // Walking out again with the door open: stamped, but REST saves still
1405 // land — rejoin is allowed, the stamp is just presence.
1406 ws.close(None).await.unwrap();
1407 wait_for_left_at(&room).await;
1408 let res = room
1409 .student
1410 .post(format!(
1411 "{}/exams/{}/attempt/answers",
1412 room.base, room.exam_id
1413 ))
1414 .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
1415 .send()
1416 .await
1417 .unwrap();
1418 assert_eq!(res.status(), StatusCode::OK);
1419
1420 // A locked-out student can still submit what they saved: close the door
1421 // once more and finish over REST.
1422 let res = room
1423 .teacher
1424 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1425 .json(&json!({ "allow_rejoin": false }))
1426 .send()
1427 .await
1428 .unwrap();
1429 assert_eq!(res.status(), StatusCode::OK);
1430 let res = room
1431 .student
1432 .post(format!(
1433 "{}/exams/{}/attempt/finish",
1434 room.base, room.exam_id
1435 ))
1436 .send()
1437 .await
1438 .unwrap();
1439 assert_eq!(res.status(), StatusCode::OK, "finish is exempt from rejoin");
1440}
1441
1442/// A walk-out stamp belongs to the sitting the room was opened for — never to
1443/// a retake started while the old socket lingered. Closing the stale room of a
1444/// finished sitting must not mark the *new* sitting as left (with the door
1445/// closed, that stamp would lock the student out of an exam room they never
1446/// entered).
1447#[tokio::test]
1448async fn exam_room_close_after_a_retake_leaves_the_new_sitting_alone() {
1449 let room = exam_room_fixture(600_000).await;
1450
1451 // An open exam with two sittings and the rejoin door closed.
1452 let exam = room
1453 .an_exam(
1454 "practice",
1455 json!({ "mode": "open", "max_attempts": 2, "allow_rejoin": false }),
1456 )
1457 .await;
1458 let exam_id = exam["id"].as_str().unwrap().to_string();
1459 let question: Value = room
1460 .teacher
1461 .post(format!("{}/exams/{exam_id}/questions", room.base))
1462 .json(
1463 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1464 "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1465 )
1466 .send()
1467 .await
1468 .unwrap()
1469 .json()
1470 .await
1471 .unwrap();
1472 let question_id = question["id"].as_str().unwrap().to_string();
1473 let opts = choice_ids(&question);
1474
1475 // Sit sitting #1 and open its room.
1476 let res = room
1477 .student
1478 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1479 .send()
1480 .await
1481 .unwrap();
1482 assert_eq!(res.status(), StatusCode::CREATED);
1483 let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
1484 .await
1485 .expect("room for sitting #1");
1486 let state = ws_next_frame(&mut ws).await.expect("connect state");
1487 assert_eq!(state["attempt"], 1, "{state}");
1488
1489 // Finish sitting #1 and start sitting #2 over REST — the old socket is
1490 // still open while the retake begins.
1491 let res = room
1492 .student
1493 .post(format!("{}/exams/{exam_id}/attempt/finish", room.base))
1494 .send()
1495 .await
1496 .unwrap();
1497 assert_eq!(res.status(), StatusCode::OK);
1498 let res = room
1499 .student
1500 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1501 .send()
1502 .await
1503 .unwrap();
1504 assert_eq!(res.status(), StatusCode::CREATED);
1505 let body: Value = res.json().await.unwrap();
1506 assert_eq!(body["attempt"], 2);
1507
1508 // Now walk out of the stale sitting-#1 room and give the teardown time.
1509 // race-window staging — do not convert to poll: sitting #1 is terminal, so
1510 // the teardown stamps nothing at all (`stamp_left` writes only an
1511 // in-progress sitting), and the assertion below is that *no* stamp lands on
1512 // sitting #2 — a negative with no positive to wait on.
1513 ws.close(None).await.unwrap();
1514 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1515
1516 // Sitting #2 was never entered, so it was never left: no stamp, and
1517 // answering it works despite the closed door.
1518 let attempt: Value = room
1519 .student
1520 .get(format!("{}/exams/{exam_id}/attempt", room.base))
1521 .send()
1522 .await
1523 .unwrap()
1524 .json()
1525 .await
1526 .unwrap();
1527 assert_eq!(attempt["attempt"], 2, "{attempt}");
1528 assert!(
1529 attempt["left_at"].is_null(),
1530 "closing the old sitting's room must not stamp the new sitting: {attempt}"
1531 );
1532 let res = room
1533 .student
1534 .post(format!("{}/exams/{exam_id}/attempt/answers", room.base))
1535 .json(&json!({ "question_id": question_id, "selected": opts[1] }))
1536 .send()
1537 .await
1538 .unwrap();
1539 assert_eq!(
1540 res.status(),
1541 StatusCode::OK,
1542 "sitting #2 is writable — the student never left it"
1543 );
1544}
1545
1546/// Messages through a stale room act on that room's own sitting — never on a
1547/// retake started while the old socket lingered. An `answer` or `finish` sent
1548/// through the old room after sitting #1 ended must be refused, not silently
1549/// applied to sitting #2 (which would scribble on — or instantly submit — a
1550/// fresh attempt the student opened elsewhere, burning a limited sitting).
1551#[tokio::test]
1552async fn exam_room_messages_bind_to_their_own_sitting() {
1553 let room = exam_room_fixture(600_000).await;
1554
1555 // An open exam with two sittings and one choice question.
1556 let exam = room
1557 .an_exam("practice", json!({ "mode": "open", "max_attempts": 2 }))
1558 .await;
1559 let exam_id = exam["id"].as_str().unwrap().to_string();
1560 let question: Value = room
1561 .teacher
1562 .post(format!("{}/exams/{exam_id}/questions", room.base))
1563 .json(
1564 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1565 "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1566 )
1567 .send()
1568 .await
1569 .unwrap()
1570 .json()
1571 .await
1572 .unwrap();
1573 let question_id = question["id"].as_str().unwrap().to_string();
1574 let opts = choice_ids(&question);
1575
1576 // Sit sitting #1 and open its room.
1577 let res = room
1578 .student
1579 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1580 .send()
1581 .await
1582 .unwrap();
1583 assert_eq!(res.status(), StatusCode::CREATED);
1584 let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
1585 .await
1586 .expect("room for sitting #1");
1587 let state = ws_next_frame(&mut ws).await.expect("connect state");
1588 assert_eq!(state["attempt"], 1, "{state}");
1589
1590 // Finish sitting #1 and start sitting #2 over REST — the old socket is
1591 // still open while the retake begins.
1592 let res = room
1593 .student
1594 .post(format!("{}/exams/{exam_id}/attempt/finish", room.base))
1595 .send()
1596 .await
1597 .unwrap();
1598 assert_eq!(res.status(), StatusCode::OK);
1599 let res = room
1600 .student
1601 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1602 .send()
1603 .await
1604 .unwrap();
1605 assert_eq!(res.status(), StatusCode::CREATED);
1606 let body: Value = res.json().await.unwrap();
1607 assert_eq!(body["attempt"], 2);
1608
1609 // An answer through the stale room must be refused — not saved into the
1610 // blank sheet of sitting #2.
1611 ws_send(
1612 &mut ws,
1613 json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }),
1614 )
1615 .await;
1616 let error = ws_frame_of_type(&mut ws, "error").await;
1617 assert!(
1618 error["message"].as_str().unwrap().contains("sitting"),
1619 "{error}"
1620 );
1621 // The room's sitting is over — that's not this question's fault, so no
1622 // blame is attached and the client fails every pending save.
1623 assert!(error.get("question_id").is_none(), "{error}");
1624
1625 // A finish through the stale room must be refused — not submit sitting #2.
1626 ws_send(&mut ws, json!({ "type": "finish" })).await;
1627 let error = ws_frame_of_type(&mut ws, "error").await;
1628 assert!(
1629 error["message"].as_str().unwrap().contains("sitting"),
1630 "{error}"
1631 );
1632
1633 // Sitting #2 is untouched: still running, sheet still blank.
1634 let attempt: Value = room
1635 .student
1636 .get(format!("{}/exams/{exam_id}/attempt", room.base))
1637 .send()
1638 .await
1639 .unwrap()
1640 .json()
1641 .await
1642 .unwrap();
1643 assert_eq!(attempt["attempt"], 2, "{attempt}");
1644 assert_eq!(
1645 attempt["status"], "in_progress",
1646 "a stale room must not submit the new sitting: {attempt}"
1647 );
1648 assert_eq!(
1649 attempt["answered"], 0,
1650 "a stale room must not write into the new sitting's sheet: {attempt}"
1651 );
1652}
1653
1654/// Two sockets on the same sitting (a second tab): closing one must not count
1655/// as leaving the exam room while the other is still connected — only the last
1656/// socket out stamps `left_at` and (with the door closed) locks answering.
1657#[tokio::test]
1658async fn exam_room_second_tab_keeps_the_student_present() {
1659 let room = exam_room_fixture(600_000).await;
1660
1661 // Close the door before anyone sits, so a false stamp locks immediately.
1662 let res = room
1663 .teacher
1664 .patch(format!("{}/exams/{}", room.base, room.exam_id))
1665 .json(&json!({ "allow_rejoin": false }))
1666 .send()
1667 .await
1668 .unwrap();
1669 assert_eq!(res.status(), StatusCode::OK);
1670 let res = room
1671 .student
1672 .post(format!("{}/exams/{}/attempt", room.base, room.exam_id))
1673 .send()
1674 .await
1675 .unwrap();
1676 assert_eq!(res.status(), StatusCode::CREATED);
1677
1678 // Two tabs in the same room.
1679 let mut ws1 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1680 .await
1681 .expect("first tab");
1682 ws_next_frame(&mut ws1).await.expect("state on tab one");
1683 let mut ws2 = ws_open(&room.base, &room.exam_id, Some(&room.cookie))
1684 .await
1685 .expect("second tab");
1686 ws_next_frame(&mut ws2).await.expect("state on tab two");
1687
1688 // Closing one tab is not leaving: the student is still in the room.
1689 ws1.close(None).await.unwrap();
1690 tokio::time::sleep(std::time::Duration::from_millis(500)).await;
1691 let attempt = my_attempt(&room).await;
1692 assert!(
1693 attempt["left_at"].is_null(),
1694 "one closed tab of two must not stamp a walk-out: {attempt}"
1695 );
1696 let res = room
1697 .student
1698 .post(format!(
1699 "{}/exams/{}/attempt/answers",
1700 room.base, room.exam_id
1701 ))
1702 .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[1] }))
1703 .send()
1704 .await
1705 .unwrap();
1706 assert_eq!(
1707 res.status(),
1708 StatusCode::OK,
1709 "still present via the second tab, so saves land"
1710 );
1711
1712 // The last tab closing is the real walk-out: stamped, and the closed door
1713 // now locks further saves.
1714 ws2.close(None).await.unwrap();
1715 wait_for_left_at(&room).await;
1716 let res = room
1717 .student
1718 .post(format!(
1719 "{}/exams/{}/attempt/answers",
1720 room.base, room.exam_id
1721 ))
1722 .json(&json!({ "question_id": room.question_id, "selected": room.choice_ids[0] }))
1723 .send()
1724 .await
1725 .unwrap();
1726 assert_eq!(res.status(), StatusCode::CONFLICT);
1727}
1728
1729/// An `open`-mode exam room: no deadline in the state frames, and a retake
1730/// (attempt #2) enters the room with a blank sheet after the first sitting is
1731/// submitted.
1732#[tokio::test]
1733async fn exam_room_open_mode_runs_untimed_and_retakes() {
1734 let room = exam_room_fixture(600_000).await;
1735
1736 // A second, open exam in the same course: two sittings, no window.
1737 let exam = room
1738 .an_exam("practice", json!({ "mode": "open", "max_attempts": 2 }))
1739 .await;
1740 let exam_id = exam["id"].as_str().unwrap().to_string();
1741 let question: Value = room
1742 .teacher
1743 .post(format!("{}/exams/{exam_id}/questions", room.base))
1744 .json(
1745 &json!({ "subject_id": room.subject_id, "text": "3 + 3?", "kind": "choice",
1746 "points": 5, "choices": [{"id": "a", "text": "5"}, {"id": "b", "text": "6"}], "correct": "b" }),
1747 )
1748 .send()
1749 .await
1750 .unwrap()
1751 .json()
1752 .await
1753 .unwrap();
1754 let question_id = question["id"].as_str().unwrap().to_string();
1755 let opts = choice_ids(&question);
1756
1757 let res = room
1758 .student
1759 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1760 .send()
1761 .await
1762 .unwrap();
1763 assert_eq!(res.status(), StatusCode::CREATED);
1764
1765 let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
1766 .await
1767 .expect("open-mode room");
1768 let state = ws_next_frame(&mut ws).await.expect("connect state");
1769 assert_eq!(state["status"], "in_progress", "{state}");
1770 assert_eq!(state["attempt"], 1, "{state}");
1771 assert!(state["deadline"].is_null(), "{state}");
1772 assert!(state["remaining_ms"].is_null(), "{state}");
1773
1774 ws_send(
1775 &mut ws,
1776 json!({ "type": "answer", "question_id": question_id, "selected": opts[1] }),
1777 )
1778 .await;
1779 ws_frame_of_type(&mut ws, "saved").await;
1780 ws_send(&mut ws, json!({ "type": "finish" })).await;
1781 ws_frame_of_type(&mut ws, "finished").await;
1782 assert!(ws_next_frame(&mut ws).await.is_none(), "room closes");
1783
1784 // Retake: sitting #2, blank sheet, fresh room.
1785 let res = room
1786 .student
1787 .post(format!("{}/exams/{exam_id}/attempt", room.base))
1788 .send()
1789 .await
1790 .unwrap();
1791 assert_eq!(res.status(), StatusCode::CREATED);
1792 let body: Value = res.json().await.unwrap();
1793 assert_eq!(body["attempt"], 2);
1794 assert_eq!(body["answered"], 0);
1795
1796 let mut ws = ws_open(&room.base, &exam_id, Some(&room.cookie))
1797 .await
1798 .expect("room for the retake");
1799 let state = ws_next_frame(&mut ws).await.expect("state");
1800 assert_eq!(state["attempt"], 2, "{state}");
1801 assert_eq!(state["answered"], 0, "{state}");
1802 ws.close(None).await.unwrap();
1803}
1804
1805// --- chatbot SSE ---------------------------------------------------------
1806//
1807// The full production topology in one process: a browser-shaped HTTP client
1808// over real TCP, the backend, a real QUIC bridge, and an AI service dialled in
1809// from outside. What is pinned is what an `EventSource` actually observes —
1810// `delta`s then a `done` — including for the client that connects *after* the
1811// answer already landed, which must not hang waiting for a stream of an event
1812// that has been and gone.
1813
1814use hezarfen_backend::ai::protocol::Response as AiResponse;
1815use hezarfen_backend::ai::protocol::{
1816 Greeting, Hello, Request as AiRequest, read_frame, write_frame,
1817};
1818use hezarfen_backend::ai::{AiBridge, BridgeConfig};
1819use hezarfen_backend::constant::{AI_ALPN, AI_CHAT_CAPABILITY, AI_PROTOCOL};
1820use std::time::Duration;
1821
1822const AI_TOKEN: &str = "e2e-ai-token";
1823
1824/// A bridge with a fake `chat.reply` service dialled into it, answering every
1825/// turn with `text`. Holding it keeps the registration alive.
1826struct ChatService {
1827 bridge: AiBridge,
1828 _endpoint: quinn::Endpoint,
1829 _conn: quinn::Connection,
1830 _control: (quinn::SendStream, quinn::RecvStream),
1831}
1832
1833async fn chat_service(text: &str) -> ChatService {
1834 let bridge = AiBridge::bind(BridgeConfig {
1835 addr: "127.0.0.1:0".parse().unwrap(),
1836 token: AI_TOKEN.to_string(),
1837 cert_path: None,
1838 key_path: None,
1839 request_timeout: Duration::from_secs(10),
1840 })
1841 .await
1842 .expect("bridge binds on an ephemeral port");
1843
1844 // Pin the bridge's own certificate, exactly as a production service does.
1845 hezarfen_backend::ai::tls::install_crypto_provider();
1846 let mut roots = rustls::RootCertStore::empty();
1847 roots.add(bridge.certificate()).expect("pin the leaf");
1848 let mut tls = rustls::ClientConfig::builder()
1849 .with_root_certificates(roots)
1850 .with_no_client_auth();
1851 tls.alpn_protocols = vec![AI_ALPN.to_vec()];
1852 let mut config = quinn::ClientConfig::new(std::sync::Arc::new(
1853 quinn::crypto::rustls::QuicClientConfig::try_from(tls).expect("QUIC-usable TLS"),
1854 ));
1855 let mut transport = quinn::TransportConfig::default();
1856 // Requests arrive as server-initiated streams.
1857 transport.max_concurrent_bidi_streams(64u32.into());
1858 config.transport_config(std::sync::Arc::new(transport));
1859 let mut endpoint =
1860 quinn::Endpoint::client("127.0.0.1:0".parse().unwrap()).expect("client bind");
1861 endpoint.set_default_client_config(config);
1862
1863 let conn = endpoint
1864 .connect(bridge.local_addr().unwrap(), "localhost")
1865 .expect("dial")
1866 .await
1867 .expect("QUIC handshake");
1868 let (mut send, mut recv) = conn.open_bi().await.expect("control stream");
1869 write_frame(
1870 &mut send,
1871 &Hello {
1872 protocol: AI_PROTOCOL.to_string(),
1873 service: "e2e-tutor".to_string(),
1874 capabilities: vec![AI_CHAT_CAPABILITY.to_string()],
1875 token: AI_TOKEN.to_string(),
1876 max_concurrent: None,
1877 },
1878 )
1879 .await
1880 .expect("send Hello");
1881 let greeting: Greeting = read_frame(&mut recv).await.expect("read Greeting");
1882 assert!(matches!(greeting, Greeting::Welcome { .. }), "{greeting:?}");
1883
1884 let answer = text.to_string();
1885 let serving = conn.clone();
1886 tokio::spawn(async move {
1887 while let Ok((mut send, mut recv)) = serving.accept_bi().await {
1888 let answer = answer.clone();
1889 tokio::spawn(async move {
1890 let Ok(request) = read_frame::<_, AiRequest>(&mut recv).await else {
1891 return;
1892 };
1893 let response = AiResponse::Ok {
1894 id: request.id.clone(),
1895 school: request.school.clone(),
1896 payload: json!({ "text": answer }),
1897 };
1898 let _ = write_frame(&mut send, &response).await;
1899 let _ = send.finish();
1900 let _ = send.stopped().await;
1901 });
1902 }
1903 });
1904
1905 // Registration completes after the welcome is on the wire.
1906 for _ in 0..300 {
1907 if bridge.has_capability(AI_CHAT_CAPABILITY) {
1908 break;
1909 }
1910 tokio::time::sleep(Duration::from_millis(10)).await;
1911 }
1912 assert!(
1913 bridge.has_capability(AI_CHAT_CAPABILITY),
1914 "the fake service never registered"
1915 );
1916
1917 ChatService {
1918 bridge,
1919 _endpoint: endpoint,
1920 _conn: conn,
1921 _control: (send, recv),
1922 }
1923}
1924
1925/// Open a thread and ask one question. Returns (thread id, reserved answer id).
1926async fn ask(client: &Client, base: &str) -> (String, String) {
1927 let thread: Value = client
1928 .post(format!("{base}/chatbot/threads"))
1929 .json(&json!({ "title": "Fizik" }))
1930 .send()
1931 .await
1932 .unwrap()
1933 .json()
1934 .await
1935 .unwrap();
1936 let thread = thread["id"].as_str().expect("thread id").to_string();
1937
1938 let res = client
1939 .post(format!("{base}/chatbot/threads/{thread}/messages"))
1940 .json(&json!({ "content": "ikinci yasa nedir?" }))
1941 .send()
1942 .await
1943 .unwrap();
1944 assert_eq!(res.status(), StatusCode::ACCEPTED);
1945 let receipt: Value = res.json().await.unwrap();
1946 assert_eq!(receipt["status"], "pending");
1947 let mid = receipt["message_id"]
1948 .as_str()
1949 .expect("message id")
1950 .to_string();
1951 (thread, mid)
1952}
1953
1954/// Read the SSE stream until its terminal event (`done` or `error`), returning
1955/// every `(event, data)` pair in arrival order. Bounded: a stream that never
1956/// terminates fails the test instead of hanging the suite.
1957async fn read_sse_to_end(res: &mut reqwest::Response, within: Duration) -> Vec<(String, Value)> {
1958 let deadline = tokio::time::Instant::now() + within;
1959 let mut buf = String::new();
1960 let mut events = Vec::new();
1961 loop {
1962 while let Some(end) = buf.find("\n\n") {
1963 let frame: String = buf.drain(..end + 2).collect();
1964 let Some(name) = frame
1965 .lines()
1966 .find_map(|line| line.strip_prefix("event:"))
1967 .map(|name| name.trim().to_string())
1968 else {
1969 continue; // a keep-alive comment
1970 };
1971 let data = frame
1972 .lines()
1973 .find_map(|line| line.strip_prefix("data:"))
1974 .expect("every chat event carries a data line")
1975 .trim();
1976 let terminal = name == "done" || name == "error";
1977 events.push((
1978 name,
1979 serde_json::from_str(data).expect("event data is json"),
1980 ));
1981 if terminal {
1982 return events;
1983 }
1984 }
1985 let chunk = tokio::time::timeout_at(deadline, res.chunk())
1986 .await
1987 .expect("the stream terminates before the deadline")
1988 .expect("stream stays open")
1989 .expect("stream yields data");
1990 buf.push_str(&String::from_utf8_lossy(&chunk));
1991 }
1992}
1993
1994/// The answer the fake service gives: long enough that the relay cuts it into
1995/// several `delta`s rather than emitting it whole.
1996fn long_answer() -> String {
1997 "kuvvet kutle carpi ivmedir. ".repeat(8)
1998}
1999
2000/// Assert one full chat stream: `delta`s that rejoin into `answer`, then a
2001/// `done` carrying the finished message.
2002fn assert_deltas_then_done(events: &[(String, Value)], mid: &str, answer: &str) {
2003 let (last, deltas) = events.split_last().expect("at least a terminal event");
2004 assert!(!deltas.is_empty(), "no delta arrived: {events:?}");
2005 assert!(deltas.iter().all(|(name, _)| name == "delta"), "{events:?}");
2006 let text: String = deltas
2007 .iter()
2008 .map(|(_, data)| data["text"].as_str().expect("delta carries text"))
2009 .collect();
2010 assert_eq!(text, answer, "the deltas must rejoin into the answer");
2011
2012 assert_eq!(last.0, "done", "{events:?}");
2013 let message = &last.1["message"];
2014 assert_eq!(message["id"], mid);
2015 assert_eq!(message["role"], "assistant");
2016 assert_eq!(message["status"], "complete");
2017 assert_eq!(message["content"], answer);
2018 assert_eq!(message["truncated"], false, "{message}");
2019 assert!(message["error_code"].is_null(), "{message}");
2020}
2021
2022/// The SSE `done` payload and the polling read are contractually required to
2023/// agree in every state — including about a clipped answer. A frontend that
2024/// streams must be able to tell the user the text was cut, and one that polls
2025/// must reach the same conclusion about the very same turn.
2026#[tokio::test]
2027async fn chat_stream_and_poll_agree_that_an_answer_was_truncated() {
2028 let cap = hezarfen_backend::constant::DEFAULT_MAX_CHATBOT_MESSAGE_LEN as usize;
2029 let service = chat_service(&"é".repeat(cap + 500)).await;
2030 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2031 let ali = client();
2032 register(&ali, &base, "ali").await;
2033 login(&ali, &base, "ali").await;
2034
2035 let (thread, mid) = ask(&ali, &base).await;
2036
2037 let mut res = ali
2038 .get(format!(
2039 "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2040 ))
2041 .send()
2042 .await
2043 .unwrap();
2044 assert_eq!(res.status(), StatusCode::OK);
2045 let events = read_sse_to_end(&mut res, Duration::from_secs(10)).await;
2046 let (name, data) = events.last().expect("a terminal event");
2047 assert_eq!(name, "done", "{events:?}");
2048 let streamed = &data["message"];
2049 assert_eq!(streamed["status"], "complete", "{streamed}");
2050 assert_eq!(streamed["truncated"], true, "{streamed}");
2051 assert_eq!(
2052 streamed["content"]
2053 .as_str()
2054 .expect("content")
2055 .chars()
2056 .count(),
2057 cap
2058 );
2059
2060 // The same row, read the other way: identical verdict, field for field.
2061 let polled: Value = ali
2062 .get(format!("{base}/chatbot/threads/{thread}/messages/{mid}"))
2063 .send()
2064 .await
2065 .unwrap()
2066 .json()
2067 .await
2068 .unwrap();
2069 assert_eq!(&polled, streamed, "the two reads must not disagree");
2070}
2071
2072#[tokio::test]
2073async fn capabilities_reports_a_registered_chat_service() {
2074 // A discovery read: once the fake `chat.reply` service has dialled in,
2075 // `GET /ai/capabilities` lists that capability with its worker fleet.
2076 let service = chat_service("F = ma").await;
2077 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2078 let ali = client();
2079 register(&ali, &base, "ali").await;
2080 login(&ali, &base, "ali").await;
2081
2082 let caps: Value = ali
2083 .get(format!("{base}/ai/capabilities"))
2084 .send()
2085 .await
2086 .unwrap()
2087 .json()
2088 .await
2089 .unwrap();
2090 assert_eq!(caps["enabled"], json!(true));
2091 assert_eq!(caps["protocol"], json!("hab/2"));
2092 let row = caps["capabilities"]
2093 .as_array()
2094 .expect("a capabilities array")
2095 .iter()
2096 .find(|c| c["capability"] == json!("chat.reply"))
2097 .expect("the fake service serves chat.reply");
2098 assert_eq!(row["workers"], json!(1));
2099 assert!(row["inflight"].is_u64(), "{row}");
2100}
2101
2102#[tokio::test]
2103async fn chat_stream_delivers_deltas_then_done_over_http() {
2104 let answer = long_answer();
2105 let service = chat_service(&answer).await;
2106 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2107 let ali = client();
2108 register(&ali, &base, "ali").await;
2109 login(&ali, &base, "ali").await;
2110
2111 let (thread, mid) = ask(&ali, &base).await;
2112
2113 // The client opens the stream while the turn is still in flight; it stays
2114 // open until the answer lands, then closes after `done`.
2115 let mut res = ali
2116 .get(format!(
2117 "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2118 ))
2119 .send()
2120 .await
2121 .unwrap();
2122 assert_eq!(res.status(), StatusCode::OK);
2123 let content_type = res
2124 .headers()
2125 .get("content-type")
2126 .expect("content-type")
2127 .to_str()
2128 .unwrap()
2129 .to_string();
2130 assert!(
2131 content_type.starts_with("text/event-stream"),
2132 "{content_type}"
2133 );
2134
2135 let events = read_sse_to_end(&mut res, Duration::from_secs(10)).await;
2136 assert_deltas_then_done(&events, &mid, &answer);
2137
2138 // The stream is closed after `done` — one stream per turn, not per thread.
2139 assert!(
2140 res.chunk().await.unwrap().is_none(),
2141 "the stream must close after done"
2142 );
2143}
2144
2145#[tokio::test]
2146async fn chat_stream_replays_an_answer_that_already_landed() {
2147 // A client that reconnects late (reload, dropped connection, a second tab)
2148 // gets the same delta*+done as one that was watching all along. Nothing is
2149 // "missed": the stream reads the row, not a live feed.
2150 let answer = long_answer();
2151 let service = chat_service(&answer).await;
2152 let (base, _db) = spawn_server_with_ai(Some(service.bridge.clone())).await;
2153 let ali = client();
2154 register(&ali, &base, "ali").await;
2155 login(&ali, &base, "ali").await;
2156
2157 let (thread, mid) = ask(&ali, &base).await;
2158
2159 // Wait — by polling, never by sleeping — until the turn has settled, so the
2160 // stream below opens strictly after the answer landed.
2161 let mut settled = Value::Null;
2162 for _ in 0..500 {
2163 let turn: Value = ali
2164 .get(format!("{base}/chatbot/threads/{thread}/messages/{mid}"))
2165 .send()
2166 .await
2167 .unwrap()
2168 .json()
2169 .await
2170 .unwrap();
2171 if turn["status"] != "pending" {
2172 settled = turn;
2173 break;
2174 }
2175 tokio::time::sleep(Duration::from_millis(10)).await;
2176 }
2177 assert_eq!(settled["status"], "complete", "{settled}");
2178 assert_eq!(settled["content"], answer);
2179
2180 let mut res = ali
2181 .get(format!(
2182 "{base}/chatbot/threads/{thread}/messages/{mid}/stream"
2183 ))
2184 .send()
2185 .await
2186 .unwrap();
2187 assert_eq!(res.status(), StatusCode::OK);
2188 let events = read_sse_to_end(&mut res, Duration::from_secs(10)).await;
2189 assert_deltas_then_done(&events, &mid, &answer);
2190}
2191
2192// ---- the board room (WebSocket) ---------------------------------------------
2193//
2194// The room is a fan-out protocol over stateful, append-only storage, so every
2195// test below asserts against the DATABASE as well as the wire: the in-memory
2196// engine forges concurrent-write wins (src/domain/cap.rs:44-49), and a frame
2197// proves only that the server said something.
2198
2199/// A booted server with creator `ali`, invited `veli`, outsider `ayse` and one
2200/// open board — the spine of every board-room test.
2201struct BoardRoom {
2202 base: String,
2203 db: Database,
2204 creator: Client,
2205 creator_cookie: String,
2206 veli_cookie: String,
2207 ayse_cookie: String,
2208 veli_id: String,
2209 board_id: String,
2210}
2211
2212async fn board_room_fixture() -> BoardRoom {
2213 let (base, db) = spawn_server().await;
2214 let creator = client();
2215 register(&creator, &base, "ali").await;
2216 login(&creator, &base, "ali").await;
2217 let veli = client();
2218 register(&veli, &base, "veli").await;
2219 login(&veli, &base, "veli").await;
2220 let ayse = client();
2221 register(&ayse, &base, "ayse").await;
2222 login(&ayse, &base, "ayse").await;
2223
2224 let me: Value = veli
2225 .get(format!("{base}/auth/me"))
2226 .send()
2227 .await
2228 .unwrap()
2229 .json()
2230 .await
2231 .unwrap();
2232 let veli_id = me["id"].as_str().unwrap().to_string();
2233
2234 let res = creator
2235 .post(format!("{base}/boards"))
2236 .json(&json!({ "title": "Geometri", "participants": [veli_id] }))
2237 .send()
2238 .await
2239 .unwrap();
2240 assert_eq!(res.status(), StatusCode::CREATED);
2241 let board: Value = res.json().await.unwrap();
2242 let board_id = board["id"].as_str().unwrap().to_string();
2243
2244 BoardRoom {
2245 creator_cookie: raw_session_cookie(&base, "ali").await,
2246 veli_cookie: raw_session_cookie(&base, "veli").await,
2247 ayse_cookie: raw_session_cookie(&base, "ayse").await,
2248 base,
2249 db,
2250 creator,
2251 veli_id,
2252 board_id,
2253 }
2254}
2255
2256/// Open the board room. `Ok` is the upgraded socket; `Err` is the HTTP status
2257/// a pre-upgrade gate refused with — the room must reject before the upgrade,
2258/// so a refusal is a status and not an instant close.
2259async fn board_open(base: &str, board_id: &str, cookie: Option<&str>) -> Result<WsStream, u16> {
2260 let url = format!("{}/boards/{board_id}/ws", base.replace("http://", "ws://"));
2261 let mut request = url.into_client_request().unwrap();
2262 if let Some(cookie) = cookie {
2263 request
2264 .headers_mut()
2265 .insert("cookie", cookie.parse().unwrap());
2266 }
2267 match connect_async(request).await {
2268 Ok((ws, _)) => Ok(ws),
2269 Err(tokio_tungstenite::tungstenite::Error::Http(response)) => {
2270 Err(response.status().as_u16())
2271 }
2272 Err(other) => panic!("unexpected handshake failure: {other}"),
2273 }
2274}
2275
2276/// Join and drain the replay, returning the strokes of the current epoch in
2277/// the order they arrived across however many `strokes` chunks it took.
2278async fn board_join(ws: &mut WsStream, after: Option<&str>, epoch: Option<i64>) -> Vec<Value> {
2279 let mut frame = json!({ "type": "join" });
2280 if let Some(after) = after {
2281 frame["after"] = json!(after);
2282 }
2283 if let Some(epoch) = epoch {
2284 frame["epoch"] = json!(epoch);
2285 }
2286 ws_send(ws, frame).await;
2287 drain_replay(ws).await
2288}
2289
2290/// Every stroke of a replay, from wherever the stream is now until `synced`.
2291async fn drain_replay(ws: &mut WsStream) -> Vec<Value> {
2292 let mut strokes = Vec::new();
2293 loop {
2294 let frame = ws_next_frame(ws).await.expect("room closed mid-replay");
2295 match frame["type"].as_str().unwrap() {
2296 "strokes" => strokes.extend(frame["strokes"].as_array().unwrap().clone()),
2297 "synced" => return strokes,
2298 // `state` ticks and other people's frames may interleave a replay.
2299 _ => continue,
2300 }
2301 }
2302}
2303
2304/// The next frame of `kind`, skipping anything else. Unlike the exam room's
2305/// helper this tolerates every other frame type: a board room is multi-writer,
2306/// so someone else's stroke can always land mid-wait.
2307async fn board_frame_of_type(ws: &mut WsStream, kind: &str) -> Value {
2308 loop {
2309 let frame = ws_next_frame(ws)
2310 .await
2311 .unwrap_or_else(|| panic!("room closed while waiting for a {kind:?} frame"));
2312 if frame["type"] == kind {
2313 return frame;
2314 }
2315 }
2316}
2317
2318/// The stored stroke ids of one epoch, in mint order, read straight out of the
2319/// database — the only proof that survives a lying frame.
2320async fn stored_stroke_ids(db: &Database, board: &str, epoch: i64) -> Vec<String> {
2321 sqlx::query_scalar::<_, Uuid>(
2322 "SELECT id FROM board_stroke \
2323 WHERE board = $1 AND epoch = $2 AND kind = 'stroke' ORDER BY id",
2324 )
2325 .bind(Uuid::parse_str(board).unwrap())
2326 .bind(epoch)
2327 .fetch_all(db)
2328 .await
2329 .unwrap()
2330 .into_iter()
2331 .map(|id| id.to_string())
2332 .collect()
2333}
2334
2335/// The stored payloads of one epoch, in mint order.
2336async fn stored_payloads(db: &Database, board: &str, epoch: i64) -> Vec<String> {
2337 sqlx::query_scalar::<_, String>(
2338 "SELECT payload FROM board_stroke \
2339 WHERE board = $1 AND epoch = $2 AND kind = 'stroke' ORDER BY id",
2340 )
2341 .bind(Uuid::parse_str(board).unwrap())
2342 .bind(epoch)
2343 .fetch_all(db)
2344 .await
2345 .unwrap()
2346}
2347
2348/// Draw one mark and wait for its ack, ignoring the fan-out of everyone else's
2349/// strokes that may arrive first.
2350async fn board_draw(ws: &mut WsStream, payload: &str) -> Value {
2351 ws_send(ws, json!({ "type": "stroke", "payload": payload })).await;
2352 board_frame_of_type(ws, "saved").await
2353}
2354
2355/// Test 1 — the core of the feature: what one participant draws reaches the
2356/// other, and is in the database afterwards. Kills the class where the room is
2357/// a chat relay: frames fly, nothing persists, and a reload loses the canvas.
2358#[tokio::test]
2359async fn a_stroke_reaches_the_other_socket_and_the_database() {
2360 let room = board_room_fixture().await;
2361 let (base, board) = (&room.base, &room.board_id);
2362 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2363 .await
2364 .expect("creator upgrade");
2365 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2366 .await
2367 .expect("participant upgrade");
2368 // Connect-time state names the room, its epoch and its roster.
2369 let state = board_frame_of_type(&mut veli, "state").await;
2370 assert_eq!(state["board"], *board);
2371 assert_eq!(state["epoch"], 0);
2372 assert_eq!(state["locked"], false);
2373 assert_eq!(state["participants"][0], room.veli_id);
2374
2375 assert_eq!(board_join(&mut veli, None, None).await.len(), 0);
2376
2377 // ali draws; veli sees it.
2378 ws_send(
2379 &mut ali,
2380 json!({ "type": "stroke", "payload": "{\"p\":[1,2]}", "client_seq": 41 }),
2381 )
2382 .await;
2383 let saved = board_frame_of_type(&mut ali, "saved").await;
2384 assert_eq!(saved["client_seq"], 41);
2385 let fanned = board_frame_of_type(&mut veli, "stroke").await;
2386 assert_eq!(fanned["payload"], "{\"p\":[1,2]}");
2387 assert_eq!(fanned["id"], saved["id"]);
2388 assert!(fanned["author"].as_str().is_some());
2389
2390 // And the other way round, so fan-out is not one-directional by accident.
2391 // ali's next `stroke` frame is veli's mark and not the echo of its own:
2392 // an author gets `saved`, never its own stroke back, or every client would
2393 // have to filter the marks it just drew itself.
2394 board_draw(&mut veli, "{\"p\":[3,4]}").await;
2395 let fanned = board_frame_of_type(&mut ali, "stroke").await;
2396 assert_eq!(fanned["payload"], "{\"p\":[3,4]}");
2397
2398 // THE assertion: stored state, re-read from the database.
2399 assert_eq!(
2400 stored_payloads(&room.db, board, 0).await,
2401 vec!["{\"p\":[1,2]}".to_string(), "{\"p\":[3,4]}".to_string()],
2402 "the database is the source of truth, not the channel"
2403 );
2404
2405 // A third socket joining now replays exactly those two, in mint order.
2406 let mut late = board_open(base, board, Some(&room.veli_cookie))
2407 .await
2408 .expect("second participant socket");
2409 let replayed = board_join(&mut late, None, None).await;
2410 assert_eq!(replayed.len(), 2);
2411 assert_eq!(replayed[0]["payload"], "{\"p\":[1,2]}");
2412 assert_eq!(replayed[1]["payload"], "{\"p\":[3,4]}");
2413}
2414
2415/// Test 2 — the permission edge that must NOT kill the socket: a participant
2416/// who is not the creator may not clear, and stays in the room drawing. Kills
2417/// the "refuse by closing" reflex, which would boot a whole class off the
2418/// board on one stray click.
2419#[tokio::test]
2420async fn a_participants_clear_is_refused_and_the_socket_keeps_drawing() {
2421 let room = board_room_fixture().await;
2422 let (base, board) = (&room.base, &room.board_id);
2423 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2424 .await
2425 .expect("upgrade");
2426 board_join(&mut veli, None, None).await;
2427 board_draw(&mut veli, "before").await;
2428
2429 ws_send(&mut veli, json!({ "type": "clear" })).await;
2430 let error = board_frame_of_type(&mut veli, "error").await;
2431 assert_eq!(error["code"], "forbidden");
2432
2433 // Alive, and still a full participant.
2434 ws_send(&mut veli, json!({ "type": "ping" })).await;
2435 board_frame_of_type(&mut veli, "pong").await;
2436 board_draw(&mut veli, "after").await;
2437 assert_eq!(
2438 stored_payloads(&room.db, board, 0).await,
2439 vec!["before".to_string(), "after".to_string()]
2440 );
2441 // The refusal wrote nothing: no clear marker, and the epoch never moved.
2442 let epochs = sqlx::query_scalar::<_, i64>("SELECT epoch FROM board WHERE id = $1")
2443 .bind(Uuid::parse_str(board).unwrap())
2444 .fetch_all(&room.db)
2445 .await
2446 .unwrap();
2447 assert_eq!(epochs, vec![0]);
2448 let clears = sqlx::query_scalar::<_, Uuid>("SELECT id FROM board_stroke WHERE kind = 'clear'")
2449 .fetch_all(&room.db)
2450 .await
2451 .unwrap();
2452 assert!(clears.is_empty());
2453
2454 // A lock is creator-only on the same terms, and equally non-fatal.
2455 ws_send(&mut veli, json!({ "type": "lock", "locked": true })).await;
2456 assert_eq!(
2457 board_frame_of_type(&mut veli, "error").await["code"],
2458 "forbidden"
2459 );
2460 board_draw(&mut veli, "still here").await;
2461}
2462
2463/// Test 3 — the user's core requirement, unambiguous: a clear empties the LIVE
2464/// canvas and deletes nothing. A joiner sees only what came after; `/history`
2465/// still holds every mark drawn before. Kills the truncate-on-clear
2466/// implementation, which passes every happy-path test and destroys a lesson.
2467#[tokio::test]
2468async fn a_clear_empties_the_live_canvas_and_history_keeps_everything() {
2469 let room = board_room_fixture().await;
2470 let (base, board) = (&room.base, &room.board_id);
2471 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2472 .await
2473 .expect("upgrade");
2474 board_join(&mut ali, None, None).await;
2475 board_draw(&mut ali, "old-1").await;
2476 board_draw(&mut ali, "old-2").await;
2477
2478 ws_send(&mut ali, json!({ "type": "clear" })).await;
2479 let cleared = board_frame_of_type(&mut ali, "cleared").await;
2480 assert_eq!(cleared["epoch"], 1, "the clear opens the NEXT epoch");
2481
2482 board_draw(&mut ali, "new-1").await;
2483
2484 // A joiner gets the post-clear canvas and nothing else.
2485 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2486 .await
2487 .expect("upgrade");
2488 let replayed = board_join(&mut veli, None, None).await;
2489 assert_eq!(replayed.len(), 1, "join replays the current epoch only");
2490 assert_eq!(replayed[0]["payload"], "new-1");
2491
2492 // Nothing was destroyed: both pre-clear strokes are still stored...
2493 assert_eq!(
2494 stored_payloads(&room.db, board, 0).await,
2495 vec!["old-1".to_string(), "old-2".to_string()]
2496 );
2497 // ...and still served, with the marker that closed their epoch.
2498 let history: Value = room
2499 .creator
2500 .get(format!("{base}/boards/{board}/history"))
2501 .send()
2502 .await
2503 .unwrap()
2504 .json()
2505 .await
2506 .unwrap();
2507 let kinds: Vec<&str> = history["items"]
2508 .as_array()
2509 .unwrap()
2510 .iter()
2511 .map(|row| row["kind"].as_str().unwrap())
2512 .collect();
2513 assert_eq!(kinds, vec!["stroke", "stroke", "clear", "stroke"]);
2514 assert_eq!(history["items"][0]["payload"], "old-1");
2515 assert_eq!(history["items"][2]["count"], 2, "the epoch's final count");
2516 assert_eq!(history["total"], 4);
2517}
2518
2519/// Test 4 — reconnect with a cursor from an epoch that no longer exists. The
2520/// client must be told the canvas was wiped and be given the WHOLE current
2521/// epoch, never a diff from a cursor that means nothing now. Kills the
2522/// "resume from `after` regardless" bug, which paints a blank board forever.
2523#[tokio::test]
2524async fn a_stale_cursor_gets_a_cleared_frame_and_a_full_replay() {
2525 let room = board_room_fixture().await;
2526 let (base, board) = (&room.base, &room.board_id);
2527 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2528 .await
2529 .expect("upgrade");
2530 board_join(&mut ali, None, None).await;
2531 board_draw(&mut ali, "old-1").await;
2532 let stale_cursor = board_draw(&mut ali, "old-2").await["id"]
2533 .as_str()
2534 .unwrap()
2535 .to_string();
2536
2537 ws_send(&mut ali, json!({ "type": "clear" })).await;
2538 board_frame_of_type(&mut ali, "cleared").await;
2539 board_draw(&mut ali, "new-1").await;
2540 board_draw(&mut ali, "new-2").await;
2541
2542 // The reconnect: an epoch-0 cursor against an epoch-1 board.
2543 let mut back = board_open(base, board, Some(&room.creator_cookie))
2544 .await
2545 .expect("reconnect");
2546 ws_send(
2547 &mut back,
2548 json!({ "type": "join", "after": stale_cursor, "epoch": 0 }),
2549 )
2550 .await;
2551 let cleared = board_frame_of_type(&mut back, "cleared").await;
2552 assert_eq!(cleared["epoch"], 1, "wipe the stale canvas first");
2553 let replayed = drain_replay(&mut back).await;
2554 assert_eq!(
2555 replayed
2556 .iter()
2557 .map(|s| s["payload"].as_str().unwrap())
2558 .collect::<Vec<_>>(),
2559 vec!["new-1", "new-2"],
2560 "a full current-epoch replay, not a diff from a dead cursor"
2561 );
2562
2563 // A cursor from the CURRENT epoch is still honoured as a cursor.
2564 let mut resume = board_open(base, board, Some(&room.creator_cookie))
2565 .await
2566 .expect("reconnect");
2567 let first_new = stored_stroke_ids(&room.db, board, 1).await[0].clone();
2568 let replayed = board_join(&mut resume, Some(&first_new), Some(1)).await;
2569 assert_eq!(replayed.len(), 1);
2570 assert_eq!(replayed[0]["payload"], "new-2");
2571}
2572
2573/// Test 5 — a subscriber that falls further behind than the hub's capacity
2574/// must NOT quietly lose strokes. The lag is forced (well past
2575/// `BOARD_HUB_CAPACITY` = 256 frames, each big enough to fill the socket
2576/// buffers), and the canvas the laggard ends up with is compared to the
2577/// database. Kills the `Err(_) => continue` handler, whose whole failure mode
2578/// is a permanently corrupt canvas on one client and no error anywhere.
2579#[tokio::test]
2580async fn a_lagged_socket_resyncs_to_exactly_what_the_database_holds() {
2581 let room = board_room_fixture().await;
2582 let (base, board) = (&room.base, &room.board_id);
2583 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2584 .await
2585 .expect("upgrade");
2586 board_join(&mut veli, None, None).await;
2587
2588 // veli stops reading. ali floods: 400 strokes of 4 KiB is ~1.6 MB, which
2589 // overruns the socket buffers, stalls the room's writer, and backs the
2590 // broadcast receiver up past its 256-frame capacity.
2591 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2592 .await
2593 .expect("upgrade");
2594 board_join(&mut ali, None, None).await;
2595 // In batches, acking each one: firing all 3000 first deadlocks the *test*
2596 // (ali stops reading, so ali's own socket fills and the server stops
2597 // reading ali), while one-at-a-time pays a round trip per stroke.
2598 //
2599 // 3000 x 4 KiB is ~12 MB. The number is empirical: the socket buffers
2600 // between the two ends swallowed ~1200 frames on this machine before the
2601 // room's writer stalled, and only then does the 256-frame channel start
2602 // dropping — so the count carries roughly 2x the measured margin.
2603 // corner-cut: a host with `net.ipv4.tcp_wmem` tuned far past the 4 MB
2604 // default could buffer more than this and the lag would stop being
2605 // forced; the test would then pass vacuously up to the resync assert,
2606 // which fails loudly rather than silently.
2607 let big = "x".repeat(4_000);
2608 let mut drawn = 0;
2609 while drawn < 3_000 {
2610 let batch = 50.min(3_000 - drawn);
2611 for n in 0..batch {
2612 ws_send(
2613 &mut ali,
2614 json!({ "type": "stroke", "payload": format!("{}:{big}", drawn + n) }),
2615 )
2616 .await;
2617 }
2618 for _ in 0..batch {
2619 board_frame_of_type(&mut ali, "saved").await;
2620 }
2621 drawn += batch;
2622 }
2623 let stored = stored_stroke_ids(&room.db, board, 0).await;
2624 assert_eq!(stored.len(), 3_000, "every flooded stroke persisted");
2625
2626 // veli starts reading again: the room notices the gap and says so.
2627 let resync = loop {
2628 let frame = ws_next_frame(&mut veli).await.expect("room stays open");
2629 if frame["type"] == "error" {
2630 break frame;
2631 }
2632 };
2633 assert_eq!(
2634 resync["code"], "resync",
2635 "a dropped frame must be announced, never swallowed"
2636 );
2637 // ...and re-serves the current epoch in full.
2638 let replayed = drain_replay(&mut veli).await;
2639 assert_eq!(
2640 replayed
2641 .iter()
2642 .map(|s| s["id"].as_str().unwrap().to_string())
2643 .collect::<Vec<_>>(),
2644 stored,
2645 "after a lag the client's canvas must equal the database's"
2646 );
2647}
2648
2649/// Test 6 — the door. An outsider learns nothing: the same 404 as a board that
2650/// was never created, and before the upgrade so it is an HTTP status rather
2651/// than an instant close. Kills existence leaks (src/lib.rs:57).
2652#[tokio::test]
2653async fn the_door_is_a_404_for_an_outsider_and_an_unknown_board() {
2654 let room = board_room_fixture().await;
2655 let (base, board) = (&room.base, &room.board_id);
2656 assert_eq!(
2657 board_open(base, board, Some(&room.ayse_cookie)).await.err(),
2658 Some(404),
2659 "a non-participant must not learn the board exists"
2660 );
2661 assert_eq!(
2662 board_open(base, common::ABSENT_ID, Some(&room.creator_cookie))
2663 .await
2664 .err(),
2665 Some(404),
2666 "indistinguishable from an unknown board"
2667 );
2668 // An over-long key is length-checked before it can be echoed anywhere.
2669 assert_eq!(
2670 board_open(base, &"x".repeat(200), Some(&room.creator_cookie))
2671 .await
2672 .err(),
2673 Some(404)
2674 );
2675 // No cookie at all is a 401, not a silent upgrade.
2676 assert_eq!(board_open(base, board, None).await.err(), Some(401));
2677 // And the participant does get in, so the 404s above are about the caller.
2678 board_open(base, board, Some(&room.veli_cookie))
2679 .await
2680 .expect("a participant is let in");
2681}
2682
2683/// Test 6b — the door is shut on a `parent` too, and shut the same way: a 404,
2684/// never a 403. Proved against the hardest case — the parent is forced onto the
2685/// roster in the database first, so the roster gate would let them in and only
2686/// the role bar refuses. No socket is the whole point: a parent that cannot
2687/// upgrade can never send a `stroke` frame, and the store proves nothing landed.
2688#[tokio::test]
2689async fn a_parent_cannot_enter_the_room_or_draw() {
2690 let room = board_room_fixture().await;
2691 let (base, board) = (&room.base, &room.board_id);
2692 let anne = client();
2693 register(&anne, base, "anne").await;
2694 promote(&room.db, "anne", "parent").await;
2695 login(&anne, base, "anne").await;
2696 let cookie = raw_session_cookie(base, "anne").await;
2697
2698 // On the roster by force — the stale row this rule leaves behind.
2699 let me: Value = anne
2700 .get(format!("{base}/auth/me"))
2701 .send()
2702 .await
2703 .unwrap()
2704 .json()
2705 .await
2706 .unwrap();
2707 // Beside `veli`, who stays: the two differ only by role, so the refusal
2708 // below cannot be blamed on the roster.
2709 let board_uuid = Uuid::parse_str(board).unwrap();
2710 sqlx::query("DELETE FROM board_participant WHERE board = $1")
2711 .bind(board_uuid)
2712 .execute(&room.db)
2713 .await
2714 .unwrap();
2715 sqlx::query(
2716 "INSERT INTO board_participant (board, participant)
2717 SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)",
2718 )
2719 .bind(board_uuid)
2720 .bind(vec![
2721 Uuid::parse_str(&room.veli_id).unwrap(),
2722 Uuid::parse_str(me["id"].as_str().unwrap()).unwrap(),
2723 ])
2724 .execute(&room.db)
2725 .await
2726 .unwrap();
2727
2728 assert_eq!(
2729 board_open(base, board, Some(&cookie)).await.err(),
2730 Some(404),
2731 "a parent on the roster must still be told the board does not exist"
2732 );
2733 // Not a 403 anywhere: identical to a board that was never minted.
2734 assert_eq!(
2735 board_open(base, common::ABSENT_ID, Some(&cookie))
2736 .await
2737 .err(),
2738 Some(404)
2739 );
2740 // No socket, so no stroke — asserted against the store, not the wire.
2741 assert!(
2742 stored_stroke_ids(&room.db, board, 0).await.is_empty(),
2743 "a parent must not have drawn"
2744 );
2745 // And the bar is about the role, not the roster: `veli` sits on the same
2746 // roster and is let straight in.
2747 board_open(base, board, Some(&room.veli_cookie))
2748 .await
2749 .expect("a student participant is still let in");
2750}
2751
2752/// Test 7 — a participant dropped mid-session stops drawing. Twice over: once
2753/// with the roster frame deliberately withheld (the socket's own gate is what
2754/// actually protects the board), and once through the REST route's fan-out —
2755/// which the removed socket never receives, because the authorization in front
2756/// of every delivery refuses it first.
2757#[tokio::test]
2758async fn a_removed_participant_can_no_longer_draw() {
2759 let room = board_room_fixture().await;
2760 let (base, board) = (&room.base, &room.board_id);
2761 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2762 .await
2763 .expect("upgrade");
2764 board_join(&mut veli, None, None).await;
2765 board_draw(&mut veli, "while invited").await;
2766
2767 // The silent removal first: write the roster straight into the database,
2768 // so no frame is published and only the per-stroke gate can catch it.
2769 sqlx::query("DELETE FROM board_participant WHERE board = $1")
2770 .bind(Uuid::parse_str(board).unwrap())
2771 .execute(&room.db)
2772 .await
2773 .unwrap();
2774 ws_send(
2775 &mut veli,
2776 json!({ "type": "stroke", "payload": "after removal" }),
2777 )
2778 .await;
2779 let error = board_frame_of_type(&mut veli, "error").await;
2780 assert_eq!(
2781 error["code"], "forbidden",
2782 "the stroke path re-reads the roster; it cannot trust a frame it may have missed"
2783 );
2784 assert_eq!(
2785 stored_payloads(&room.db, board, 0).await,
2786 vec!["while invited".to_string()],
2787 "the refused stroke wrote nothing"
2788 );
2789 // Re-entry is the outsider's 404 now.
2790 assert_eq!(
2791 board_open(base, board, Some(&room.veli_cookie)).await.err(),
2792 Some(404)
2793 );
2794
2795 // And the announced removal: re-invite, reconnect, then drop over REST.
2796 let res = room
2797 .creator
2798 .patch(format!("{base}/boards/{board}"))
2799 .json(&json!({ "participants": [room.veli_id] }))
2800 .send()
2801 .await
2802 .unwrap();
2803 assert_eq!(res.status(), StatusCode::OK);
2804 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2805 .await
2806 .expect("re-invited");
2807 board_join(&mut veli, None, None).await;
2808 let res = room
2809 .creator
2810 .patch(format!("{base}/boards/{board}"))
2811 .json(&json!({ "participants": [] }))
2812 .send()
2813 .await
2814 .unwrap();
2815 assert_eq!(res.status(), StatusCode::OK);
2816 // The removed socket is *not* handed the new roster: authorization runs in
2817 // front of every delivery now, so what reaches it is its own refusal and
2818 // not one more fact about a board it is no longer on.
2819 let refusal = board_frame_of_type(&mut veli, "error").await;
2820 assert_eq!(refusal["code"], "forbidden", "{refusal}");
2821 assert_eq!(
2822 refusal["message"], "you are no longer on this board",
2823 "a roster removal must still explain itself — and say something other \
2824 than the role bar's refusal, or a client cannot tell them apart"
2825 );
2826 // And the room drops the socket rather than leaving it open and mute.
2827 loop {
2828 match ws_next_frame(&mut veli).await {
2829 None => break,
2830 Some(frame) => {
2831 assert_ne!(frame["type"], "saved", "a dropped socket must not save");
2832 assert_ne!(
2833 frame["type"], "participants",
2834 "a removed socket is told it is out, never who is in"
2835 );
2836 }
2837 }
2838 }
2839}
2840
2841/// A bulk invite (`POST /boards/{id}/invite`) must reach the live room like any
2842/// other roster change. The room authorizes every delivery against the roster it
2843/// is told about, so a path that widens the array and stays silent leaves the
2844/// new participant unrenderable to the people already drawing — and this one is
2845/// easy to forget precisely because it only ever *adds*, so it can never trip
2846/// the removal test above.
2847#[tokio::test]
2848async fn a_bulk_invite_announces_the_widened_roster_to_the_room() {
2849 let room = board_room_fixture().await;
2850 let (base, board) = (room.base.as_str(), room.board_id.as_str());
2851 // The invite gates are teacher+, and the fixture's creator is a student.
2852 promote(&room.db, "ali", "teacher").await;
2853
2854 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2855 .await
2856 .expect("invited");
2857 board_join(&mut veli, None, None).await;
2858
2859 // A school-wide event resolves to every account, which here is the three the
2860 // fixture registered — so the invite adds exactly the outsider, ayşe.
2861 let res = room
2862 .creator
2863 .post(format!("{base}/events"))
2864 .json(&json!({ "title": "Tüm okul" }))
2865 .send()
2866 .await
2867 .unwrap();
2868 assert_eq!(res.status(), StatusCode::CREATED);
2869 let event: Value = res.json().await.unwrap();
2870 let event_id = event["id"].as_str().unwrap().to_string();
2871
2872 let res = room
2873 .creator
2874 .post(format!("{base}/boards/{board}/invite"))
2875 .json(&json!({ "kind": "event", "event": event_id }))
2876 .send()
2877 .await
2878 .unwrap();
2879 assert_eq!(res.status(), StatusCode::OK);
2880 let widened: Value = res.json().await.unwrap();
2881
2882 let frame = board_frame_of_type(&mut veli, "participants").await;
2883 let announced = frame["participants"].as_array().unwrap();
2884 assert!(
2885 announced.iter().any(|id| id == &json!(room.veli_id)),
2886 "the standing participant must still be on the announced roster: {frame}"
2887 );
2888 assert_eq!(
2889 announced.len(),
2890 2,
2891 "the outsider should have been added and announced: {frame}"
2892 );
2893 // The wire and the reply are the same list, and the creator is in neither
2894 // array — they are a participant by construction.
2895 let mut from_frame: Vec<&Value> = announced.iter().collect();
2896 let served = widened["participants"].as_array().unwrap();
2897 let mut from_body: Vec<&Value> = served.iter().collect();
2898 from_frame.sort_by_key(|id| id.as_str().unwrap());
2899 from_body.sort_by_key(|id| id.as_str().unwrap());
2900 assert_eq!(from_frame, from_body, "{frame} vs {widened}");
2901 assert_eq!(frame["creator"], widened["creator"], "{frame}");
2902
2903 // The stored row is the authority — the mem engine forges write wins, so a
2904 // frame alone proves only that the server said something.
2905 let stored: Value = room
2906 .creator
2907 .get(format!("{base}/boards/{board}"))
2908 .send()
2909 .await
2910 .unwrap()
2911 .json()
2912 .await
2913 .unwrap();
2914 assert_eq!(stored["participants"], widened["participants"]);
2915}
2916
2917/// Test 8 — `client_seq` is the client's correlation id and is echoed
2918/// verbatim, including a value no `i32` holds; a message without one gets a
2919/// reply without the key at all. Kills the "helpfully normalize it" bug that
2920/// silently breaks in-flight matching (mirrors src/web/exam_ws.rs:506-510).
2921#[tokio::test]
2922async fn client_seq_is_echoed_verbatim_or_omitted() {
2923 let room = board_room_fixture().await;
2924 let mut ali = board_open(&room.base, &room.board_id, Some(&room.creator_cookie))
2925 .await
2926 .expect("upgrade");
2927 board_join(&mut ali, None, None).await;
2928
2929 let huge: u64 = 18_446_744_073_709_551_615;
2930 ws_send(
2931 &mut ali,
2932 json!({ "type": "stroke", "payload": "a", "client_seq": huge }),
2933 )
2934 .await;
2935 let saved = board_frame_of_type(&mut ali, "saved").await;
2936 assert_eq!(saved["client_seq"].as_u64(), Some(huge));
2937
2938 // A refusal carries it too, or an in-flight failure cannot be matched.
2939 ws_send(
2940 &mut ali,
2941 json!({ "type": "stroke", "payload": "", "client_seq": 5 }),
2942 )
2943 .await;
2944 let error = board_frame_of_type(&mut ali, "error").await;
2945 assert_eq!(error["client_seq"], 5);
2946
2947 // Omitted stays omitted — never `null`.
2948 let saved = board_draw(&mut ali, "b").await;
2949 assert!(
2950 saved.get("client_seq").is_none(),
2951 "a client that sends no seq must see byte-identical frames: {saved}"
2952 );
2953}
2954
2955/// Test 9 — replay across the `BOARD_REPLAY_CHUNK` (200) boundary: every
2956/// stroke exactly once, in mint order, no gap at the seam and no row served
2957/// twice. Kills both classic paging bugs (`>=` vs `>` on the cursor, and a
2958/// loop that stops at the first full chunk).
2959#[tokio::test]
2960async fn replay_crosses_the_chunk_boundary_exactly_once() {
2961 let room = board_room_fixture().await;
2962 let (base, board) = (&room.base, &room.board_id);
2963 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2964 .await
2965 .expect("upgrade");
2966 board_join(&mut ali, None, None).await;
2967 for n in 0..205 {
2968 board_draw(&mut ali, &format!("mark-{n}")).await;
2969 }
2970 let stored = stored_stroke_ids(&room.db, board, 0).await;
2971 assert_eq!(stored.len(), 205);
2972
2973 let mut veli = board_open(base, board, Some(&room.veli_cookie))
2974 .await
2975 .expect("upgrade");
2976 let replayed = board_join(&mut veli, None, None).await;
2977 let ids: Vec<String> = replayed
2978 .iter()
2979 .map(|s| s["id"].as_str().unwrap().to_string())
2980 .collect();
2981 assert_eq!(ids, stored, "every stroke once, in mint order");
2982 assert_eq!(
2983 replayed
2984 .iter()
2985 .map(|s| s["payload"].as_str().unwrap())
2986 .collect::<Vec<_>>(),
2987 (0..205).map(|n| format!("mark-{n}")).collect::<Vec<_>>()
2988 );
2989}
2990
2991/// Test 10 — the lock is a live pause, not a disconnect, and it reaches the
2992/// room whichever way it was thrown (socket or REST). Kills the cached-flag
2993/// implementation, where a client that missed the frame keeps drawing.
2994#[tokio::test]
2995async fn a_lock_pauses_drawing_for_everyone_and_a_thaw_resumes_it() {
2996 let room = board_room_fixture().await;
2997 let (base, board) = (&room.base, &room.board_id);
2998 let mut ali = board_open(base, board, Some(&room.creator_cookie))
2999 .await
3000 .expect("upgrade");
3001 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3002 .await
3003 .expect("upgrade");
3004 board_join(&mut ali, None, None).await;
3005 board_join(&mut veli, None, None).await;
3006
3007 ws_send(&mut ali, json!({ "type": "lock", "locked": true })).await;
3008 let locked = board_frame_of_type(&mut veli, "locked").await;
3009 assert_eq!(locked["locked"], true);
3010
3011 ws_send(&mut veli, json!({ "type": "stroke", "payload": "sneaky" })).await;
3012 assert_eq!(
3013 board_frame_of_type(&mut veli, "error").await["code"],
3014 "locked"
3015 );
3016 assert!(stored_payloads(&room.db, board, 0).await.is_empty());
3017
3018 // Thawed over REST this time: the room must re-read, not trust its cache.
3019 let res = room
3020 .creator
3021 .patch(format!("{base}/boards/{board}"))
3022 .json(&json!({ "locked": false }))
3023 .send()
3024 .await
3025 .unwrap();
3026 assert_eq!(res.status(), StatusCode::OK);
3027 assert_eq!(
3028 board_frame_of_type(&mut veli, "locked").await["locked"],
3029 false
3030 );
3031 board_draw(&mut veli, "allowed again").await;
3032 assert_eq!(
3033 stored_payloads(&room.db, board, 0).await,
3034 vec!["allowed again".to_string()]
3035 );
3036}
3037
3038/// Test 11 — the two terminal REST frames end the room. A closed board is
3039/// read-only but still readable; a deleted one is gone, and a socket that
3040/// outlives its board must not answer for it.
3041#[tokio::test]
3042async fn closing_and_deleting_the_board_end_the_room() {
3043 let room = board_room_fixture().await;
3044 let (base, board) = (&room.base, &room.board_id);
3045 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3046 .await
3047 .expect("upgrade");
3048 board_join(&mut veli, None, None).await;
3049 board_draw(&mut veli, "before the close").await;
3050
3051 let res = room
3052 .creator
3053 .post(format!("{base}/boards/{board}/close"))
3054 .send()
3055 .await
3056 .unwrap();
3057 assert_eq!(res.status(), StatusCode::OK);
3058 let closed = board_frame_of_type(&mut veli, "closed").await;
3059 assert!(closed["closed_at"].as_i64().is_some());
3060 assert!(
3061 ws_next_frame(&mut veli).await.is_none(),
3062 "a closed board ends the room"
3063 );
3064 // Read-only, not gone: the canvas still replays, drawing does not.
3065 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3066 .await
3067 .expect("a closed board is still readable");
3068 assert_eq!(board_join(&mut veli, None, None).await.len(), 1);
3069 ws_send(
3070 &mut veli,
3071 json!({ "type": "stroke", "payload": "too late" }),
3072 )
3073 .await;
3074 assert_eq!(
3075 board_frame_of_type(&mut veli, "error").await["code"],
3076 "board_closed"
3077 );
3078 assert_eq!(stored_payloads(&room.db, board, 0).await.len(), 1);
3079
3080 let res = room
3081 .creator
3082 .delete(format!("{base}/boards/{board}"))
3083 .send()
3084 .await
3085 .unwrap();
3086 assert_eq!(res.status(), StatusCode::NO_CONTENT);
3087 board_frame_of_type(&mut veli, "deleted").await;
3088 assert!(
3089 ws_next_frame(&mut veli).await.is_none(),
3090 "a deleted board ends the room"
3091 );
3092 assert!(stored_payloads(&room.db, board, 0).await.is_empty());
3093}
3094
3095/// Test 12 — two sockets drawing at once. Every accepted stroke is in the
3096/// database exactly once and both clients can reach that same canvas: the
3097/// concurrent case the whole feature exists for.
3098#[tokio::test]
3099async fn simultaneous_drawing_lands_every_stroke_exactly_once() {
3100 let room = board_room_fixture().await;
3101 let (base, board) = (&room.base, &room.board_id);
3102 let mut ali = board_open(base, board, Some(&room.creator_cookie))
3103 .await
3104 .expect("upgrade");
3105 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3106 .await
3107 .expect("upgrade");
3108 board_join(&mut ali, None, None).await;
3109 board_join(&mut veli, None, None).await;
3110
3111 // Interleaved without waiting for acks, so the two writers really overlap.
3112 for n in 0..20 {
3113 ws_send(
3114 &mut ali,
3115 json!({ "type": "stroke", "payload": format!("ali-{n}") }),
3116 )
3117 .await;
3118 ws_send(
3119 &mut veli,
3120 json!({ "type": "stroke", "payload": format!("veli-{n}") }),
3121 )
3122 .await;
3123 }
3124 for _ in 0..20 {
3125 board_frame_of_type(&mut ali, "saved").await;
3126 }
3127 for _ in 0..20 {
3128 board_frame_of_type(&mut veli, "saved").await;
3129 }
3130
3131 let stored = stored_payloads(&room.db, board, 0).await;
3132 assert_eq!(stored.len(), 40, "no stroke lost, none duplicated");
3133 let mut unique = stored.clone();
3134 unique.sort();
3135 unique.dedup();
3136 assert_eq!(unique.len(), 40);
3137
3138 // A fresh joiner sees that exact canvas — the DB, not either socket's view.
3139 let mut late = board_open(base, board, Some(&room.veli_cookie))
3140 .await
3141 .expect("upgrade");
3142 assert_eq!(
3143 board_join(&mut late, None, None)
3144 .await
3145 .iter()
3146 .map(|s| s["payload"].as_str().unwrap().to_string())
3147 .collect::<Vec<_>>(),
3148 stored
3149 );
3150}
3151
3152/// Test 13 — junk in, error out, room alive. A malformed frame or an unknown
3153/// type must never take the canvas down with it.
3154#[tokio::test]
3155async fn junk_frames_do_not_end_the_room() {
3156 let room = board_room_fixture().await;
3157 let mut ali = board_open(&room.base, &room.board_id, Some(&room.creator_cookie))
3158 .await
3159 .expect("upgrade");
3160 board_join(&mut ali, None, None).await;
3161
3162 ws_send(&mut ali, json!({ "type": "nonsense" })).await;
3163 board_frame_of_type(&mut ali, "error").await;
3164 ali.send(Message::Text("{not json".into())).await.unwrap();
3165 board_frame_of_type(&mut ali, "error").await;
3166 // An oversized payload is refused by the domain's own gate.
3167 ws_send(
3168 &mut ali,
3169 json!({ "type": "stroke", "payload": "x".repeat(4_097) }),
3170 )
3171 .await;
3172 board_frame_of_type(&mut ali, "error").await;
3173
3174 board_draw(&mut ali, "still fine").await;
3175 assert_eq!(
3176 stored_payloads(&room.db, &room.board_id, 0).await,
3177 vec!["still fine".to_string()]
3178 );
3179}
3180
3181/// Test 14 (grafted from candidate B) — the half no other board test reaches:
3182/// a `participants` frame drops *only* the socket it removed. Test 7 proves the
3183/// removed one is dropped; nothing proved the survivors keep drawing, so a
3184/// `forward` that closed the room on every roster change would pass the suite.
3185#[tokio::test]
3186async fn a_roster_change_drops_only_the_socket_it_removed() {
3187 let room = board_room_fixture().await;
3188 let (base, board) = (&room.base, &room.board_id);
3189 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3190 .await
3191 .expect("upgrade");
3192 let mut ali = board_open(base, board, Some(&room.creator_cookie))
3193 .await
3194 .expect("upgrade");
3195 board_join(&mut veli, None, None).await;
3196 board_join(&mut ali, None, None).await;
3197
3198 // The creator empties the invite list over REST.
3199 let res = room
3200 .creator
3201 .patch(format!("{base}/boards/{board}"))
3202 .json(&json!({ "participants": [] }))
3203 .send()
3204 .await
3205 .unwrap();
3206 assert_eq!(res.status(), StatusCode::OK);
3207
3208 // The dropped participant is closed…
3209 loop {
3210 match ws_next_frame(&mut veli).await {
3211 None => break,
3212 Some(frame) => assert_ne!(frame["type"], "saved", "a dropped socket must not save"),
3213 }
3214 }
3215 // … while the creator, still on the board, sees the new roster and keeps
3216 // drawing on the very same socket.
3217 let roster = board_frame_of_type(&mut ali, "participants").await;
3218 assert!(roster["participants"].as_array().unwrap().is_empty());
3219 board_draw(&mut ali, "still mine").await;
3220 assert_eq!(
3221 stored_payloads(&room.db, board, 0).await,
3222 vec!["still mine".to_string()]
3223 );
3224}
3225
3226/// Test 15 — clearing a blank canvas is a *live* board saying "nothing to do",
3227/// and the room must say so with a non-terminal code. It shipped as
3228/// `board_closed` — the terminal one — because the classifier guessed the code
3229/// from a substring of the refusal's words, and the reworded refusal happens to
3230/// contain "closed". A creator who double-clicks clear would have been told the
3231/// board was finished forever, on a board still open and still drawable.
3232#[tokio::test]
3233async fn clearing_a_blank_canvas_never_tells_the_room_the_board_is_closed() {
3234 let room = board_room_fixture().await;
3235 let (base, board) = (&room.base, &room.board_id);
3236 let mut ali = board_open(base, board, Some(&room.creator_cookie))
3237 .await
3238 .expect("upgrade");
3239 board_join(&mut ali, None, None).await;
3240
3241 // Nothing drawn yet: there is no epoch to close.
3242 ws_send(&mut ali, json!({ "type": "clear" })).await;
3243 let error = board_frame_of_type(&mut ali, "error").await;
3244 assert_eq!(error["code"], "canvas_blank", "{error}");
3245
3246 // The same refusal after a real clear — the second press of the button.
3247 board_draw(&mut ali, "one").await;
3248 ws_send(&mut ali, json!({ "type": "clear" })).await;
3249 board_frame_of_type(&mut ali, "cleared").await;
3250 ws_send(&mut ali, json!({ "type": "clear" })).await;
3251 assert_eq!(
3252 board_frame_of_type(&mut ali, "error").await["code"],
3253 "canvas_blank"
3254 );
3255
3256 // And the board really is live: the socket draws on, into the new epoch.
3257 board_draw(&mut ali, "two").await;
3258 assert_eq!(
3259 stored_payloads(&room.db, board, 1).await,
3260 vec!["two".to_string()]
3261 );
3262}
3263
3264/// The class layer over real HTTP with three cookie jars: the office builds the
3265/// class, the teacher hands over their own course, and the student — who was
3266/// never enrolled by anyone — finds it on `GET /instances/me`. Taking them out of
3267/// the class takes the seat back with them.
3268#[tokio::test]
3269async fn a_class_seats_its_roster_and_gives_the_seat_back() {
3270 let (base, db) = spawn_server().await;
3271 let manager = client();
3272 let teacher = client();
3273 let student = client();
3274
3275 for (c, name) in [(&manager, "mgr"), (&teacher, "tch"), (&student, "veli")] {
3276 assert_eq!(register(c, &base, name).await.status(), StatusCode::CREATED);
3277 }
3278 promote(&db, "mgr", "manager").await;
3279 promote(&db, "tch", "teacher").await;
3280 for (c, name) in [(&manager, "mgr"), (&teacher, "tch"), (&student, "veli")] {
3281 login(c, &base, name).await;
3282 }
3283
3284 let id_of = |v: &Value| v["id"].as_str().unwrap().to_string();
3285 let student_id = id_of(
3286 &student
3287 .get(format!("{base}/auth/me"))
3288 .send()
3289 .await
3290 .unwrap()
3291 .json::<Value>()
3292 .await
3293 .unwrap(),
3294 );
3295
3296 // The office opens the class — with `tch` as its homeroom teacher, so the
3297 // teacher who brings the course can act on the instance it makes — and puts
3298 // the student in it.
3299 let teacher_id = id_of(
3300 &teacher
3301 .get(format!("{base}/auth/me"))
3302 .send()
3303 .await
3304 .unwrap()
3305 .json::<Value>()
3306 .await
3307 .unwrap(),
3308 );
3309 let res = manager
3310 .post(format!("{base}/classes"))
3311 .json(&json!({ "name": "9-A", "grade_level": 9, "teacher_id": teacher_id }))
3312 .send()
3313 .await
3314 .unwrap();
3315 assert_eq!(res.status(), StatusCode::CREATED);
3316 // `POST /classes` answers `{class, skipped, stocked_from}` — it stocks the
3317 // new section from its grade's blueprint, and there is none here.
3318 let class = id_of(&res.json::<Value>().await.unwrap()["class"]);
3319 let res = manager
3320 .post(format!("{base}/classes/{class}/members"))
3321 .json(&json!({ "user_id": student_id }))
3322 .send()
3323 .await
3324 .unwrap();
3325 assert_eq!(res.status(), StatusCode::CREATED);
3326
3327 // The teacher hands their own course to the class …
3328 let res = teacher
3329 .post(format!("{base}/courses"))
3330 .json(&json!({ "title": "Cebir" }))
3331 .send()
3332 .await
3333 .unwrap();
3334 assert_eq!(res.status(), StatusCode::CREATED);
3335 let course = id_of(&res.json::<Value>().await.unwrap());
3336 let res = teacher
3337 .post(format!("{base}/classes/{class}/instances"))
3338 .json(&json!({ "course_id": course }))
3339 .send()
3340 .await
3341 .unwrap();
3342 assert_eq!(res.status(), StatusCode::CREATED);
3343 let instance = id_of(&res.json::<Value>().await.unwrap());
3344
3345 // … and the student, whom nobody ever enrolled, is in it: the şube teaching
3346 // the course is what seats them.
3347 let mine: Value = student
3348 .get(format!("{base}/instances/me"))
3349 .send()
3350 .await
3351 .unwrap()
3352 .json()
3353 .await
3354 .unwrap();
3355 assert_eq!(mine["total"], 1, "the class seated them: {mine}");
3356 assert_eq!(mine["items"][0]["course"], json!(course));
3357 assert_eq!(mine["items"][0]["id"], json!(instance));
3358 let catalog: Value = student
3359 .get(format!("{base}/courses/{course}"))
3360 .send()
3361 .await
3362 .unwrap()
3363 .json()
3364 .await
3365 .unwrap();
3366 assert_eq!(catalog["title"], "Cebir");
3367
3368 // Out of the class, out of the instance — the seat comes back.
3369 let res = manager
3370 .delete(format!("{base}/classes/{class}/members/{student_id}"))
3371 .send()
3372 .await
3373 .unwrap();
3374 assert_eq!(res.status(), StatusCode::NO_CONTENT);
3375 let mine: Value = student
3376 .get(format!("{base}/instances/me"))
3377 .send()
3378 .await
3379 .unwrap()
3380 .json()
3381 .await
3382 .unwrap();
3383 assert_eq!(mine["total"], 0, "the seat went with them: {mine}");
3384 let roster: Value = teacher
3385 .get(format!("{base}/instances/{instance}/enrollments"))
3386 .send()
3387 .await
3388 .unwrap()
3389 .json()
3390 .await
3391 .unwrap();
3392 assert_eq!(roster["total"], 0, "and off the teacher's roster: {roster}");
3393 let read: Value = teacher
3394 .get(format!("{base}/instances/{instance}"))
3395 .send()
3396 .await
3397 .unwrap()
3398 .json()
3399 .await
3400 .unwrap();
3401 assert_eq!(read["enrollment_count"], json!(0), "and off the counter");
3402}
3403
3404/// The role bar has to close READS, not only writes. `forward` used to hand the
3405/// frame to the socket first and authorize afterwards — and only on a
3406/// `participants` frame or the 15-second state tick — so a participant demoted
3407/// to `parent`, the role with no whiteboard access at all, kept being served
3408/// every mark drawn on a live canvas until the tick caught up. Driven over a
3409/// real socket, because the leak lives in the fan-out and nowhere else.
3410///
3411/// The role is moved straight in the database, which is both the school's
3412/// documented bootstrap and the harshest case: no `participants` frame is
3413/// published to prompt the room, so only the authorization in front of the send
3414/// can refuse it.
3415#[tokio::test]
3416async fn a_demoted_participant_stops_reading_the_canvas_at_once() {
3417 let room = board_room_fixture().await;
3418 let (base, board) = (&room.base, &room.board_id);
3419 let mut ali = board_open(base, board, Some(&room.creator_cookie))
3420 .await
3421 .expect("creator upgrade");
3422 let mut veli = board_open(base, board, Some(&room.veli_cookie))
3423 .await
3424 .expect("participant upgrade");
3425 board_join(&mut veli, None, None).await;
3426
3427 // Still a student: the fan-out reaches them.
3428 board_draw(&mut ali, "{\"p\":[1,2]}").await;
3429 let fanned = board_frame_of_type(&mut veli, "stroke").await;
3430 assert_eq!(fanned["payload"], "{\"p\":[1,2]}");
3431
3432 promote(&room.db, "veli", "parent").await;
3433 board_draw(&mut ali, "{\"p\":[3,4]}").await;
3434
3435 // The next thing that socket hears is its refusal, and the room ends. It
3436 // must never be the mark: `parent` has no whiteboard access whatsoever.
3437 let mut refused = false;
3438 while let Some(frame) = ws_next_frame(&mut veli).await {
3439 assert_ne!(
3440 frame["type"], "stroke",
3441 "a demoted participant read live canvas content: {frame}"
3442 );
3443 if frame["type"] == "error" {
3444 assert_eq!(frame["code"], "forbidden", "{frame}");
3445 // Its own words, distinct from a roster removal's: the client can
3446 // tell "you were taken off this board" from "your account may no
3447 // longer use boards at all".
3448 assert_eq!(frame["message"], "your role can no longer use boards");
3449 refused = true;
3450 }
3451 }
3452 assert!(refused, "the socket must be told why it was dropped");
3453
3454 // Nothing was destroyed by the refusal, and the room carries on for the
3455 // people still entitled to it.
3456 assert_eq!(
3457 stored_payloads(&room.db, board, 0).await,
3458 vec!["{\"p\":[1,2]}".to_string(), "{\"p\":[3,4]}".to_string()],
3459 );
3460 board_draw(&mut ali, "{\"p\":[5,6]}").await;
3461}
3462
3463/// The past is read-only: with its academic year archived, every write into the
3464/// year's structure answers `409 academic_year_archived` — the dönem, the
3465/// instances, their rosters, exams, homework, roll call and the class itself —
3466/// every read still answers, the live exam room's door refuses the upgrade with
3467/// a real HTTP 409 (before the WebSocket handshake completes), and re-opening
3468/// the year thaws all of it.
3469///
3470/// Since the K12 remodel a şube hangs off a *year*, not a dönem (a dönem is a
3471/// grading slice inside it), so that is the unit the freeze had to move to. No
3472/// route archives a year yet — the archive half of the API is still the dönem's
3473/// — so the past is minted through the column, and the dönem's own archive route
3474/// is exercised beside it at the end.
3475#[tokio::test]
3476async fn a_manager_archived_year_refuses_every_write_and_answers_every_read() {
3477 let (base, db) = spawn_server().await;
3478 let mudur = client();
3479 let ogrenci = client();
3480 let kaan = client();
3481 register(&mudur, &base, "mudur").await;
3482 register(&ogrenci, &base, "ogrenci").await;
3483 register(&kaan, &base, "kaan").await;
3484 promote(&db, "mudur", "manager").await;
3485 login(&mudur, &base, "mudur").await;
3486 login(&ogrenci, &base, "ogrenci").await;
3487 login(&kaan, &base, "kaan").await;
3488
3489 let json_of = async |res: reqwest::Response| res.json::<Value>().await.unwrap();
3490 let student_id =
3491 json_of(ogrenci.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"]
3492 .as_str()
3493 .unwrap()
3494 .to_string();
3495 let kaan_id = json_of(kaan.get(format!("{base}/auth/me")).send().await.unwrap()).await["id"]
3496 .as_str()
3497 .unwrap()
3498 .to_string();
3499 let now = json_of(mudur.get(format!("{base}/time")).send().await.unwrap()).await["now"]
3500 .as_i64()
3501 .unwrap();
3502
3503 // --- a year's worth of structure, all hanging off one year ------------
3504 let res = mudur
3505 .post(format!("{base}/academic-years"))
3506 .json(&json!({
3507 "name": "2026-2027",
3508 "starts_at": now - 86_400_000,
3509 "ends_at": now + 86_400_000,
3510 }))
3511 .send()
3512 .await
3513 .unwrap();
3514 assert_eq!(res.status(), StatusCode::CREATED);
3515 let year: Value = res.json().await.unwrap();
3516 let year_id = year["id"].as_str().unwrap().to_string();
3517 assert!(
3518 year["archived_at"].is_null(),
3519 "a fresh year is open: {year}"
3520 );
3521
3522 let res = mudur
3523 .post(format!("{base}/terms"))
3524 .json(&json!({
3525 "name": "2026 Fall",
3526 "year": year_id,
3527 "starts_at": now - 86_400_000,
3528 "ends_at": now + 86_400_000,
3529 }))
3530 .send()
3531 .await
3532 .unwrap();
3533 assert_eq!(res.status(), StatusCode::CREATED);
3534 let term: Value = res.json().await.unwrap();
3535 let term_id = term["id"].as_str().unwrap().to_string();
3536 assert_eq!(term["year"], json!(year_id), "the dönem names its year");
3537
3538 let res = mudur
3539 .post(format!("{base}/courses"))
3540 .json(&json!({ "title": "algebra" }))
3541 .send()
3542 .await
3543 .unwrap();
3544 assert_eq!(res.status(), StatusCode::CREATED);
3545 let course_id = json_of(res).await["id"].as_str().unwrap().to_string();
3546
3547 let subject_id = json_of(
3548 mudur
3549 .post(format!("{base}/courses/{course_id}/subjects"))
3550 .json(&json!({ "name": "arithmetic" }))
3551 .send()
3552 .await
3553 .unwrap(),
3554 )
3555 .await["id"]
3556 .as_str()
3557 .unwrap()
3558 .to_string();
3559
3560 // 9-A teaches it: the class is the structure the year closes over, and the
3561 // instance is what every one of the writes below hangs off.
3562 let res = mudur
3563 .post(format!("{base}/classes"))
3564 .json(&json!({ "name": "9-A", "grade_level": 9, "year": year_id }))
3565 .send()
3566 .await
3567 .unwrap();
3568 assert_eq!(res.status(), StatusCode::CREATED);
3569 let class_id = json_of(res).await["class"]["id"]
3570 .as_str()
3571 .unwrap()
3572 .to_string();
3573
3574 let res = mudur
3575 .post(format!("{base}/classes/{class_id}/instances"))
3576 .json(&json!({ "course_id": course_id }))
3577 .send()
3578 .await
3579 .unwrap();
3580 assert_eq!(res.status(), StatusCode::CREATED);
3581 let instance_id = json_of(res).await["id"].as_str().unwrap().to_string();
3582
3583 // The attach auto-minted the grade-level offering with an empty syllabus;
3584 // select the fresh topic onto it so the question and the homework below
3585 // may tag it.
3586 let offering_id = json_of(
3587 mudur
3588 .get(format!("{base}/instances/{instance_id}"))
3589 .send()
3590 .await
3591 .unwrap(),
3592 )
3593 .await["offering"]
3594 .as_str()
3595 .unwrap()
3596 .to_string();
3597 let res = mudur
3598 .post(format!("{base}/offerings/{offering_id}/subjects"))
3599 .json(&json!({ "subject": subject_id }))
3600 .send()
3601 .await
3602 .unwrap();
3603 assert_eq!(res.status(), StatusCode::CREATED);
3604
3605 let exam: Value = json_of(
3606 mudur
3607 .post(format!("{base}/instances/{instance_id}/exams"))
3608 .json(&json!({
3609 "title": "midterm", "kind": "yazili", "term": term_id,
3610 "mode": "open", "max_attempts": 2,
3611 }))
3612 .send()
3613 .await
3614 .unwrap(),
3615 )
3616 .await;
3617 let exam_id = exam["id"].as_str().unwrap().to_string();
3618 let question: Value = json_of(
3619 mudur
3620 .post(format!("{base}/exams/{exam_id}/questions"))
3621 .json(
3622 &json!({ "subject_id": subject_id, "text": "2 + 2?", "kind": "choice",
3623 "points": 10,
3624 "choices": [{"id": "a", "text": "3"}, {"id": "b", "text": "4"}],
3625 "correct": "b" }),
3626 )
3627 .send()
3628 .await
3629 .unwrap(),
3630 )
3631 .await;
3632 let question_id = question["id"].as_str().unwrap().to_string();
3633 let opts = choice_ids(&question);
3634
3635 let res = mudur
3636 .post(format!("{base}/instances/{instance_id}/sessions"))
3637 .json(&json!({ "starts_at": now + 3_600_000 }))
3638 .send()
3639 .await
3640 .unwrap();
3641 assert_eq!(res.status(), StatusCode::CREATED);
3642 let session_id = json_of(res).await["id"].as_str().unwrap().to_string();
3643
3644 let res = mudur
3645 .post(format!("{base}/instances/{instance_id}/homework"))
3646 .json(
3647 &json!({ "title": "read ch3", "subject_id": subject_id, "due_at": now + 604_800_000 }),
3648 )
3649 .send()
3650 .await
3651 .unwrap();
3652 assert_eq!(res.status(), StatusCode::CREATED);
3653 let homework_id = json_of(res).await["id"].as_str().unwrap().to_string();
3654
3655 let res = mudur
3656 .post(format!("{base}/course-notes"))
3657 .json(&json!({ "course": course_id, "title": "recap", "content": "quadratics" }))
3658 .send()
3659 .await
3660 .unwrap();
3661 assert_eq!(res.status(), StatusCode::CREATED);
3662 let note_id = json_of(res).await["id"].as_str().unwrap().to_string();
3663
3664 let res = mudur
3665 .post(format!("{base}/instances/{instance_id}/enrollments"))
3666 .json(&json!({ "user_id": student_id }))
3667 .send()
3668 .await
3669 .unwrap();
3670 assert_eq!(res.status(), StatusCode::OK);
3671
3672 // The student is mid-sitting when the year closes: a live attempt whose
3673 // room door is about to be walled.
3674 let res = ogrenci
3675 .post(format!("{base}/exams/{exam_id}/attempt"))
3676 .send()
3677 .await
3678 .unwrap();
3679 assert_eq!(res.status(), StatusCode::CREATED, "start the live sitting");
3680 let student_cookie = raw_session_cookie(&base, "ogrenci").await;
3681
3682 // --- the year goes past -------------------------------------------------
3683 let res = mudur
3684 .post(format!("{base}/academic-years/{year_id}/archive"))
3685 .send()
3686 .await
3687 .unwrap();
3688 assert_eq!(res.status(), StatusCode::OK);
3689 let archived: Value = res.json().await.unwrap();
3690 let stamp = archived["archived_at"]
3691 .as_i64()
3692 .expect("the archive answers the stamped year");
3693 assert!(
3694 stamp >= now,
3695 "the stamp is the archive's own clock: {archived}"
3696 );
3697 assert_eq!(archived["id"], json!(year_id), "{archived}");
3698
3699 // A second archive is a `200` with the stamp that already stood: the year
3700 // is never re-dated by a double click, and nothing is written twice.
3701 let res = mudur
3702 .post(format!("{base}/academic-years/{year_id}/archive"))
3703 .send()
3704 .await
3705 .unwrap();
3706 assert_eq!(res.status(), StatusCode::OK, "re-archiving stays a 200");
3707 assert_eq!(
3708 json_of(res).await["archived_at"].as_i64(),
3709 Some(stamp),
3710 "re-archiving must not move the stamp"
3711 );
3712
3713 let read: Value = json_of(
3714 mudur
3715 .get(format!("{base}/academic-years/{year_id}"))
3716 .send()
3717 .await
3718 .unwrap(),
3719 )
3720 .await;
3721 assert_eq!(
3722 read["archived_at"],
3723 json!(stamp),
3724 "the read shows it: {read}"
3725 );
3726
3727 // --- every write into the closed year is a 409 --------------------------
3728 let refusals: Vec<(&str, reqwest::Response)> = vec![
3729 (
3730 "PATCH /terms/{id}",
3731 mudur
3732 .patch(format!("{base}/terms/{term_id}"))
3733 .json(&json!({ "name": "renamed" }))
3734 .send()
3735 .await
3736 .unwrap(),
3737 ),
3738 (
3739 "PATCH /instances/{id}",
3740 mudur
3741 .patch(format!("{base}/instances/{instance_id}"))
3742 .json(&json!({ "ders_saati": 4 }))
3743 .send()
3744 .await
3745 .unwrap(),
3746 ),
3747 (
3748 "POST /instances/{id}/enrollments",
3749 mudur
3750 .post(format!("{base}/instances/{instance_id}/enrollments"))
3751 .json(&json!({ "user_id": kaan_id }))
3752 .send()
3753 .await
3754 .unwrap(),
3755 ),
3756 (
3757 "POST /sessions/{id}/attendance",
3758 mudur
3759 .post(format!("{base}/sessions/{session_id}/attendance"))
3760 .json(&json!({ "status": "present", "user_id": student_id }))
3761 .send()
3762 .await
3763 .unwrap(),
3764 ),
3765 (
3766 "PATCH /exams/{id}",
3767 mudur
3768 .patch(format!("{base}/exams/{exam_id}"))
3769 .json(&json!({ "title": "renamed" }))
3770 .send()
3771 .await
3772 .unwrap(),
3773 ),
3774 (
3775 "POST /exams/{id}/attempt/answers",
3776 ogrenci
3777 .post(format!("{base}/exams/{exam_id}/attempt/answers"))
3778 .json(&json!({ "question_id": question_id, "selected": opts[1] }))
3779 .send()
3780 .await
3781 .unwrap(),
3782 ),
3783 (
3784 "POST /homework/{id}/results",
3785 mudur
3786 .post(format!("{base}/homework/{homework_id}/results"))
3787 .json(&json!({ "user": student_id, "status": "done", "mark": 90 }))
3788 .send()
3789 .await
3790 .unwrap(),
3791 ),
3792 (
3793 "POST /classes/{id}/members",
3794 mudur
3795 .post(format!("{base}/classes/{class_id}/members"))
3796 .json(&json!({ "user_id": kaan_id }))
3797 .send()
3798 .await
3799 .unwrap(),
3800 ),
3801 ];
3802 for (what, res) in refusals {
3803 let status = res.status();
3804 let body: Value = res.json().await.unwrap();
3805 assert_eq!(status, StatusCode::CONFLICT, "{what} status: {body}");
3806 assert_eq!(
3807 body["code"], "academic_year_archived",
3808 "{what} code: {body}"
3809 );
3810 }
3811
3812 // --- every read still answers -----------------------------------------
3813 for url in [
3814 format!("{base}/terms/{term_id}"),
3815 format!("{base}/academic-years/{year_id}"),
3816 format!("{base}/instances/{instance_id}"),
3817 format!("{base}/courses/{course_id}"),
3818 format!("{base}/exams/{exam_id}"),
3819 format!("{base}/sessions/{session_id}"),
3820 format!("{base}/homework/{homework_id}"),
3821 format!("{base}/course-notes/{note_id}"),
3822 format!("{base}/classes/{class_id}"),
3823 ] {
3824 let res = mudur.get(&url).send().await.unwrap();
3825 assert_eq!(res.status(), StatusCode::OK, "read stays open: {url}");
3826 }
3827
3828 // --- the exam room's door: refused before the upgrade ------------------
3829 let refused = ws_open(&base, &exam_id, Some(&student_cookie))
3830 .await
3831 .expect_err("an archived year's room must refuse the handshake");
3832 assert_eq!(refused, 409, "the room door answers a real HTTP 409");
3833
3834 // --- re-opening the year thaws the whole set ---------------------------
3835 // Archiving a year is one-way — there is no unarchive route — so the
3836 // column is cleared here the way an operator would, to prove the gates
3837 // read the stamp and not some one-shot state. The dönem's own
3838 // `archive`/`unarchive` pair (below) is the supported way to re-open a
3839 // graded slice inside the year.
3840 sqlx::query("UPDATE academic_year SET archived_at = NULL WHERE id = $1")
3841 .bind(Uuid::parse_str(&year_id).unwrap())
3842 .execute(&db)
3843 .await
3844 .unwrap();
3845
3846 // A write that was refused a moment ago now lands.
3847 let res = mudur
3848 .patch(format!("{base}/instances/{instance_id}"))
3849 .json(&json!({ "ders_saati": 4 }))
3850 .send()
3851 .await
3852 .unwrap();
3853 assert_eq!(
3854 res.status(),
3855 StatusCode::OK,
3856 "the reopened year takes writes"
3857 );
3858 assert_eq!(json_of(res).await["ders_saati"], json!(4));
3859
3860 // The room door opens again, and the live sitting is still there.
3861 let mut ws = ws_open(&base, &exam_id, Some(&student_cookie))
3862 .await
3863 .expect("the reopened year's room");
3864 let state = ws_next_frame(&mut ws).await.expect("connect state frame");
3865 assert_eq!(state["type"], "state", "{state}");
3866
3867 // Archive under the open socket: `finish` comes back as an error frame
3868 // carrying the archived refusal instead of submitting the sheet.
3869 let res = mudur
3870 .post(format!("{base}/academic-years/{year_id}/archive"))
3871 .send()
3872 .await
3873 .unwrap();
3874 assert_eq!(
3875 res.status(),
3876 StatusCode::OK,
3877 "the year closes under the socket"
3878 );
3879 ws_send(&mut ws, json!({ "type": "finish" })).await;
3880 let error = ws_frame_of_type(&mut ws, "error").await;
3881 assert!(
3882 error["message"].as_str().unwrap().contains("archived"),
3883 "the room's finish refusal names the archived year: {error}"
3884 );
3885
3886 // Reopen once more and the same frame submits the sitting.
3887 sqlx::query("UPDATE academic_year SET archived_at = NULL WHERE id = $1")
3888 .bind(Uuid::parse_str(&year_id).unwrap())
3889 .execute(&db)
3890 .await
3891 .unwrap();
3892 ws_send(&mut ws, json!({ "type": "finish" })).await;
3893 let finished = ws_frame_of_type(&mut ws, "finished").await;
3894 assert!(finished["finished_at"].as_i64().is_some(), "{finished}");
3895
3896 // --- the dönem's own archive: idempotent, and discoverable --------------
3897 let res = mudur
3898 .post(format!("{base}/terms/{term_id}/archive"))
3899 .send()
3900 .await
3901 .unwrap();
3902 assert_eq!(res.status(), StatusCode::OK);
3903 let archived: Value = res.json().await.unwrap();
3904 let stamp = archived["archived_at"].as_i64().expect("archived_at stamp");
3905
3906 let res = mudur
3907 .post(format!("{base}/terms/{term_id}/archive"))
3908 .send()
3909 .await
3910 .unwrap();
3911 assert_eq!(res.status(), StatusCode::OK);
3912 assert_eq!(
3913 json_of(res).await["archived_at"].as_i64(),
3914 Some(stamp),
3915 "re-archiving must not move the stamp"
3916 );
3917
3918 let res = mudur
3919 .post(format!("{base}/terms/{term_id}/unarchive"))
3920 .send()
3921 .await
3922 .unwrap();
3923 assert_eq!(res.status(), StatusCode::OK);
3924 assert!(
3925 json_of(res).await["archived_at"].is_null(),
3926 "unarchive clears the stamp"
3927 );
3928
3929 // --- discoverable in the document Swagger renders ----------------------
3930 let spec: Value = json_of(
3931 mudur
3932 .get(format!("{base}/api-docs/openapi.json"))
3933 .send()
3934 .await
3935 .unwrap(),
3936 )
3937 .await;
3938 for path in [
3939 "/terms/{id}/archive",
3940 "/terms/{id}/unarchive",
3941 "/academic-years/{id}/archive",
3942 ] {
3943 assert!(
3944 spec["paths"][path]["post"].is_object(),
3945 "{path} must be a documented POST in the served spec"
3946 );
3947 }
3948}
3949
3950/// The vendor surface over real TCP, with a browser's cookie jar: the builder
3951/// logs in, brings a school into being, and the admin that call seeded logs
3952/// into it — the whole onboarding path, end to end.
3953#[tokio::test]
3954async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() {
3955 let (base, _db) = spawn_server().await;
3956 let vendor = client();
3957
3958 let res = vendor
3959 .post(format!("{base}/builder/login"))
3960 .json(&json!({ "username": "operator", "password": "secret1" }))
3961 .send()
3962 .await
3963 .unwrap();
3964 assert_eq!(res.status(), StatusCode::OK);
3965 assert_eq!(res.json::<Value>().await.unwrap()["username"], "operator");
3966
3967 let res = vendor
3968 .post(format!("{base}/schools"))
3969 .json(&json!({
3970 "name": "TCP Koleji",
3971 "admin_username": "admin",
3972 "admin_password": "secret1",
3973 }))
3974 .send()
3975 .await
3976 .unwrap();
3977 assert_eq!(res.status(), StatusCode::CREATED);
3978 let school = res.json::<Value>().await.unwrap();
3979 assert!(school["id"].as_str().is_some_and(|id| id.len() == 36), "{school}");
3980 assert!(school.get("slug").is_none());
3981 assert_eq!(school["status"], "active");
3982
3983 // A separate jar: the school admin is a different principal on the wire.
3984 let admin = client();
3985 let res = admin
3986 .post(format!("{base}/auth/login"))
3987 .json(&json!({ "username": "admin", "password": "secret1" }))
3988 .send()
3989 .await
3990 .unwrap();
3991 assert_eq!(res.status(), StatusCode::OK, "the seeded admin logs in");
3992
3993 let me = admin
3994 .get(format!("{base}/auth/me"))
3995 .send()
3996 .await
3997 .unwrap()
3998 .json::<Value>()
3999 .await
4000 .unwrap();
4001 assert_eq!(me["username"], "admin");
4002 assert_eq!(me["role"], "admin");
4003
4004 // The builder's own cookie is not a school cookie, over TCP either.
4005 assert_eq!(
4006 vendor
4007 .get(format!("{base}/auth/me"))
4008 .send()
4009 .await
4010 .unwrap()
4011 .status(),
4012 StatusCode::UNAUTHORIZED
4013 );
4014}
4015
4016// ---- multi-school: suspension refuses sockets too (REFUTE lane B) -----------
4017
4018/// Open a board room, optionally authenticated. Same shape as [`ws_open`].
4019async fn board_ws_open(base: &str, board_id: &str, cookie: Option<&str>) -> Result<WsStream, u16> {
4020 let url = format!("{}/boards/{board_id}/ws", base.replace("http://", "ws://"));
4021 let mut request = url.into_client_request().unwrap();
4022 if let Some(cookie) = cookie {
4023 request
4024 .headers_mut()
4025 .insert("cookie", cookie.parse().unwrap());
4026 }
4027 match connect_async(request).await {
4028 Ok((ws, _)) => Ok(ws),
4029 Err(tokio_tungstenite::tungstenite::Error::Http(response)) => {
4030 Err(response.status().as_u16())
4031 }
4032 Err(other) => panic!("unexpected handshake failure: {other}"),
4033 }
4034}
4035
4036/// Invariant 2, socket half: after the vendor suspends a school over the real
4037/// builder API, its live cookies stop opening WebSockets — both the whiteboard
4038/// room and the exam room — and start working again on a resume.
4039#[tokio::test]
4040async fn probe_a_suspended_school_refuses_websocket_upgrades() {
4041 let (base, db) = spawn_server().await;
4042
4043 let teacher = client();
4044 register(&teacher, &base, "hoca").await;
4045 promote(&db, "hoca", "teacher").await;
4046 login(&teacher, &base, "hoca").await;
4047 let cookie = raw_session_cookie(&base, "hoca").await;
4048
4049 let res = teacher
4050 .post(format!("{base}/boards"))
4051 .json(&json!({ "title": "room", "participants": [] }))
4052 .send()
4053 .await
4054 .unwrap();
4055 assert_eq!(res.status(), StatusCode::CREATED);
4056 let board = res.json::<Value>().await.unwrap()["id"]
4057 .as_str()
4058 .unwrap()
4059 .to_string();
4060
4061 // Alive: the socket opens.
4062 let ws = board_ws_open(&base, &board, Some(&cookie)).await;
4063 assert!(ws.is_ok(), "board socket before suspension: {:?}", ws.err());
4064 drop(ws);
4065
4066 // The vendor suspends the school through its own API.
4067 let vendor = client();
4068 let res = vendor
4069 .post(format!("{base}/builder/login"))
4070 .json(&json!({ "username": "operator", "password": "secret1" }))
4071 .send()
4072 .await
4073 .unwrap();
4074 assert_eq!(res.status(), StatusCode::OK);
4075 let res = vendor
4076 .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}"))
4077 .json(&json!({ "status": "suspended" }))
4078 .send()
4079 .await
4080 .unwrap();
4081 assert_eq!(res.status(), StatusCode::OK, "suspend demo");
4082 assert_eq!(res.json::<Value>().await.unwrap()["status"], "suspended");
4083
4084 // The very next HTTP request on the already-issued cookie.
4085 assert_eq!(
4086 teacher
4087 .get(format!("{base}/auth/me"))
4088 .send()
4089 .await
4090 .unwrap()
4091 .status(),
4092 StatusCode::FORBIDDEN,
4093 "a live cookie after suspension"
4094 );
4095
4096 // The whiteboard socket is refused before the upgrade.
4097 assert_eq!(
4098 board_ws_open(&base, &board, Some(&cookie)).await.err(),
4099 Some(403),
4100 "the board socket opened for a suspended school"
4101 );
4102 // So is the exam room, on any id.
4103 assert_eq!(
4104 ws_open(&base, common::ABSENT_ID, Some(&cookie)).await.err(),
4105 Some(403),
4106 "the exam socket opened for a suspended school"
4107 );
4108
4109 // Resume: the same cookie, the same socket.
4110 let res = vendor
4111 .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}"))
4112 .json(&json!({ "status": "active" }))
4113 .send()
4114 .await
4115 .unwrap();
4116 assert_eq!(res.status(), StatusCode::OK, "resume demo");
4117 assert_eq!(
4118 teacher
4119 .get(format!("{base}/auth/me"))
4120 .send()
4121 .await
4122 .unwrap()
4123 .status(),
4124 StatusCode::OK,
4125 "the same cookie after a resume"
4126 );
4127 assert!(
4128 board_ws_open(&base, &board, Some(&cookie)).await.is_ok(),
4129 "the board socket after a resume"
4130 );
4131}
4132
4133/// The K12 remodel's whole academic spine, over real TCP and a browser's cookie
4134/// jar: one term, two şubeler teaching one catalog course, and the instances
4135/// that make them two — each with its own roster, its own exam, and its own
4136/// weight in the karne. It is the plan's end-to-end scenario, and what the old
4137/// school-wide singleton could not have produced: 5-A's exam is invisible to
4138/// 5-B, and a student of 5-A is on 5-A's roster alone.
4139#[tokio::test]
4140async fn a_course_taught_by_two_subeler_is_two_instances_end_to_end() {
4141 let (base, db) = spawn_server().await;
4142 let mudur = client();
4143 let hoca = client();
4144 let veli = client();
4145 register(&mudur, &base, "mudur").await;
4146 register(&hoca, &base, "hoca").await;
4147 register(&veli, &base, "veli").await;
4148 promote(&db, "mudur", "manager").await;
4149 promote(&db, "hoca", "teacher").await;
4150 for (c, name) in [(&mudur, "mudur"), (&hoca, "hoca"), (&veli, "veli")] {
4151 login(c, &base, name).await;
4152 }
4153
4154 let id_of = |v: &Value| v["id"].as_str().unwrap().to_string();
4155 let hoca_id = id_of(
4156 &hoca
4157 .get(format!("{base}/auth/me"))
4158 .send()
4159 .await
4160 .unwrap()
4161 .json::<Value>()
4162 .await
4163 .unwrap(),
4164 );
4165 let veli_id = id_of(
4166 &veli
4167 .get(format!("{base}/auth/me"))
4168 .send()
4169 .await
4170 .unwrap()
4171 .json::<Value>()
4172 .await
4173 .unwrap(),
4174 );
4175
4176 // --- the calendar: one year, one dönem inside it ------------------------
4177 let res = mudur
4178 .post(format!("{base}/academic-years"))
4179 .json(&json!({
4180 "name": "2026-2027",
4181 "starts_at": 1_750_000_000_000_i64,
4182 "ends_at": 1_800_000_000_000_i64,
4183 }))
4184 .send()
4185 .await
4186 .unwrap();
4187 assert_eq!(res.status(), StatusCode::CREATED);
4188 let year = id_of(&res.json::<Value>().await.unwrap());
4189
4190 let res = mudur
4191 .post(format!("{base}/terms"))
4192 .json(&json!({
4193 "name": "1. Dönem",
4194 "year": year,
4195 "starts_at": 1_750_000_000_000_i64,
4196 "ends_at": 1_800_000_000_000_i64,
4197 }))
4198 .send()
4199 .await
4200 .unwrap();
4201 assert_eq!(res.status(), StatusCode::CREATED, "{}", res.status());
4202 let term = id_of(&res.json::<Value>().await.unwrap());
4203
4204 // --- two şubeler, one catalog course ------------------------------------
4205 let res = mudur
4206 .post(format!("{base}/classes"))
4207 .json(&json!({ "name": "5-A", "grade_level": 5, "year": year, "teacher_id": hoca_id }))
4208 .send()
4209 .await
4210 .unwrap();
4211 assert_eq!(res.status(), StatusCode::CREATED);
4212 let five_a = id_of(&res.json::<Value>().await.unwrap()["class"]);
4213 let res = mudur
4214 .post(format!("{base}/classes"))
4215 .json(&json!({ "name": "5-B", "grade_level": 5, "year": year }))
4216 .send()
4217 .await
4218 .unwrap();
4219 assert_eq!(res.status(), StatusCode::CREATED);
4220 let five_b = id_of(&res.json::<Value>().await.unwrap()["class"]);
4221
4222 let res = mudur
4223 .post(format!("{base}/courses"))
4224 .json(&json!({ "title": "Matematik", "kind": "course" }))
4225 .send()
4226 .await
4227 .unwrap();
4228 assert_eq!(res.status(), StatusCode::CREATED);
4229 let course = id_of(&res.json::<Value>().await.unwrap());
4230
4231 let res = mudur
4232 .post(format!("{base}/classes/{five_a}/instances"))
4233 .json(&json!({ "course_id": course }))
4234 .send()
4235 .await
4236 .unwrap();
4237 assert_eq!(res.status(), StatusCode::CREATED);
4238 let instance_a = id_of(&res.json::<Value>().await.unwrap());
4239 let res = mudur
4240 .post(format!("{base}/classes/{five_b}/instances"))
4241 .json(&json!({ "course_id": course }))
4242 .send()
4243 .await
4244 .unwrap();
4245 assert_eq!(res.status(), StatusCode::CREATED);
4246 let instance_b = id_of(&res.json::<Value>().await.unwrap());
4247 assert_ne!(
4248 instance_a, instance_b,
4249 "one course taught by two şubeler is two instances"
4250 );
4251
4252 // --- 5-A's roster is its own -------------------------------------------
4253 let res = mudur
4254 .post(format!("{base}/classes/{five_a}/members"))
4255 .json(&json!({ "user_id": veli_id }))
4256 .send()
4257 .await
4258 .unwrap();
4259 assert_eq!(res.status(), StatusCode::CREATED, "{:?}", res.status());
4260 let roster_a: Value = mudur
4261 .get(format!("{base}/instances/{instance_a}/enrollments"))
4262 .send()
4263 .await
4264 .unwrap()
4265 .json()
4266 .await
4267 .unwrap();
4268 assert_eq!(roster_a["total"], 1, "{roster_a}");
4269 assert_eq!(roster_a["items"][0]["user"]["id"], json!(veli_id));
4270 let roster_b: Value = mudur
4271 .get(format!("{base}/instances/{instance_b}/enrollments"))
4272 .send()
4273 .await
4274 .unwrap()
4275 .json()
4276 .await
4277 .unwrap();
4278 assert_eq!(roster_b["total"], 0, "5-B seated nobody: {roster_b}");
4279
4280 // --- 5-A's exam is its own ---------------------------------------------
4281 let res = hoca
4282 .post(format!("{base}/instances/{instance_a}/exams"))
4283 .json(&json!({ "title": "1. Yazılı", "kind": "yazili", "term": term }))
4284 .send()
4285 .await
4286 .unwrap();
4287 assert_eq!(res.status(), StatusCode::CREATED, "{:?}", res.status());
4288 let exam = id_of(&res.json::<Value>().await.unwrap());
4289 let blind: Value = mudur
4290 .get(format!("{base}/instances/{instance_b}/exams"))
4291 .send()
4292 .await
4293 .unwrap()
4294 .json()
4295 .await
4296 .unwrap();
4297 assert_eq!(
4298 blind["total"], 0,
4299 "5-B must not see the exam 5-A sat: {blind}"
4300 );
4301
4302 // --- the mark becomes a karne line, weighted by the instance -----------
4303 let res = hoca
4304 .post(format!("{base}/exams/{exam}/results"))
4305 .json(&json!({ "mark": 85, "user_id": veli_id }))
4306 .send()
4307 .await
4308 .unwrap();
4309 assert_eq!(res.status(), StatusCode::OK, "{:?}", res.status());
4310
4311 let res = veli
4312 .get(format!("{base}/marks/karne?term={term}"))
4313 .send()
4314 .await
4315 .unwrap();
4316 assert_eq!(res.status(), StatusCode::OK);
4317 let karne: Value = res.json().await.unwrap();
4318 assert_eq!(karne["instances"][0]["course"], json!("Matematik"));
4319 assert_eq!(karne["instances"][0]["average"], json!(85.0));
4320 assert_eq!(
4321 karne["instances"][0]["band"],
4322 json!("5"),
4323 "85 is a 5 on the default bands: {karne}"
4324 );
4325 assert_eq!(karne["instances"][0]["ders_saati"], json!(1));
4326 assert_eq!(karne["year_average"], json!(85.0));
4327 assert_eq!(karne["verdict"], json!("gecti"));
4328
4329 // The şube raises the course's weekly hours: the same mark now weighs
4330 // differently in the year's average, and the line says so.
4331 let res = mudur
4332 .patch(format!("{base}/instances/{instance_a}"))
4333 .json(&json!({ "ders_saati": 5 }))
4334 .send()
4335 .await
4336 .unwrap();
4337 assert_eq!(res.status(), StatusCode::OK);
4338 assert_eq!(res.json::<Value>().await.unwrap()["ders_saati"], json!(5));
4339 let karne: Value = veli
4340 .get(format!("{base}/marks/karne?term={term}"))
4341 .send()
4342 .await
4343 .unwrap()
4344 .json()
4345 .await
4346 .unwrap();
4347 assert_eq!(karne["instances"][0]["ders_saati"], json!(5));
4348 assert_eq!(karne["year_average"], json!(85.0));
4349
4350 // --- leaving a şube is a stint, and rejoining opens a second ------------
4351 let res = mudur
4352 .delete(format!("{base}/classes/{five_a}/members/{veli_id}"))
4353 .send()
4354 .await
4355 .unwrap();
4356 assert_eq!(res.status(), StatusCode::NO_CONTENT);
4357 let res = mudur
4358 .post(format!("{base}/classes/{five_a}/members"))
4359 .json(&json!({ "user_id": veli_id }))
4360 .send()
4361 .await
4362 .unwrap();
4363 assert_eq!(res.status(), StatusCode::CREATED, "{:?}", res.status());
4364 let members: Value = mudur
4365 .get(format!("{base}/classes/{five_a}/members"))
4366 .send()
4367 .await
4368 .unwrap()
4369 .json()
4370 .await
4371 .unwrap();
4372 assert_eq!(members["total"], 1, "one live stint reads back: {members}");
4373 let stints: i64 =
4374 sqlx::query_scalar("SELECT count(*) FROM class_member WHERE class = $1 AND app_user = $2")
4375 .bind(Uuid::parse_str(&five_a).unwrap())
4376 .bind(Uuid::parse_str(&veli_id).unwrap())
4377 .fetch_one(&db)
4378 .await
4379 .unwrap();
4380 assert_eq!(stints, 2, "the leave and the rejoin are two rows");
4381}