🔎 Turkish search folding for users, per-question exam-room errors
Browse files at this commite0f9d631c4cbbaac7570e28c0b772a2ea25c925dParent: ca93ae9- fix
- 🔎 Turkish search folding for users, per-question exam-room errors
5 changed files +156 -11
- src/domain/subject.rs +1 -1
- src/domain/user.rs +12 -7
- src/web/exam_ws.rs +47 -3
- tests/e2e.rs +23 -0
- tests/integration.rs +73 -0
src/domain/subject.rsmodified+1 -1
| @@ -137,7 +137,7 @@ impl Subject { | |||
| 137 | } | 137 | } |
| 138 | 138 | ||
| 139 | pub async fn update( | 139 | pub async fn update( |
| 140 | - mut self, | 140 | + self, |
| 141 | name: SubjectName, | 141 | name: SubjectName, |
| 142 | description: SubjectDescription, | 142 | description: SubjectDescription, |
| 143 | db: &Database, | 143 | db: &Database, |
src/domain/user.rsmodified+12 -7
| @@ -9,6 +9,7 @@ use crate::database::{Database, USER_TABLE}; | |||
| 9 | use crate::domain::preferences::{Language, Theme}; | 9 | use crate::domain::preferences::{Language, Theme}; |
| 10 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; | 10 | use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; |
| 11 | use crate::domain::role::Role; | 11 | use crate::domain::role::Role; |
| 12 | +use crate::domain::text_fold::{fold, fold_sql}; | ||
| 12 | use crate::error::{AppError, ValidationError}; | 13 | use crate::error::{AppError, ValidationError}; |
| 13 | use crate::validate::{validate_password, validate_username}; | 14 | use crate::validate::{validate_password, validate_username}; |
| 14 | 15 | ||
| @@ -301,7 +302,9 @@ impl User { | |||
| 301 | Ok(result.take::<Vec<User>>(0)?) | 302 | Ok(result.take::<Vec<User>>(0)?) |
| 302 | } | 303 | } |
| 303 | 304 | ||
| 304 | - /// Case-insensitive fragment search over username, name, and surname — | 305 | + /// Case- and diacritic-insensitive fragment search over username, name, |
| 306 | + /// and surname. Needle and columns both go through | ||
| 307 | + /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — | ||
| 305 | /// backs the user pickers. `role` narrows to one role (e.g. only students | 308 | /// backs the user pickers. `role` narrows to one role (e.g. only students |
| 306 | /// for an enroll picker); `None` searches everyone. A blank `query` | 309 | /// for an enroll picker); `None` searches everyone. A blank `query` |
| 307 | /// matches everyone, so blank + `role` is a role-scoped listing. Returns | 310 | /// matches everyone, so blank + `role` is a role-scoped listing. Returns |
| @@ -313,14 +316,16 @@ impl User { | |||
| 313 | role: Option<Role>, | 316 | role: Option<Role>, |
| 314 | db: &Database, | 317 | db: &Database, |
| 315 | ) -> Result<Vec<User>, AppError> { | 318 | ) -> Result<Vec<User>, AppError> { |
| 316 | - let needle = query.trim().to_lowercase(); | 319 | + let needle = fold(query.trim()); |
| 320 | + let text_clause = format!( | ||
| 321 | + "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", | ||
| 322 | + fold_sql("username"), | ||
| 323 | + fold_sql("name ?? ''"), | ||
| 324 | + fold_sql("surname ?? ''"), | ||
| 325 | + ); | ||
| 317 | let mut clauses = Vec::new(); | 326 | let mut clauses = Vec::new(); |
| 318 | if !needle.is_empty() { | 327 | if !needle.is_empty() { |
| 319 | - clauses.push( | 328 | + clauses.push(text_clause.as_str()); |
| 320 | - "(string::lowercase(username) CONTAINS $q \ | ||
| 321 | - OR string::lowercase(name ?? '') CONTAINS $q \ | ||
| 322 | - OR string::lowercase(surname ?? '') CONTAINS $q)", | ||
| 323 | - ); | ||
| 324 | } | 329 | } |
| 325 | if role.is_some() { | 330 | if role.is_some() { |
| 326 | clauses.push("role = $role"); | 331 | clauses.push("role = $role"); |
src/web/exam_ws.rsmodified+47 -3
| @@ -14,7 +14,11 @@ | |||
| 14 | //! - `{"type":"pong"}` | 14 | //! - `{"type":"pong"}` |
| 15 | //! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) | 15 | //! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) |
| 16 | //! - `{"type":"expired"}` then Close — the deadline passed mid-session | 16 | //! - `{"type":"expired"}` then Close — the deadline passed mid-session |
| 17 | -//! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline | 17 | +//! - `{"type":"error", message, question_id?}` — bad JSON, unknown type, |
| 18 | +//! validation, deadline. `question_id` is present only when the failure | ||
| 19 | +//! belongs to that one `answer` (its payload or its question); absent means | ||
| 20 | +//! the failure is connection- or sitting-level, so every save in flight is | ||
| 21 | +//! equally refused | ||
| 18 | //! | 22 | //! |
| 19 | //! client → server | 23 | //! client → server |
| 20 | //! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id) | 24 | //! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id) |
| @@ -368,9 +372,14 @@ async fn handle_message( | |||
| 368 | // like `save_answer_checked` — and dropped before the socket | 372 | // like `save_answer_checked` — and dropped before the socket |
| 369 | // sends, so a slow client never stalls a writer. | 373 | // sends, so a slow client never stalls a writer. |
| 370 | let guard = EXAM_LOCK.read().await; | 374 | let guard = EXAM_LOCK.read().await; |
| 375 | + // Tracks how far the gates got: only once the sitting resolved can | ||
| 376 | + // a failure possibly be about this one question rather than about | ||
| 377 | + // the room. See [`error_frame_for`]. | ||
| 378 | + let mut in_save = false; | ||
| 371 | let saved = match Exam::read(exam_id, db).await { | 379 | let saved = match Exam::read(exam_id, db).await { |
| 372 | Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { | 380 | Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { |
| 373 | Ok(attempt) => { | 381 | Ok(attempt) => { |
| 382 | + in_save = true; | ||
| 374 | save_answer_in(&exam, &attempt, &question_id, selected, text, db).await | 383 | save_answer_in(&exam, &attempt, &question_id, selected, text, db).await |
| 375 | } | 384 | } |
| 376 | Err(err) => Err(err), | 385 | Err(err) => Err(err), |
| @@ -394,7 +403,14 @@ async fn handle_message( | |||
| 394 | // right away rather than waiting out the tick. | 403 | // right away rather than waiting out the tick. |
| 395 | push_state(socket, exam_id, attempt_id, db).await | 404 | push_state(socket, exam_id, attempt_id, db).await |
| 396 | } | 405 | } |
| 397 | - Err(err) => send(socket, error_frame(&err)).await, | 406 | + Err(err) => { |
| 407 | + let attributed = in_save && attributable(&err); | ||
| 408 | + send( | ||
| 409 | + socket, | ||
| 410 | + error_frame_for(&err, attributed.then_some(question_id.as_str())), | ||
| 411 | + ) | ||
| 412 | + .await | ||
| 413 | + } | ||
| 398 | } | 414 | } |
| 399 | } | 415 | } |
| 400 | ClientMessage::Finish => { | 416 | ClientMessage::Finish => { |
| @@ -426,9 +442,34 @@ async fn handle_message( | |||
| 426 | } | 442 | } |
| 427 | } | 443 | } |
| 428 | 444 | ||
| 445 | +/// Whether a failure raised *inside* the save (past the exam and sitting | ||
| 446 | +/// gates) is about the answered question alone, so the client can fail that | ||
| 447 | +/// one save instead of every save in flight. | ||
| 448 | +/// | ||
| 449 | +/// Only the two question-shaped failures qualify: [`AppError::Validation`] | ||
| 450 | +/// (the payload doesn't fit the question — wrong kind, unknown choice, too | ||
| 451 | +/// long) and [`AppError::NotFound`] (no such question in this exam). Every | ||
| 452 | +/// other variant from the save path is about the sitter or the sitting — | ||
| 453 | +/// `Unauthorized`/`Forbidden` (promoted out of `student`, unenrolled), | ||
| 454 | +/// `Conflict` (walked out with rejoin closed) — and dooms the next save just | ||
| 455 | +/// as much as this one, so it stays unattributed and keeps fail-everything. | ||
| 456 | +/// Db/Internal stay unattributed too: a database that just failed is not a | ||
| 457 | +/// per-question fact, and over-reporting there is the safe side. | ||
| 458 | +fn attributable(err: &AppError) -> bool { | ||
| 459 | + matches!(err, AppError::Validation(_) | AppError::NotFound) | ||
| 460 | +} | ||
| 461 | + | ||
| 429 | /// The public words for an error — the same strings the HTTP layer would use, | 462 | /// The public words for an error — the same strings the HTTP layer would use, |
| 430 | /// with internals logged, never sent. | 463 | /// with internals logged, never sent. |
| 431 | fn error_frame(err: &AppError) -> Value { | 464 | fn error_frame(err: &AppError) -> Value { |
| 465 | + error_frame_for(err, None) | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +/// [`error_frame`] plus the optional blame: `question_id` when the failure | ||
| 469 | +/// belongs to one `answer` message. Absent keeps its original meaning — an | ||
| 470 | +/// unattributed failure — so a client that ignores the field behaves exactly | ||
| 471 | +/// as before. | ||
| 472 | +fn error_frame_for(err: &AppError, question: Option<&str>) -> Value { | ||
| 432 | let message = match err { | 473 | let message = match err { |
| 433 | AppError::Validation(err) => err.to_string(), | 474 | AppError::Validation(err) => err.to_string(), |
| 434 | AppError::NotFound => "not found".to_string(), | 475 | AppError::NotFound => "not found".to_string(), |
| @@ -451,5 +492,8 @@ fn error_frame(err: &AppError) -> Value { | |||
| 451 | "internal server error".to_string() | 492 | "internal server error".to_string() |
| 452 | } | 493 | } |
| 453 | }; | 494 | }; |
| 454 | - json!({ "type": "error", "message": message }) | 495 | + match question { |
| 496 | + Some(question) => json!({ "type": "error", "message": message, "question_id": question }), | ||
| 497 | + None => json!({ "type": "error", "message": message }), | ||
| 498 | + } | ||
| 455 | } | 499 | } |
tests/e2e.rsmodified+23 -0
| @@ -702,20 +702,37 @@ async fn exam_room_websocket_round_trip() { | |||
| 702 | error["message"].as_str().unwrap().contains("selected"), | 702 | error["message"].as_str().unwrap().contains("selected"), |
| 703 | "{error}" | 703 | "{error}" |
| 704 | ); | 704 | ); |
| 705 | + // ... and it names the question it belongs to, so a client with several | ||
| 706 | + // saves in flight fails only this one. | ||
| 707 | + assert_eq!(error["question_id"], question_id.as_str(), "{error}"); | ||
| 708 | + | ||
| 709 | + // A question that isn't in this exam is attributable too — that one save | ||
| 710 | + // is doomed, the others aren't. | ||
| 711 | + ws_send( | ||
| 712 | + &mut ws, | ||
| 713 | + json!({ "type": "answer", "question_id": "nosuchquestion", "text": "x" }), | ||
| 714 | + ) | ||
| 715 | + .await; | ||
| 716 | + let error = ws_frame_of_type(&mut ws, "error").await; | ||
| 717 | + assert_eq!(error["question_id"], "nosuchquestion", "{error}"); | ||
| 705 | 718 | ||
| 706 | // Junk and unknown message types too — the room shrugs and stays up. | 719 | // Junk and unknown message types too — the room shrugs and stays up. |
| 720 | + // These are frame-level, not save-level: no question to blame, so the | ||
| 721 | + // client keeps failing everything in flight. | ||
| 707 | ws.send(Message::Text("not json".into())).await.unwrap(); | 722 | ws.send(Message::Text("not json".into())).await.unwrap(); |
| 708 | let error = ws_frame_of_type(&mut ws, "error").await; | 723 | let error = ws_frame_of_type(&mut ws, "error").await; |
| 709 | assert!( | 724 | assert!( |
| 710 | error["message"].as_str().unwrap().contains("unrecognized"), | 725 | error["message"].as_str().unwrap().contains("unrecognized"), |
| 711 | "{error}" | 726 | "{error}" |
| 712 | ); | 727 | ); |
| 728 | + assert!(error.get("question_id").is_none(), "{error}"); | ||
| 713 | ws_send(&mut ws, json!({ "type": "selfdestruct" })).await; | 729 | ws_send(&mut ws, json!({ "type": "selfdestruct" })).await; |
| 714 | let error = ws_frame_of_type(&mut ws, "error").await; | 730 | let error = ws_frame_of_type(&mut ws, "error").await; |
| 715 | assert!( | 731 | assert!( |
| 716 | error["message"].as_str().unwrap().contains("unrecognized"), | 732 | error["message"].as_str().unwrap().contains("unrecognized"), |
| 717 | "{error}" | 733 | "{error}" |
| 718 | ); | 734 | ); |
| 735 | + assert!(error.get("question_id").is_none(), "{error}"); | ||
| 719 | ws_send(&mut ws, json!({ "type": "ping" })).await; | 736 | ws_send(&mut ws, json!({ "type": "ping" })).await; |
| 720 | ws_frame_of_type(&mut ws, "pong").await; | 737 | ws_frame_of_type(&mut ws, "pong").await; |
| 721 | 738 | ||
| @@ -882,6 +899,9 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { | |||
| 882 | error["message"].as_str().unwrap().contains("only students"), | 899 | error["message"].as_str().unwrap().contains("only students"), |
| 883 | "{error}" | 900 | "{error}" |
| 884 | ); | 901 | ); |
| 902 | + // Sitter-level, not question-level: the sheet is closed for every question, | ||
| 903 | + // so the frame blames none of them and the client fails everything. | ||
| 904 | + assert!(error.get("question_id").is_none(), "{error}"); | ||
| 885 | 905 | ||
| 886 | // ... and over REST — the two paths share the wall. | 906 | // ... and over REST — the two paths share the wall. |
| 887 | let res = student | 907 | let res = student |
| @@ -1371,6 +1391,9 @@ async fn exam_room_messages_bind_to_their_own_sitting() { | |||
| 1371 | error["message"].as_str().unwrap().contains("sitting"), | 1391 | error["message"].as_str().unwrap().contains("sitting"), |
| 1372 | "{error}" | 1392 | "{error}" |
| 1373 | ); | 1393 | ); |
| 1394 | + // The room's sitting is over — that's not this question's fault, so no | ||
| 1395 | + // blame is attached and the client fails every pending save. | ||
| 1396 | + assert!(error.get("question_id").is_none(), "{error}"); | ||
| 1374 | 1397 | ||
| 1375 | // A finish through the stale room must be refused — not submit sitting #2. | 1398 | // A finish through the stale room must be refused — not submit sitting #2. |
| 1376 | ws_send(&mut ws, json!({ "type": "finish" })).await; | 1399 | ws_send(&mut ws, json!({ "type": "finish" })).await; |
tests/integration.rsmodified+73 -0
| @@ -9803,6 +9803,79 @@ async fn search_rejects_a_blank_query() { | |||
| 9803 | assert_eq!(res.status, StatusCode::BAD_REQUEST); | 9803 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 9804 | } | 9804 | } |
| 9805 | 9805 | ||
| 9806 | +/// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) | ||
| 9807 | +/// lowercases to `i` + U+0307 in both Rust and SurrealQL, which used to make | ||
| 9808 | +/// `ilker` and `İLKER` two disjoint searches — a teacher typing lowercase got | ||
| 9809 | +/// an empty picker. Same defect, same fix as the bank-question search. | ||
| 9810 | +#[tokio::test] | ||
| 9811 | +async fn user_search_folds_turkish_casing() { | ||
| 9812 | + let (app, db) = app_and_db().await; | ||
| 9813 | + let teacher = login_as(&app, &db, "teacher", "teacher").await; | ||
| 9814 | + | ||
| 9815 | + let ilker = login(&app, "ilker_a").await; | ||
| 9816 | + let res = send( | ||
| 9817 | + &app, | ||
| 9818 | + "PATCH", | ||
| 9819 | + "/users/me", | ||
| 9820 | + Some(&ilker), | ||
| 9821 | + Some(json!({ "name": "İLKER", "surname": "ÇAĞLAR" })), | ||
| 9822 | + ) | ||
| 9823 | + .await; | ||
| 9824 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 9825 | + | ||
| 9826 | + let ilknur = login(&app, "ilknur_b").await; | ||
| 9827 | + let res = send( | ||
| 9828 | + &app, | ||
| 9829 | + "PATCH", | ||
| 9830 | + "/users/me", | ||
| 9831 | + Some(&ilknur), | ||
| 9832 | + Some(json!({ "name": "ilknur", "surname": "Işık" })), | ||
| 9833 | + ) | ||
| 9834 | + .await; | ||
| 9835 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 9836 | + | ||
| 9837 | + // Every casing of the shared `ilk` prefix finds both, in both directions: | ||
| 9838 | + // `ilk`, `İLK`, `ılk`, `ILK`. | ||
| 9839 | + for needle in ["ilk", "%C4%B0LK", "%C4%B1lk", "ILK"] { | ||
| 9840 | + let res = send( | ||
| 9841 | + &app, | ||
| 9842 | + "GET", | ||
| 9843 | + &format!("/users/search?q={needle}"), | ||
| 9844 | + Some(&teacher), | ||
| 9845 | + None, | ||
| 9846 | + ) | ||
| 9847 | + .await; | ||
| 9848 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 9849 | + let hits = common::items(&res.body); | ||
| 9850 | + assert_eq!(hits.len(), 2, "needle {needle} missed: {hits:?}"); | ||
| 9851 | + } | ||
| 9852 | + | ||
| 9853 | + // Diacritics fold on the surname too, both ways (`ÇAĞLAR` ↔ `caglar`, | ||
| 9854 | + // `Işık` ↔ `isik`). | ||
| 9855 | + for (needle, username) in [ | ||
| 9856 | + ("caglar", "ilker_a"), | ||
| 9857 | + ("%C3%A7a%C4%9Flar", "ilker_a"), | ||
| 9858 | + ("isik", "ilknur_b"), | ||
| 9859 | + ("I%C5%9F%C4%B1k", "ilknur_b"), | ||
| 9860 | + ] { | ||
| 9861 | + let res = send( | ||
| 9862 | + &app, | ||
| 9863 | + "GET", | ||
| 9864 | + &format!("/users/search?q={needle}"), | ||
| 9865 | + Some(&teacher), | ||
| 9866 | + None, | ||
| 9867 | + ) | ||
| 9868 | + .await; | ||
| 9869 | + let hits = common::items(&res.body); | ||
| 9870 | + assert_eq!(hits.len(), 1, "needle {needle} missed: {hits:?}"); | ||
| 9871 | + assert_eq!(hits[0]["username"], username); | ||
| 9872 | + } | ||
| 9873 | + | ||
| 9874 | + // Folding widens the match, it does not match everything. | ||
| 9875 | + let res = send(&app, "GET", "/users/search?q=zeynep", Some(&teacher), None).await; | ||
| 9876 | + assert_eq!(common::items(&res.body).len(), 0); | ||
| 9877 | +} | ||
| 9878 | + | ||
| 9806 | // --- courses: catalog dedup ------------------------------------------------- | 9879 | // --- courses: catalog dedup ------------------------------------------------- |
| 9807 | 9880 | ||
| 9808 | /// A user who both created a course (while staff) and is enrolled in it (after | 9881 | /// A user who both created a course (while staff) and is enrolled in it (after |