From e0f9d631c4cbbaac7570e28c0b772a2ea25c925d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 25 Jul 2026 04:50:18 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=94=8E=20Turkish=20search=20foldin?= =?UTF-8?q?g=20for=20users,=20per-question=20exam-room=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - User::search folded its needle with Rust to_lowercase and its columns with SurrealQL string::lowercase; both turn İ into i + U+0307, so searching "ilker" never found "İLKER". It now runs both sides through the shared text_fold table, like the question bank already does - exam-room error frames carry question_id when the failure belongs to one save — a validation reject or an unknown question, raised inside the save past the sitting gates. The client could not tell which save failed and had to fail every one in flight - auth, conflict, malformed-frame and database errors stay unattributed on purpose: they doom the next save too, and a failed database is not a per-question fact. An absent question_id keeps its old meaning - Subject::update is field-scoped: the handler holds no lock across its read and write, so a whole-row save reverted a concurrent edit of the other field - annotate the three whole-row saves that genuinely cannot be raced (exam update holds EXAM_LOCK across the read; the two image upserts build their struct in place under a deterministic slot id) --- src/domain/subject.rs | 2 +- src/domain/user.rs | 19 ++++++----- src/web/exam_ws.rs | 50 +++++++++++++++++++++++++++-- tests/e2e.rs | 23 ++++++++++++++ tests/integration.rs | 73 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 156 insertions(+), 11 deletions(-) diff --git a/src/domain/subject.rs b/src/domain/subject.rs index f3c8f8e..2d6eae6 100644 --- a/src/domain/subject.rs +++ b/src/domain/subject.rs @@ -137,7 +137,7 @@ impl Subject { } pub async fn update( - mut self, + self, name: SubjectName, description: SubjectDescription, db: &Database, diff --git a/src/domain/user.rs b/src/domain/user.rs index 75d3439..d37556a 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -9,6 +9,7 @@ use crate::database::{Database, USER_TABLE}; use crate::domain::preferences::{Language, Theme}; use crate::domain::profile::{BirthDate, Email, PersonName, Phone}; use crate::domain::role::Role; +use crate::domain::text_fold::{fold, fold_sql}; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_password, validate_username}; @@ -301,7 +302,9 @@ impl User { Ok(result.take::>(0)?) } - /// Case-insensitive fragment search over username, name, and surname — + /// Case- and diacritic-insensitive fragment search over username, name, + /// and surname. Needle and columns both go through + /// [`crate::domain::text_fold`], so `ilker` finds `İLKER` and back — /// backs the user pickers. `role` narrows to one role (e.g. only students /// for an enroll picker); `None` searches everyone. A blank `query` /// matches everyone, so blank + `role` is a role-scoped listing. Returns @@ -313,14 +316,16 @@ impl User { role: Option, db: &Database, ) -> Result, AppError> { - let needle = query.trim().to_lowercase(); + let needle = fold(query.trim()); + let text_clause = format!( + "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", + fold_sql("username"), + fold_sql("name ?? ''"), + fold_sql("surname ?? ''"), + ); let mut clauses = Vec::new(); if !needle.is_empty() { - clauses.push( - "(string::lowercase(username) CONTAINS $q \ - OR string::lowercase(name ?? '') CONTAINS $q \ - OR string::lowercase(surname ?? '') CONTAINS $q)", - ); + clauses.push(text_clause.as_str()); } if role.is_some() { clauses.push("role = $role"); diff --git a/src/web/exam_ws.rs b/src/web/exam_ws.rs index 3be9692..b27e00c 100644 --- a/src/web/exam_ws.rs +++ b/src/web/exam_ws.rs @@ -14,7 +14,11 @@ //! - `{"type":"pong"}` //! - `{"type":"finished", finished_at}` then Close — submitted (here or elsewhere) //! - `{"type":"expired"}` then Close — the deadline passed mid-session -//! - `{"type":"error", message}` — bad JSON, unknown type, validation, deadline +//! - `{"type":"error", message, question_id?}` — bad JSON, unknown type, +//! validation, deadline. `question_id` is present only when the failure +//! belongs to that one `answer` (its payload or its question); absent means +//! the failure is connection- or sitting-level, so every save in flight is +//! equally refused //! //! client → server //! - `{"type":"answer", question_id, selected? | text?}` (`selected` = choice id) @@ -368,9 +372,14 @@ async fn handle_message( // like `save_answer_checked` — and dropped before the socket // sends, so a slow client never stalls a writer. let guard = EXAM_LOCK.read().await; + // Tracks how far the gates got: only once the sitting resolved can + // a failure possibly be about this one question rather than about + // the room. See [`error_frame_for`]. + let mut in_save = false; let saved = match Exam::read(exam_id, db).await { Ok(Some(exam)) => match writable_room_attempt(&exam, attempt_id, user, db).await { Ok(attempt) => { + in_save = true; save_answer_in(&exam, &attempt, &question_id, selected, text, db).await } Err(err) => Err(err), @@ -394,7 +403,14 @@ async fn handle_message( // right away rather than waiting out the tick. push_state(socket, exam_id, attempt_id, db).await } - Err(err) => send(socket, error_frame(&err)).await, + Err(err) => { + let attributed = in_save && attributable(&err); + send( + socket, + error_frame_for(&err, attributed.then_some(question_id.as_str())), + ) + .await + } } } ClientMessage::Finish => { @@ -426,9 +442,34 @@ async fn handle_message( } } +/// Whether a failure raised *inside* the save (past the exam and sitting +/// gates) is about the answered question alone, so the client can fail that +/// one save instead of every save in flight. +/// +/// Only the two question-shaped failures qualify: [`AppError::Validation`] +/// (the payload doesn't fit the question — wrong kind, unknown choice, too +/// long) and [`AppError::NotFound`] (no such question in this exam). Every +/// other variant from the save path is about the sitter or the sitting — +/// `Unauthorized`/`Forbidden` (promoted out of `student`, unenrolled), +/// `Conflict` (walked out with rejoin closed) — and dooms the next save just +/// as much as this one, so it stays unattributed and keeps fail-everything. +/// Db/Internal stay unattributed too: a database that just failed is not a +/// per-question fact, and over-reporting there is the safe side. +fn attributable(err: &AppError) -> bool { + matches!(err, AppError::Validation(_) | AppError::NotFound) +} + /// The public words for an error — the same strings the HTTP layer would use, /// with internals logged, never sent. fn error_frame(err: &AppError) -> Value { + error_frame_for(err, None) +} + +/// [`error_frame`] plus the optional blame: `question_id` when the failure +/// belongs to one `answer` message. Absent keeps its original meaning — an +/// unattributed failure — so a client that ignores the field behaves exactly +/// as before. +fn error_frame_for(err: &AppError, question: Option<&str>) -> Value { let message = match err { AppError::Validation(err) => err.to_string(), AppError::NotFound => "not found".to_string(), @@ -451,5 +492,8 @@ fn error_frame(err: &AppError) -> Value { "internal server error".to_string() } }; - json!({ "type": "error", "message": message }) + match question { + Some(question) => json!({ "type": "error", "message": message, "question_id": question }), + None => json!({ "type": "error", "message": message }), + } } diff --git a/tests/e2e.rs b/tests/e2e.rs index 1c598e9..95416f2 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -702,20 +702,37 @@ async fn exam_room_websocket_round_trip() { error["message"].as_str().unwrap().contains("selected"), "{error}" ); + // ... and it names the question it belongs to, so a client with several + // saves in flight fails only this one. + assert_eq!(error["question_id"], question_id.as_str(), "{error}"); + + // A question that isn't in this exam is attributable too — that one save + // is doomed, the others aren't. + ws_send( + &mut ws, + json!({ "type": "answer", "question_id": "nosuchquestion", "text": "x" }), + ) + .await; + let error = ws_frame_of_type(&mut ws, "error").await; + assert_eq!(error["question_id"], "nosuchquestion", "{error}"); // Junk and unknown message types too — the room shrugs and stays up. + // These are frame-level, not save-level: no question to blame, so the + // client keeps failing everything in flight. ws.send(Message::Text("not json".into())).await.unwrap(); let error = ws_frame_of_type(&mut ws, "error").await; assert!( error["message"].as_str().unwrap().contains("unrecognized"), "{error}" ); + assert!(error.get("question_id").is_none(), "{error}"); ws_send(&mut ws, json!({ "type": "selfdestruct" })).await; let error = ws_frame_of_type(&mut ws, "error").await; assert!( error["message"].as_str().unwrap().contains("unrecognized"), "{error}" ); + assert!(error.get("question_id").is_none(), "{error}"); ws_send(&mut ws, json!({ "type": "ping" })).await; ws_frame_of_type(&mut ws, "pong").await; @@ -882,6 +899,9 @@ async fn exam_room_promotion_mid_exam_closes_the_sheet() { error["message"].as_str().unwrap().contains("only students"), "{error}" ); + // Sitter-level, not question-level: the sheet is closed for every question, + // so the frame blames none of them and the client fails everything. + assert!(error.get("question_id").is_none(), "{error}"); // ... and over REST — the two paths share the wall. let res = student @@ -1371,6 +1391,9 @@ async fn exam_room_messages_bind_to_their_own_sitting() { error["message"].as_str().unwrap().contains("sitting"), "{error}" ); + // The room's sitting is over — that's not this question's fault, so no + // blame is attached and the client fails every pending save. + assert!(error.get("question_id").is_none(), "{error}"); // A finish through the stale room must be refused — not submit sitting #2. ws_send(&mut ws, json!({ "type": "finish" })).await; diff --git a/tests/integration.rs b/tests/integration.rs index c5a45ee..92bfd6c 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -9803,6 +9803,79 @@ async fn search_rejects_a_blank_query() { assert_eq!(res.status, StatusCode::BAD_REQUEST); } +/// The app is EN/TR, so the user picker must fold Turkish casing: `İ` (U+0130) +/// lowercases to `i` + U+0307 in both Rust and SurrealQL, which used to make +/// `ilker` and `İLKER` two disjoint searches — a teacher typing lowercase got +/// an empty picker. Same defect, same fix as the bank-question search. +#[tokio::test] +async fn user_search_folds_turkish_casing() { + let (app, db) = app_and_db().await; + let teacher = login_as(&app, &db, "teacher", "teacher").await; + + let ilker = login(&app, "ilker_a").await; + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ilker), + Some(json!({ "name": "İLKER", "surname": "ÇAĞLAR" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + let ilknur = login(&app, "ilknur_b").await; + let res = send( + &app, + "PATCH", + "/users/me", + Some(&ilknur), + Some(json!({ "name": "ilknur", "surname": "Işık" })), + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + + // Every casing of the shared `ilk` prefix finds both, in both directions: + // `ilk`, `İLK`, `ılk`, `ILK`. + for needle in ["ilk", "%C4%B0LK", "%C4%B1lk", "ILK"] { + let res = send( + &app, + "GET", + &format!("/users/search?q={needle}"), + Some(&teacher), + None, + ) + .await; + assert_eq!(res.status, StatusCode::OK, "{}", res.body); + let hits = common::items(&res.body); + assert_eq!(hits.len(), 2, "needle {needle} missed: {hits:?}"); + } + + // Diacritics fold on the surname too, both ways (`ÇAĞLAR` ↔ `caglar`, + // `Işık` ↔ `isik`). + for (needle, username) in [ + ("caglar", "ilker_a"), + ("%C3%A7a%C4%9Flar", "ilker_a"), + ("isik", "ilknur_b"), + ("I%C5%9F%C4%B1k", "ilknur_b"), + ] { + let res = send( + &app, + "GET", + &format!("/users/search?q={needle}"), + Some(&teacher), + None, + ) + .await; + let hits = common::items(&res.body); + assert_eq!(hits.len(), 1, "needle {needle} missed: {hits:?}"); + assert_eq!(hits[0]["username"], username); + } + + // Folding widens the match, it does not match everything. + let res = send(&app, "GET", "/users/search?q=zeynep", Some(&teacher), None).await; + assert_eq!(common::items(&res.body).len(), 0); +} + // --- courses: catalog dedup ------------------------------------------------- /// A user who both created a course (while staff) and is enrolled in it (after