From d0c4bb170c727083e4694af61a5bff48fcfff79c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 14:50:56 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20bank=5Fquestion?= =?UTF-8?q?,=20bank=5Fquestion=5Fimage,=20pool=5Fquestion,=20solution=20in?= =?UTF-8?q?to=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/constant.rs | 4 +- src/db/bank_question.rs | 802 +++++++++++++++++++++++++++ src/db/bank_question_image.rs | 473 ++++++++++++++++ src/db/mod.rs | 4 + src/db/pool_question.rs | 623 +++++++++++++++++++++ src/db/solution.rs | 386 +++++++++++++ src/domain/bank_question.rs | 836 +---------------------------- src/domain/bank_question_image.rs | 475 +--------------- src/domain/pomodoro.rs | 2 +- src/domain/pool_question.rs | 685 +---------------------- src/domain/solution.rs | 396 +------------- src/service/bank_question.rs | 178 ++++++ src/service/bank_question_image.rs | 63 +++ src/service/mod.rs | 4 + src/service/pool_question.rs | 86 +++ src/service/solution.rs | 80 +++ src/web/bank_questions.rs | 164 +++--- src/web/exams/mod.rs | 2 - src/web/exams/questions.rs | 20 +- src/web/questions.rs | 54 +- tests/integration.rs | 29 +- tests/regress_bank_images.rs | 21 +- 22 files changed, 2900 insertions(+), 2487 deletions(-) create mode 100644 src/db/bank_question.rs create mode 100644 src/db/bank_question_image.rs create mode 100644 src/db/pool_question.rs create mode 100644 src/db/solution.rs create mode 100644 src/service/bank_question.rs create mode 100644 src/service/bank_question_image.rs create mode 100644 src/service/pool_question.rs create mode 100644 src/service/solution.rs diff --git a/src/constant.rs b/src/constant.rs index 994c2b8..e6856af 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -850,7 +850,7 @@ pub const MIN_CHUNK_CHARS: usize = 24; // --- query text -------------------------------------------------------- -/// The whole of [`crate::domain::bank_question::BankQuestion::usage_counts`]: +/// The whole of [`crate::db::bank_question::usage_counts`]: /// **one** statement (no `;`), so a page of templates costs one round trip no /// matter how long it is. Named so a test can assert that, since a per-row /// `count()` is exactly the N+1 this page was cleaned of once. @@ -1024,7 +1024,7 @@ pub const POMODORO_COUNTED_TODAY_FIELD: &str = "pomodoro_counted_today"; /// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at /// least this long, and it must be within the day's quota. /// -/// Without them the pair is the farm [`crate::domain::pool_question::PoolQuestion::approve`] +/// Without them the pair is the farm [`crate::db::pool_question::approve`] /// reasons about from the other end: `finish` is self-service, a stint costs two /// requests and no second person, so a counter moved once per round-trip is /// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`, diff --git a/src/db/bank_question.rs b/src/db/bank_question.rs new file mode 100644 index 0000000..40d373d --- /dev/null +++ b/src/db/bank_question.rs @@ -0,0 +1,802 @@ +//! The `bank_question` table: template creates, the visibility-gated paged +//! listing, the page-wide usage tally, the compare-and-set every PATCH writes +//! through, and the delete that sweeps the slot table and clears both +//! provenance links in one transaction. The PATCH re-derive lives in +//! [`crate::service::bank_question`]; the pure entity and newtypes in +//! [`crate::domain::bank_question`]. + +use std::collections::HashMap; + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::constant::USAGE_COUNTS_SQL; +use crate::database::{Database, transaction_with_retry, write_with_retry}; +use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{QuestionPoints, QuestionSpec, QuestionText}; +use crate::domain::subject::SubjectId; +use crate::domain::text_fold::{search_fold, search_fold_sql}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// One `GROUP BY from_bank` row of [`usage_counts`]. +#[derive(SurrealValue)] +struct UsageCount { + from_bank: BankQuestionId, + n: i64, +} + +/// What one [`delete`] transaction removed — the template (an empty list once +/// someone else deleted it first) and the image rows swept with it. +#[derive(SurrealValue)] +struct DeleteOutcome { + question: Vec, + images: Vec, +} + +pub async fn create( + db: &Database, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + insert(db, owner, subject, text, points, spec, None).await +} + +/// Like [`create`], but records the origin exam the template was saved from +/// (`POST …/questions/{qid}/to-bank`). +pub async fn create_from_exam( + db: &Database, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: ExamId, +) -> Result { + insert(db, owner, subject, text, points, spec, Some(source)).await +} + +#[allow(clippy::too_many_arguments)] +async fn insert( + db: &Database, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source_exam: Option, +) -> Result { + let question = BankQuestion::from_parts( + BankQuestionId::generate(), + owner, + // Creation always carries a validated subject; only a subject + // delete ever clears it. + Some(subject), + text, + points, + spec, + source_exam, + // Never published on creation — publishing is its own PATCH. + BankVisibility::default(), + Timestamp::now(), + ); + let created: Option = db.create(question.id.record()).content(question).await?; + created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) +} + +pub async fn read(db: &Database, id: &BankQuestionId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// One page of the bank the caller may see, **newest first** (ULID ids sort by +/// creation, so `id DESC` is newest-first) — plus the total row count under +/// the same filters, so a client can page past the window. +/// +/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: +/// the old version read the whole table and sliced it in memory, which hid +/// every template past the client's first page. `q` is a case- and +/// diacritic-insensitive fragment of the question text (blank = no text +/// filter): needle and column both go through +/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. +/// +/// `visible_to` is the security filter, and it is a WHERE clause like every +/// other one — never a post-filter, or `total` would count templates the +/// caller can't have and paging would return short pages of them: +/// `Some(me)` sees the school-published templates plus their own, +/// `None` (admins only) sees everything. +/// +/// `visibility` is the *user's* filter ("only mine" / "shared with the +/// school") and is ANDed on top of that gate, so it can only ever narrow: +/// `school` still hides another teacher's private rows, and `private` +/// intersected with the gate leaves exactly the caller's own drafts. It +/// joins the same `clauses` vec as the rest, so `total` honours it too — +/// a count that ignored it would break paging. +// Flat filter args, like every other `list` here — a builder struct for +// four `Option`s and a window would be more machinery than the call sites. +#[allow(clippy::too_many_arguments)] +pub async fn list( + db: &Database, + visible_to: Option<&UserId>, + owner: Option<&UserId>, + subject: Option<&SubjectId>, + visibility: Option<&BankVisibility>, + q: Option<&str>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); + let mut clauses = Vec::new(); + if visible_to.is_some() { + clauses.push("(visibility = 'school' OR owner = $viewer)"); + } + if visibility.is_some() { + clauses.push("visibility = $visibility"); + } + if owner.is_some() { + clauses.push("owner = $owner"); + } + if subject.is_some() { + clauses.push("subject = $subject"); + } + let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); + if needle.is_some() { + clauses.push(text_clause.as_str()); + } + let where_clause = if clauses.is_empty() { + "true".to_string() + } else { + clauses.join(" AND ") + }; + // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. + let window = match limit { + Some(_) => "LIMIT $limit START $offset", + None => "START $offset", + }; + // The count runs over the *same* WHERE, so `total` can never disagree + // with what paging through the list actually yields. + let mut query = db + .query(format!( + "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; + SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" + )) + .bind(("offset", offset)); + if let Some(viewer) = visible_to { + query = query.bind(("viewer", viewer.record())); + } + if let Some(visibility) = visibility { + query = query.bind(("visibility", visibility.as_str().to_string())); + } + if let Some(owner) = owner { + query = query.bind(("owner", owner.record())); + } + if let Some(subject) = subject { + query = query.bind(("subject", subject.record())); + } + if let Some(needle) = needle { + query = query.bind(("q", needle)); + } + if let Some(limit) = limit { + query = query.bind(("limit", limit)); + } + let mut result = query.await?.check()?; + let questions = result.take::>(0)?; + // `GROUP ALL` yields no row at all when nothing matched. + let total = result.take::>(1)?.first().copied().unwrap_or(0); + Ok((questions, total)) +} + +/// How many exam questions were instantiated from each of `ids` — the +/// `from_bank` side of the provenance link, tallied for a whole page in +/// **one** grouped query (a `count()` per row would be the N+1 this page +/// already had removed once). Keys are template record keys; a template +/// nobody ever used has no entry at all, so the caller reads a miss as +/// zero — and the UI can stay quiet rather than print "0". +/// +/// Counts *questions*, not distinct exams: one exam that inserted the same +/// template twice counts twice, which is what "copies made from this +/// template" means and what the divergence trap is actually about. +pub async fn usage_counts( + db: &Database, + ids: &[&BankQuestionId], +) -> Result, AppError> { + if ids.is_empty() { + return Ok(HashMap::new()); + } + let records: Vec = ids.iter().map(|id| id.record()).collect(); + let mut result = db + .query(USAGE_COUNTS_SQL) + .bind(("ids", records)) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .map(|row| (row.from_bank.key().to_string(), row.n)) + .collect()) +} + +/// Write the editable fields of the template, but only while the row still +/// reads as the snapshot `expected` was loaded from — `None` means a concurrent +/// edit (or the subject-delete cascade that clears `subject`) landed inside +/// the handler's read-merge window, so nothing was written: reload, +/// re-merge, retry. This is a genuine read-modify-write — every editable +/// field is re-stated from the snapshot, and the kind/choices/correct trio +/// has to be (a text-only edit re-submits the stored options *with their +/// ids* so each keeps its picture) — so without the compare-and-set the +/// later writer silently reverts the earlier one — and the window is a +/// database round trip wide, which is exactly how far apart two concurrent +/// requests to this one process can sit. +/// +/// Every field the merge re-states is in the guard, which is the same list +/// the `SET` writes. `choices` is compared whole: its objects carry two +/// required string keys, so none is ever dropped for being `NONE` (the trap +/// [`crate::db::settings::save_if_unchanged`] works around). +/// +/// Rides [`write_with_retry`] because an image write now moves this row too +/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the +/// same instant makes the store answer "conflict, retry", and a bare +/// `check()` would turn that into a 500 for an edit that only had to be +/// re-sent. A lost round writes nothing, and the guard is re-evaluated on +/// the next one, so a genuine stale merge still comes back as `None`. +/// Admissible: an `UPDATE` can never answer "already exists". +pub async fn update_if_unchanged( + db: &Database, + expected: BankQuestion, + subject: Option, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + visibility: BankVisibility, +) -> Result, AppError> { + let (kind, choices, correct) = spec.into_parts(); + let rows: Vec = write_with_retry( + db, + "UPDATE $id SET subject = $subject, text = $text, points = $points, + kind = $kind, choices = $choices, correct = $correct, + visibility = $visibility + WHERE subject = $was_subject AND text = $was_text + AND points = $was_points AND kind = $was_kind + AND choices = $was_choices AND correct = $was_correct + AND visibility = $was_visibility + RETURN AFTER", + &[ + ( + "was_subject".into(), + expected.subject.clone().map(|s| s.record()).into_value(), + ), + ("was_text".into(), expected.text.clone().into_value()), + ("was_points".into(), expected.points.into_value()), + ("was_kind".into(), expected.kind.clone().into_value()), + ("was_choices".into(), expected.choices.clone().into_value()), + ("was_correct".into(), expected.correct.clone().into_value()), + ( + "was_visibility".into(), + expected.visibility.clone().into_value(), + ), + ("id".into(), expected.id.record().into_value()), + ("subject".into(), subject.map(|s| s.record()).into_value()), + ("text".into(), text.into_value()), + ("points".into(), points.into_value()), + ("kind".into(), kind.into_value()), + ("choices".into(), choices.into_value()), + ("correct".into(), correct.into_value()), + ("visibility".into(), visibility.into_value()), + ], + ) + .await?; + Ok(rows.into_iter().next()) +} + +/// Delete the template and cascade-remove its bank images, so none points +/// at a missing template. Bank rows have no answers. The image rows this +/// actually removed come back with it: the blobs are the web layer's to +/// take off disk, but only for *these* rows — an upload that committed +/// after the caller listed the template's images is swept here too, and a +/// pre-read snapshot would strand its blob for good +/// ([`crate::db::note::delete`]'s story, this domain over). +/// +/// Children first, in one transaction: as two queries, a failure between +/// them left image rows swept under a template that survived, or (the other +/// order) a template gone with its images still there. Rides the retry +/// because an image write now moves this very row +/// ([`crate::db::bank_question_image::upsert`]) — the two contend by +/// design, and a lost round through a bare `check()` would be a 500 for a +/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE` +/// in here can answer "already exists". +/// +/// Exam questions tied to this template keep living: only their provenance +/// links are cleared, field-scoped (never a whole-row save — the question +/// isn't ours and may be edited concurrently), so nothing can read a link to +/// a template that no longer exists. *Both* directions point at a template, +/// so both are cleared: `from_bank` on the questions instantiated from it, +/// and `banked_as` on the question it was saved out of. +pub async fn delete( + db: &Database, + target: BankQuestion, +) -> Result<(BankQuestion, Vec), AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); + UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; + UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; + LET $gone = (DELETE $b RETURN BEFORE); + RETURN { question: $gone, images: $images }; + COMMIT TRANSACTION;", + &[("b".into(), target.id.record().into_value())], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; + let question = outcome + .question + .into_iter() + .next() + .ok_or(AppError::NotFound)?; + Ok((question, outcome.images)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; + + fn spec() -> QuestionSpec { + use crate::domain::exam_question::{ChoiceInput, QuestionKind}; + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some(vec![ + ChoiceInput { + id: Some("a".into()), + text: "yes".into(), + }, + ChoiceInput { + id: Some("b".into()), + text: "no".into(), + }, + ]), + Some("b".into()), + &[], + ) + .unwrap() + } + + /// A row stored before `visibility` existed has no such key — it must decode + /// as `private`, the safe value. Asserted on the decoder itself, so no + /// schema DEFAULT can paper over it: a `school` default here would publish + /// every pre-existing template in the school at once. + #[tokio::test] + async fn a_row_without_the_field_decodes_private() { + use surrealdb::types::Value; + + let db = crate::database::init_mem().await.unwrap(); + let question = create( + &db, + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("q").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); + + let mut stored = question.into_value(); + let Value::Object(map) = &mut stored else { + panic!("a bank question serializes to an object"); + }; + assert!(map.remove("visibility").is_some()); + let old = BankQuestion::from_value(stored).unwrap(); + assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); + assert!(!old.get_visibility().is_school()); + } + + /// The visibility gate is a WHERE clause, so `total` counts exactly what the + /// page can contain — never someone else's private templates. + #[tokio::test] + async fn list_hides_private_templates_from_others() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let other = UserId::generate(); + let private = create( + &db, + owner.clone(), + SubjectId::generate(), + QuestionText::try_new("secret").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + let published = create( + &db, + owner.clone(), + SubjectId::generate(), + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + let subject = published.get_subject().cloned(); + update_if_unchanged( + &db, + published, + subject, + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), + ) + .await + .unwrap(); + + // The stranger sees the published one alone, and `total` agrees. + let (items, total) = list(&db, Some(&other), None, None, None, None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "shared"); + // The owner sees both; an admin (`None`) too. + let (items, total) = list(&db, Some(&owner), None, None, None, None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (2, 2)); + let (items, total) = list(&db, None, None, None, None, None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (2, 2)); + // An explicit `owner=` filter can't widen the gate. + let (items, total) = list(&db, Some(&other), Some(&owner), None, None, None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); + } + + /// The bite test for the compare-and-set that replaced the writer lease of + /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has + /// since moved past must be refused, not written — otherwise it reverts + /// whatever landed in between. Asserts the *stored* row, never a race + /// outcome: the in-memory engine can drop one of two concurrent writes and + /// still answer `Ok`. + #[tokio::test] + async fn a_merge_built_on_a_stale_snapshot_is_refused() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let stale = create( + &db, + owner, + SubjectId::generate(), + QuestionText::try_new("first").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + // Somebody else's edit lands on the row this snapshot came from. + let landed = update_if_unchanged( + &db, + stale.clone(), + None, + QuestionText::try_new("theirs").unwrap(), + QuestionPoints::try_new(2).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), + ) + .await + .unwrap(); + assert!(landed.is_some(), "the first write is on a fresh snapshot"); + + let refused = update_if_unchanged( + &db, + stale, + None, + QuestionText::try_new("mine").unwrap(), + QuestionPoints::try_new(3).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), + ) + .await + .unwrap(); + assert!(refused.is_none(), "a stale merge must not be written"); + let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_text().as_str(), "theirs"); + assert_eq!(stored.get_points().as_i64(), 2); + } + + /// The `visibility` filter ANDs onto the security gate, so it narrows and + /// never widens: a stranger asking for `school` still can't see a private + /// row, and `private` means "my own drafts" for everyone but an admin. + #[tokio::test] + async fn visibility_filter_narrows_never_widens() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let other = UserId::generate(); + let mine = |text: &str| { + create( + &db, + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(text).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + }; + mine("draft").await.unwrap(); + let published = mine("shared").await.unwrap(); + let subject = published.get_subject().cloned(); + update_if_unchanged( + &db, + published, + subject, + QuestionText::try_new("shared").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), + ) + .await + .unwrap(); + let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(); + let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(); + + // Owner: `private` = their drafts, `school` = the published one. + let (items, total) = list(&db, Some(&owner), None, None, Some(&private), None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "draft"); + let (items, total) = list(&db, Some(&owner), None, None, Some(&school), None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + assert_eq!(items[0].get_text().as_str(), "shared"); + // A stranger's `private` is empty — never someone else's draft. + let (items, total) = list(&db, Some(&other), None, None, Some(&private), None, None, 0) + .await + .unwrap(); + assert!(items.is_empty()); + assert_eq!(total, 0); + // …and their `school` stops at the published one, gate intact. + let (items, total) = list(&db, Some(&other), None, None, Some(&school), None, None, 0) + .await + .unwrap(); + assert_eq!((items.len(), total), (1, 1)); + // Composes with the other filters: right owner, wrong visibility. + let (items, total) = list( + &db, + Some(&owner), + Some(&owner), + None, + Some(&school), + Some("draft"), + None, + 0, + ) + .await + .unwrap(); + assert!(items.is_empty()); + assert_eq!(total, 0); + } + + /// The whole page's tally in one grouped statement: right number per + /// template, unused templates absent (so the UI prints nothing rather than + /// "0"), and questions authored by hand never counted. + #[tokio::test] + async fn usage_counts_tallies_a_page_in_one_statement() { + // One statement, so a page costs one round trip — a `;` here would mean + // the per-row N+1 crept back in. + assert!( + !USAGE_COUNTS_SQL.contains(';'), + "usage_counts must be one statement" + ); + + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + let template = |text: &str| { + create( + &db, + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(text).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + }; + let used_twice = template("twice").await.unwrap(); + let used_once = template("once").await.unwrap(); + let unused = template("never").await.unwrap(); + + // Real exam rows: instantiating a template moves the exam's counter + // (what keeps a question from outliving its exam), so a minted id + // nothing wrote is a 404. + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); + let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); + // A real subject row: an exam question claims a reference on its + // subject, so a minted id it never wrote would be refused. + let subject = crate::domain::subject::Subject::create( + &crate::db::course::a_test_course(&db).await, + crate::domain::subject::SubjectName::try_new("topic").unwrap(), + crate::domain::subject::SubjectDescription::try_new("").unwrap(), + &db, + ) + .await + .unwrap(); + async fn instantiate( + exam: &ExamId, + subject: &SubjectId, + source: &BankQuestion, + db: &Database, + ) { + crate::db::exam_question::create_from_bank( + db, + exam, + subject.clone(), + source.get_text().clone(), + source.get_points(), + source.spec(), + source.get_id().clone(), + ) + .await + .unwrap(); + } + // Two copies of the same template, in two different exams. + instantiate(&exam, subject.get_id(), &used_twice, &db).await; + instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; + instantiate(&exam, subject.get_id(), &used_once, &db).await; + // A hand-authored question has no `from_bank` and must not be tallied. + crate::db::exam_question::create( + &db, + &exam, + subject.get_id().clone(), + QuestionText::try_new("mine").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + + let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; + let counts = usage_counts(&db, &ids).await.unwrap(); + assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); + assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); + assert_eq!( + counts.get(unused.get_id().key()), + None, + "unused stays absent" + ); + assert_eq!(counts.len(), 2); + + // A template outside the page is never counted into it. + let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap(); + assert_eq!(narrow.len(), 1); + assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); + // An empty page asks nothing at all. + assert!(usage_counts(&db, &[]).await.unwrap().is_empty()); + } + + #[tokio::test] + async fn list_is_school_wide() { + let db = crate::database::init_mem().await.unwrap(); + for _ in 0..2 { + create( + &db, + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("q").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + } + // Different owners, yet both listed. + let (items, total) = list(&db, None, None, None, None, None, None, 0) + .await + .unwrap(); + assert_eq!(items.len(), 2); + assert_eq!(total, 2); + } + + /// The window is SQL, not an in-memory slice, and `total` ignores it. + #[tokio::test] + async fn list_pages_newest_first_and_filters_text() { + let db = crate::database::init_mem().await.unwrap(); + let owner = UserId::generate(); + for i in 0..5 { + create( + &db, + owner.clone(), + SubjectId::generate(), + QuestionText::try_new(&format!("question {i}")).unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + } + let (page, total) = list(&db, None, None, None, None, None, Some(2), 0) + .await + .unwrap(); + assert_eq!(total, 5); + assert_eq!(page.len(), 2); + // Newest first: the last-created row leads. + assert_eq!(page[0].get_text().as_str(), "question 4"); + // The tail is reachable by offset. + let (tail, _) = list(&db, None, None, None, None, None, Some(2), 4) + .await + .unwrap(); + assert_eq!(tail[0].get_text().as_str(), "question 0"); + // Text filter runs in SQL, case-insensitively, and narrows `total`. + let (hits, total) = list(&db, None, None, None, None, Some("QUESTION 3"), None, 0) + .await + .unwrap(); + assert_eq!((hits.len(), total), (1, 1)); + // Owner filter with nobody's templates. + let (none, total) = list( + &db, + None, + Some(&UserId::generate()), + None, + None, + None, + None, + 0, + ) + .await + .unwrap(); + assert!(none.is_empty()); + assert_eq!(total, 0); + } + + /// Turkish `İ`/`ı` must not split the search into two disjoint halves. + #[tokio::test] + async fn list_text_filter_folds_turkish_casing() { + let db = crate::database::init_mem().await.unwrap(); + create( + &db, + UserId::generate(), + SubjectId::generate(), + QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), + QuestionPoints::try_new(1).unwrap(), + spec(), + ) + .await + .unwrap(); + for needle in [ + "istanbul", + "İSTANBUL", + "İstanbul", + "ıstanbul", + "ilçe", + "ILCE", + ] { + let (hits, total) = list(&db, None, None, None, None, Some(needle), None, 0) + .await + .unwrap(); + assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); + } + let (miss, total) = list(&db, None, None, None, None, Some("ankara"), None, 0) + .await + .unwrap(); + assert!(miss.is_empty()); + assert_eq!(total, 0); + } +} diff --git a/src/db/bank_question_image.rs b/src/db/bank_question_image.rs new file mode 100644 index 0000000..988b2a1 --- /dev/null +++ b/src/db/bank_question_image.rs @@ -0,0 +1,473 @@ +//! The `bank_question_image` slot table: the per-slot upsert that pins the +//! template's existence into its own transaction, the page-wide listing, and +//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web +//! layer; the pure entity and newtypes in +//! [`crate::domain::bank_question_image`]. + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::database::{Database, transaction_with_retry}; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId}; +use crate::domain::exam_question::ChoiceId; +use crate::error::AppError; + +/// What one [`upsert`] transaction returns: the row it +/// stored and the blob name it replaced. Both are arrays because SurrealDB +/// drops an object key valued `NONE` on the way out, while an empty array +/// survives — "nothing was replaced" has to be readable, not missing. +#[derive(SurrealValue)] +struct UpsertOutcome { + stored: Vec, + replaced: Vec, +} + +/// Create or replace the slot's image row — the deterministic id makes this +/// the whole "one image per slot" story — handing back what it stored plus +/// the blob name it replaced, for the caller to take off disk. +/// +/// Both halves are the transaction's doing. The template's own `points` is +/// moved and put straight back inside it, the way +/// [`crate::db::pool_question::bump_question_and_write`] moves +/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other +/// int column): that makes the template's *existence* part of this write. +/// A bare `UPSERT` guarded by having read the template first does not +/// survive its delete window — the read sees a row +/// [`crate::db::bank_question::delete`] has removed but +/// not committed, while that delete's image sweep ran on a snapshot +/// predating this row, so both commit and the image outlives the template +/// it hangs on. Nothing could ever read, delete, or sweep it afterwards: +/// every image route goes through the template. Moving the value makes the +/// two transactions touch one key, so the store refuses a side; writing the +/// same value back would be elided and collide with nothing. +/// +/// The replaced blob name comes out of this same transaction rather than a +/// read in front of it (the shape +/// [`crate::db::pool_question::set_image`] has): two +/// uploads to one slot both write this row, so they contend and the loser +/// re-reads the winner's blob name, where two pre-reads both saw the *old* +/// blob and left the loser's fresh one orphaned on disk. +/// +/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is +/// deterministic per (question, slot) and the table carries no `UNIQUE` +/// index, so the write always resolves onto the row its id names and can +/// never answer "already exists". +pub async fn upsert( + db: &Database, + image: BankQuestionImage, +) -> Result<(BankQuestionImage, Option), AppError> { + // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic + let (question, id) = (image.bank_question.record(), image.id.record()); + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $was_points = (SELECT VALUE points FROM ONLY $b); + LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); + IF array::len($bumped) = 0 { THROW 'no_question' }; + UPDATE $b SET points = $was_points; + LET $replaced = (SELECT VALUE file FROM $id); + LET $stored = (UPSERT $id CONTENT $image); + RETURN { stored: $stored, replaced: $replaced }; + COMMIT TRANSACTION;", + &[ + ("b".into(), question.into_value()), + ("id".into(), id.into_value()), + ("image".into(), image.into_value()), + ], + &["no_question"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_question")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its + // slot follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + let failed = || AppError::Internal("failed to store bank question image".into()); + let outcome = result + .take::>(slot)? + .into_iter() + .next() + .ok_or_else(failed)?; + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; + Ok((stored, outcome.replaced.into_iter().next())) +} + +pub async fn read_slot( + db: &Database, + question: &BankQuestionId, + slot: Option<&ChoiceId>, +) -> Result, AppError> { + Ok(db + .select(BankQuestionImageId::for_slot(question, slot).record()) + .await?) +} + +pub async fn list_for_question( + db: &Database, + question: &BankQuestionId, +) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM bank_question_image WHERE bank_question = $b") + .bind(("b", question.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The image rows of several templates in one query — for bucketing onto a +/// listing's *page* (never the whole table: the bank spans the school). +pub async fn list_for_questions( + db: &Database, + questions: &[&BankQuestionId], +) -> Result, AppError> { + if questions.is_empty() { + return Ok(Vec::new()); + } + let records: Vec = questions.iter().map(|q| q.record()).collect(); + let mut result = db + .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") + .bind(("ids", records)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Drop the option pictures whose choice is gone — every choice image of +/// the question whose `slot` is *not* in `keep` (the question's own +/// illustration always stays), returning the removed rows so the caller can +/// take their blobs off disk. +/// +/// This is what makes an edit non-destructive: a PATCH that reorders, +/// renames, or drops options passes the surviving choice ids as `keep`, so +/// only the pictures of genuinely removed options go. `keep = &[]` (a text +/// question, or an all-new choice list) still clears the lot. +pub async fn delete_choices_not_in( + db: &Database, + question: &BankQuestionId, + keep: &[ChoiceId], +) -> Result, AppError> { + let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); + let mut result = db + .query( + "DELETE bank_question_image \ + WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", + ) + .bind(("b", question.record())) + .bind(("keep", keep)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +pub async fn delete( + db: &Database, + image: BankQuestionImage, +) -> Result { + let deleted: Option = db.delete(image.id.record()).await?; + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::Database; + + fn png() -> crate::domain::note_file::FileContentType { + crate::domain::note_file::FileContentType::try_new("image/png").unwrap() + } + + /// A real template row: an image write moves its `points` inside its own + /// transaction, so a minted id nothing ever wrote is refused. + async fn a_template(db: &Database) -> BankQuestionId { + let id = BankQuestionId::generate(); + db.query( + "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, + visibility = 'private', created_at = 1", + ) + .bind(("b", id.record())) + .await + .unwrap() + .check() + .unwrap(); + id + } + + fn choice_ids() -> Vec { + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; + QuestionSpec::try_new( + QuestionKind::try_new("choice").unwrap(), + Some( + ["a", "b", "c"] + .iter() + .map(|l| ChoiceInput { + id: Some((*l).into()), + text: (*l).into(), + }) + .collect(), + ), + Some("a".into()), + &[], + ) + .unwrap() + .into_parts() + .1 + .unwrap() + .iter() + .map(|c| c.get_id().clone()) + .collect() + } + + #[tokio::test] + async fn upsert_replaces_per_slot() { + let db = crate::database::init_mem().await.unwrap(); + let question = a_template(&db).await; + + let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)) + .await + .unwrap(); + assert_eq!(retired, None, "a first upload retires no blob"); + let (second, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 5)) + .await + .unwrap(); + // Same slot, same row — the replace swapped the blob pointer, and the + // write itself names the blob the caller must unlink. + assert_ne!(first.get_file(), second.get_file()); + assert_eq!(retired.as_deref(), Some(first.get_file())); + let rows = list_for_question(&db, &question).await.unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get_size(), 5); + } + + /// The bank half of the non-destructive edit: keeping an option keeps its + /// picture, and only a removed option's picture goes. + #[tokio::test] + async fn only_the_dropped_options_lose_their_pictures() { + let db = crate::database::init_mem().await.unwrap(); + let question = a_template(&db).await; + let ids = choice_ids(); + upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) + .await + .unwrap(); + for id in &ids { + upsert(&db, BankQuestionImage::new(&question, Some(id), png(), 1)) + .await + .unwrap(); + } + + let keep = vec![ids[0].clone(), ids[1].clone()]; + let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap(); + assert_eq!(dropped.len(), 1); + assert_eq!(dropped[0].get_slot(), Some(&ids[2])); + + let left = list_for_question(&db, &question).await.unwrap(); + assert_eq!(left.len(), 3); + } + + #[tokio::test] + async fn an_empty_keep_set_clears_every_option_picture() { + let db = crate::database::init_mem().await.unwrap(); + let question = a_template(&db).await; + let ids = choice_ids(); + upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) + .await + .unwrap(); + for id in &ids[..2] { + upsert(&db, BankQuestionImage::new(&question, Some(id), png(), 1)) + .await + .unwrap(); + } + + let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap(); + assert_eq!(dropped.len(), 2); + assert!(dropped.iter().all(|image| image.get_slot().is_some())); + + let left = list_for_question(&db, &question).await.unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].get_slot(), None); + } + + /// The [`crate::db::pool_question`] defect, one domain + /// over: an image written inside its template's delete window must not + /// outlive it. Guarding the write by *reading* the template does not do it + /// — the read sees a row [`crate::db::bank_question::delete`] has removed + /// but not committed, while its `DELETE bank_question_image WHERE + /// bank_question = $b` ran on a snapshot predating this row, so both + /// commit and the image is left pointing at a template that is gone. + /// Nothing can reach it after that: every image route resolves the + /// template first, no boot sweep visits this table, and its blob stays on + /// disk for good. [`upsert`] moves the template's own `points` instead, so + /// the two transactions touch one key and the store refuses a side. + /// + /// The blob half is asserted through the list the delete hands back: that + /// list — never a snapshot read before it — is what the web layer unlinks + /// from, so an image that committed inside the window and is *not* in it is + /// a blob stranded on disk. + /// + /// The window is opened by the schema, not by a lucky interleaving: a + /// `DEFINE EVENT` on `bank_question` fires inside the delete's own + /// transaction the instant the row goes. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both and answers `Ok` to each, so this passes there on broken + /// code. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { + let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; + db.query( + "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut swept, mut orphans, mut stranded) = (0, 0, 0); + for round in 0..4 { + let question = a_template(&db).await; + let template = crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .unwrap(); + + let drop_it = { + let db = db.clone(); + tokio::spawn(async move { crate::db::bank_question::delete(&db, template).await }) + }; + // The upload starts inside the held window — the template row is + // gone but uncommitted, which is exactly what the handler's + // ownership read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, question) = (db.clone(), question.clone()); + tokio::spawn(async move { + upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the upload is a correct answer; the only defect is + // stored state. Neither side may 500 — they contend by design and a + // lost round is re-sent, not reported. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced upload must be answered, not 500: {child:?}" + ); + assert!( + !matches!(drop_it, Err(AppError::Db(_))), + "round {round}: a raced delete must retry, not 500: {drop_it:?}" + ); + + // Stored state is the whole verdict; a return value is not evidence. + if crate::db::bank_question::read(&db, &question) + .await + .unwrap() + .is_none() + { + swept += 1; + orphans += list_for_question(&db, &question).await.unwrap().len(); + if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) + && !images + .iter() + .any(|image| image.get_file() == stored.get_file()) + { + stranded += 1; + } + } + } + eprintln!( + "bank_question::delete raced by an upload: {swept}/4 rounds deleted the template" + ); + assert!( + swept > 0, + "no round ever deleted the template, so the window was never reached" + ); + assert_eq!(orphans, 0, "an image row outlived its template"); + assert_eq!( + stranded, 0, + "an image committed inside the window was swept without being handed back, so its blob stays on disk" + ); + } + + /// Two uploads to one slot must leave exactly one live blob and hand every + /// other one back to be unlinked. Reading the slot's old blob name *before* + /// the write gave both racers the same answer: both retired the same old + /// blob, and the loser's fresh one stayed on disk with nothing naming it. + /// [`upsert`] reads it inside its own transaction instead, so the + /// loser contends on the row it writes and re-reads the winner's name. + /// + /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this + /// table holds the first write open inside its own transaction, so the + /// second reads the slot before the first commits. + /// + /// Real server, and `#[ignore]`d for it, for the reason above: the embedded + /// engine has no write-write conflict detection to make a loser re-read. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn two_uploads_to_one_slot_leave_no_blob_unretired() { + let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; + db.query( + "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ + THEN { SLEEP 300ms; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let mut unretired = 0; + for round in 0..3 { + let question = a_template(&db).await; + // A first picture, so both racers have an old blob to retire. + let (original, _) = upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) + .await + .unwrap(); + + let mut writes = Vec::new(); + for size in [2, 3] { + let (db, question) = (db.clone(), question.clone()); + writes.push(tokio::spawn(async move { + upsert(&db, BankQuestionImage::new(&question, None, png(), size)).await + })); + } + let mut written = vec![original.get_file().to_string()]; + let mut retired = Vec::new(); + for write in writes { + let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| { + panic!("round {round}: a raced upload must not 500: {err:?}") + }); + written.push(stored.get_file().to_string()); + retired.extend(replaced); + } + + // Stored state is the whole verdict: exactly one blob is live, and + // every other one this round wrote must have been handed back — + // once. A name written and never returned is a file on disk with + // nothing pointing at it. + let live = read_slot(&db, &question, None).await.unwrap().unwrap(); + assert!( + !retired.iter().any(|name| name == live.get_file()), + "round {round}: the live row's own blob was retired" + ); + unretired += written + .iter() + .filter(|name| *name != live.get_file() && !retired.contains(name)) + .count(); + } + assert_eq!( + unretired, 0, + "a blob was written and never handed back to be unlinked — it stays on disk forever" + ); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..644c6e6 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,6 +2,8 @@ pub mod appointment; pub mod appointment_slot; +pub mod bank_question; +pub mod bank_question_image; pub mod cap; pub mod class_blueprint; pub mod course; @@ -15,6 +17,8 @@ pub mod meal_booking; pub mod note; pub mod page; pub mod payment_ledger; +pub mod pool_question; pub mod session; pub mod settings; +pub mod solution; pub mod user; diff --git a/src/db/pool_question.rs b/src/db/pool_question.rs new file mode 100644 index 0000000..0ddfc5b --- /dev/null +++ b/src/db/pool_question.rs @@ -0,0 +1,623 @@ +//! The `pool_question` table: ask/insert, the two listings, the guarded +//! approve that rides the publish counters along, the pending-only image +//! writes, and the delete that cascades solutions — plus +//! [`bump_question_and_write`], the existence-move every child write goes +//! through. The pure entity and newtypes live in +//! [`crate::domain::pool_question`]; the web layer reaches these through +//! [`crate::service::pool_question`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::{ + POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; +use crate::domain::solution::Solution; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Move the question's `asked_at` **and** run `statement` — a write to +/// something hanging off a question — in one transaction, handing back the row +/// it returned. `NotFound` means the question is gone and nothing was written. +/// +/// The move is what makes the question's **existence** part of the child's own +/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: +/// the `UPDATE` matches nothing once the row is deleted, and a delete racing +/// this one touches the very key this transaction writes, so the two cannot +/// both commit. Reading the question first does *not* survive that race — the +/// read sees a row [`delete`] has removed but not committed, while its +/// `DELETE solution WHERE question = $q` ran on a snapshot predating this +/// insert, so both commit and the child outlives its question with neither +/// caller told anything. +/// +/// `asked_at` rather than a revision column because this row carries no counter +/// to bump and must not grow one for this alone. It is put back *by captured +/// value* in the same transaction, so nothing outside ever observes the move +/// and the row is byte-identical afterwards (the pool lists order on it). +/// Writing the same value would buy nothing: an `UPDATE` that leaves the +/// document unchanged is elided and never reaches the store's write set, so it +/// collides with nothing. +/// +/// Admissible for [`transaction_with_retry`] as long as `statement` is: the +/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already +/// exists". +pub(crate) async fn bump_question_and_write( + question: &PoolQuestionId, + statement: &str, + mut bindings: Vec<(String, surrealdb::types::Value)>, + db: &Database, +) -> Result, AppError> { + bindings.push(("q".into(), question.record().into_value())); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); + LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); + IF array::len($bumped) = 0 {{ THROW 'no_question' }}; + UPDATE $q SET asked_at = $was_asked; + LET $row = ({statement}); + RETURN $row; + COMMIT TRANSACTION;" + ), + &bindings, + &["no_question"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic "not + // executed" — only the THROW's own slot names the reason. + if errors + .values() + .any(|error| error.to_string().contains("no_question")) + { + return Err(AppError::NotFound); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is the last statement before `COMMIT`, so its slot + // follows the statement count rather than a hand-kept number; + // `num_statements` counts BEGIN and COMMIT. + let slot = result.num_statements().saturating_sub(2); + Ok(result.take::>(slot)?.into_iter().next()) +} + +pub async fn insert(db: &Database, question: PoolQuestion) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + let created: Option = db.create(question.id.record()).content(question).await?; + created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) +} + +pub async fn read(db: &Database, id: &PoolQuestionId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every question, newest first — the teacher+ view (approval queue and +/// pool in one list). +pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The pool as a non-staff user sees it, newest first: every approved +/// question, plus the caller's own pending ones. +pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { + let mut result = db + .query( + "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ + ORDER BY asked_at DESC, id DESC", + ) + .bind(("approved", STATUS_APPROVED)) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Publish a pending question into the pool, stamping who approved it. +/// The `WHERE status = $pending` guard makes the transition atomic: of two +/// racing approvals exactly one wins, and an approve can never land on a +/// question deleted mid-flight. `None` = the question wasn't pending +/// (already approved, or gone) — the caller sorts out which. +/// +/// Two lifetime badge counters ride that same guard, inside this +/// transaction: the approver's `pool_approved_total` and the *asker's* +/// `pool_published_total`. Both hang off `array::len($done) > 0` — the +/// guard's own verdict — so the pair moves once per real transition and +/// never on a second approve of an already-approved question. +/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that +/// holds.) The second conjunct is the self-approval rule below. +/// +/// Two rules keep the pair unfarmable, one per side of the transition. +/// +/// The asker is credited at *approval*, not at asking: a bare +/// [`insert`] is self-service and the author can +/// delete their own question and ask again forever, so a counter moved +/// there is farmable. Approval is teacher-gated and one-way, which is why +/// the family is named `pool_published` and not `pool_asked`. That closes +/// the student side. +/// +/// And a *self*-approval — a teacher+ approving a question they asked +/// themselves, which the route deliberately still allows — moves neither +/// counter, hence the `$done[0].asker != $by` half of the condition. It is +/// the same farm from the other end (ask, approve, delete, repeat, with no +/// second person involved), and the two together are why a counter can only +/// move when one person's work was judged by another's. Nothing else about +/// a self-approval changes: same 200, same freeze, same stamp — this skips +/// the credit, not the approval. +/// +/// Re-sent while the store answers "conflict, retry": the guard reads a +/// column a rival approve writes, and both counters sit on user rows every +/// other counter site writes too. Sound to re-send — every statement is an +/// `UPDATE`, none of which can legitimately answer "already exists" — and a +/// lost round aborts having written nothing, increments included. +pub async fn approve( + db: &Database, + id: &PoolQuestionId, + approver: &UserId, +) -> Result, AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $done = (UPDATE $q SET status = $approved, approved_by = $by + WHERE status = $pending RETURN AFTER); + IF array::len($done) > 0 AND $done[0].asker != $by {{ + UPDATE $by SET + {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; + LET $asker = $done[0].asker; + UPDATE $asker SET + {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; + }}; + RETURN $done; + COMMIT TRANSACTION;" + ), + &[ + ("q".into(), id.record().into_value()), + ("approved".into(), STATUS_APPROVED.to_string().into_value()), + ("by".into(), approver.record().into_value()), + ("pending".into(), STATUS_PENDING.to_string().into_value()), + ], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The trailing `RETURN` is always the last statement before `COMMIT`, + // so its slot follows the statement count rather than a hand-kept + // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). + let slot = result.num_statements().saturating_sub(2); + Ok(result.take::>(slot)?.into_iter().next()) +} + +/// Point the question at a freshly written image blob. Guarded on +/// `pending` for the same reason approval is: an image landing after +/// approval would put unmoderated bytes in the pool, so an upload that +/// loses the race gets `None` (and the caller takes the orphan blob back +/// off disk). Returns the *before* row — its `image_file` is the replaced +/// blob the caller must remove. +pub async fn set_image( + db: &Database, + id: &PoolQuestionId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ + WHERE status = $pending RETURN BEFORE", + ) + .bind(("q", id.record())) + .bind(("file", file.to_string())) + .bind(("ct", content_type.clone())) + .bind(("size", size)) + .bind(("pending", STATUS_PENDING)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Detach the question's image (pending only, like `set_image`). Returns +/// the *before* row — its `image_file` is the blob the caller must remove. +pub async fn clear_image( + db: &Database, + id: &PoolQuestionId, +) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ + WHERE status = $pending RETURN BEFORE", + ) + .bind(("q", id.record())) + .bind(("pending", STATUS_PENDING)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Delete the question and its solutions in one transaction, returning +/// the removed rows — the question's *and* the swept solutions' — so the +/// caller can take every image blob off disk (solutions carry photos too, +/// and a row-only sweep would strand theirs forever). +/// +/// Rides the retry because a solution offer now writes this very row +/// ([`bump_question_and_write`]): the two contend by design, and a lost +/// round through a bare `check()` was a 500 for a delete that only had to +/// be re-sent. Admissible — a `DELETE` can never answer "already exists". +pub async fn delete( + db: &Database, + id: &PoolQuestionId, +) -> Result)>, AppError> { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE solution WHERE question = $q RETURN BEFORE; + DELETE $q RETURN BEFORE; + COMMIT TRANSACTION;", + &[("q".into(), id.record().into_value())], + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. + let solutions = result.take::>(1)?; + Ok(result + .take::>(2)? + .into_iter() + .next() + .map(|question| (question, solutions))) +} + +#[cfg(test)] +mod tests { + use ulid::Ulid; + + use super::*; + use crate::database; + use crate::domain::solution::SolutionBody; + + /// The two counter columns plus a row to carry them: the `user` table is + /// SCHEMAFULL in production, and the counters are `option` there. + async fn a_user(db: &Database) -> UserId { + let user = UserId::from_key(&Ulid::new().to_string()); + db.query(format!( + "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; + CREATE $usr SET username = $name, password_hash = 'x';" + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// `(pool_approved_total, pool_published_total)` as stored — absent reads + /// zero, the way `BadgeStats::load` reads it. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), + ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows = result.take::>>(0).unwrap(); + let row = rows.into_iter().next().unwrap_or_default(); + ( + row.first().copied().unwrap_or(0), + row.get(1).copied().unwrap_or(0), + ) + } + + fn question(asker: &UserId) -> PoolQuestion { + use crate::domain::pool_question::{PoolQuestionBody, PoolQuestionTitle}; + PoolQuestion::new( + asker, + PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), + PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), + ) + } + + #[tokio::test] + async fn approval_is_a_one_way_race_safe_transition() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + + let q = insert(&db, question(&asker)).await.unwrap(); + assert_eq!(q.get_status(), STATUS_PENDING); + assert!(q.get_approved_by().is_none()); + + let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); + assert!(approved.is_approved()); + assert_eq!(approved.get_approved_by(), Some(&teacher)); + + // A second approval finds nothing pending. + assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); + // And a missing question approves to None, not an error. + assert!( + approve(&db, &PoolQuestionId::generate(), &teacher) + .await + .unwrap() + .is_none() + ); + } + /// The publish counters ride the guard, so they move exactly once per real + /// transition: the approver's on the approve side, the asker's on the + /// published side, and neither on a second approve of the same question. + #[tokio::test] + async fn approval_moves_both_counters_once_and_only_once() { + let db = database::init_mem().await.unwrap(); + let asker = a_user(&db).await; + let teacher = a_user(&db).await; + + let q = insert(&db, question(&asker)).await.unwrap(); + assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); + + approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); + assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); + assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); + + // The guard finds nothing pending, so neither counter may move — this + // is what stops an approve loop from farming either one. + assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); + assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); + assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); + + // And an approve that lands on nothing at all writes nothing. + assert!( + approve(&db, &PoolQuestionId::generate(), &teacher) + .await + .unwrap() + .is_none() + ); + assert_eq!(counters(&teacher, &db).await, (1, 0)); + } + + /// A teacher may ask a question and the route does not bar them from + /// approving it — that still works, unchanged. What it does not do is pay + /// for itself: ask, approve, delete, repeat is the staff-side farm, and + /// neither counter moves when one person is both ends of the transition. + #[tokio::test] + async fn self_approval_still_approves_but_moves_neither_counter() { + let db = database::init_mem().await.unwrap(); + let teacher = a_user(&db).await; + + let q = insert(&db, question(&teacher)).await.unwrap(); + let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); + // The approval itself is untouched: published, stamped, frozen. + assert!(approved.is_approved()); + assert_eq!(approved.get_approved_by(), Some(&teacher)); + assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); + + // And the skip is about the *pair*, not about the teacher: approving + // somebody else's question right after still pays. + let asker = a_user(&db).await; + let other = insert(&db, question(&asker)).await.unwrap(); + approve(&db, other.get_id(), &teacher) + .await + .unwrap() + .unwrap(); + assert_eq!(counters(&teacher, &db).await, (1, 0)); + assert_eq!(counters(&asker, &db).await, (0, 1)); + } + + #[tokio::test] + async fn visibility_hides_others_pending_questions() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let other = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + + let pending = insert(&db, question(&asker)).await.unwrap(); + let published = insert(&db, question(&other)).await.unwrap(); + approve(&db, published.get_id(), &teacher) + .await + .unwrap() + .unwrap(); + + // The asker sees their own pending question plus the pool; a stranger + // sees only the pool; the teacher view (list_all) sees everything. + assert_eq!(list_visible_to(&db, &asker).await.unwrap().len(), 2); + let stranger_view = list_visible_to(&db, &other).await.unwrap(); + assert_eq!(stranger_view.len(), 1); + assert_eq!(stranger_view[0].get_id(), published.get_id()); + assert_eq!(list_all(&db).await.unwrap().len(), 2); + assert!(read(&db, pending.get_id()).await.unwrap().is_some()); + } + + #[tokio::test] + async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let teacher = UserId::from_key(&Ulid::new().to_string()); + let png = FileContentType::try_new("image/png").unwrap(); + + let q = insert(&db, question(&asker)).await.unwrap(); + let before = set_image(&db, q.get_id(), "blob_a", &png, 3) + .await + .unwrap() + .unwrap(); + assert!(before.get_image_file().is_none()); + + // A replace reports the old blob for cleanup. + let before = set_image(&db, q.get_id(), "blob_b", &png, 5) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_a")); + let stored = read(&db, q.get_id()).await.unwrap().unwrap(); + assert_eq!(stored.get_image_file(), Some("blob_b")); + assert_eq!(stored.get_image_size(), Some(5)); + + // Clearing reports the detached blob and empties the fields. + let before = clear_image(&db, q.get_id()).await.unwrap().unwrap(); + assert_eq!(before.get_image_file(), Some("blob_b")); + assert!( + read(&db, q.get_id()) + .await + .unwrap() + .unwrap() + .get_image_file() + .is_none() + ); + + // Once approved, the image is frozen with the rest of the content. + approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); + assert!( + set_image(&db, q.get_id(), "blob_c", &png, 7) + .await + .unwrap() + .is_none() + ); + assert!(clear_image(&db, q.get_id()).await.unwrap().is_none()); + } + + #[tokio::test] + async fn delete_cascades_solutions_and_returns_the_row() { + let db = database::init_mem().await.unwrap(); + let asker = UserId::from_key(&Ulid::new().to_string()); + let helper = UserId::from_key(&Ulid::new().to_string()); + + let q = insert(&db, question(&asker)).await.unwrap(); + let offered = crate::db::solution::insert( + &db, + Solution::new( + q.get_id(), + &helper, + SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), + ), + ) + .await + .unwrap(); + + // The swept solutions ride back with the question so the caller can + // take their image blobs off disk. + let (removed, swept) = delete(&db, q.get_id()).await.unwrap().unwrap(); + assert_eq!(removed.get_id(), q.get_id()); + assert_eq!(swept.len(), 1); + assert_eq!(swept[0].get_id(), offered.get_id()); + assert!(read(&db, q.get_id()).await.unwrap().is_none()); + assert!( + crate::db::solution::list_for(&db, q.get_id(), None, 0) + .await + .unwrap() + .0 + .is_empty() + ); + + // Deleting the already-deleted is None, not an error. + assert!(delete(&db, q.get_id()).await.unwrap().is_none()); + } + + /// The [`crate::db::exam_answer`] defect, one domain + /// over: a solution offered inside its question's delete window must not + /// outlive it. Guarding the offer by *reading* the question does not do it + /// — the read sees a row [`delete`] has removed but not committed, while + /// its `DELETE solution WHERE question = $q` ran on a snapshot predating + /// the offer, so both commit and the solution is left pointing at a + /// question that is gone. Nothing can reach it after that: every route to + /// a solution goes through its question, so neither a reader nor a second + /// delete can ever clear it, and its photo stays on disk for good. + /// [`bump_question_and_write`] moves the question's own `asked_at` + /// instead, so the two transactions touch one key and the store refuses + /// one of them. + /// + /// The window is opened by the database, not by a lucky interleaving: a + /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own + /// transaction the instant the row goes, so the `SLEEP` lands exactly + /// between the delete and its cascade every time. + /// + /// Real server, and `#[ignore]`d for it: the subject *is* the store's + /// conflict detection, which `init_mem`'s embedded engine does not have — + /// it commits both writes and answers `Ok` to each, so this passes there on + /// broken code. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { + let (db, _serialized) = database::init_test_server("solution_race").await; + // Hold the delete open for a full second after the row is gone, while + // its cascade still has to run. + db.query( + "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ + THEN { SLEEP 1s; };", + ) + .await + .unwrap() + .check() + .unwrap(); + + let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); + for round in 0..4 { + let asker = UserId::from_key(&Ulid::new().to_string()); + let helper = UserId::from_key(&Ulid::new().to_string()); + let q = insert(&db, question(&asker)).await.unwrap(); + let id = q.get_id().clone(); + + let drop_it = { + let (db, id) = (db.clone(), id.clone()); + tokio::spawn(async move { delete(&db, &id).await }) + }; + // The offer starts inside the held window — the question row is + // gone but uncommitted, which is exactly what a read believes. + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + let child = { + let (db, id) = (db.clone(), id.clone()); + tokio::spawn(async move { + crate::db::solution::insert( + &db, + Solution::new( + &id, + &helper, + SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), + ), + ) + .await + }) + }; + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); + // A 404 for the offer is a correct answer; the only defect is + // stored state. The delete must not 500 either — it contends with + // the offer by design and a lost round is re-sent, not reported. + assert!( + !matches!(child, Err(AppError::Db(_))), + "round {round}: a raced offer must be answered, not 500: {child:?}" + ); + if matches!(drop_it, Err(AppError::Db(_))) { + delete_500 += 1; + } + + // Stored state is the whole verdict; a return value is not evidence. + if read(&db, &id).await.unwrap().is_none() { + swept += 1; + solutions += crate::db::solution::list_for(&db, &id, None, 0) + .await + .unwrap() + .0 + .len(); + } + } + eprintln!("pool_question::delete raced by an offer: {swept}/4 rounds deleted the question"); + assert!( + swept > 0, + "no round ever deleted the question, so the window was never reached" + ); + assert_eq!(solutions, 0, "a solution outlived its question"); + assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); + } +} diff --git a/src/db/solution.rs b/src/db/solution.rs new file mode 100644 index 0000000..18a76ea --- /dev/null +++ b/src/db/solution.rs @@ -0,0 +1,386 @@ +//! The `solution` table: offers (through the pool question's +//! existence-move), the question-scoped reads and page, the grouped counts, +//! and the unconditional body/image writes of an unmoderated row. The pure +//! entity and newtypes live in [`crate::domain::solution`]; the web layer +//! reaches these through [`crate::service::solution`]. + +use std::collections::HashMap; + +use surrealdb::types::{RecordId, SurrealValue}; + +use crate::database::Database; +use crate::db::page::PagedList; +use crate::db::pool_question::bump_question_and_write; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::PoolQuestionId; +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; +use crate::error::AppError; + +/// One `GROUP BY question` row of [`counts_for`]. +#[derive(SurrealValue)] +struct SolutionCount { + question: PoolQuestionId, + n: i64, +} + +/// Offer the solution. `NotFound` = the question is gone, and nothing was +/// written: the create rides [`bump_question_and_write`], so the question's +/// existence is a *write* to its row rather than a read the handler made a +/// moment earlier — a bare create landing inside +/// [`crate::db::pool_question::delete`]'s +/// window was swept by nothing and left a solution no route could ever +/// reach or remove (every path to one goes through its question), photo +/// blob included. +/// +/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call +/// on a table with no `UNIQUE` index, so a re-send cannot answer "already +/// exists" — the one thing the retry could not survive. +pub async fn insert(db: &Database, solution: Solution) -> Result { + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber + let (question, id) = (solution.question.clone(), solution.id.record()); + bump_question_and_write( + &question, + "CREATE $id CONTENT $solution", + vec![ + ("id".into(), id.into_value()), + ("solution".into(), solution.into_value()), + ], + db, + ) + .await? + .ok_or_else(|| AppError::Internal("failed to create solution".into())) +} + +/// Read a solution only if it belongs to `question` — keeps the nested +/// route honest (a solution id under someone else's question 404s). +pub async fn read_for( + db: &Database, + id: &SolutionId, + question: &PoolQuestionId, +) -> Result, AppError> { + let solution: Option = db.select(id.record()).await?; + Ok(solution.filter(|solution| &solution.question == question)) +} + +/// The question's solutions, oldest first — a discussion reads downward. +/// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond +/// offers *stable* across re-queries, not insertion-ordered (ULID low bits +/// are random within a millisecond, so same-ms order is arbitrary). +pub async fn list_for( + db: &Database, + question: &PoolQuestionId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "solution WHERE question = $q", + "ORDER BY offered_at ASC, id ASC", + ) + .bind("q", question.record()) + .run(limit, offset, db) + .await +} + +/// Per-question solution tallies for a page of questions, in one grouped +/// query — a per-row `count()` would cost a query per question. Keys are +/// question record keys; a question with no solutions has no entry, so +/// the caller reads misses as zero. +pub async fn counts_for( + db: &Database, + questions: &[PoolQuestionId], +) -> Result, AppError> { + if questions.is_empty() { + return Ok(HashMap::new()); + } + let ids: Vec = questions.iter().map(|question| question.record()).collect(); + let mut result = db + .query( + "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question", + ) + .bind(("qs", ids)) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .map(|row| (row.question.key().to_string(), row.n)) + .collect()) +} + +/// Replace the body. Unconditional (solutions have no moderation state to +/// guard, unlike a question's `pending` gate) — `None` only means the row +/// was deleted mid-flight. Authorship is the web layer's check. +pub async fn set_body( + db: &Database, + id: &SolutionId, + body: &SolutionBody, +) -> Result, AppError> { + let mut result = db + .query("UPDATE $s SET body = $b RETURN AFTER") + .bind(("s", id.record())) + .bind(("b", body.clone())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Point the solution at a freshly written image blob. Unconditional for +/// the same reason as [`set_body`]. Returns the *before* row — its +/// `image_file` is the replaced blob the caller must remove; `None` means +/// the row was deleted mid-flight (the fresh blob is the caller's orphan +/// to take back off disk). +pub async fn set_image( + db: &Database, + id: &SolutionId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + let mut result = db + .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") + .bind(("s", id.record())) + .bind(("file", file.to_string())) + .bind(("ct", content_type.clone())) + .bind(("size", size)) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +/// Detach the solution's image. Returns the *before* row — its +/// `image_file` is the blob the caller must remove. +pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { + let mut result = db + .query( + "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ + RETURN BEFORE", + ) + .bind(("s", id.record())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +pub async fn delete(db: &Database, solution: Solution) -> Result { + let deleted: Option = db.delete(solution.id.record()).await?; + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use ulid::Ulid; + + use super::*; + use crate::database; + use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; + use crate::domain::timestamp::Timestamp; + use crate::domain::user::UserId; + + /// A real question row: offering a solution moves its question's + /// `asked_at` (that is what keeps a solution from outliving its question), + /// so a minted id nothing wrote is a 404. + async fn question_row(db: &Database) -> PoolQuestionId { + crate::db::pool_question::insert( + db, + PoolQuestion::new( + &UserId::from_key(&Ulid::new().to_string()), + PoolQuestionTitle::try_new("soru").unwrap(), + PoolQuestionBody::try_new("neden").unwrap(), + ), + ) + .await + .unwrap() + .get_id() + .clone() + } + + #[tokio::test] + async fn rows_scope_to_their_question_and_list_oldest_first() { + let db = database::init_mem().await.unwrap(); + let question_a = question_row(&db).await; + let question_b = question_row(&db).await; + let author = UserId::from_key(&Ulid::new().to_string()); + + // Distinct offer times so the assertion pins the real contract — + // older `offered_at` sorts first — not the same-millisecond `id` + // tiebreak, whose random ULID low bits would make the order a coin + // flip (two `now()` reads can land in one millisecond). + let mut first = Solution::new( + &question_a, + &author, + SolutionBody::try_new("Önce türevi al.").unwrap(), + ); + first.offered_at = Timestamp::from_millis(1); + let first = insert(&db, first).await.unwrap(); + let mut second = Solution::new( + &question_a, + &author, + SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), + ); + second.offered_at = Timestamp::from_millis(2); + let second = insert(&db, second).await.unwrap(); + + let (listed, _) = list_for(&db, &question_a, None, 0).await.unwrap(); + assert_eq!(listed.len(), 2); + assert_eq!(listed[0].get_id(), first.get_id()); + assert_eq!(listed[1].get_id(), second.get_id()); + assert!( + list_for(&db, &question_b, None, 0) + .await + .unwrap() + .0 + .is_empty() + ); + + // Readable under its own question, invisible under another. + assert!( + read_for(&db, first.get_id(), &question_a) + .await + .unwrap() + .is_some() + ); + assert!( + read_for(&db, first.get_id(), &question_b) + .await + .unwrap() + .is_none() + ); + + delete(&db, first).await.unwrap(); + assert_eq!( + list_for(&db, &question_a, None, 0).await.unwrap().0.len(), + 1 + ); + } + + #[tokio::test] + async fn image_set_replace_clear_report_the_replaced_blob() { + let db = database::init_mem().await.unwrap(); + let question = question_row(&db).await; + let author = UserId::from_key(&Ulid::new().to_string()); + let png = FileContentType::try_new("image/png").unwrap(); + + let solution = insert( + &db, + Solution::new( + &question, + &author, + SolutionBody::try_new("Grafiği çiz.").unwrap(), + ), + ) + .await + .unwrap(); + + let before = set_image(&db, solution.get_id(), "blob_a", &png, 3) + .await + .unwrap() + .unwrap(); + assert!(before.get_image_file().is_none()); + + // A replace reports the old blob for cleanup. + let before = set_image(&db, solution.get_id(), "blob_b", &png, 5) + .await + .unwrap() + .unwrap(); + assert_eq!(before.get_image_file(), Some("blob_a")); + let stored = read_for(&db, solution.get_id(), &question) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.get_image_file(), Some("blob_b")); + assert_eq!(stored.get_image_size(), Some(5)); + + // Clearing reports the detached blob and empties the fields. + let before = clear_image(&db, solution.get_id()).await.unwrap().unwrap(); + assert_eq!(before.get_image_file(), Some("blob_b")); + assert!( + read_for(&db, solution.get_id(), &question) + .await + .unwrap() + .unwrap() + .get_image_file() + .is_none() + ); + + // A row deleted mid-flight surfaces as None, not an error. + let deleted = delete(&db, solution.clone()).await.unwrap(); + assert_eq!(deleted.get_id(), solution.get_id()); + assert!( + set_image(&db, solution.get_id(), "blob_c", &png, 7) + .await + .unwrap() + .is_none() + ); + assert!(clear_image(&db, solution.get_id()).await.unwrap().is_none()); + } + + #[tokio::test] + async fn set_body_edits_in_place() { + let db = database::init_mem().await.unwrap(); + let question = question_row(&db).await; + let author = UserId::from_key(&Ulid::new().to_string()); + + let solution = insert( + &db, + Solution::new( + &question, + &author, + SolutionBody::try_new("İlk deneme.").unwrap(), + ), + ) + .await + .unwrap(); + + let edited = set_body( + &db, + solution.get_id(), + &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), + ) + .await + .unwrap() + .unwrap(); + assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); + assert_eq!(edited.get_id(), solution.get_id()); + + // Editing a missing solution is None, not an error. + assert!( + set_body( + &db, + &SolutionId::from_key(&Ulid::new().to_string()), + &SolutionBody::try_new("boş").unwrap(), + ) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn counts_for_groups_per_question() { + let db = database::init_mem().await.unwrap(); + let two = question_row(&db).await; + let one = question_row(&db).await; + let none = question_row(&db).await; + let author = UserId::from_key(&Ulid::new().to_string()); + + for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { + for body in bodies { + insert( + &db, + Solution::new(question, &author, SolutionBody::try_new(body).unwrap()), + ) + .await + .unwrap(); + } + } + + let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()]) + .await + .unwrap(); + assert_eq!(counts.get(two.key()), Some(&2)); + assert_eq!(counts.get(one.key()), Some(&1)); + // No solutions = no entry; the caller reads the miss as zero. + assert_eq!(counts.get(none.key()), None); + assert!(counts_for(&db, &[]).await.unwrap().is_empty()); + } +} diff --git a/src/domain/bank_question.rs b/src/domain/bank_question.rs index 3ae60bf..02e3e06 100644 --- a/src/domain/bank_question.rs +++ b/src/domain/bank_question.rs @@ -6,26 +6,22 @@ //! `ExamQuestion` with its own id, images, and answers; the two never share a //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants //! because every write goes through one. - -use std::collections::HashMap; +//! +//! Pure types only: the queries live in [`crate::db::bank_question`], the +//! PATCH re-derive in [`crate::service::bank_question`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL, USAGE_COUNTS_SQL, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; -use crate::domain::bank_question_image::BankQuestionImage; +use crate::constant::{BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; use crate::domain::exam::ExamId; use crate::domain::exam_question::{ Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::monotonic_id::next_ulid; use crate::domain::subject::SubjectId; -use crate::domain::text_fold::{search_fold, search_fold_sql}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; /// Who may see a template. `private` — the owner (and admins) alone; `school` — /// every teacher. @@ -68,22 +64,6 @@ impl BankVisibility { #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BankQuestionId(RecordId); -/// One `GROUP BY from_bank` row of [`BankQuestion::usage_counts`]. -#[derive(SurrealValue)] -struct UsageCount { - from_bank: BankQuestionId, - n: i64, -} - -/// What one [`BankQuestion::delete`] transaction removed — the template (an -/// empty list once someone else deleted it first) and the image rows swept -/// with it. -#[derive(SurrealValue)] -struct DeleteOutcome { - question: Vec, - images: Vec, -} - impl BankQuestionId { /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and /// a random ULID is only millisecond-accurate — templates saved inside one @@ -122,25 +102,25 @@ impl BankQuestionId { /// template would have raised it. #[derive(Debug, Clone, SurrealValue)] pub struct BankQuestion { - id: BankQuestionId, - owner: UserId, + pub(crate) id: BankQuestionId, + pub(crate) owner: UserId, /// The origin subject, or `None` once that subject was deleted. /// `#[surreal(default)]` for the same reason `visibility` has one: rows /// written before the field went optional still decode. #[surreal(default)] - subject: Option, - text: QuestionText, - kind: QuestionKind, - points: QuestionPoints, - choices: Option>, - correct: Option, + pub(crate) subject: Option, + pub(crate) text: QuestionText, + pub(crate) kind: QuestionKind, + pub(crate) points: QuestionPoints, + pub(crate) choices: Option>, + pub(crate) correct: Option, /// The exam question this template was saved from, if any. - source_exam: Option, + pub(crate) source_exam: Option, /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile /// here): rows written before the field existed decode as `private`. #[surreal(default)] - visibility: BankVisibility, - created_at: Timestamp, + pub(crate) visibility: BankVisibility, + pub(crate) created_at: Timestamp, } impl BankQuestion { @@ -201,328 +181,8 @@ impl BankQuestion { ) } - pub async fn create( - owner: UserId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - db: &Database, - ) -> Result { - Self::insert(owner, subject, text, points, spec, None, db).await - } - - /// Like [`Self::create`], but records the origin exam the template was - /// saved from (`POST …/questions/{qid}/to-bank`). - pub async fn create_from_exam( - owner: UserId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - source: ExamId, - db: &Database, - ) -> Result { - Self::insert(owner, subject, text, points, spec, Some(source), db).await - } - - #[allow(clippy::too_many_arguments)] - async fn insert( - owner: UserId, - subject: SubjectId, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - source_exam: Option, - db: &Database, - ) -> Result { - let question = BankQuestion::from_parts( - BankQuestionId::generate(), - owner, - // Creation always carries a validated subject; only a subject - // delete ever clears it. - Some(subject), - text, - points, - spec, - source_exam, - // Never published on creation — publishing is its own PATCH. - BankVisibility::default(), - Timestamp::now(), - ); - let created: Option = - db.create(question.id.record()).content(question).await?; - created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) - } - - pub async fn read( - id: &BankQuestionId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// One page of the bank the caller may see, **newest first** (ULID ids sort by - /// creation, so `id DESC` is newest-first) — plus the total row count under - /// the same filters, so a client can page past the window. - /// - /// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: - /// the old version read the whole table and sliced it in memory, which hid - /// every template past the client's first page. `q` is a case- and - /// diacritic-insensitive fragment of the question text (blank = no text - /// filter): needle and column both go through - /// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. - /// - /// `visible_to` is the security filter, and it is a WHERE clause like every - /// other one — never a post-filter, or `total` would count templates the - /// caller can't have and paging would return short pages of them: - /// `Some(me)` sees the school-published templates plus their own, - /// `None` (admins only) sees everything. - /// - /// `visibility` is the *user's* filter ("only mine" / "shared with the - /// school") and is ANDed on top of that gate, so it can only ever narrow: - /// `school` still hides another teacher's private rows, and `private` - /// intersected with the gate leaves exactly the caller's own drafts. It - /// joins the same `clauses` vec as the rest, so `total` honours it too — - /// a count that ignored it would break paging. - // Flat filter args, like every other `list` here — a builder struct for - // four `Option`s and a window would be more machinery than the call sites. - #[allow(clippy::too_many_arguments)] - pub async fn list( - visible_to: Option<&UserId>, - owner: Option<&UserId>, - subject: Option<&SubjectId>, - visibility: Option<&BankVisibility>, - q: Option<&str>, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); - let mut clauses = Vec::new(); - if visible_to.is_some() { - clauses.push("(visibility = 'school' OR owner = $viewer)"); - } - if visibility.is_some() { - clauses.push("visibility = $visibility"); - } - if owner.is_some() { - clauses.push("owner = $owner"); - } - if subject.is_some() { - clauses.push("subject = $subject"); - } - let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); - if needle.is_some() { - clauses.push(text_clause.as_str()); - } - let where_clause = if clauses.is_empty() { - "true".to_string() - } else { - clauses.join(" AND ") - }; - // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. - let window = match limit { - Some(_) => "LIMIT $limit START $offset", - None => "START $offset", - }; - // The count runs over the *same* WHERE, so `total` can never disagree - // with what paging through the list actually yields. - let mut query = db - .query(format!( - "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; - SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" - )) - .bind(("offset", offset)); - if let Some(viewer) = visible_to { - query = query.bind(("viewer", viewer.record())); - } - if let Some(visibility) = visibility { - query = query.bind(("visibility", visibility.as_str().to_string())); - } - if let Some(owner) = owner { - query = query.bind(("owner", owner.record())); - } - if let Some(subject) = subject { - query = query.bind(("subject", subject.record())); - } - if let Some(needle) = needle { - query = query.bind(("q", needle)); - } - if let Some(limit) = limit { - query = query.bind(("limit", limit)); - } - let mut result = query.await?.check()?; - let questions = result.take::>(0)?; - // `GROUP ALL` yields no row at all when nothing matched. - let total = result.take::>(1)?.first().copied().unwrap_or(0); - Ok((questions, total)) - } - - /// How many exam questions were instantiated from each of `ids` — the - /// `from_bank` side of the provenance link, tallied for a whole page in - /// **one** grouped query (a `count()` per row would be the N+1 this page - /// already had removed once). Keys are template record keys; a template - /// nobody ever used has no entry at all, so the caller reads a miss as - /// zero — and the UI can stay quiet rather than print "0". - /// - /// Counts *questions*, not distinct exams: one exam that inserted the same - /// template twice counts twice, which is what "copies made from this - /// template" means and what the divergence trap is actually about. - pub async fn usage_counts( - ids: &[&BankQuestionId], - db: &Database, - ) -> Result, AppError> { - if ids.is_empty() { - return Ok(HashMap::new()); - } - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let mut result = db - .query(USAGE_COUNTS_SQL) - .bind(("ids", records)) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|row| (row.from_bank.key().to_string(), row.n)) - .collect()) - } - - /// Write the editable fields of the template, but only while the row still - /// reads as the snapshot `self` was loaded from — `None` means a concurrent - /// edit (or the subject-delete cascade that clears `subject`) landed inside - /// the handler's read-merge window, so nothing was written: reload, - /// re-merge, retry. This is a genuine read-modify-write — every editable - /// field is re-stated from the snapshot, and the kind/choices/correct trio - /// has to be (a text-only edit re-submits the stored options *with their - /// ids* so each keeps its picture) — so without the compare-and-set the - /// later writer silently reverts the earlier one — and the window is a - /// database round trip wide, which is exactly how far apart two concurrent - /// requests to this one process can sit. - /// - /// Every field the merge re-states is in the guard, which is the same list - /// the `SET` writes. `choices` is compared whole: its objects carry two - /// required string keys, so none is ever dropped for being `NONE` (the trap - /// [`crate::db::settings::save_if_unchanged`] works around). - /// - /// Rides [`write_with_retry`] because an image write now moves this row too - /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an - /// upload landing in the same instant makes the store answer "conflict, - /// retry", and a bare `check()` would turn that into a 500 for an edit that - /// only had to be re-sent. A lost round writes nothing, and the guard is - /// re-evaluated on the next one, so a genuine stale merge still comes back - /// as `None`. Admissible: an `UPDATE` can never answer "already exists". - pub async fn update_if_unchanged( - self, - subject: Option, - text: QuestionText, - points: QuestionPoints, - spec: QuestionSpec, - visibility: BankVisibility, - db: &Database, - ) -> Result, AppError> { - let (kind, choices, correct) = spec.into_parts(); - let rows: Vec = write_with_retry( - db, - "UPDATE $id SET subject = $subject, text = $text, points = $points, - kind = $kind, choices = $choices, correct = $correct, - visibility = $visibility - WHERE subject = $was_subject AND text = $was_text - AND points = $was_points AND kind = $was_kind - AND choices = $was_choices AND correct = $was_correct - AND visibility = $was_visibility - RETURN AFTER", - &[ - ( - "was_subject".into(), - self.subject.clone().map(|s| s.record()).into_value(), - ), - ("was_text".into(), self.text.clone().into_value()), - ("was_points".into(), self.points.into_value()), - ("was_kind".into(), self.kind.clone().into_value()), - ("was_choices".into(), self.choices.clone().into_value()), - ("was_correct".into(), self.correct.clone().into_value()), - ( - "was_visibility".into(), - self.visibility.clone().into_value(), - ), - ("id".into(), self.id.record().into_value()), - ("subject".into(), subject.map(|s| s.record()).into_value()), - ("text".into(), text.into_value()), - ("points".into(), points.into_value()), - ("kind".into(), kind.into_value()), - ("choices".into(), choices.into_value()), - ("correct".into(), correct.into_value()), - ("visibility".into(), visibility.into_value()), - ], - ) - .await?; - Ok(rows.into_iter().next()) - } - - /// Delete the template and cascade-remove its bank images, so none points - /// at a missing template. Bank rows have no answers. The image rows this - /// actually removed come back with it: the blobs are the web layer's to - /// take off disk, but only for *these* rows — an upload that committed - /// after the caller listed the template's images is swept here too, and a - /// pre-read snapshot would strand its blob for good - /// ([`crate::db::note::delete`]'s story, this domain over). - /// - /// Children first, in one transaction: as two queries, a failure between - /// them left image rows swept under a template that survived, or (the other - /// order) a template gone with its images still there. Rides the retry - /// because an image write now moves this very row - /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]) — the - /// two contend by design, and a lost round through a bare `check()` would be - /// a 500 for a delete that only had to be re-sent. Admissible: no `UPDATE` - /// or `DELETE` in here can answer "already exists". - /// - /// Exam questions tied to this template keep living: only their provenance - /// links are cleared, field-scoped (never a whole-row save — the question - /// isn't ours and may be edited concurrently), so nothing can read a link to - /// a template that no longer exists. *Both* directions point at a template, - /// so both are cleared: `from_bank` on the questions instantiated from it, - /// and `banked_as` on the question it was saved out of. - pub async fn delete( - self, - db: &Database, - ) -> Result<(BankQuestion, Vec), AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); - UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; - LET $gone = (DELETE $b RETURN BEFORE); - RETURN { question: $gone, images: $images }; - COMMIT TRANSACTION;", - &[("b".into(), self.id.record().into_value())], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; - let question = outcome - .question - .into_iter() - .next() - .ok_or(AppError::NotFound)?; - Ok((question, outcome.images)) - } - #[allow(clippy::too_many_arguments)] - fn from_parts( + pub(crate) fn from_parts( id: BankQuestionId, owner: UserId, subject: Option, @@ -554,472 +214,10 @@ impl BankQuestion { mod tests { use super::*; - fn spec() -> QuestionSpec { - use crate::domain::exam_question::ChoiceInput; - QuestionSpec::try_new( - QuestionKind::try_new("choice").unwrap(), - Some(vec![ - ChoiceInput { - id: Some("a".into()), - text: "yes".into(), - }, - ChoiceInput { - id: Some("b".into()), - text: "no".into(), - }, - ]), - Some("b".into()), - &[], - ) - .unwrap() - } - - /// A row stored before `visibility` existed has no such key — it must decode - /// as `private`, the safe value. Asserted on the decoder itself, so no - /// schema DEFAULT can paper over it: a `school` default here would publish - /// every pre-existing template in the school at once. - #[tokio::test] - async fn a_row_without_the_field_decodes_private() { - use surrealdb::types::Value; - - let db = crate::database::init_mem().await.unwrap(); - let question = BankQuestion::create( - UserId::generate(), - SubjectId::generate(), - QuestionText::try_new("q").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); - - let mut stored = question.into_value(); - let Value::Object(ref mut map) = stored else { - panic!("a bank question serializes to an object"); - }; - assert!(map.remove("visibility").is_some()); - let old = BankQuestion::from_value(stored).unwrap(); - assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); - assert!(!old.get_visibility().is_school()); - } - - /// The visibility gate is a WHERE clause, so `total` counts exactly what the - /// page can contain — never someone else's private templates. - #[tokio::test] - async fn list_hides_private_templates_from_others() { - let db = crate::database::init_mem().await.unwrap(); - let owner = UserId::generate(); - let other = UserId::generate(); - let private = BankQuestion::create( - owner.clone(), - SubjectId::generate(), - QuestionText::try_new("secret").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - let published = BankQuestion::create( - owner.clone(), - SubjectId::generate(), - QuestionText::try_new("shared").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - let subject = published.get_subject().cloned(); - published - .update_if_unchanged( - subject, - QuestionText::try_new("shared").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), - &db, - ) - .await - .unwrap(); - - // The stranger sees the published one alone, and `total` agrees. - let (items, total) = BankQuestion::list(Some(&other), None, None, None, None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (1, 1)); - assert_eq!(items[0].get_text().as_str(), "shared"); - // The owner sees both; an admin (`None`) too. - let (items, total) = BankQuestion::list(Some(&owner), None, None, None, None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (2, 2)); - let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (2, 2)); - // An explicit `owner=` filter can't widen the gate. - let (items, total) = - BankQuestion::list(Some(&other), Some(&owner), None, None, None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (1, 1)); - assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); - } - - /// The bite test for the compare-and-set that replaced the writer lease of - /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has - /// since moved past must be refused, not written — otherwise it reverts - /// whatever landed in between. Asserts the *stored* row, never a race - /// outcome: the in-memory engine can drop one of two concurrent writes and - /// still answer `Ok`. - #[tokio::test] - async fn a_merge_built_on_a_stale_snapshot_is_refused() { - let db = crate::database::init_mem().await.unwrap(); - let owner = UserId::generate(); - let stale = BankQuestion::create( - owner, - SubjectId::generate(), - QuestionText::try_new("first").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - // Somebody else's edit lands on the row this snapshot came from. - let landed = stale - .clone() - .update_if_unchanged( - None, - QuestionText::try_new("theirs").unwrap(), - QuestionPoints::try_new(2).unwrap(), - spec(), - BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), - &db, - ) - .await - .unwrap(); - assert!(landed.is_some(), "the first write is on a fresh snapshot"); - - let refused = stale - .update_if_unchanged( - None, - QuestionText::try_new("mine").unwrap(), - QuestionPoints::try_new(3).unwrap(), - spec(), - BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), - &db, - ) - .await - .unwrap(); - assert!(refused.is_none(), "a stale merge must not be written"); - let stored = BankQuestion::read(landed.unwrap().get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_text().as_str(), "theirs"); - assert_eq!(stored.get_points().as_i64(), 2); - } - - /// The `visibility` filter ANDs onto the security gate, so it narrows and - /// never widens: a stranger asking for `school` still can't see a private - /// row, and `private` means "my own drafts" for everyone but an admin. - #[tokio::test] - async fn visibility_filter_narrows_never_widens() { - let db = crate::database::init_mem().await.unwrap(); - let owner = UserId::generate(); - let other = UserId::generate(); - let mine = |text: &str| { - BankQuestion::create( - owner.clone(), - SubjectId::generate(), - QuestionText::try_new(text).unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - }; - mine("draft").await.unwrap(); - let published = mine("shared").await.unwrap(); - let subject = published.get_subject().cloned(); - published - .update_if_unchanged( - subject, - QuestionText::try_new("shared").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), - &db, - ) - .await - .unwrap(); - let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(); - let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(); - - // Owner: `private` = their drafts, `school` = the published one. - let (items, total) = - BankQuestion::list(Some(&owner), None, None, Some(&private), None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (1, 1)); - assert_eq!(items[0].get_text().as_str(), "draft"); - let (items, total) = - BankQuestion::list(Some(&owner), None, None, Some(&school), None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (1, 1)); - assert_eq!(items[0].get_text().as_str(), "shared"); - // A stranger's `private` is empty — never someone else's draft. - let (items, total) = - BankQuestion::list(Some(&other), None, None, Some(&private), None, None, 0, &db) - .await - .unwrap(); - assert!(items.is_empty()); - assert_eq!(total, 0); - // …and their `school` stops at the published one, gate intact. - let (items, total) = - BankQuestion::list(Some(&other), None, None, Some(&school), None, None, 0, &db) - .await - .unwrap(); - assert_eq!((items.len(), total), (1, 1)); - // Composes with the other filters: right owner, wrong visibility. - let (items, total) = BankQuestion::list( - Some(&owner), - Some(&owner), - None, - Some(&school), - Some("draft"), - None, - 0, - &db, - ) - .await - .unwrap(); - assert!(items.is_empty()); - assert_eq!(total, 0); - } - - /// The whole page's tally in one grouped statement: right number per - /// template, unused templates absent (so the UI prints nothing rather than - /// "0"), and questions authored by hand never counted. - #[tokio::test] - async fn usage_counts_tallies_a_page_in_one_statement() { - // One statement, so a page costs one round trip — a `;` here would mean - // the per-row N+1 crept back in. - assert!( - !USAGE_COUNTS_SQL.contains(';'), - "usage_counts must be one statement" - ); - - let db = crate::database::init_mem().await.unwrap(); - let owner = UserId::generate(); - let template = |text: &str| { - BankQuestion::create( - owner.clone(), - SubjectId::generate(), - QuestionText::try_new(text).unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - }; - let used_twice = template("twice").await.unwrap(); - let used_once = template("once").await.unwrap(); - let unused = template("never").await.unwrap(); - - // Real exam rows: instantiating a template moves the exam's counter - // (what keeps a question from outliving its exam), so a minted id - // nothing wrote is a 404. - let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); - let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); - // A real subject row: an exam question claims a reference on its - // subject, so a minted id it never wrote would be refused. - let subject = crate::domain::subject::Subject::create( - &crate::db::course::a_test_course(&db).await, - crate::domain::subject::SubjectName::try_new("topic").unwrap(), - crate::domain::subject::SubjectDescription::try_new("").unwrap(), - &db, - ) - .await - .unwrap(); - async fn instantiate( - exam: &ExamId, - subject: &SubjectId, - source: &BankQuestion, - db: &Database, - ) { - crate::db::exam_question::create_from_bank( - db, - exam, - subject.clone(), - source.get_text().clone(), - source.get_points(), - source.spec(), - source.get_id().clone(), - ) - .await - .unwrap(); - } - // Two copies of the same template, in two different exams. - instantiate(&exam, subject.get_id(), &used_twice, &db).await; - instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; - instantiate(&exam, subject.get_id(), &used_once, &db).await; - // A hand-authored question has no `from_bank` and must not be tallied. - crate::db::exam_question::create( - &db, - &exam, - subject.get_id().clone(), - QuestionText::try_new("mine").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - ) - .await - .unwrap(); - - let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; - let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap(); - assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); - assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); - assert_eq!( - counts.get(unused.get_id().key()), - None, - "unused stays absent" - ); - assert_eq!(counts.len(), 2); - - // A template outside the page is never counted into it. - let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db) - .await - .unwrap(); - assert_eq!(narrow.len(), 1); - assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); - // An empty page asks nothing at all. - assert!( - BankQuestion::usage_counts(&[], &db) - .await - .unwrap() - .is_empty() - ); - } - #[test] fn visibility_rejects_anything_else() { assert!(BankVisibility::try_new("public").is_err()); assert!(BankVisibility::try_new("").is_err()); assert!(BankVisibility::try_new("school").unwrap().is_school()); } - - #[tokio::test] - async fn list_is_school_wide() { - let db = crate::database::init_mem().await.unwrap(); - for _ in 0..2 { - BankQuestion::create( - UserId::generate(), - SubjectId::generate(), - QuestionText::try_new("q").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - } - // Different owners, yet both listed. - let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) - .await - .unwrap(); - assert_eq!(items.len(), 2); - assert_eq!(total, 2); - } - - /// The window is SQL, not an in-memory slice, and `total` ignores it. - #[tokio::test] - async fn list_pages_newest_first_and_filters_text() { - let db = crate::database::init_mem().await.unwrap(); - let owner = UserId::generate(); - for i in 0..5 { - BankQuestion::create( - owner.clone(), - SubjectId::generate(), - QuestionText::try_new(&format!("question {i}")).unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - } - let (page, total) = BankQuestion::list(None, None, None, None, None, Some(2), 0, &db) - .await - .unwrap(); - assert_eq!(total, 5); - assert_eq!(page.len(), 2); - // Newest first: the last-created row leads. - assert_eq!(page[0].get_text().as_str(), "question 4"); - // The tail is reachable by offset. - let (tail, _) = BankQuestion::list(None, None, None, None, None, Some(2), 4, &db) - .await - .unwrap(); - assert_eq!(tail[0].get_text().as_str(), "question 0"); - // Text filter runs in SQL, case-insensitively, and narrows `total`. - let (hits, total) = - BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db) - .await - .unwrap(); - assert_eq!((hits.len(), total), (1, 1)); - // Owner filter with nobody's templates. - let (none, total) = BankQuestion::list( - None, - Some(&UserId::generate()), - None, - None, - None, - None, - 0, - &db, - ) - .await - .unwrap(); - assert!(none.is_empty()); - assert_eq!(total, 0); - } - - /// Turkish `İ`/`ı` must not split the search into two disjoint halves. - #[tokio::test] - async fn list_text_filter_folds_turkish_casing() { - let db = crate::database::init_mem().await.unwrap(); - BankQuestion::create( - UserId::generate(), - SubjectId::generate(), - QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), - QuestionPoints::try_new(1).unwrap(), - spec(), - &db, - ) - .await - .unwrap(); - for needle in [ - "istanbul", - "İSTANBUL", - "İstanbul", - "ıstanbul", - "ilçe", - "ILCE", - ] { - let (hits, total) = - BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db) - .await - .unwrap(); - assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); - } - let (miss, total) = - BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db) - .await - .unwrap(); - assert!(miss.is_empty()); - assert_eq!(total, 0); - } } diff --git a/src/domain/bank_question_image.rs b/src/domain/bank_question_image.rs index 3a6cc14..b040b93 100644 --- a/src/domain/bank_question_image.rs +++ b/src/domain/bank_question_image.rs @@ -8,18 +8,17 @@ //! `file` — a fresh server-generated ULID per upload. The row id is //! *deterministic* per (question, slot), so "one image per slot" holds by //! construction and a replace is a plain UPSERT. The web layer owns the blob -//! I/O and its ordering; this module owns the rows. +//! I/O and its ordering; the queries live in +//! [`crate::db::bank_question_image`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; use crate::constant::BANK_QUESTION_IMAGE_TABLE; -use crate::database::{Database, transaction_with_retry}; use crate::domain::bank_question::BankQuestionId; use crate::domain::exam_question::ChoiceId; use crate::domain::key; use crate::domain::note_file::FileContentType; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct BankQuestionImageId(RecordId); @@ -48,31 +47,22 @@ impl BankQuestionImageId { #[derive(Debug, Clone, SurrealValue)] pub struct BankQuestionImage { - id: BankQuestionImageId, - bank_question: BankQuestionId, + pub(crate) id: BankQuestionImageId, + pub(crate) bank_question: BankQuestionId, /// `NONE` = the question's illustration; otherwise the id of the option /// this picture belongs to. - slot: Option, + pub(crate) slot: Option, /// The blob's on-disk name — a fresh ULID every upload. - file: String, - content_type: FileContentType, - size: i64, -} - -/// What one [`BankQuestionImage::upsert`] transaction returns: the row it -/// stored and the blob name it replaced. Both are arrays because SurrealDB -/// drops an object key valued `NONE` on the way out, while an empty array -/// survives — "nothing was replaced" has to be readable, not missing. -#[derive(SurrealValue)] -struct UpsertOutcome { - stored: Vec, - replaced: Vec, + pub(crate) file: String, + pub(crate) content_type: FileContentType, + pub(crate) size: i64, } impl BankQuestionImage { /// Assemble a row (fresh blob name generated here) without persisting it. /// The caller writes the blob under [`Self::get_file`] first, then calls - /// [`Self::upsert`] — so a stored row always points at a real blob. + /// [`crate::db::bank_question_image::upsert`] — so a stored row always + /// points at a real blob. pub fn new( question: &BankQuestionId, slot: Option<&ChoiceId>, @@ -89,6 +79,10 @@ impl BankQuestionImage { } } + pub fn get_id(&self) -> &BankQuestionImageId { + &self.id + } + pub fn get_bank_question(&self) -> &BankQuestionId { &self.bank_question } @@ -108,187 +102,14 @@ impl BankQuestionImage { pub fn get_size(&self) -> i64 { self.size } - - /// Create or replace the slot's image row — the deterministic id makes this - /// the whole "one image per slot" story — handing back what it stored plus - /// the blob name it replaced, for the caller to take off disk. - /// - /// Both halves are the transaction's doing. The template's own `points` is - /// moved and put straight back inside it, the way - /// [`crate::domain::pool_question::bump_question_and_write`] moves - /// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other - /// int column): that makes the template's *existence* part of this write. - /// A bare `UPSERT` guarded by having read the template first does not - /// survive its delete window — the read sees a row - /// [`crate::domain::bank_question::BankQuestion::delete`] has removed but - /// not committed, while that delete's image sweep ran on a snapshot - /// predating this row, so both commit and the image outlives the template - /// it hangs on. Nothing could ever read, delete, or sweep it afterwards: - /// every image route goes through the template. Moving the value makes the - /// two transactions touch one key, so the store refuses a side; writing the - /// same value back would be elided and collide with nothing. - /// - /// The replaced blob name comes out of this same transaction rather than a - /// read in front of it (the shape - /// [`crate::domain::pool_question::PoolQuestion::set_image`] has): two - /// uploads to one slot both write this row, so they contend and the loser - /// re-reads the winner's blob name, where two pre-reads both saw the *old* - /// blob and left the loser's fresh one orphaned on disk. - /// - /// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is - /// deterministic per (question, slot) and the table carries no `UNIQUE` - /// index, so the write always resolves onto the row its id names and can - /// never answer "already exists". - pub async fn upsert( - self, - db: &Database, - ) -> Result<(BankQuestionImage, Option), AppError> { - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic - let (question, id) = (self.bank_question.record(), self.id.record()); - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $was_points = (SELECT VALUE points FROM ONLY $b); - LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); - IF array::len($bumped) = 0 { THROW 'no_question' }; - UPDATE $b SET points = $was_points; - LET $replaced = (SELECT VALUE file FROM $id); - LET $stored = (UPSERT $id CONTENT $image); - RETURN { stored: $stored, replaced: $replaced }; - COMMIT TRANSACTION;", - &[ - ("b".into(), question.into_value()), - ("id".into(), id.into_value()), - ("image".into(), self.into_value()), - ], - &["no_question"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_question")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its - // slot follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - let failed = || AppError::Internal("failed to store bank question image".into()); - let outcome = result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(failed)?; - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; - Ok((stored, outcome.replaced.into_iter().next())) - } - - pub async fn read_slot( - question: &BankQuestionId, - slot: Option<&ChoiceId>, - db: &Database, - ) -> Result, AppError> { - Ok(db - .select(BankQuestionImageId::for_slot(question, slot).record()) - .await?) - } - - pub async fn list_for_question( - question: &BankQuestionId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question = $b") - .bind(("b", question.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The image rows of several templates in one query — for bucketing onto a - /// listing's *page* (never the whole table: the bank spans the school). - pub async fn list_for_questions( - questions: &[&BankQuestionId], - db: &Database, - ) -> Result, AppError> { - if questions.is_empty() { - return Ok(Vec::new()); - } - let records: Vec = questions.iter().map(|q| q.record()).collect(); - let mut result = db - .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Drop the option pictures whose choice is gone — every choice image of - /// the question whose `slot` is *not* in `keep` (the question's own - /// illustration always stays), returning the removed rows so the caller can - /// take their blobs off disk. - /// - /// This is what makes an edit non-destructive: a PATCH that reorders, - /// renames, or drops options passes the surviving choice ids as `keep`, so - /// only the pictures of genuinely removed options go. `keep = &[]` (a text - /// question, or an all-new choice list) still clears the lot. - pub async fn delete_choices_not_in( - question: &BankQuestionId, - keep: &[ChoiceId], - db: &Database, - ) -> Result, AppError> { - let keep: Vec = keep.iter().map(|id| id.as_str().to_string()).collect(); - let mut result = db - .query( - "DELETE bank_question_image \ - WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", - ) - .bind(("b", question.record())) - .bind(("keep", keep)) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - use crate::domain::bank_question::BankQuestion; - use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; - - fn png() -> FileContentType { - FileContentType::try_new("image/png").unwrap() - } - - /// A real template row: an image write moves its `points` inside its own - /// transaction, so a minted id nothing ever wrote is refused. - async fn a_template(db: &Database) -> BankQuestionId { - let id = BankQuestionId::generate(); - db.query( - "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, - visibility = 'private', created_at = 1", - ) - .bind(("b", id.record())) - .await - .unwrap() - .check() - .unwrap(); - id - } fn choice_ids() -> Vec { + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; QuestionSpec::try_new( QuestionKind::try_new("choice").unwrap(), Some( @@ -312,8 +133,8 @@ mod tests { .collect() } - #[tokio::test] - async fn for_slot_keys_by_question_and_choice_id() { + #[test] + fn for_slot_keys_by_question_and_choice_id() { let question = BankQuestionId::from_key("abc"); let ids = choice_ids(); assert_eq!( @@ -330,266 +151,4 @@ mod tests { BankQuestionImageId::for_slot(&question, Some(&ids[1])) ); } - - #[tokio::test] - async fn upsert_replaces_per_slot() { - let db = crate::database::init_mem().await.unwrap(); - let question = a_template(&db).await; - - let (first, retired) = BankQuestionImage::new(&question, None, png(), 3) - .upsert(&db) - .await - .unwrap(); - assert_eq!(retired, None, "a first upload retires no blob"); - let (second, retired) = BankQuestionImage::new(&question, None, png(), 5) - .upsert(&db) - .await - .unwrap(); - // Same slot, same row — the replace swapped the blob pointer, and the - // write itself names the blob the caller must unlink. - assert_ne!(first.get_file(), second.get_file()); - assert_eq!(retired.as_deref(), Some(first.get_file())); - let rows = BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].get_size(), 5); - } - - /// The bank half of the non-destructive edit: keeping an option keeps its - /// picture, and only a removed option's picture goes. - #[tokio::test] - async fn only_the_dropped_options_lose_their_pictures() { - let db = crate::database::init_mem().await.unwrap(); - let question = a_template(&db).await; - let ids = choice_ids(); - BankQuestionImage::new(&question, None, png(), 1) - .upsert(&db) - .await - .unwrap(); - for id in &ids { - BankQuestionImage::new(&question, Some(id), png(), 1) - .upsert(&db) - .await - .unwrap(); - } - - let keep = vec![ids[0].clone(), ids[1].clone()]; - let dropped = BankQuestionImage::delete_choices_not_in(&question, &keep, &db) - .await - .unwrap(); - assert_eq!(dropped.len(), 1); - assert_eq!(dropped[0].get_slot(), Some(&ids[2])); - - let left = BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - assert_eq!(left.len(), 3); - } - - #[tokio::test] - async fn an_empty_keep_set_clears_every_option_picture() { - let db = crate::database::init_mem().await.unwrap(); - let question = a_template(&db).await; - let ids = choice_ids(); - BankQuestionImage::new(&question, None, png(), 1) - .upsert(&db) - .await - .unwrap(); - for id in &ids[..2] { - BankQuestionImage::new(&question, Some(id), png(), 1) - .upsert(&db) - .await - .unwrap(); - } - - let dropped = BankQuestionImage::delete_choices_not_in(&question, &[], &db) - .await - .unwrap(); - assert_eq!(dropped.len(), 2); - assert!(dropped.iter().all(|image| image.get_slot().is_some())); - - let left = BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap(); - assert_eq!(left.len(), 1); - assert_eq!(left[0].get_slot(), None); - } - - /// The [`crate::domain::pool_question::PoolQuestion`] defect, one domain - /// over: an image written inside its template's delete window must not - /// outlive it. Guarding the write by *reading* the template does not do it - /// — the read sees a row [`BankQuestion::delete`] has removed but not - /// committed, while its `DELETE bank_question_image WHERE bank_question = - /// $b` ran on a snapshot predating this row, so both commit and the image - /// is left pointing at a template that is gone. Nothing can reach it after - /// that: every image route resolves the template first, no boot sweep - /// visits this table, and its blob stays on disk for good. [`Self::upsert`] - /// moves the template's own `points` instead, so the two transactions touch - /// one key and the store refuses a side. - /// - /// The blob half is asserted through the list the delete hands back: that - /// list — never a snapshot read before it — is what the web layer unlinks - /// from, so an image that committed inside the window and is *not* in it is - /// a blob stranded on disk. - /// - /// The window is opened by the schema, not by a lucky interleaving: a - /// `DEFINE EVENT` on `bank_question` fires inside the delete's own - /// transaction the instant the row goes. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both and answers `Ok` to each, so this passes there on broken - /// code. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { - let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; - db.query( - "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut swept, mut orphans, mut stranded) = (0, 0, 0); - for round in 0..4 { - let question = a_template(&db).await; - let template = BankQuestion::read(&question, &db).await.unwrap().unwrap(); - - let drop_it = { - let db = db.clone(); - tokio::spawn(async move { template.delete(&db).await }) - }; - // The upload starts inside the held window — the template row is - // gone but uncommitted, which is exactly what the handler's - // ownership read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, question) = (db.clone(), question.clone()); - tokio::spawn(async move { - BankQuestionImage::new(&question, None, png(), 3) - .upsert(&db) - .await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the upload is a correct answer; the only defect is - // stored state. Neither side may 500 — they contend by design and a - // lost round is re-sent, not reported. - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced upload must be answered, not 500: {child:?}" - ); - assert!( - !matches!(drop_it, Err(AppError::Db(_))), - "round {round}: a raced delete must retry, not 500: {drop_it:?}" - ); - - // Stored state is the whole verdict; a return value is not evidence. - if BankQuestion::read(&question, &db).await.unwrap().is_none() { - swept += 1; - orphans += BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap() - .len(); - if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) - && !images - .iter() - .any(|image| image.get_file() == stored.get_file()) - { - stranded += 1; - } - } - } - eprintln!("BankQuestion::delete raced by an upload: {swept}/4 rounds deleted the template"); - assert!( - swept > 0, - "no round ever deleted the template, so the window was never reached" - ); - assert_eq!(orphans, 0, "an image row outlived its template"); - assert_eq!( - stranded, 0, - "an image committed inside the window was swept without being handed back, so its blob stays on disk" - ); - } - - /// Two uploads to one slot must leave exactly one live blob and hand every - /// other one back to be unlinked. Reading the slot's old blob name *before* - /// the write gave both racers the same answer: both retired the same old - /// blob, and the loser's fresh one stayed on disk with nothing naming it. - /// [`Self::upsert`] reads it inside its own transaction instead, so the - /// loser contends on the row it writes and re-reads the winner's name. - /// - /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this - /// table holds the first write open inside its own transaction, so the - /// second reads the slot before the first commits. - /// - /// Real server, and `#[ignore]`d for it, for the reason above: the embedded - /// engine has no write-write conflict detection to make a loser re-read. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn two_uploads_to_one_slot_leave_no_blob_unretired() { - let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; - db.query( - "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ - THEN { SLEEP 300ms; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let mut unretired = 0; - for round in 0..3 { - let question = a_template(&db).await; - // A first picture, so both racers have an old blob to retire. - let (original, _) = BankQuestionImage::new(&question, None, png(), 1) - .upsert(&db) - .await - .unwrap(); - - let mut writes = Vec::new(); - for size in [2, 3] { - let (db, question) = (db.clone(), question.clone()); - writes.push(tokio::spawn(async move { - BankQuestionImage::new(&question, None, png(), size) - .upsert(&db) - .await - })); - } - let mut written = vec![original.get_file().to_string()]; - let mut retired = Vec::new(); - for write in writes { - let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| { - panic!("round {round}: a raced upload must not 500: {err:?}") - }); - written.push(stored.get_file().to_string()); - retired.extend(replaced); - } - - // Stored state is the whole verdict: exactly one blob is live, and - // every other one this round wrote must have been handed back — - // once. A name written and never returned is a file on disk with - // nothing pointing at it. - let live = BankQuestionImage::read_slot(&question, None, &db) - .await - .unwrap() - .unwrap(); - assert!( - !retired.iter().any(|name| name == live.get_file()), - "round {round}: the live row's own blob was retired" - ); - unretired += written - .iter() - .filter(|name| *name != live.get_file() && !retired.contains(name)) - .count(); - } - assert_eq!( - unretired, 0, - "a blob was written and never handed back to be unlinked — it stays on disk forever" - ); - } } diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 3d9a983..9a440fd 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -146,7 +146,7 @@ impl PomodoroSession { /// They move only for a stint that **counts**, which is /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this - /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] + /// is the farm [`crate::db::pool_question::approve`] /// argues about from the other end: finishing is self-service, one stint is /// two requests and no second person, so a counter moved once per /// round-trip is farmable — two hundred pairs inside the rate limit bought diff --git a/src/domain/pool_question.rs b/src/domain/pool_question.rs index 8b63202..86d5c85 100644 --- a/src/domain/pool_question.rs +++ b/src/domain/pool_question.rs @@ -8,95 +8,29 @@ //! the row as metadata (`image_*`); the bytes live on disk under //! [`crate::config::Config::files_path`] in a file named by `image_file` — a //! fresh server-generated ULID per upload. The web layer owns the blob I/O; -//! this module owns the rows. +//! the queries live in [`crate::db::pool_question`], the workflows in +//! [`crate::service::pool_question`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ - MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_APPROVED_TOTAL_FIELD, - POOL_PUBLISHED_TOTAL_FIELD, POOL_QUESTION_TABLE, STATUS_APPROVED, STATUS_PENDING, + MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, + STATUS_PENDING, }; -use crate::database::{Database, transaction_with_retry}; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; -use crate::domain::solution::Solution; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; -/// Move the question's `asked_at` **and** run `statement` — a write to -/// something hanging off a question — in one transaction, handing back the row -/// it returned. `NotFound` means the question is gone and nothing was written. -/// -/// The move is what makes the question's **existence** part of the child's own -/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: -/// the `UPDATE` matches nothing once the row is deleted, and a delete racing -/// this one touches the very key this transaction writes, so the two cannot -/// both commit. Reading the question first does *not* survive that race — the -/// read sees a row [`PoolQuestion::delete`] has removed but not committed, -/// while its `DELETE solution WHERE question = $q` ran on a snapshot predating -/// this insert, so both commit and the child outlives its question with neither -/// caller told anything. -/// -/// `asked_at` rather than a revision column because this row carries no counter -/// to bump and must not grow one for this alone. It is put back *by captured -/// value* in the same transaction, so nothing outside ever observes the move -/// and the row is byte-identical afterwards (the pool lists order on it). -/// Writing the same value would buy nothing: an `UPDATE` that leaves the -/// document unchanged is elided and never reaches the store's write set, so it -/// collides with nothing. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the -/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already -/// exists". -pub(crate) async fn bump_question_and_write( - question: &PoolQuestionId, - statement: &str, - mut bindings: Vec<(String, surrealdb::types::Value)>, - db: &Database, -) -> Result, AppError> { - bindings.push(("q".into(), question.record().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); - LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); - IF array::len($bumped) = 0 {{ THROW 'no_question' }}; - UPDATE $q SET asked_at = $was_asked; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_question"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_question")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is the last statement before `COMMIT`, so its slot - // follows the statement count rather than a hand-kept number; - // `num_statements` counts BEGIN and COMMIT. - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) -} - #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct PoolQuestionId(RecordId); impl PoolQuestionId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break ([`PoolQuestion::list_all`]), + /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break + /// ([`crate::db::pool_question::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) @@ -148,18 +82,18 @@ impl PoolQuestionBody { #[derive(Debug, Clone, SurrealValue)] pub struct PoolQuestion { - id: PoolQuestionId, - asker: UserId, - title: PoolQuestionTitle, - body: PoolQuestionBody, - status: String, - asked_at: Timestamp, - approved_by: Option, + pub(crate) id: PoolQuestionId, + pub(crate) asker: UserId, + pub(crate) title: PoolQuestionTitle, + pub(crate) body: PoolQuestionBody, + pub(crate) status: String, + pub(crate) asked_at: Timestamp, + pub(crate) approved_by: Option, /// The photo's on-disk blob name — a fresh ULID every upload; `None` when /// the question carries no image. - image_file: Option, - image_content_type: Option, - image_size: Option, + pub(crate) image_file: Option, + pub(crate) image_content_type: Option, + pub(crate) image_size: Option, } impl PoolQuestion { @@ -221,589 +155,4 @@ impl PoolQuestion { pub fn get_image_size(&self) -> Option { self.image_size } - - pub async fn insert(self, db: &Database) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let created: Option = db.create(self.id.record()).content(self).await?; - created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) - } - - pub async fn read( - id: &PoolQuestionId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every question, newest first — the teacher+ view (approval queue and - /// pool in one list). - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// The pool as a non-staff user sees it, newest first: every approved - /// question, plus the caller's own pending ones. - pub async fn list_visible_to( - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ - ORDER BY asked_at DESC, id DESC", - ) - .bind(("approved", STATUS_APPROVED)) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Publish a pending question into the pool, stamping who approved it. - /// The `WHERE status = $pending` guard makes the transition atomic: of two - /// racing approvals exactly one wins, and an approve can never land on a - /// question deleted mid-flight. `None` = the question wasn't pending - /// (already approved, or gone) — the caller sorts out which. - /// - /// Two lifetime badge counters ride that same guard, inside this - /// transaction: the approver's `pool_approved_total` and the *asker's* - /// `pool_published_total`. Both hang off `array::len($done) > 0` — the - /// guard's own verdict — so the pair moves once per real transition and - /// never on a second approve of an already-approved question. - /// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that - /// holds.) The second conjunct is the self-approval rule below. - /// - /// Two rules keep the pair unfarmable, one per side of the transition. - /// - /// The asker is credited at *approval*, not at asking: a bare - /// [`insert`](PoolQuestion::insert) is self-service and the author can - /// delete their own question and ask again forever, so a counter moved - /// there is farmable. Approval is teacher-gated and one-way, which is why - /// the family is named `pool_published` and not `pool_asked`. That closes - /// the student side. - /// - /// And a *self*-approval — a teacher+ approving a question they asked - /// themselves, which the route deliberately still allows — moves neither - /// counter, hence the `$done[0].asker != $by` half of the condition. It is - /// the same farm from the other end (ask, approve, delete, repeat, with no - /// second person involved), and the two together are why a counter can only - /// move when one person's work was judged by another's. Nothing else about - /// a self-approval changes: same 200, same freeze, same stamp — this skips - /// the credit, not the approval. - /// - /// Re-sent while the store answers "conflict, retry": the guard reads a - /// column a rival approve writes, and both counters sit on user rows every - /// other counter site writes too. Sound to re-send — every statement is an - /// `UPDATE`, none of which can legitimately answer "already exists" — and a - /// lost round aborts having written nothing, increments included. - pub async fn approve( - id: &PoolQuestionId, - approver: &UserId, - db: &Database, - ) -> Result, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $done = (UPDATE $q SET status = $approved, approved_by = $by - WHERE status = $pending RETURN AFTER); - IF array::len($done) > 0 AND $done[0].asker != $by {{ - UPDATE $by SET - {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; - LET $asker = $done[0].asker; - UPDATE $asker SET - {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; - }}; - RETURN $done; - COMMIT TRANSACTION;" - ), - &[ - ("q".into(), id.record().into_value()), - ("approved".into(), STATUS_APPROVED.to_string().into_value()), - ("by".into(), approver.record().into_value()), - ("pending".into(), STATUS_PENDING.to_string().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`, - // so its slot follows the statement count rather than a hand-kept - // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). - let slot = result.num_statements().saturating_sub(2); - Ok(result.take::>(slot)?.into_iter().next()) - } - - /// Point the question at a freshly written image blob. Guarded on - /// `pending` for the same reason approval is: an image landing after - /// approval would put unmoderated bytes in the pool, so an upload that - /// loses the race gets `None` (and the caller takes the orphan blob back - /// off disk). Returns the *before* row — its `image_file` is the replaced - /// blob the caller must remove. - pub async fn set_image( - id: &PoolQuestionId, - file: &str, - content_type: &FileContentType, - size: i64, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ - WHERE status = $pending RETURN BEFORE", - ) - .bind(("q", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Detach the question's image (pending only, like `set_image`). Returns - /// the *before* row — its `image_file` is the blob the caller must remove. - pub async fn clear_image( - id: &PoolQuestionId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - WHERE status = $pending RETURN BEFORE", - ) - .bind(("q", id.record())) - .bind(("pending", STATUS_PENDING)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Delete the question and its solutions in one transaction, returning - /// the removed rows — the question's *and* the swept solutions' — so the - /// caller can take every image blob off disk (solutions carry photos too, - /// and a row-only sweep would strand theirs forever). - /// - /// Rides the retry because a solution offer now writes this very row - /// ([`bump_question_and_write`]): the two contend by design, and a lost - /// round through a bare `check()` was a 500 for a delete that only had to - /// be re-sent. Admissible — a `DELETE` can never answer "already exists". - pub async fn delete( - id: &PoolQuestionId, - db: &Database, - ) -> Result)>, AppError> { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE solution WHERE question = $q RETURN BEFORE; - DELETE $q RETURN BEFORE; - COMMIT TRANSACTION;", - &[("q".into(), id.record().into_value())], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. - let solutions = result.take::>(1)?; - Ok(result - .take::>(2)? - .into_iter() - .next() - .map(|question| (question, solutions))) - } -} - -#[cfg(test)] -mod tests { - use ulid::Ulid; - - use super::*; - use crate::database; - use crate::domain::solution::{Solution, SolutionBody}; - - /// The two counter columns plus a row to carry them: the `user` table is - /// SCHEMAFULL in production, and the counters are `option` there. - async fn a_user(db: &Database) -> UserId { - let user = UserId::from_key(&Ulid::new().to_string()); - db.query(format!( - "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; - CREATE $usr SET username = $name, password_hash = 'x';" - )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); - user - } - - /// `(pool_approved_total, pool_published_total)` as stored — absent reads - /// zero, the way `BadgeStats::load` reads it. - async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), - ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows = result.take::>>(0).unwrap(); - let row = rows.into_iter().next().unwrap_or_default(); - ( - row.first().copied().unwrap_or(0), - row.get(1).copied().unwrap_or(0), - ) - } - - fn question(asker: &UserId) -> PoolQuestion { - PoolQuestion::new( - asker, - PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), - PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), - ) - } - - #[tokio::test] - async fn approval_is_a_one_way_race_safe_transition() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::new().to_string()); - let teacher = UserId::from_key(&Ulid::new().to_string()); - - let q = question(&asker).insert(&db).await.unwrap(); - assert_eq!(q.get_status(), STATUS_PENDING); - assert!(q.get_approved_by().is_none()); - - let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - assert!(approved.is_approved()); - assert_eq!(approved.get_approved_by(), Some(&teacher)); - - // A second approval finds nothing pending. - assert!( - PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .is_none() - ); - // And a missing question approves to None, not an error. - assert!( - PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) - .await - .unwrap() - .is_none() - ); - } - - /// The publish counters ride the guard, so they move exactly once per real - /// transition: the approver's on the approve side, the asker's on the - /// published side, and neither on a second approve of the same question. - #[tokio::test] - async fn approval_moves_both_counters_once_and_only_once() { - let db = database::init_mem().await.unwrap(); - let asker = a_user(&db).await; - let teacher = a_user(&db).await; - - let q = question(&asker).insert(&db).await.unwrap(); - assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); - - PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); - assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); - - // The guard finds nothing pending, so neither counter may move — this - // is what stops an approve loop from farming either one. - assert!( - PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .is_none() - ); - assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); - assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); - - // And an approve that lands on nothing at all writes nothing. - assert!( - PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) - .await - .unwrap() - .is_none() - ); - assert_eq!(counters(&teacher, &db).await, (1, 0)); - } - - /// A teacher may ask a question and the route does not bar them from - /// approving it — that still works, unchanged. What it does not do is pay - /// for itself: ask, approve, delete, repeat is the staff-side farm, and - /// neither counter moves when one person is both ends of the transition. - #[tokio::test] - async fn self_approval_still_approves_but_moves_neither_counter() { - let db = database::init_mem().await.unwrap(); - let teacher = a_user(&db).await; - - let q = question(&teacher).insert(&db).await.unwrap(); - let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - // The approval itself is untouched: published, stamped, frozen. - assert!(approved.is_approved()); - assert_eq!(approved.get_approved_by(), Some(&teacher)); - assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); - - // And the skip is about the *pair*, not about the teacher: approving - // somebody else's question right after still pays. - let asker = a_user(&db).await; - let other = question(&asker).insert(&db).await.unwrap(); - PoolQuestion::approve(other.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(counters(&teacher, &db).await, (1, 0)); - assert_eq!(counters(&asker, &db).await, (0, 1)); - } - - #[tokio::test] - async fn visibility_hides_others_pending_questions() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::new().to_string()); - let other = UserId::from_key(&Ulid::new().to_string()); - let teacher = UserId::from_key(&Ulid::new().to_string()); - - let pending = question(&asker).insert(&db).await.unwrap(); - let published = question(&other).insert(&db).await.unwrap(); - PoolQuestion::approve(published.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - - // The asker sees their own pending question plus the pool; a stranger - // sees only the pool; the teacher view (list_all) sees everything. - assert_eq!( - PoolQuestion::list_visible_to(&asker, &db) - .await - .unwrap() - .len(), - 2 - ); - let stranger_view = PoolQuestion::list_visible_to(&other, &db).await.unwrap(); - assert_eq!(stranger_view.len(), 1); - assert_eq!(stranger_view[0].get_id(), published.get_id()); - assert_eq!(PoolQuestion::list_all(&db).await.unwrap().len(), 2); - assert!( - PoolQuestion::read(pending.get_id(), &db) - .await - .unwrap() - .is_some() - ); - } - - #[tokio::test] - async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::new().to_string()); - let teacher = UserId::from_key(&Ulid::new().to_string()); - let png = FileContentType::try_new("image/png").unwrap(); - - let q = question(&asker).insert(&db).await.unwrap(); - let before = PoolQuestion::set_image(q.get_id(), "blob_a", &png, 3, &db) - .await - .unwrap() - .unwrap(); - assert!(before.get_image_file().is_none()); - - // A replace reports the old blob for cleanup. - let before = PoolQuestion::set_image(q.get_id(), "blob_b", &png, 5, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_a")); - let stored = PoolQuestion::read(q.get_id(), &db).await.unwrap().unwrap(); - assert_eq!(stored.get_image_file(), Some("blob_b")); - assert_eq!(stored.get_image_size(), Some(5)); - - // Clearing reports the detached blob and empties the fields. - let before = PoolQuestion::clear_image(q.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_b")); - assert!( - PoolQuestion::read(q.get_id(), &db) - .await - .unwrap() - .unwrap() - .get_image_file() - .is_none() - ); - - // Once approved, the image is frozen with the rest of the content. - PoolQuestion::approve(q.get_id(), &teacher, &db) - .await - .unwrap() - .unwrap(); - assert!( - PoolQuestion::set_image(q.get_id(), "blob_c", &png, 7, &db) - .await - .unwrap() - .is_none() - ); - assert!( - PoolQuestion::clear_image(q.get_id(), &db) - .await - .unwrap() - .is_none() - ); - } - - #[tokio::test] - async fn delete_cascades_solutions_and_returns_the_row() { - let db = database::init_mem().await.unwrap(); - let asker = UserId::from_key(&Ulid::new().to_string()); - let helper = UserId::from_key(&Ulid::new().to_string()); - - let q = question(&asker).insert(&db).await.unwrap(); - let offered = Solution::new( - q.get_id(), - &helper, - SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), - ) - .insert(&db) - .await - .unwrap(); - - // The swept solutions ride back with the question so the caller can - // take their image blobs off disk. - let (removed, swept) = PoolQuestion::delete(q.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(removed.get_id(), q.get_id()); - assert_eq!(swept.len(), 1); - assert_eq!(swept[0].get_id(), offered.get_id()); - assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none()); - assert!( - Solution::list_for(q.get_id(), None, 0, &db) - .await - .unwrap() - .0 - .is_empty() - ); - - // Deleting the already-deleted is None, not an error. - assert!( - PoolQuestion::delete(q.get_id(), &db) - .await - .unwrap() - .is_none() - ); - } - - /// The [`crate::domain::exam_answer::ExamAnswer::save`] defect, one domain - /// over: a solution offered inside its question's delete window must not - /// outlive it. Guarding the offer by *reading* the question does not do it - /// — the read sees a row [`PoolQuestion::delete`] has removed but not - /// committed, while its `DELETE solution WHERE question = $q` ran on a - /// snapshot predating the offer, so both commit and the solution is left - /// pointing at a question that is gone. Nothing can reach it after that: - /// every route to a solution goes through its question, so neither a - /// reader nor a second delete can ever clear it, and its photo stays on - /// disk for good. [`bump_question_and_write`] moves the question's own - /// `asked_at` instead, so the two transactions touch one key and the store - /// refuses one of them. - /// - /// The window is opened by the database, not by a lucky interleaving: a - /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own - /// transaction the instant the row goes, so the `SLEEP` lands exactly - /// between the delete and its cascade every time. - /// - /// Real server, and `#[ignore]`d for it: the subject *is* the store's - /// conflict detection, which `init_mem`'s embedded engine does not have — - /// it commits both writes and answers `Ok` to each, so this passes there on - /// broken code. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { - let (db, _serialized) = database::init_test_server("solution_race").await; - // Hold the delete open for a full second after the row is gone, while - // its cascade still has to run. - db.query( - "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ - THEN { SLEEP 1s; };", - ) - .await - .unwrap() - .check() - .unwrap(); - - let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); - for round in 0..4 { - let asker = UserId::from_key(&Ulid::new().to_string()); - let helper = UserId::from_key(&Ulid::new().to_string()); - let q = question(&asker).insert(&db).await.unwrap(); - let id = q.get_id().clone(); - - let drop_it = { - let (db, id) = (db.clone(), id.clone()); - tokio::spawn(async move { PoolQuestion::delete(&id, &db).await }) - }; - // The offer starts inside the held window — the question row is - // gone but uncommitted, which is exactly what a read believes. - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - let child = { - let (db, id) = (db.clone(), id.clone()); - tokio::spawn(async move { - Solution::new( - &id, - &helper, - SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), - ) - .insert(&db) - .await - }) - }; - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); - // A 404 for the offer is a correct answer; the only defect is - // stored state. The delete must not 500 either — it contends with - // the offer by design and a lost round is re-sent, not reported. - assert!( - !matches!(child, Err(AppError::Db(_))), - "round {round}: a raced offer must be answered, not 500: {child:?}" - ); - if matches!(drop_it, Err(AppError::Db(_))) { - delete_500 += 1; - } - - // Stored state is the whole verdict; a return value is not evidence. - if PoolQuestion::read(&id, &db).await.unwrap().is_none() { - swept += 1; - solutions += Solution::list_for(&id, None, 0, &db).await.unwrap().0.len(); - } - } - eprintln!("PoolQuestion::delete raced by an offer: {swept}/4 rounds deleted the question"); - assert!( - swept > 0, - "no round ever deleted the question, so the window was never reached" - ); - assert_eq!(solutions, 0, "a solution outlived its question"); - assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); - } } diff --git a/src/domain/solution.rs b/src/domain/solution.rs index 452bab9..8d05515 100644 --- a/src/domain/solution.rs +++ b/src/domain/solution.rs @@ -5,21 +5,18 @@ //! Like a question, a solution may carry one photo (`image_*` metadata on the //! row, bytes on disk under a server-generated ULID) — but unlike a question //! it has no moderation state, so its author may edit the body and swap the -//! photo at any time; there is nothing to freeze. - -use std::collections::HashMap; +//! photo at any time; there is nothing to freeze. The queries live in +//! [`crate::db::solution`], the funnels in [`crate::service::solution`]. use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; -use crate::database::Database; use crate::domain::monotonic_id::next_ulid; use crate::domain::note_file::FileContentType; -use crate::db::page::PagedList; -use crate::domain::pool_question::{PoolQuestionId, bump_question_and_write}; +use crate::domain::pool_question::PoolQuestionId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_required; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -27,7 +24,8 @@ pub struct SolutionId(RecordId); impl SolutionId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break ([`Solution::list_for_question`]), + /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break + /// ([`crate::db::solution::list_for`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) @@ -65,23 +63,16 @@ impl SolutionBody { #[derive(Debug, Clone, SurrealValue)] pub struct Solution { - id: SolutionId, - question: PoolQuestionId, - author: UserId, - body: SolutionBody, - offered_at: Timestamp, + pub(crate) id: SolutionId, + pub(crate) question: PoolQuestionId, + pub(crate) author: UserId, + pub(crate) body: SolutionBody, + pub(crate) offered_at: Timestamp, /// The photo's on-disk blob name — a fresh ULID every upload; `None` when /// the solution carries no image. - image_file: Option, - image_content_type: Option, - image_size: Option, -} - -/// One `GROUP BY question` row of [`Solution::counts_for`]. -#[derive(SurrealValue)] -struct SolutionCount { - question: PoolQuestionId, - n: i64, + pub(crate) image_file: Option, + pub(crate) image_content_type: Option, + pub(crate) image_size: Option, } impl Solution { @@ -129,369 +120,14 @@ impl Solution { pub fn get_image_size(&self) -> Option { self.image_size } - - /// Offer the solution. `NotFound` = the question is gone, and nothing was - /// written: the create rides [`bump_question_and_write`], so the question's - /// existence is a *write* to its row rather than a read the handler made a - /// moment earlier — a bare create landing inside - /// [`PoolQuestion::delete`](crate::domain::pool_question::PoolQuestion::delete)'s - /// window was swept by nothing and left a solution no route could ever - /// reach or remove (every path to one goes through its question), photo - /// blob included. - /// - /// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call - /// on a table with no `UNIQUE` index, so a re-send cannot answer "already - /// exists" — the one thing the retry could not survive. - pub async fn insert(self, db: &Database) -> Result { - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber - let (question, id) = (self.question.clone(), self.id.record()); - bump_question_and_write( - &question, - "CREATE $id CONTENT $solution", - vec![ - ("id".into(), id.into_value()), - ("solution".into(), self.into_value()), - ], - db, - ) - .await? - .ok_or_else(|| AppError::Internal("failed to create solution".into())) - } - - /// Read a solution only if it belongs to `question` — keeps the nested - /// route honest (a solution id under someone else's question 404s). - pub async fn read_for( - id: &SolutionId, - question: &PoolQuestionId, - db: &Database, - ) -> Result, AppError> { - let solution: Option = db.select(id.record()).await?; - Ok(solution.filter(|solution| &solution.question == question)) - } - - /// The question's solutions, oldest first — a discussion reads downward. - /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond - /// offers *stable* across re-queries, not insertion-ordered (ULID low bits - /// are random within a millisecond, so same-ms order is arbitrary). - pub async fn list_for( - question: &PoolQuestionId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "solution WHERE question = $q", - "ORDER BY offered_at ASC, id ASC", - ) - .bind("q", question.record()) - .run(limit, offset, db) - .await - } - - /// Per-question solution tallies for a page of questions, in one grouped - /// query — a per-row `count()` would cost a query per question. Keys are - /// question record keys; a question with no solutions has no entry, so - /// the caller reads misses as zero. - pub async fn counts_for( - questions: &[PoolQuestionId], - db: &Database, - ) -> Result, AppError> { - if questions.is_empty() { - return Ok(HashMap::new()); - } - let ids: Vec = questions.iter().map(|question| question.record()).collect(); - let mut result = db - .query("SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question") - .bind(("qs", ids)) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .map(|row| (row.question.key().to_string(), row.n)) - .collect()) - } - - /// Replace the body. Unconditional (solutions have no moderation state to - /// guard, unlike a question's `pending` gate) — `None` only means the row - /// was deleted mid-flight. Authorship is the web layer's check. - pub async fn set_body( - id: &SolutionId, - body: &SolutionBody, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET body = $b RETURN AFTER") - .bind(("s", id.record())) - .bind(("b", body.clone())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Point the solution at a freshly written image blob. Unconditional for - /// the same reason as [`Self::set_body`]. Returns the *before* row — its - /// `image_file` is the replaced blob the caller must remove; `None` means - /// the row was deleted mid-flight (the fresh blob is the caller's orphan - /// to take back off disk). - pub async fn set_image( - id: &SolutionId, - file: &str, - content_type: &FileContentType, - size: i64, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") - .bind(("s", id.record())) - .bind(("file", file.to_string())) - .bind(("ct", content_type.clone())) - .bind(("size", size)) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - /// Detach the solution's image. Returns the *before* row — its - /// `image_file` is the blob the caller must remove. - pub async fn clear_image(id: &SolutionId, db: &Database) -> Result, AppError> { - let mut result = db - .query( - "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ - RETURN BEFORE", - ) - .bind(("s", id.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - pub async fn delete(self, db: &Database) -> Result { - let deleted: Option = db.delete(self.id.record()).await?; - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { - use ulid::Ulid; - use super::*; - /// A real question row: offering a solution moves its question's - /// `asked_at` (that is what keeps a solution from outliving its question), - /// so a minted id nothing wrote is a 404. - async fn question_row(db: &Database) -> PoolQuestionId { - use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; - PoolQuestion::new( - &UserId::from_key(&Ulid::new().to_string()), - PoolQuestionTitle::try_new("soru").unwrap(), - PoolQuestionBody::try_new("neden").unwrap(), - ) - .insert(db) - .await - .unwrap() - .get_id() - .clone() - } - - #[tokio::test] - async fn rows_scope_to_their_question_and_list_oldest_first() { - let db = crate::database::init_mem().await.unwrap(); - let question_a = question_row(&db).await; - let question_b = question_row(&db).await; - let author = UserId::from_key(&Ulid::new().to_string()); - - // Distinct offer times so the assertion pins the real contract — - // older `offered_at` sorts first — not the same-millisecond `id` - // tiebreak, whose random ULID low bits would make the order a coin - // flip (two `now()` reads can land in one millisecond). - let mut first = Solution::new( - &question_a, - &author, - SolutionBody::try_new("Önce türevi al.").unwrap(), - ); - first.offered_at = Timestamp::from_millis(1); - let first = first.insert(&db).await.unwrap(); - let mut second = Solution::new( - &question_a, - &author, - SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), - ); - second.offered_at = Timestamp::from_millis(2); - let second = second.insert(&db).await.unwrap(); - - let (listed, _) = Solution::list_for(&question_a, None, 0, &db).await.unwrap(); - assert_eq!(listed.len(), 2); - assert_eq!(listed[0].get_id(), first.get_id()); - assert_eq!(listed[1].get_id(), second.get_id()); - assert!( - Solution::list_for(&question_b, None, 0, &db) - .await - .unwrap() - .0 - .is_empty() - ); - - // Readable under its own question, invisible under another. - assert!( - Solution::read_for(first.get_id(), &question_a, &db) - .await - .unwrap() - .is_some() - ); - assert!( - Solution::read_for(first.get_id(), &question_b, &db) - .await - .unwrap() - .is_none() - ); - - first.delete(&db).await.unwrap(); - assert_eq!( - Solution::list_for(&question_a, None, 0, &db) - .await - .unwrap() - .0 - .len(), - 1 - ); - } - - #[tokio::test] - async fn image_set_replace_clear_report_the_replaced_blob() { - let db = crate::database::init_mem().await.unwrap(); - let question = question_row(&db).await; - let author = UserId::from_key(&Ulid::new().to_string()); - let png = FileContentType::try_new("image/png").unwrap(); - - let solution = Solution::new( - &question, - &author, - SolutionBody::try_new("Grafiği çiz.").unwrap(), - ) - .insert(&db) - .await - .unwrap(); - - let before = Solution::set_image(solution.get_id(), "blob_a", &png, 3, &db) - .await - .unwrap() - .unwrap(); - assert!(before.get_image_file().is_none()); - - // A replace reports the old blob for cleanup. - let before = Solution::set_image(solution.get_id(), "blob_b", &png, 5, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_a")); - let stored = Solution::read_for(solution.get_id(), &question, &db) - .await - .unwrap() - .unwrap(); - assert_eq!(stored.get_image_file(), Some("blob_b")); - assert_eq!(stored.get_image_size(), Some(5)); - - // Clearing reports the detached blob and empties the fields. - let before = Solution::clear_image(solution.get_id(), &db) - .await - .unwrap() - .unwrap(); - assert_eq!(before.get_image_file(), Some("blob_b")); - assert!( - Solution::read_for(solution.get_id(), &question, &db) - .await - .unwrap() - .unwrap() - .get_image_file() - .is_none() - ); - - // A row deleted mid-flight surfaces as None, not an error. - solution.clone().delete(&db).await.unwrap(); - assert!( - Solution::set_image(solution.get_id(), "blob_c", &png, 7, &db) - .await - .unwrap() - .is_none() - ); - assert!( - Solution::clear_image(solution.get_id(), &db) - .await - .unwrap() - .is_none() - ); - } - - #[tokio::test] - async fn set_body_edits_in_place() { - let db = crate::database::init_mem().await.unwrap(); - let question = question_row(&db).await; - let author = UserId::from_key(&Ulid::new().to_string()); - - let solution = Solution::new( - &question, - &author, - SolutionBody::try_new("İlk deneme.").unwrap(), - ) - .insert(&db) - .await - .unwrap(); - - let edited = Solution::set_body( - solution.get_id(), - &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), - &db, - ) - .await - .unwrap() - .unwrap(); - assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); - assert_eq!(edited.get_id(), solution.get_id()); - - // Editing a missing solution is None, not an error. - assert!( - Solution::set_body( - &SolutionId::generate(), - &SolutionBody::try_new("boş").unwrap(), - &db, - ) - .await - .unwrap() - .is_none() - ); - } - - #[tokio::test] - async fn counts_for_groups_per_question() { - let db = crate::database::init_mem().await.unwrap(); - let two = question_row(&db).await; - let one = question_row(&db).await; - let none = question_row(&db).await; - let author = UserId::from_key(&Ulid::new().to_string()); - - for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { - for body in bodies { - Solution::new(question, &author, SolutionBody::try_new(body).unwrap()) - .insert(&db) - .await - .unwrap(); - } - } - - let counts = Solution::counts_for(&[two.clone(), one.clone(), none.clone()], &db) - .await - .unwrap(); - assert_eq!(counts.get(two.key()), Some(&2)); - assert_eq!(counts.get(one.key()), Some(&1)); - // No solutions = no entry; the caller reads the miss as zero. - assert_eq!(counts.get(none.key()), None); - assert!(Solution::counts_for(&[], &db).await.unwrap().is_empty()); - } - - #[tokio::test] - async fn body_rules() { + #[test] + fn body_rules() { assert!(SolutionBody::try_new("").is_err()); assert!(SolutionBody::try_new(" ").is_err()); assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err()); diff --git a/src/service/bank_question.rs b/src/service/bank_question.rs new file mode 100644 index 0000000..2a83367 --- /dev/null +++ b/src/service/bank_question.rs @@ -0,0 +1,178 @@ +//! Bank-question workflows: the PATCH re-derive — the merge (set / clear / +//! keep per field) re-judged against a fresh read every retry round, with the +//! kind/choices/correct trio re-validated as a unit — plus the read, list, +//! create, usage-tally, and delete funnels the web layer goes through. The +//! queries and their transactions live in [`crate::db::bank_question`]; the +//! pure entity and newtypes in [`crate::domain::bank_question`]. + +use std::collections::HashMap; + +use crate::constant::CAS_UPDATE_RETRIES; +use crate::database::Database; +use crate::db::bank_question; +use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::domain::exam::ExamId; +use crate::domain::exam_question::{ + Choice, ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, +}; +use crate::domain::subject::SubjectId; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn read(db: &Database, id: &BankQuestionId) -> Result, AppError> { + bank_question::read(db, id).await +} + +pub async fn create( + db: &Database, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, +) -> Result { + bank_question::create(db, owner, subject, text, points, spec).await +} + +/// Like [`create`], but records the origin exam the template was saved from +/// (`POST …/questions/{qid}/to-bank`). +pub async fn create_from_exam( + db: &Database, + owner: UserId, + subject: SubjectId, + text: QuestionText, + points: QuestionPoints, + spec: QuestionSpec, + source: ExamId, +) -> Result { + bank_question::create_from_exam(db, owner, subject, text, points, spec, source).await +} + +/// One page of the bank the caller may see, plus the total under the same +/// filters — the visibility gate is a WHERE clause inside, never a post-filter. +#[allow(clippy::too_many_arguments)] +pub async fn list( + db: &Database, + visible_to: Option<&UserId>, + owner: Option<&UserId>, + subject: Option<&SubjectId>, + visibility: Option<&BankVisibility>, + q: Option<&str>, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + bank_question::list(db, visible_to, owner, subject, visibility, q, limit, offset).await +} + +/// How many exam questions were instantiated from each of `ids`, in one +/// grouped query for the whole page. +pub async fn usage_counts( + db: &Database, + ids: &[&BankQuestionId], +) -> Result, AppError> { + bank_question::usage_counts(db, ids).await +} + +/// A `PATCH /bank-questions/{bid}` request after field validation: every +/// value the request *sets* is already validated (text, points, and kind by +/// their newtypes; the submitted choices as `ChoiceInput`s; the subject by +/// the web's existence read). What is *kept* — and whether the merged +/// kind/choices/correct trio is a legal question — are the update's own +/// decisions, re-derived against a fresh read every retry round, so they live +/// here and not in the web layer. `choices`/`correct` carry the web DTO's +/// set-or-clear spelling (`Some(None)` = explicit `null`). +pub struct BankQuestionPatch { + pub subject: Option, + pub text: Option, + pub points: Option, + pub kind: Option, + pub choices: Option>>, + pub correct: Option>, + pub visibility: Option, +} + +/// Re-derive and save the template: merge the patch over a fresh read, +/// re-validate the kind-dependent fields as a unit, and land the whole merge +/// with the compare-and-set — retried while the row keeps moving under the +/// snapshot. Concurrent PATCHes of one template no longer queue behind each +/// other: the lost update they used to cause is refused by the guard, and the +/// next round re-merges over what actually landed. +pub async fn update( + db: &Database, + id: &BankQuestionId, + patch: &BankQuestionPatch, +) -> Result { + let mut left = CAS_UPDATE_RETRIES; + loop { + let question = bank_question::read(db, id) + .await? + .ok_or(AppError::NotFound)?; + // Omitted keeps the stored subject — which may already be `None`, cleared + // by that subject's delete. + let subject = match &patch.subject { + Some(subject) => Some(subject.clone()), + None => question.get_subject().cloned(), + }; + let text = patch + .text + .clone() + .unwrap_or_else(|| question.get_text().clone()); + let points = patch.points.unwrap_or_else(|| question.get_points()); + let kind = patch + .kind + .clone() + .unwrap_or_else(|| question.get_kind().clone()); + // Merge the kind-dependent fields (set / clear / keep per field), then + // re-validate them as a unit — a PATCH can't leave a half-question behind. + // Omitting `choices` re-submits the stored options *with their ids*, so a + // text-only edit keeps every identity (and every picture) untouched. + let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); + let choices = match &patch.choices { + Some(update) => update.clone(), + None => question.get_choices().map(|stored| { + stored + .iter() + .map(|choice| ChoiceInput { + id: Some(choice.get_id().as_str().to_string()), + text: choice.get_text().as_str().to_string(), + }) + .collect() + }), + }; + let correct = patch + .correct + .clone() + .unwrap_or_else(|| question.get_correct().map(|id| id.as_str().to_string())); + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; + let visibility = patch + .visibility + .clone() + .unwrap_or_else(|| question.get_visibility().clone()); + + if let Some(updated) = bank_question::update_if_unchanged( + db, question, subject, text, points, spec, visibility, + ) + .await? + { + return Ok(updated); + } + // The row moved under the snapshot every gate above judged: re-read and + // re-merge, so both edits land instead of the later reverting the earlier. + left -= 1; + if left == 0 { + return Err(AppError::Conflict( + "the template kept changing underneath this update — try again", + )); + } + } +} + +/// Delete the template and cascade-remove its image rows; the swept rows come +/// back with it, and their blob files are the web layer's to unlink. +pub async fn delete( + db: &Database, + target: BankQuestion, +) -> Result<(BankQuestion, Vec), AppError> { + bank_question::delete(db, target).await +} diff --git a/src/service/bank_question_image.rs b/src/service/bank_question_image.rs new file mode 100644 index 0000000..e6689fc --- /dev/null +++ b/src/service/bank_question_image.rs @@ -0,0 +1,63 @@ +//! Bank-question image funnels: the per-slot upsert, the slot/page reads, the +//! choice sweep a non-destructive PATCH runs, and the single-row delete. The +//! queries and their transactions live in +//! [`crate::db::bank_question_image`]; the blob files themselves stay the web +//! layer's to write and unlink. + +use crate::database::Database; +use crate::db::bank_question_image; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::domain::exam_question::ChoiceId; +use crate::error::AppError; + +/// Create or replace the slot's image row, handing back what it stored plus +/// the blob name it replaced, for the caller to take off disk. +pub async fn upsert( + db: &Database, + image: BankQuestionImage, +) -> Result<(BankQuestionImage, Option), AppError> { + bank_question_image::upsert(db, image).await +} + +pub async fn read_slot( + db: &Database, + question: &BankQuestionId, + slot: Option<&ChoiceId>, +) -> Result, AppError> { + bank_question_image::read_slot(db, question, slot).await +} + +pub async fn list_for_question( + db: &Database, + question: &BankQuestionId, +) -> Result, AppError> { + bank_question_image::list_for_question(db, question).await +} + +/// The image rows of several templates in one query — for bucketing onto a +/// listing's *page*. +pub async fn list_for_questions( + db: &Database, + questions: &[&BankQuestionId], +) -> Result, AppError> { + bank_question_image::list_for_questions(db, questions).await +} + +/// Drop the option pictures whose choice is gone — every choice image of +/// the question whose `slot` is *not* in `keep` — returning the removed rows +/// so the caller can take their blobs off disk. +pub async fn delete_choices_not_in( + db: &Database, + question: &BankQuestionId, + keep: &[ChoiceId], +) -> Result, AppError> { + bank_question_image::delete_choices_not_in(db, question, keep).await +} + +pub async fn delete( + db: &Database, + image: BankQuestionImage, +) -> Result { + bank_question_image::delete(db, image).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..d1f2a01 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,8 @@ pub mod appointment; pub mod appointment_slot; +pub mod bank_question; +pub mod bank_question_image; pub mod class_blueprint; pub mod course; pub mod course_session; @@ -13,6 +15,8 @@ pub mod exam_question; pub mod meal_booking; pub mod note; pub mod payment_ledger; +pub mod pool_question; pub mod session; pub mod settings; +pub mod solution; pub mod user; diff --git a/src/service/pool_question.rs b/src/service/pool_question.rs new file mode 100644 index 0000000..c333fac --- /dev/null +++ b/src/service/pool_question.rs @@ -0,0 +1,86 @@ +//! Pool-question funnels: ask, the two listings, the approve with its +//! 409-vs-404 split, the pending-only image writes, and the delete whose +//! swept solutions ride back for the web layer's blob cleanup. The queries +//! and their transactions live in [`crate::db::pool_question`]; the pure +//! entity and newtypes in [`crate::domain::pool_question`]. + +use crate::database::Database; +use crate::db::pool_question; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; +use crate::domain::solution::Solution; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn insert(db: &Database, question: PoolQuestion) -> Result { + pool_question::insert(db, question).await +} + +pub async fn read(db: &Database, id: &PoolQuestionId) -> Result, AppError> { + pool_question::read(db, id).await +} + +/// Every question, newest first — the teacher+ view (approval queue and +/// pool in one list). +pub async fn list_all(db: &Database) -> Result, AppError> { + pool_question::list_all(db).await +} + +/// The pool as a non-staff user sees it, newest first: every approved +/// question, plus the caller's own pending ones. +pub async fn list_visible_to(db: &Database, user: &UserId) -> Result, AppError> { + pool_question::list_visible_to(db, user).await +} + +/// Approve a pending question, stamping `approver`. A `None` from the +/// guarded write is ambiguous — already approved, or gone — so this sorts it +/// out with a read: the question missing is a 404, anything else is the 409 +/// the route's second approve answers. +pub async fn approve( + db: &Database, + id: &PoolQuestionId, + approver: &UserId, +) -> Result { + match pool_question::approve(db, id, approver).await? { + Some(question) => Ok(question), + // Nothing was pending under that id: either it's already approved + // (409) or it never existed / was deleted (404). + None => { + if pool_question::read(db, id).await?.is_none() { + return Err(AppError::NotFound); + } + Err(AppError::Conflict("the question is already approved")) + } + } +} + +/// Point the question at a freshly written image blob; `None` means the +/// question was approved or deleted mid-upload (the fresh blob is the +/// caller's orphan to take back off disk). +pub async fn set_image( + db: &Database, + id: &PoolQuestionId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + pool_question::set_image(db, id, file, content_type, size).await +} + +/// Detach the question's image (pending only, like [`set_image`]); `None` +/// means the question is no longer pending. +pub async fn clear_image( + db: &Database, + id: &PoolQuestionId, +) -> Result, AppError> { + pool_question::clear_image(db, id).await +} + +/// Delete the question and cascade its solutions; the removed rows come back +/// so the web layer can take every image blob off disk. +pub async fn delete( + db: &Database, + id: &PoolQuestionId, +) -> Result)>, AppError> { + pool_question::delete(db, id).await +} diff --git a/src/service/solution.rs b/src/service/solution.rs new file mode 100644 index 0000000..61074c3 --- /dev/null +++ b/src/service/solution.rs @@ -0,0 +1,80 @@ +//! Solution funnels: the offer (through the question's existence-move), the +//! question-scoped read and page, the grouped counts, and the unconditional +//! body/image writes of an unmoderated row. The queries live in +//! [`crate::db::solution`]; the pure entity and newtypes in +//! [`crate::domain::solution`]. + +use std::collections::HashMap; + +use crate::database::Database; +use crate::db::solution; +use crate::domain::note_file::FileContentType; +use crate::domain::pool_question::PoolQuestionId; +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; +use crate::error::AppError; + +/// Offer the solution; `NotFound` = the question is gone, and nothing was +/// written. +pub async fn insert(db: &Database, offer: Solution) -> Result { + solution::insert(db, offer).await +} + +/// Read a solution only if it belongs to `question` — keeps the nested +/// route honest (a solution id under someone else's question 404s). +pub async fn read_for( + db: &Database, + id: &SolutionId, + question: &PoolQuestionId, +) -> Result, AppError> { + solution::read_for(db, id, question).await +} + +/// The question's solutions, oldest first. +pub async fn list_for( + db: &Database, + question: &PoolQuestionId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + solution::list_for(db, question, limit, offset).await +} + +/// Per-question solution tallies for a page of questions, in one grouped +/// query. +pub async fn counts_for( + db: &Database, + questions: &[PoolQuestionId], +) -> Result, AppError> { + solution::counts_for(db, questions).await +} + +/// Replace the body; `None` only means the row was deleted mid-flight. +pub async fn set_body( + db: &Database, + id: &SolutionId, + body: &SolutionBody, +) -> Result, AppError> { + solution::set_body(db, id, body).await +} + +/// Point the solution at a freshly written image blob; the *before* row names +/// the replaced blob the caller must remove. +pub async fn set_image( + db: &Database, + id: &SolutionId, + file: &str, + content_type: &FileContentType, + size: i64, +) -> Result, AppError> { + solution::set_image(db, id, file, content_type, size).await +} + +/// Detach the solution's image; the *before* row names the blob the caller +/// must remove. +pub async fn clear_image(db: &Database, id: &SolutionId) -> Result, AppError> { + solution::clear_image(db, id).await +} + +pub async fn delete(db: &Database, target: Solution) -> Result { + solution::delete(db, target).await +} diff --git a/src/web/bank_questions.rs b/src/web/bank_questions.rs index cc2cd42..997d83a 100644 --- a/src/web/bank_questions.rs +++ b/src/web/bank_questions.rs @@ -25,17 +25,19 @@ use utoipa::{IntoParams, ToSchema}; use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; -use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam_question::{ - Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, + ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; use crate::domain::note_file::FileContentType; use crate::domain::role::Role; use crate::domain::subject::{Subject, SubjectId}; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::bank_question; +use crate::service::bank_question_image; use crate::state::AppState; use super::dto::person_map; @@ -309,7 +311,7 @@ async fn bank_images_by_question( db: &crate::database::Database, ) -> Result>, AppError> { let mut buckets: HashMap> = HashMap::new(); - for image in BankQuestionImage::list_for_questions(questions, db).await? { + for image in bank_question_image::list_for_questions(db, questions).await? { buckets .entry(image.get_bank_question().key().to_string()) .or_default() @@ -338,7 +340,7 @@ impl BankImageMeta { /// The template, or a 404. async fn question_or_404(st: &AppState, bid: &str) -> Result { - BankQuestion::read(&BankQuestionId::from_key(bid), &st.db) + bank_question::read(&st.db, &BankQuestionId::from_key(bid)) .await? .ok_or(AppError::NotFound) } @@ -419,7 +421,10 @@ pub(crate) async fn store_image( ) -> Result { let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); let file = image.get_file().to_string(); - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await + store_blob(st, &file, data, || async { + bank_question_image::upsert(&st.db, image).await + }) + .await } /// Add a template to the bank. Requires teacher+. `subject_id` is origin @@ -459,7 +464,7 @@ async fn create_question( &[], )?; let question = - BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?; + bank_question::create(&st.db, user.get_id().clone(), subject, text, points, spec).await?; Ok(( StatusCode::CREATED, Json(BankQuestionResponse::new(&question, &[])), @@ -515,7 +520,8 @@ async fn list_questions( let viewer = (!user.get_role().at_least(Role::Admin)).then(|| user.get_id().clone()); // Filters, order, and window are all SQL — `total` comes from a count over // the same WHERE, so a client can page past the first window. - let (questions, total) = BankQuestion::list( + let (questions, total) = bank_question::list( + &st.db, viewer.as_ref(), owner.as_ref(), subject.as_ref(), @@ -523,7 +529,6 @@ async fn list_questions( filter.q.as_deref(), limit, offset, - &st.db, ) .await?; @@ -533,7 +538,7 @@ async fn list_questions( let ids: Vec<&BankQuestionId> = questions.iter().map(BankQuestion::get_id).collect(); let buckets = bank_images_by_question(&ids, &st.db).await?; // One grouped query for the whole page — never a count per row. - let used = BankQuestion::usage_counts(&ids, &st.db).await?; + let used = bank_question::usage_counts(&st.db, &ids).await?; let subject_ids: Vec<&SubjectId> = questions .iter() .filter_map(BankQuestion::get_subject) @@ -596,7 +601,7 @@ async fn get_question( Path(bid): Path, ) -> Result, AppError> { let question = visible_question(&st, &user, &bid).await?; - let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; + let images = bank_question_image::list_for_question(&st.db, question.get_id()).await?; Ok(Json(BankQuestionResponse::new(&question, &images))) } @@ -636,62 +641,38 @@ async fn update_question( Path(bid): Path, Json(req): Json, ) -> Result, AppError> { - // Read, merge and write again while the row keeps moving underneath: the - // guarded write refuses on a snapshot that has gone stale, so both edits - // land instead of the later one reverting the earlier. - let mut left = CAS_UPDATE_RETRIES; - let updated = loop { - let question = owned_question(&st, &user, &bid).await?; - // Omitted keeps the stored subject — which may already be `None`, cleared - // by that subject's delete. - let subject = match req.subject_id { + // Authz first (404 invisible, 403 not the owner), then the fields the + // request sets are validated right here; the read-merge-retry loop that + // lands them lives in the service, which re-reads and re-merges while the + // row keeps moving underneath — its guarded write refuses on a snapshot + // that has gone stale, so both edits land instead of the later one + // reverting the earlier. + owned_question(&st, &user, &bid).await?; + let patch = bank_question::BankQuestionPatch { + subject: match req.subject_id { Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), - None => question.get_subject().cloned(), - }; - let text = match req.text { - Some(ref text) => QuestionText::try_new(text)?, - None => question.get_text().clone(), - }; - let points = match req.points { - Some(points) => QuestionPoints::try_new(points)?, - None => question.get_points(), - }; - // Merge the kind-dependent fields (set / clear / keep per field), then - // re-validate them as a unit — a PATCH can't leave a half-question behind. - let kind = match req.kind { - Some(ref kind) => QuestionKind::try_new(kind)?, - None => question.get_kind().clone(), - }; - // Omitting `choices` re-submits the stored options *with their ids*, so a - // text-only edit keeps every identity (and every picture) untouched. - let choices = match req.choices.clone() { - Some(update) => ChoiceBody::into_inputs(update), - None => ChoiceBody::from_stored(question.get_choices()), - }; - let correct = match req.correct.clone() { - Some(update) => update, - None => question.get_correct().map(|id| id.as_str().to_string()), - }; - let stored: Vec = question.get_choices().unwrap_or_default().to_vec(); - let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; - let visibility = match req.visibility { - Some(ref visibility) => BankVisibility::try_new(visibility)?, - None => question.get_visibility().clone(), - }; - - if let Some(updated) = question - .update_if_unchanged(subject, text, points, spec, visibility, &st.db) - .await? - { - break updated; - } - left -= 1; - if left == 0 { - return Err(AppError::Conflict( - "the template kept changing underneath this update — try again", - )); - } + None => None, + }, + text: match req.text { + Some(ref text) => Some(QuestionText::try_new(text)?), + None => None, + }, + points: req.points.map(QuestionPoints::try_new).transpose()?, + kind: match req.kind { + Some(ref kind) => Some(QuestionKind::try_new(kind)?), + None => None, + }, + // Set-or-clear spelling: omitting `choices` keeps the stored options + // (re-submitted with their ids, so a text-only edit keeps every + // picture), resolved against a fresh read every retry round. + choices: req.choices.map(ChoiceBody::into_inputs), + correct: req.correct, + visibility: match req.visibility { + Some(ref visibility) => Some(BankVisibility::try_new(visibility)?), + None => None, + }, }; + let updated = bank_question::update(&st.db, &BankQuestionId::from_key(&bid), &patch).await?; let bid = updated.get_id().clone(); // Only the options that are actually *gone* lose their pictures — an option // that survives the edit keeps its image wherever it moved in the list. @@ -701,10 +682,10 @@ async fn update_question( .iter() .map(|choice| choice.get_id().clone()) .collect(); - for image in BankQuestionImage::delete_choices_not_in(&bid, &keep, &st.db).await? { + for image in bank_question_image::delete_choices_not_in(&st.db, &bid, &keep).await? { remove_blob(&st.files_path, image.get_file()).await; } - let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?; + let images = bank_question_image::list_for_question(&st.db, updated.get_id()).await?; Ok(Json(BankQuestionResponse::new(&updated, &images))) } @@ -733,7 +714,7 @@ async fn delete_question( // in between strands at worst an unreachable blob. The blobs come from what // the delete *swept*, never a list read before it: an upload that landed in // between is swept too, and its blob would be stranded for good. - let (_, images) = question.delete(&st.db).await?; + let (_, images) = bank_question::delete(&st.db, question).await?; for image in &images { remove_blob(&st.files_path, image.get_file()).await; } @@ -800,7 +781,7 @@ async fn get_question_image( Path(bid): Path, ) -> Result { let question = visible_question(&st, &user, &bid).await?; - let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) + let image = bank_question_image::read_slot(&st.db, question.get_id(), None) .await? .ok_or(AppError::NotFound)?; serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await @@ -826,10 +807,10 @@ async fn delete_question_image( Path(bid): Path, ) -> Result { let question = owned_question(&st, &user, &bid).await?; - let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) + let image = bank_question_image::read_slot(&st.db, question.get_id(), None) .await? .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; + let image = bank_question_image::delete(&st.db, image).await?; remove_blob(&st.files_path, image.get_file()).await; Ok(StatusCode::NO_CONTENT) } @@ -896,7 +877,7 @@ async fn get_choice_image( ) -> Result { let question = visible_question(&st, &user, &bid).await?; let slot = bank_choice_slot(&question, &choice_id)?; - let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + let image = bank_question_image::read_slot(&st.db, question.get_id(), Some(&slot)) .await? .ok_or(AppError::NotFound)?; serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await @@ -926,10 +907,10 @@ async fn delete_choice_image( ) -> Result { let question = owned_question(&st, &user, &bid).await?; let slot = bank_choice_slot(&question, &choice_id)?; - let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) + let image = bank_question_image::read_slot(&st.db, question.get_id(), Some(&slot)) .await? .ok_or(AppError::NotFound)?; - let image = image.delete(&st.db).await?; + let image = bank_question_image::delete(&st.db, image).await?; remove_blob(&st.files_path, image.get_file()).await; Ok(StatusCode::NO_CONTENT) } @@ -951,7 +932,10 @@ mod tests { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role) + .await + .unwrap() + .0 } /// Every bank route is `RequireTeacher` today, so this is pinned at the @@ -961,13 +945,13 @@ mod tests { async fn demoted_owner_loses_their_own_template() { let db = init_mem().await.unwrap(); let owner = user("ogretmen", Role::Teacher, &db).await; - let question = BankQuestion::create( + let question = bank_question::create( + &db, owner.get_id().clone(), SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), QuestionText::try_new("2 + 2 = ?").unwrap(), QuestionPoints::try_new(1).unwrap(), QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), - &db, ) .await .unwrap(); @@ -1008,19 +992,21 @@ mod tests { // The bank is teacher+ end to end, so a school-wide row is no way in // either. - let question = question - .update_if_unchanged( - None, - QuestionText::try_new("2 + 2 = ?").unwrap(), - QuestionPoints::try_new(1).unwrap(), - QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]) - .unwrap(), - BankVisibility::try_new("school").unwrap(), - &db, - ) - .await - .unwrap() - .expect("nothing raced this update"); + let question = bank_question::update( + &db, + question.get_id(), + &bank_question::BankQuestionPatch { + subject: None, + text: None, + points: None, + kind: None, + choices: None, + correct: None, + visibility: Some(BankVisibility::try_new("school").unwrap()), + }, + ) + .await + .unwrap(); let student = user("ogrenci", Role::Student, &db).await; assert!(!can_see(&question, &student)); assert!(can_see(&question, &admin)); diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 2569481..701b231 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -14,8 +14,6 @@ use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; use crate::domain::badge; -use crate::domain::bank_question::{BankQuestion, BankQuestionId}; -use crate::domain::bank_question_image::BankQuestionImage; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle, diff --git a/src/web/exams/questions.rs b/src/web/exams/questions.rs index 5e46570..251764d 100644 --- a/src/web/exams/questions.rs +++ b/src/web/exams/questions.rs @@ -1,5 +1,9 @@ use super::*; +use crate::domain::bank_question::BankQuestionId; +use crate::domain::bank_question_image::BankQuestionImage; +use crate::service::bank_question; +use crate::service::bank_question_image; use crate::service::exam_question; // ---- questions -------------------------------------------------------------- @@ -477,7 +481,7 @@ pub(crate) async fn question_from_bank( exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; - let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) + let template = bank_question::read(&st.db, &BankQuestionId::from_key(&bid)) .await? .ok_or(AppError::NotFound)?; // A template the caller may not see is a 404, exactly as it is on the bank's @@ -503,7 +507,7 @@ pub(crate) async fn question_from_bank( // The copy is all-or-nothing: any mid-loop failure rolls back the fresh // question row (its cascade drops the copied image rows) and the blobs // written so far, leaving the source and destination untouched. - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let sources = bank_question_image::list_for_question(&st.db, template.get_id()).await?; let mut copied: Vec = Vec::new(); for source in &sources { let step = async { @@ -615,7 +619,7 @@ pub(crate) async fn question_refresh_from_bank( reason: "this question did not come from a bank template", })); }; - let template = BankQuestion::read(&source, &st.db) + let template = bank_question::read(&st.db, &source) .await? .ok_or(AppError::NotFound)?; if !crate::web::bank_questions::can_see(&template, &user) { @@ -627,7 +631,7 @@ pub(crate) async fn question_refresh_from_bank( // question untouched, since a half-applied refresh has no old content left // to roll back to. Bounded — at most one illustration plus ten option // pictures, each under the school's file cap. - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let sources = bank_question_image::list_for_question(&st.db, template.get_id()).await?; let mut incoming: Vec<(&BankQuestionImage, Vec)> = Vec::with_capacity(sources.len()); for source in &sources { let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) @@ -735,14 +739,14 @@ pub(crate) async fn question_to_bank( // `create_from_exam` mints its own id and insert (the funnel), fed the // question's fields plus the origin exam it was saved off. - let template = BankQuestion::create_from_exam( + let template = bank_question::create_from_exam( + &st.db, user.get_id().clone(), question.get_subject().clone(), question.get_text().clone(), question.get_points(), question.spec(), exam.get_id().clone(), - &st.db, ) .await?; @@ -778,7 +782,7 @@ pub(crate) async fn question_to_bank( for file in &copied { remove_blob(&st.files_path, file).await; } - let _ = template.delete(&st.db).await; + let _ = bank_question::delete(&st.db, template).await; return Err(err); } } @@ -806,7 +810,7 @@ pub(crate) async fn question_to_bank( ); } - let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; + let images = bank_question_image::list_for_question(&st.db, template.get_id()).await?; Ok(( StatusCode::CREATED, Json(BankQuestionResponse::new(&template, &images)), diff --git a/src/web/questions.rs b/src/web/questions.rs index bbcd84a..58a98e2 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -27,6 +27,8 @@ use crate::domain::role::Role; use crate::domain::solution::{Solution, SolutionBody, SolutionId}; use crate::domain::user::User; use crate::error::{AppError, ErrorResponse, ValidationError}; +use crate::service::pool_question; +use crate::service::solution; use crate::state::AppState; use super::{ @@ -88,7 +90,7 @@ fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), App } async fn question_or_404(st: &AppState, id: &str) -> Result { - PoolQuestion::read(&PoolQuestionId::from_key(id), &st.db) + pool_question::read(&st.db, &PoolQuestionId::from_key(id)) .await? .ok_or(AppError::NotFound) } @@ -227,7 +229,7 @@ async fn question_responses( .iter() .map(|question| question.get_id().clone()) .collect(); - let counts = Solution::counts_for(&question_ids, &st.db).await?; + let counts = solution::counts_for(&st.db, &question_ids).await?; Ok(questions .iter() .map(|question| { @@ -266,9 +268,8 @@ async fn ask_question( } let title = PoolQuestionTitle::try_new(&req.title)?; let body = PoolQuestionBody::try_new(&req.body)?; - let question = PoolQuestion::new(user.get_id(), title, body) - .insert(&st.db) - .await?; + let question = + pool_question::insert(&st.db, PoolQuestion::new(user.get_id(), title, body)).await?; let responses = question_responses(std::slice::from_ref(&question), &st).await?; let response = responses .into_iter() @@ -311,9 +312,9 @@ async fn list_questions( } let mut questions = if user.get_role().at_least(Role::Teacher) { - PoolQuestion::list_all(&st.db).await? + pool_question::list_all(&st.db).await? } else { - PoolQuestion::list_visible_to(user.get_id(), &st.db).await? + pool_question::list_visible_to(&st.db, user.get_id()).await? }; if let Some(ref status) = filter.status { questions.retain(|question| question.get_status() == status); @@ -377,17 +378,8 @@ async fn approve_question( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result, AppError> { - let approved = - PoolQuestion::approve(&PoolQuestionId::from_key(&id), user.get_id(), &st.db).await?; - let question = match approved { - Some(question) => question, - // Nothing was pending under that id: either it's already approved - // (409) or it never existed / was deleted (404). - None => { - question_or_404(&st, &id).await?; - return Err(AppError::Conflict("the question is already approved")); - } - }; + let question = + pool_question::approve(&st.db, &PoolQuestionId::from_key(&id), user.get_id()).await?; // Both counters moved inside the approval's own transaction; the badges // they may have earned are a decoration on top of it. Losing one to a // transient database error must never fail the approval behind it, and the @@ -435,7 +427,7 @@ async fn delete_question( "only the asker or a teacher+ may delete a question", )); } - let (removed, swept) = PoolQuestion::delete(question.get_id(), &st.db) + let (removed, swept) = pool_question::delete(&st.db, question.get_id()) .await? .ok_or(AppError::NotFound)?; // Rows went first (in one transaction); now every blob they pointed at — @@ -493,7 +485,7 @@ async fn upload_image( let file = ulid::Ulid::new().to_string(); store_blob(&st, &file, &upload.data, || async { - match PoolQuestion::set_image(question.get_id(), &file, &upload.content_type, size, &st.db) + match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) .await? { // The guarded UPDATE found the question still pending: point-of-truth @@ -569,7 +561,7 @@ async fn delete_image( if question.get_image_file().is_none() { return Err(AppError::NotFound); } - let before = PoolQuestion::clear_image(question.get_id(), &st.db) + let before = pool_question::clear_image(&st.db, question.get_id()) .await? .ok_or(AppError::Conflict("the question is no longer pending"))?; if let Some(file) = before.get_image_file() { @@ -591,7 +583,7 @@ async fn visible_solution( ) -> Result { let question = question_or_404(st, id).await?; ensure_visible(&question, user)?; - Solution::read_for(&SolutionId::from_key(sid), question.get_id(), &st.db) + solution::read_for(&st.db, &SolutionId::from_key(sid), question.get_id()) .await? .ok_or(AppError::NotFound) } @@ -648,9 +640,11 @@ async fn offer_solution( )); } let body = SolutionBody::try_new(&req.body)?; - let solution = Solution::new(question.get_id(), user.get_id(), body) - .insert(&st.db) - .await?; + let solution = solution::insert( + &st.db, + Solution::new(question.get_id(), user.get_id(), body), + ) + .await?; let people = person_map([user.get_id().clone()], &st.db).await?; Ok(( StatusCode::CREATED, @@ -683,7 +677,7 @@ async fn list_solutions( let (limit, offset) = page.resolve()?; let question = question_or_404(&st, &id).await?; ensure_visible(&question, &user)?; - let (solutions, total) = Solution::list_for(question.get_id(), limit, offset, &st.db).await?; + let (solutions, total) = solution::list_for(&st.db, question.get_id(), limit, offset).await?; let slice = solutions.as_slice(); let people = person_map( slice.iter().map(|solution| solution.get_author().clone()), @@ -728,7 +722,7 @@ async fn delete_solution( } // Row first, blob after — a crash in between strands at worst an // unreachable file. - let deleted = solution.delete(&st.db).await?; + let deleted = solution::delete(&st.db, solution).await?; if let Some(file) = deleted.get_image_file() { remove_blob(&st.files_path, file).await; } @@ -767,7 +761,7 @@ async fn edit_solution( ) -> Result, AppError> { let solution = author_solution(&st, &user, &id, &sid).await?; let body = SolutionBody::try_new(&req.body)?; - let updated = Solution::set_body(solution.get_id(), &body, &st.db) + let updated = solution::set_body(&st.db, solution.get_id(), &body) .await? .ok_or(AppError::NotFound)?; let people = person_map([user.get_id().clone()], &st.db).await?; @@ -817,7 +811,7 @@ async fn upload_solution_image( let file = ulid::Ulid::new().to_string(); store_blob(&st, &file, &upload.data, || async { - match Solution::set_image(solution.get_id(), &file, &upload.content_type, size, &st.db) + match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) .await? { // Row write done; the replaced blob (if any) comes off disk. @@ -896,7 +890,7 @@ async fn delete_solution_image( if solution.get_image_file().is_none() { return Err(AppError::NotFound); } - let before = Solution::clear_image(solution.get_id(), &st.db) + let before = solution::clear_image(&st.db, solution.get_id()) .await? .ok_or(AppError::NotFound)?; if let Some(file) = before.get_image_file() { diff --git a/tests/integration.rs b/tests/integration.rs index 65a4ac1..338c891 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -20670,7 +20670,8 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { /// A whole-row save from the stale struct would resurrect the dead exam link. #[tokio::test] async fn a_bank_patch_does_not_clobber_a_concurrent_write() { - use hezarfen_backend::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; + use hezarfen_backend::db::bank_question::{read, update_if_unchanged}; + use hezarfen_backend::domain::bank_question::{BankQuestionId, BankVisibility}; use hezarfen_backend::domain::exam_question::{ QuestionKind, QuestionPoints, QuestionSpec, QuestionText, }; @@ -20702,7 +20703,7 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { // The handler's read, then the exam delete lands mid-window and clears the // template's `source_exam`. - let stale = BankQuestion::read(&BankQuestionId::from_key(&bid), &db) + let stale = read(&db, &BankQuestionId::from_key(&bid)) .await .unwrap() .expect("template exists"); @@ -20718,18 +20719,18 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); // The stale struct writes its own fields only. - let updated = stale - .update_if_unchanged( - None, - QuestionText::try_new("edited").unwrap(), - QuestionPoints::try_new(7).unwrap(), - QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), - &db, - ) - .await - .expect("update ran") - .expect("update written — the exam delete touched no compared column"); + let updated = update_if_unchanged( + &db, + stale, + None, + QuestionText::try_new("edited").unwrap(), + QuestionPoints::try_new(7).unwrap(), + QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), + ) + .await + .expect("update ran") + .expect("update written — the exam delete touched no compared column"); assert_eq!(updated.get_text().as_str(), "edited"); assert!( updated.get_source_exam().is_none(), diff --git a/tests/regress_bank_images.rs b/tests/regress_bank_images.rs index d7fa2ee..e17b7d2 100644 --- a/tests/regress_bank_images.rs +++ b/tests/regress_bank_images.rs @@ -29,6 +29,7 @@ use axum::http::StatusCode; use common::{create_course, create_subject, id_of, login_as, send}; use hezarfen_backend::build_router; use hezarfen_backend::database::Database; +use hezarfen_backend::db::bank_question_image::{list_for_question, upsert}; use hezarfen_backend::domain::bank_question::BankQuestionId; use hezarfen_backend::domain::bank_question_image::BankQuestionImage; use hezarfen_backend::domain::note_file::FileContentType; @@ -136,9 +137,7 @@ async fn an_image_write_under_a_missing_template_is_refused() { assert_eq!(dropped.status, StatusCode::NO_CONTENT); let question = BankQuestionId::from_key(&bid); - let refused = BankQuestionImage::new(&question, None, png(), 3) - .upsert(&db) - .await; + let refused = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await; assert!( matches!(refused, Err(AppError::NotFound)), "a slot write under a deleted template must be refused: {refused:?}" @@ -146,10 +145,7 @@ async fn an_image_write_under_a_missing_template_is_refused() { // Stored state is the verdict — a refusal that still wrote the row would be // the very defect this pins. assert!( - BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap() - .is_empty(), + list_for_question(&db, &question).await.unwrap().is_empty(), "the refused write left an orphan row" ); } @@ -180,9 +176,7 @@ async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() { "a replace retires the blob it replaced: {after:?}" ); let question = BankQuestionId::from_key(&bid); - let rows = BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap(); + let rows = list_for_question(&db, &question).await.unwrap(); assert_eq!(rows.len(), 1, "one row per slot"); assert_eq!( after, @@ -204,10 +198,5 @@ async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() { "the delete left a blob behind: {:?}", blobs(&files) ); - assert!( - BankQuestionImage::list_for_question(&question, &db) - .await - .unwrap() - .is_empty() - ); + assert!(list_for_question(&db, &question).await.unwrap().is_empty()); }