Split bank_question, bank_question_image, pool_question, solution into domain/db/service layers
Browse files at this commitd0c4bb170c727083e4694af61a5bff48fcfff79cParent: 387eb31- chore
- split bank_question, bank_question_image, pool_question, solution into domain/db/service layers
22 changed files +2900 -2487
- src/constant.rs +2 -2
- src/db/bank_question.rs +802 -0
- src/db/bank_question_image.rs +473 -0
- src/db/mod.rs +4 -0
- src/db/pool_question.rs +623 -0
- src/db/solution.rs +386 -0
- src/domain/bank_question.rs +17 -819
- src/domain/bank_question_image.rs +17 -458
- src/domain/pomodoro.rs +1 -1
- src/domain/pool_question.rs +17 -668
- src/domain/solution.rs +16 -380
- src/service/bank_question.rs +178 -0
- src/service/bank_question_image.rs +63 -0
- src/service/mod.rs +4 -0
- src/service/pool_question.rs +86 -0
- src/service/solution.rs +80 -0
- src/web/bank_questions.rs +75 -89
- src/web/exams/mod.rs +0 -2
- src/web/exams/questions.rs +12 -8
- src/web/questions.rs +24 -30
- tests/integration.rs +15 -14
- tests/regress_bank_images.rs +5 -16
src/constant.rsmodified+2 -2
| @@ -850,7 +850,7 @@ pub const MIN_CHUNK_CHARS: usize = 24; | |||
| 850 | 850 | ||
| 851 | // --- query text -------------------------------------------------------- | 851 | // --- query text -------------------------------------------------------- |
| 852 | 852 | ||
| 853 | -/// The whole of [`crate::domain::bank_question::BankQuestion::usage_counts`]: | 853 | +/// The whole of [`crate::db::bank_question::usage_counts`]: |
| 854 | /// **one** statement (no `;`), so a page of templates costs one round trip no | 854 | /// **one** statement (no `;`), so a page of templates costs one round trip no |
| 855 | /// matter how long it is. Named so a test can assert that, since a per-row | 855 | /// matter how long it is. Named so a test can assert that, since a per-row |
| 856 | /// `count()` is exactly the N+1 this page was cleaned of once. | 856 | /// `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"; | |||
| 1024 | /// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at | 1024 | /// `pomodoro_focus_ms_total` (and towards the study streak): it must have run at |
| 1025 | /// least this long, and it must be within the day's quota. | 1025 | /// least this long, and it must be within the day's quota. |
| 1026 | /// | 1026 | /// |
| 1027 | -/// Without them the pair is the farm [`crate::domain::pool_question::PoolQuestion::approve`] | 1027 | +/// Without them the pair is the farm [`crate::db::pool_question::approve`] |
| 1028 | /// reasons about from the other end: `finish` is self-service, a stint costs two | 1028 | /// reasons about from the other end: `finish` is self-service, a stint costs two |
| 1029 | /// requests and no second person, so a counter moved once per round-trip is | 1029 | /// requests and no second person, so a counter moved once per round-trip is |
| 1030 | /// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`, | 1030 | /// farmable — 200 pairs in a minute and a half bought `pomodoro_finished_200`, |
src/db/bank_question.rsadded+802 -0
| @@ -0,0 +1,802 @@ | |||
| 1 | +//! The `bank_question` table: template creates, the visibility-gated paged | ||
| 2 | +//! listing, the page-wide usage tally, the compare-and-set every PATCH writes | ||
| 3 | +//! through, and the delete that sweeps the slot table and clears both | ||
| 4 | +//! provenance links in one transaction. The PATCH re-derive lives in | ||
| 5 | +//! [`crate::service::bank_question`]; the pure entity and newtypes in | ||
| 6 | +//! [`crate::domain::bank_question`]. | ||
| 7 | + | ||
| 8 | +use std::collections::HashMap; | ||
| 9 | + | ||
| 10 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 11 | + | ||
| 12 | +use crate::constant::USAGE_COUNTS_SQL; | ||
| 13 | +use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 14 | +use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | ||
| 15 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 16 | +use crate::domain::exam::ExamId; | ||
| 17 | +use crate::domain::exam_question::{QuestionPoints, QuestionSpec, QuestionText}; | ||
| 18 | +use crate::domain::subject::SubjectId; | ||
| 19 | +use crate::domain::text_fold::{search_fold, search_fold_sql}; | ||
| 20 | +use crate::domain::timestamp::Timestamp; | ||
| 21 | +use crate::domain::user::UserId; | ||
| 22 | +use crate::error::AppError; | ||
| 23 | + | ||
| 24 | +/// One `GROUP BY from_bank` row of [`usage_counts`]. | ||
| 25 | +#[derive(SurrealValue)] | ||
| 26 | +struct UsageCount { | ||
| 27 | + from_bank: BankQuestionId, | ||
| 28 | + n: i64, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// What one [`delete`] transaction removed — the template (an empty list once | ||
| 32 | +/// someone else deleted it first) and the image rows swept with it. | ||
| 33 | +#[derive(SurrealValue)] | ||
| 34 | +struct DeleteOutcome { | ||
| 35 | + question: Vec<BankQuestion>, | ||
| 36 | + images: Vec<BankQuestionImage>, | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +pub async fn create( | ||
| 40 | + db: &Database, | ||
| 41 | + owner: UserId, | ||
| 42 | + subject: SubjectId, | ||
| 43 | + text: QuestionText, | ||
| 44 | + points: QuestionPoints, | ||
| 45 | + spec: QuestionSpec, | ||
| 46 | +) -> Result<BankQuestion, AppError> { | ||
| 47 | + insert(db, owner, subject, text, points, spec, None).await | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Like [`create`], but records the origin exam the template was saved from | ||
| 51 | +/// (`POST …/questions/{qid}/to-bank`). | ||
| 52 | +pub async fn create_from_exam( | ||
| 53 | + db: &Database, | ||
| 54 | + owner: UserId, | ||
| 55 | + subject: SubjectId, | ||
| 56 | + text: QuestionText, | ||
| 57 | + points: QuestionPoints, | ||
| 58 | + spec: QuestionSpec, | ||
| 59 | + source: ExamId, | ||
| 60 | +) -> Result<BankQuestion, AppError> { | ||
| 61 | + insert(db, owner, subject, text, points, spec, Some(source)).await | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +#[allow(clippy::too_many_arguments)] | ||
| 65 | +async fn insert( | ||
| 66 | + db: &Database, | ||
| 67 | + owner: UserId, | ||
| 68 | + subject: SubjectId, | ||
| 69 | + text: QuestionText, | ||
| 70 | + points: QuestionPoints, | ||
| 71 | + spec: QuestionSpec, | ||
| 72 | + source_exam: Option<ExamId>, | ||
| 73 | +) -> Result<BankQuestion, AppError> { | ||
| 74 | + let question = BankQuestion::from_parts( | ||
| 75 | + BankQuestionId::generate(), | ||
| 76 | + owner, | ||
| 77 | + // Creation always carries a validated subject; only a subject | ||
| 78 | + // delete ever clears it. | ||
| 79 | + Some(subject), | ||
| 80 | + text, | ||
| 81 | + points, | ||
| 82 | + spec, | ||
| 83 | + source_exam, | ||
| 84 | + // Never published on creation — publishing is its own PATCH. | ||
| 85 | + BankVisibility::default(), | ||
| 86 | + Timestamp::now(), | ||
| 87 | + ); | ||
| 88 | + let created: Option<BankQuestion> = db.create(question.id.record()).content(question).await?; | ||
| 89 | + created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { | ||
| 93 | + Ok(db.select(id.record()).await?) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// One page of the bank the caller may see, **newest first** (ULID ids sort by | ||
| 97 | +/// creation, so `id DESC` is newest-first) — plus the total row count under | ||
| 98 | +/// the same filters, so a client can page past the window. | ||
| 99 | +/// | ||
| 100 | +/// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: | ||
| 101 | +/// the old version read the whole table and sliced it in memory, which hid | ||
| 102 | +/// every template past the client's first page. `q` is a case- and | ||
| 103 | +/// diacritic-insensitive fragment of the question text (blank = no text | ||
| 104 | +/// filter): needle and column both go through | ||
| 105 | +/// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. | ||
| 106 | +/// | ||
| 107 | +/// `visible_to` is the security filter, and it is a WHERE clause like every | ||
| 108 | +/// other one — never a post-filter, or `total` would count templates the | ||
| 109 | +/// caller can't have and paging would return short pages of them: | ||
| 110 | +/// `Some(me)` sees the school-published templates plus their own, | ||
| 111 | +/// `None` (admins only) sees everything. | ||
| 112 | +/// | ||
| 113 | +/// `visibility` is the *user's* filter ("only mine" / "shared with the | ||
| 114 | +/// school") and is ANDed on top of that gate, so it can only ever narrow: | ||
| 115 | +/// `school` still hides another teacher's private rows, and `private` | ||
| 116 | +/// intersected with the gate leaves exactly the caller's own drafts. It | ||
| 117 | +/// joins the same `clauses` vec as the rest, so `total` honours it too — | ||
| 118 | +/// a count that ignored it would break paging. | ||
| 119 | +// Flat filter args, like every other `list` here — a builder struct for | ||
| 120 | +// four `Option`s and a window would be more machinery than the call sites. | ||
| 121 | +#[allow(clippy::too_many_arguments)] | ||
| 122 | +pub async fn list( | ||
| 123 | + db: &Database, | ||
| 124 | + visible_to: Option<&UserId>, | ||
| 125 | + owner: Option<&UserId>, | ||
| 126 | + subject: Option<&SubjectId>, | ||
| 127 | + visibility: Option<&BankVisibility>, | ||
| 128 | + q: Option<&str>, | ||
| 129 | + limit: Option<i64>, | ||
| 130 | + offset: i64, | ||
| 131 | +) -> Result<(Vec<BankQuestion>, i64), AppError> { | ||
| 132 | + let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); | ||
| 133 | + let mut clauses = Vec::new(); | ||
| 134 | + if visible_to.is_some() { | ||
| 135 | + clauses.push("(visibility = 'school' OR owner = $viewer)"); | ||
| 136 | + } | ||
| 137 | + if visibility.is_some() { | ||
| 138 | + clauses.push("visibility = $visibility"); | ||
| 139 | + } | ||
| 140 | + if owner.is_some() { | ||
| 141 | + clauses.push("owner = $owner"); | ||
| 142 | + } | ||
| 143 | + if subject.is_some() { | ||
| 144 | + clauses.push("subject = $subject"); | ||
| 145 | + } | ||
| 146 | + let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); | ||
| 147 | + if needle.is_some() { | ||
| 148 | + clauses.push(text_clause.as_str()); | ||
| 149 | + } | ||
| 150 | + let where_clause = if clauses.is_empty() { | ||
| 151 | + "true".to_string() | ||
| 152 | + } else { | ||
| 153 | + clauses.join(" AND ") | ||
| 154 | + }; | ||
| 155 | + // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. | ||
| 156 | + let window = match limit { | ||
| 157 | + Some(_) => "LIMIT $limit START $offset", | ||
| 158 | + None => "START $offset", | ||
| 159 | + }; | ||
| 160 | + // The count runs over the *same* WHERE, so `total` can never disagree | ||
| 161 | + // with what paging through the list actually yields. | ||
| 162 | + let mut query = db | ||
| 163 | + .query(format!( | ||
| 164 | + "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; | ||
| 165 | + SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" | ||
| 166 | + )) | ||
| 167 | + .bind(("offset", offset)); | ||
| 168 | + if let Some(viewer) = visible_to { | ||
| 169 | + query = query.bind(("viewer", viewer.record())); | ||
| 170 | + } | ||
| 171 | + if let Some(visibility) = visibility { | ||
| 172 | + query = query.bind(("visibility", visibility.as_str().to_string())); | ||
| 173 | + } | ||
| 174 | + if let Some(owner) = owner { | ||
| 175 | + query = query.bind(("owner", owner.record())); | ||
| 176 | + } | ||
| 177 | + if let Some(subject) = subject { | ||
| 178 | + query = query.bind(("subject", subject.record())); | ||
| 179 | + } | ||
| 180 | + if let Some(needle) = needle { | ||
| 181 | + query = query.bind(("q", needle)); | ||
| 182 | + } | ||
| 183 | + if let Some(limit) = limit { | ||
| 184 | + query = query.bind(("limit", limit)); | ||
| 185 | + } | ||
| 186 | + let mut result = query.await?.check()?; | ||
| 187 | + let questions = result.take::<Vec<BankQuestion>>(0)?; | ||
| 188 | + // `GROUP ALL` yields no row at all when nothing matched. | ||
| 189 | + let total = result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0); | ||
| 190 | + Ok((questions, total)) | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +/// How many exam questions were instantiated from each of `ids` — the | ||
| 194 | +/// `from_bank` side of the provenance link, tallied for a whole page in | ||
| 195 | +/// **one** grouped query (a `count()` per row would be the N+1 this page | ||
| 196 | +/// already had removed once). Keys are template record keys; a template | ||
| 197 | +/// nobody ever used has no entry at all, so the caller reads a miss as | ||
| 198 | +/// zero — and the UI can stay quiet rather than print "0". | ||
| 199 | +/// | ||
| 200 | +/// Counts *questions*, not distinct exams: one exam that inserted the same | ||
| 201 | +/// template twice counts twice, which is what "copies made from this | ||
| 202 | +/// template" means and what the divergence trap is actually about. | ||
| 203 | +pub async fn usage_counts( | ||
| 204 | + db: &Database, | ||
| 205 | + ids: &[&BankQuestionId], | ||
| 206 | +) -> Result<HashMap<String, i64>, AppError> { | ||
| 207 | + if ids.is_empty() { | ||
| 208 | + return Ok(HashMap::new()); | ||
| 209 | + } | ||
| 210 | + let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect(); | ||
| 211 | + let mut result = db | ||
| 212 | + .query(USAGE_COUNTS_SQL) | ||
| 213 | + .bind(("ids", records)) | ||
| 214 | + .await? | ||
| 215 | + .check()?; | ||
| 216 | + Ok(result | ||
| 217 | + .take::<Vec<UsageCount>>(0)? | ||
| 218 | + .into_iter() | ||
| 219 | + .map(|row| (row.from_bank.key().to_string(), row.n)) | ||
| 220 | + .collect()) | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +/// Write the editable fields of the template, but only while the row still | ||
| 224 | +/// reads as the snapshot `expected` was loaded from — `None` means a concurrent | ||
| 225 | +/// edit (or the subject-delete cascade that clears `subject`) landed inside | ||
| 226 | +/// the handler's read-merge window, so nothing was written: reload, | ||
| 227 | +/// re-merge, retry. This is a genuine read-modify-write — every editable | ||
| 228 | +/// field is re-stated from the snapshot, and the kind/choices/correct trio | ||
| 229 | +/// has to be (a text-only edit re-submits the stored options *with their | ||
| 230 | +/// ids* so each keeps its picture) — so without the compare-and-set the | ||
| 231 | +/// later writer silently reverts the earlier one — and the window is a | ||
| 232 | +/// database round trip wide, which is exactly how far apart two concurrent | ||
| 233 | +/// requests to this one process can sit. | ||
| 234 | +/// | ||
| 235 | +/// Every field the merge re-states is in the guard, which is the same list | ||
| 236 | +/// the `SET` writes. `choices` is compared whole: its objects carry two | ||
| 237 | +/// required string keys, so none is ever dropped for being `NONE` (the trap | ||
| 238 | +/// [`crate::db::settings::save_if_unchanged`] works around). | ||
| 239 | +/// | ||
| 240 | +/// Rides [`write_with_retry`] because an image write now moves this row too | ||
| 241 | +/// ([`crate::db::bank_question_image::upsert`]): an upload landing in the | ||
| 242 | +/// same instant makes the store answer "conflict, retry", and a bare | ||
| 243 | +/// `check()` would turn that into a 500 for an edit that only had to be | ||
| 244 | +/// re-sent. A lost round writes nothing, and the guard is re-evaluated on | ||
| 245 | +/// the next one, so a genuine stale merge still comes back as `None`. | ||
| 246 | +/// Admissible: an `UPDATE` can never answer "already exists". | ||
| 247 | +pub async fn update_if_unchanged( | ||
| 248 | + db: &Database, | ||
| 249 | + expected: BankQuestion, | ||
| 250 | + subject: Option<SubjectId>, | ||
| 251 | + text: QuestionText, | ||
| 252 | + points: QuestionPoints, | ||
| 253 | + spec: QuestionSpec, | ||
| 254 | + visibility: BankVisibility, | ||
| 255 | +) -> Result<Option<BankQuestion>, AppError> { | ||
| 256 | + let (kind, choices, correct) = spec.into_parts(); | ||
| 257 | + let rows: Vec<BankQuestion> = write_with_retry( | ||
| 258 | + db, | ||
| 259 | + "UPDATE $id SET subject = $subject, text = $text, points = $points, | ||
| 260 | + kind = $kind, choices = $choices, correct = $correct, | ||
| 261 | + visibility = $visibility | ||
| 262 | + WHERE subject = $was_subject AND text = $was_text | ||
| 263 | + AND points = $was_points AND kind = $was_kind | ||
| 264 | + AND choices = $was_choices AND correct = $was_correct | ||
| 265 | + AND visibility = $was_visibility | ||
| 266 | + RETURN AFTER", | ||
| 267 | + &[ | ||
| 268 | + ( | ||
| 269 | + "was_subject".into(), | ||
| 270 | + expected.subject.clone().map(|s| s.record()).into_value(), | ||
| 271 | + ), | ||
| 272 | + ("was_text".into(), expected.text.clone().into_value()), | ||
| 273 | + ("was_points".into(), expected.points.into_value()), | ||
| 274 | + ("was_kind".into(), expected.kind.clone().into_value()), | ||
| 275 | + ("was_choices".into(), expected.choices.clone().into_value()), | ||
| 276 | + ("was_correct".into(), expected.correct.clone().into_value()), | ||
| 277 | + ( | ||
| 278 | + "was_visibility".into(), | ||
| 279 | + expected.visibility.clone().into_value(), | ||
| 280 | + ), | ||
| 281 | + ("id".into(), expected.id.record().into_value()), | ||
| 282 | + ("subject".into(), subject.map(|s| s.record()).into_value()), | ||
| 283 | + ("text".into(), text.into_value()), | ||
| 284 | + ("points".into(), points.into_value()), | ||
| 285 | + ("kind".into(), kind.into_value()), | ||
| 286 | + ("choices".into(), choices.into_value()), | ||
| 287 | + ("correct".into(), correct.into_value()), | ||
| 288 | + ("visibility".into(), visibility.into_value()), | ||
| 289 | + ], | ||
| 290 | + ) | ||
| 291 | + .await?; | ||
| 292 | + Ok(rows.into_iter().next()) | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +/// Delete the template and cascade-remove its bank images, so none points | ||
| 296 | +/// at a missing template. Bank rows have no answers. The image rows this | ||
| 297 | +/// actually removed come back with it: the blobs are the web layer's to | ||
| 298 | +/// take off disk, but only for *these* rows — an upload that committed | ||
| 299 | +/// after the caller listed the template's images is swept here too, and a | ||
| 300 | +/// pre-read snapshot would strand its blob for good | ||
| 301 | +/// ([`crate::db::note::delete`]'s story, this domain over). | ||
| 302 | +/// | ||
| 303 | +/// Children first, in one transaction: as two queries, a failure between | ||
| 304 | +/// them left image rows swept under a template that survived, or (the other | ||
| 305 | +/// order) a template gone with its images still there. Rides the retry | ||
| 306 | +/// because an image write now moves this very row | ||
| 307 | +/// ([`crate::db::bank_question_image::upsert`]) — the two contend by | ||
| 308 | +/// design, and a lost round through a bare `check()` would be a 500 for a | ||
| 309 | +/// delete that only had to be re-sent. Admissible: no `UPDATE` or `DELETE` | ||
| 310 | +/// in here can answer "already exists". | ||
| 311 | +/// | ||
| 312 | +/// Exam questions tied to this template keep living: only their provenance | ||
| 313 | +/// links are cleared, field-scoped (never a whole-row save — the question | ||
| 314 | +/// isn't ours and may be edited concurrently), so nothing can read a link to | ||
| 315 | +/// a template that no longer exists. *Both* directions point at a template, | ||
| 316 | +/// so both are cleared: `from_bank` on the questions instantiated from it, | ||
| 317 | +/// and `banked_as` on the question it was saved out of. | ||
| 318 | +pub async fn delete( | ||
| 319 | + db: &Database, | ||
| 320 | + target: BankQuestion, | ||
| 321 | +) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { | ||
| 322 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 323 | + db, | ||
| 324 | + "BEGIN TRANSACTION; | ||
| 325 | + LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); | ||
| 326 | + UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; | ||
| 327 | + UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; | ||
| 328 | + LET $gone = (DELETE $b RETURN BEFORE); | ||
| 329 | + RETURN { question: $gone, images: $images }; | ||
| 330 | + COMMIT TRANSACTION;", | ||
| 331 | + &[("b".into(), target.id.record().into_value())], | ||
| 332 | + &[], | ||
| 333 | + ) | ||
| 334 | + .await?; | ||
| 335 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 336 | + return Err(error.into()); | ||
| 337 | + } | ||
| 338 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its | ||
| 339 | + // slot follows the statement count rather than a hand-kept number; | ||
| 340 | + // `num_statements` counts BEGIN and COMMIT. | ||
| 341 | + let slot = result.num_statements().saturating_sub(2); | ||
| 342 | + let outcome = result | ||
| 343 | + .take::<Vec<DeleteOutcome>>(slot)? | ||
| 344 | + .into_iter() | ||
| 345 | + .next() | ||
| 346 | + .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; | ||
| 347 | + let question = outcome | ||
| 348 | + .question | ||
| 349 | + .into_iter() | ||
| 350 | + .next() | ||
| 351 | + .ok_or(AppError::NotFound)?; | ||
| 352 | + Ok((question, outcome.images)) | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +#[cfg(test)] | ||
| 356 | +mod tests { | ||
| 357 | + use super::*; | ||
| 358 | + use crate::constant::{BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; | ||
| 359 | + | ||
| 360 | + fn spec() -> QuestionSpec { | ||
| 361 | + use crate::domain::exam_question::{ChoiceInput, QuestionKind}; | ||
| 362 | + QuestionSpec::try_new( | ||
| 363 | + QuestionKind::try_new("choice").unwrap(), | ||
| 364 | + Some(vec![ | ||
| 365 | + ChoiceInput { | ||
| 366 | + id: Some("a".into()), | ||
| 367 | + text: "yes".into(), | ||
| 368 | + }, | ||
| 369 | + ChoiceInput { | ||
| 370 | + id: Some("b".into()), | ||
| 371 | + text: "no".into(), | ||
| 372 | + }, | ||
| 373 | + ]), | ||
| 374 | + Some("b".into()), | ||
| 375 | + &[], | ||
| 376 | + ) | ||
| 377 | + .unwrap() | ||
| 378 | + } | ||
| 379 | + | ||
| 380 | + /// A row stored before `visibility` existed has no such key — it must decode | ||
| 381 | + /// as `private`, the safe value. Asserted on the decoder itself, so no | ||
| 382 | + /// schema DEFAULT can paper over it: a `school` default here would publish | ||
| 383 | + /// every pre-existing template in the school at once. | ||
| 384 | + #[tokio::test] | ||
| 385 | + async fn a_row_without_the_field_decodes_private() { | ||
| 386 | + use surrealdb::types::Value; | ||
| 387 | + | ||
| 388 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 389 | + let question = create( | ||
| 390 | + &db, | ||
| 391 | + UserId::generate(), | ||
| 392 | + SubjectId::generate(), | ||
| 393 | + QuestionText::try_new("q").unwrap(), | ||
| 394 | + QuestionPoints::try_new(1).unwrap(), | ||
| 395 | + spec(), | ||
| 396 | + ) | ||
| 397 | + .await | ||
| 398 | + .unwrap(); | ||
| 399 | + assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 400 | + | ||
| 401 | + let mut stored = question.into_value(); | ||
| 402 | + let Value::Object(map) = &mut stored else { | ||
| 403 | + panic!("a bank question serializes to an object"); | ||
| 404 | + }; | ||
| 405 | + assert!(map.remove("visibility").is_some()); | ||
| 406 | + let old = BankQuestion::from_value(stored).unwrap(); | ||
| 407 | + assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 408 | + assert!(!old.get_visibility().is_school()); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + /// The visibility gate is a WHERE clause, so `total` counts exactly what the | ||
| 412 | + /// page can contain — never someone else's private templates. | ||
| 413 | + #[tokio::test] | ||
| 414 | + async fn list_hides_private_templates_from_others() { | ||
| 415 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 416 | + let owner = UserId::generate(); | ||
| 417 | + let other = UserId::generate(); | ||
| 418 | + let private = create( | ||
| 419 | + &db, | ||
| 420 | + owner.clone(), | ||
| 421 | + SubjectId::generate(), | ||
| 422 | + QuestionText::try_new("secret").unwrap(), | ||
| 423 | + QuestionPoints::try_new(1).unwrap(), | ||
| 424 | + spec(), | ||
| 425 | + ) | ||
| 426 | + .await | ||
| 427 | + .unwrap(); | ||
| 428 | + let published = create( | ||
| 429 | + &db, | ||
| 430 | + owner.clone(), | ||
| 431 | + SubjectId::generate(), | ||
| 432 | + QuestionText::try_new("shared").unwrap(), | ||
| 433 | + QuestionPoints::try_new(1).unwrap(), | ||
| 434 | + spec(), | ||
| 435 | + ) | ||
| 436 | + .await | ||
| 437 | + .unwrap(); | ||
| 438 | + let subject = published.get_subject().cloned(); | ||
| 439 | + update_if_unchanged( | ||
| 440 | + &db, | ||
| 441 | + published, | ||
| 442 | + subject, | ||
| 443 | + QuestionText::try_new("shared").unwrap(), | ||
| 444 | + QuestionPoints::try_new(1).unwrap(), | ||
| 445 | + spec(), | ||
| 446 | + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), | ||
| 447 | + ) | ||
| 448 | + .await | ||
| 449 | + .unwrap(); | ||
| 450 | + | ||
| 451 | + // The stranger sees the published one alone, and `total` agrees. | ||
| 452 | + let (items, total) = list(&db, Some(&other), None, None, None, None, None, 0) | ||
| 453 | + .await | ||
| 454 | + .unwrap(); | ||
| 455 | + assert_eq!((items.len(), total), (1, 1)); | ||
| 456 | + assert_eq!(items[0].get_text().as_str(), "shared"); | ||
| 457 | + // The owner sees both; an admin (`None`) too. | ||
| 458 | + let (items, total) = list(&db, Some(&owner), None, None, None, None, None, 0) | ||
| 459 | + .await | ||
| 460 | + .unwrap(); | ||
| 461 | + assert_eq!((items.len(), total), (2, 2)); | ||
| 462 | + let (items, total) = list(&db, None, None, None, None, None, None, 0) | ||
| 463 | + .await | ||
| 464 | + .unwrap(); | ||
| 465 | + assert_eq!((items.len(), total), (2, 2)); | ||
| 466 | + // An explicit `owner=` filter can't widen the gate. | ||
| 467 | + let (items, total) = list(&db, Some(&other), Some(&owner), None, None, None, None, 0) | ||
| 468 | + .await | ||
| 469 | + .unwrap(); | ||
| 470 | + assert_eq!((items.len(), total), (1, 1)); | ||
| 471 | + assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 472 | + } | ||
| 473 | + | ||
| 474 | + /// The bite test for the compare-and-set that replaced the writer lease of | ||
| 475 | + /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has | ||
| 476 | + /// since moved past must be refused, not written — otherwise it reverts | ||
| 477 | + /// whatever landed in between. Asserts the *stored* row, never a race | ||
| 478 | + /// outcome: the in-memory engine can drop one of two concurrent writes and | ||
| 479 | + /// still answer `Ok`. | ||
| 480 | + #[tokio::test] | ||
| 481 | + async fn a_merge_built_on_a_stale_snapshot_is_refused() { | ||
| 482 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 483 | + let owner = UserId::generate(); | ||
| 484 | + let stale = create( | ||
| 485 | + &db, | ||
| 486 | + owner, | ||
| 487 | + SubjectId::generate(), | ||
| 488 | + QuestionText::try_new("first").unwrap(), | ||
| 489 | + QuestionPoints::try_new(1).unwrap(), | ||
| 490 | + spec(), | ||
| 491 | + ) | ||
| 492 | + .await | ||
| 493 | + .unwrap(); | ||
| 494 | + // Somebody else's edit lands on the row this snapshot came from. | ||
| 495 | + let landed = update_if_unchanged( | ||
| 496 | + &db, | ||
| 497 | + stale.clone(), | ||
| 498 | + None, | ||
| 499 | + QuestionText::try_new("theirs").unwrap(), | ||
| 500 | + QuestionPoints::try_new(2).unwrap(), | ||
| 501 | + spec(), | ||
| 502 | + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), | ||
| 503 | + ) | ||
| 504 | + .await | ||
| 505 | + .unwrap(); | ||
| 506 | + assert!(landed.is_some(), "the first write is on a fresh snapshot"); | ||
| 507 | + | ||
| 508 | + let refused = update_if_unchanged( | ||
| 509 | + &db, | ||
| 510 | + stale, | ||
| 511 | + None, | ||
| 512 | + QuestionText::try_new("mine").unwrap(), | ||
| 513 | + QuestionPoints::try_new(3).unwrap(), | ||
| 514 | + spec(), | ||
| 515 | + BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), | ||
| 516 | + ) | ||
| 517 | + .await | ||
| 518 | + .unwrap(); | ||
| 519 | + assert!(refused.is_none(), "a stale merge must not be written"); | ||
| 520 | + let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap(); | ||
| 521 | + assert_eq!(stored.get_text().as_str(), "theirs"); | ||
| 522 | + assert_eq!(stored.get_points().as_i64(), 2); | ||
| 523 | + } | ||
| 524 | + | ||
| 525 | + /// The `visibility` filter ANDs onto the security gate, so it narrows and | ||
| 526 | + /// never widens: a stranger asking for `school` still can't see a private | ||
| 527 | + /// row, and `private` means "my own drafts" for everyone but an admin. | ||
| 528 | + #[tokio::test] | ||
| 529 | + async fn visibility_filter_narrows_never_widens() { | ||
| 530 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 531 | + let owner = UserId::generate(); | ||
| 532 | + let other = UserId::generate(); | ||
| 533 | + let mine = |text: &str| { | ||
| 534 | + create( | ||
| 535 | + &db, | ||
| 536 | + owner.clone(), | ||
| 537 | + SubjectId::generate(), | ||
| 538 | + QuestionText::try_new(text).unwrap(), | ||
| 539 | + QuestionPoints::try_new(1).unwrap(), | ||
| 540 | + spec(), | ||
| 541 | + ) | ||
| 542 | + }; | ||
| 543 | + mine("draft").await.unwrap(); | ||
| 544 | + let published = mine("shared").await.unwrap(); | ||
| 545 | + let subject = published.get_subject().cloned(); | ||
| 546 | + update_if_unchanged( | ||
| 547 | + &db, | ||
| 548 | + published, | ||
| 549 | + subject, | ||
| 550 | + QuestionText::try_new("shared").unwrap(), | ||
| 551 | + QuestionPoints::try_new(1).unwrap(), | ||
| 552 | + spec(), | ||
| 553 | + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), | ||
| 554 | + ) | ||
| 555 | + .await | ||
| 556 | + .unwrap(); | ||
| 557 | + let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(); | ||
| 558 | + let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(); | ||
| 559 | + | ||
| 560 | + // Owner: `private` = their drafts, `school` = the published one. | ||
| 561 | + let (items, total) = list(&db, Some(&owner), None, None, Some(&private), None, None, 0) | ||
| 562 | + .await | ||
| 563 | + .unwrap(); | ||
| 564 | + assert_eq!((items.len(), total), (1, 1)); | ||
| 565 | + assert_eq!(items[0].get_text().as_str(), "draft"); | ||
| 566 | + let (items, total) = list(&db, Some(&owner), None, None, Some(&school), None, None, 0) | ||
| 567 | + .await | ||
| 568 | + .unwrap(); | ||
| 569 | + assert_eq!((items.len(), total), (1, 1)); | ||
| 570 | + assert_eq!(items[0].get_text().as_str(), "shared"); | ||
| 571 | + // A stranger's `private` is empty — never someone else's draft. | ||
| 572 | + let (items, total) = list(&db, Some(&other), None, None, Some(&private), None, None, 0) | ||
| 573 | + .await | ||
| 574 | + .unwrap(); | ||
| 575 | + assert!(items.is_empty()); | ||
| 576 | + assert_eq!(total, 0); | ||
| 577 | + // …and their `school` stops at the published one, gate intact. | ||
| 578 | + let (items, total) = list(&db, Some(&other), None, None, Some(&school), None, None, 0) | ||
| 579 | + .await | ||
| 580 | + .unwrap(); | ||
| 581 | + assert_eq!((items.len(), total), (1, 1)); | ||
| 582 | + // Composes with the other filters: right owner, wrong visibility. | ||
| 583 | + let (items, total) = list( | ||
| 584 | + &db, | ||
| 585 | + Some(&owner), | ||
| 586 | + Some(&owner), | ||
| 587 | + None, | ||
| 588 | + Some(&school), | ||
| 589 | + Some("draft"), | ||
| 590 | + None, | ||
| 591 | + 0, | ||
| 592 | + ) | ||
| 593 | + .await | ||
| 594 | + .unwrap(); | ||
| 595 | + assert!(items.is_empty()); | ||
| 596 | + assert_eq!(total, 0); | ||
| 597 | + } | ||
| 598 | + | ||
| 599 | + /// The whole page's tally in one grouped statement: right number per | ||
| 600 | + /// template, unused templates absent (so the UI prints nothing rather than | ||
| 601 | + /// "0"), and questions authored by hand never counted. | ||
| 602 | + #[tokio::test] | ||
| 603 | + async fn usage_counts_tallies_a_page_in_one_statement() { | ||
| 604 | + // One statement, so a page costs one round trip — a `;` here would mean | ||
| 605 | + // the per-row N+1 crept back in. | ||
| 606 | + assert!( | ||
| 607 | + !USAGE_COUNTS_SQL.contains(';'), | ||
| 608 | + "usage_counts must be one statement" | ||
| 609 | + ); | ||
| 610 | + | ||
| 611 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 612 | + let owner = UserId::generate(); | ||
| 613 | + let template = |text: &str| { | ||
| 614 | + create( | ||
| 615 | + &db, | ||
| 616 | + owner.clone(), | ||
| 617 | + SubjectId::generate(), | ||
| 618 | + QuestionText::try_new(text).unwrap(), | ||
| 619 | + QuestionPoints::try_new(1).unwrap(), | ||
| 620 | + spec(), | ||
| 621 | + ) | ||
| 622 | + }; | ||
| 623 | + let used_twice = template("twice").await.unwrap(); | ||
| 624 | + let used_once = template("once").await.unwrap(); | ||
| 625 | + let unused = template("never").await.unwrap(); | ||
| 626 | + | ||
| 627 | + // Real exam rows: instantiating a template moves the exam's counter | ||
| 628 | + // (what keeps a question from outliving its exam), so a minted id | ||
| 629 | + // nothing wrote is a 404. | ||
| 630 | + let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | ||
| 631 | + let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | ||
| 632 | + // A real subject row: an exam question claims a reference on its | ||
| 633 | + // subject, so a minted id it never wrote would be refused. | ||
| 634 | + let subject = crate::domain::subject::Subject::create( | ||
| 635 | + &crate::db::course::a_test_course(&db).await, | ||
| 636 | + crate::domain::subject::SubjectName::try_new("topic").unwrap(), | ||
| 637 | + crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 638 | + &db, | ||
| 639 | + ) | ||
| 640 | + .await | ||
| 641 | + .unwrap(); | ||
| 642 | + async fn instantiate( | ||
| 643 | + exam: &ExamId, | ||
| 644 | + subject: &SubjectId, | ||
| 645 | + source: &BankQuestion, | ||
| 646 | + db: &Database, | ||
| 647 | + ) { | ||
| 648 | + crate::db::exam_question::create_from_bank( | ||
| 649 | + db, | ||
| 650 | + exam, | ||
| 651 | + subject.clone(), | ||
| 652 | + source.get_text().clone(), | ||
| 653 | + source.get_points(), | ||
| 654 | + source.spec(), | ||
| 655 | + source.get_id().clone(), | ||
| 656 | + ) | ||
| 657 | + .await | ||
| 658 | + .unwrap(); | ||
| 659 | + } | ||
| 660 | + // Two copies of the same template, in two different exams. | ||
| 661 | + instantiate(&exam, subject.get_id(), &used_twice, &db).await; | ||
| 662 | + instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; | ||
| 663 | + instantiate(&exam, subject.get_id(), &used_once, &db).await; | ||
| 664 | + // A hand-authored question has no `from_bank` and must not be tallied. | ||
| 665 | + crate::db::exam_question::create( | ||
| 666 | + &db, | ||
| 667 | + &exam, | ||
| 668 | + subject.get_id().clone(), | ||
| 669 | + QuestionText::try_new("mine").unwrap(), | ||
| 670 | + QuestionPoints::try_new(1).unwrap(), | ||
| 671 | + spec(), | ||
| 672 | + ) | ||
| 673 | + .await | ||
| 674 | + .unwrap(); | ||
| 675 | + | ||
| 676 | + let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; | ||
| 677 | + let counts = usage_counts(&db, &ids).await.unwrap(); | ||
| 678 | + assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); | ||
| 679 | + assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); | ||
| 680 | + assert_eq!( | ||
| 681 | + counts.get(unused.get_id().key()), | ||
| 682 | + None, | ||
| 683 | + "unused stays absent" | ||
| 684 | + ); | ||
| 685 | + assert_eq!(counts.len(), 2); | ||
| 686 | + | ||
| 687 | + // A template outside the page is never counted into it. | ||
| 688 | + let narrow = usage_counts(&db, &[used_once.get_id()]).await.unwrap(); | ||
| 689 | + assert_eq!(narrow.len(), 1); | ||
| 690 | + assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); | ||
| 691 | + // An empty page asks nothing at all. | ||
| 692 | + assert!(usage_counts(&db, &[]).await.unwrap().is_empty()); | ||
| 693 | + } | ||
| 694 | + | ||
| 695 | + #[tokio::test] | ||
| 696 | + async fn list_is_school_wide() { | ||
| 697 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 698 | + for _ in 0..2 { | ||
| 699 | + create( | ||
| 700 | + &db, | ||
| 701 | + UserId::generate(), | ||
| 702 | + SubjectId::generate(), | ||
| 703 | + QuestionText::try_new("q").unwrap(), | ||
| 704 | + QuestionPoints::try_new(1).unwrap(), | ||
| 705 | + spec(), | ||
| 706 | + ) | ||
| 707 | + .await | ||
| 708 | + .unwrap(); | ||
| 709 | + } | ||
| 710 | + // Different owners, yet both listed. | ||
| 711 | + let (items, total) = list(&db, None, None, None, None, None, None, 0) | ||
| 712 | + .await | ||
| 713 | + .unwrap(); | ||
| 714 | + assert_eq!(items.len(), 2); | ||
| 715 | + assert_eq!(total, 2); | ||
| 716 | + } | ||
| 717 | + | ||
| 718 | + /// The window is SQL, not an in-memory slice, and `total` ignores it. | ||
| 719 | + #[tokio::test] | ||
| 720 | + async fn list_pages_newest_first_and_filters_text() { | ||
| 721 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 722 | + let owner = UserId::generate(); | ||
| 723 | + for i in 0..5 { | ||
| 724 | + create( | ||
| 725 | + &db, | ||
| 726 | + owner.clone(), | ||
| 727 | + SubjectId::generate(), | ||
| 728 | + QuestionText::try_new(&format!("question {i}")).unwrap(), | ||
| 729 | + QuestionPoints::try_new(1).unwrap(), | ||
| 730 | + spec(), | ||
| 731 | + ) | ||
| 732 | + .await | ||
| 733 | + .unwrap(); | ||
| 734 | + } | ||
| 735 | + let (page, total) = list(&db, None, None, None, None, None, Some(2), 0) | ||
| 736 | + .await | ||
| 737 | + .unwrap(); | ||
| 738 | + assert_eq!(total, 5); | ||
| 739 | + assert_eq!(page.len(), 2); | ||
| 740 | + // Newest first: the last-created row leads. | ||
| 741 | + assert_eq!(page[0].get_text().as_str(), "question 4"); | ||
| 742 | + // The tail is reachable by offset. | ||
| 743 | + let (tail, _) = list(&db, None, None, None, None, None, Some(2), 4) | ||
| 744 | + .await | ||
| 745 | + .unwrap(); | ||
| 746 | + assert_eq!(tail[0].get_text().as_str(), "question 0"); | ||
| 747 | + // Text filter runs in SQL, case-insensitively, and narrows `total`. | ||
| 748 | + let (hits, total) = list(&db, None, None, None, None, Some("QUESTION 3"), None, 0) | ||
| 749 | + .await | ||
| 750 | + .unwrap(); | ||
| 751 | + assert_eq!((hits.len(), total), (1, 1)); | ||
| 752 | + // Owner filter with nobody's templates. | ||
| 753 | + let (none, total) = list( | ||
| 754 | + &db, | ||
| 755 | + None, | ||
| 756 | + Some(&UserId::generate()), | ||
| 757 | + None, | ||
| 758 | + None, | ||
| 759 | + None, | ||
| 760 | + None, | ||
| 761 | + 0, | ||
| 762 | + ) | ||
| 763 | + .await | ||
| 764 | + .unwrap(); | ||
| 765 | + assert!(none.is_empty()); | ||
| 766 | + assert_eq!(total, 0); | ||
| 767 | + } | ||
| 768 | + | ||
| 769 | + /// Turkish `İ`/`ı` must not split the search into two disjoint halves. | ||
| 770 | + #[tokio::test] | ||
| 771 | + async fn list_text_filter_folds_turkish_casing() { | ||
| 772 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 773 | + create( | ||
| 774 | + &db, | ||
| 775 | + UserId::generate(), | ||
| 776 | + SubjectId::generate(), | ||
| 777 | + QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), | ||
| 778 | + QuestionPoints::try_new(1).unwrap(), | ||
| 779 | + spec(), | ||
| 780 | + ) | ||
| 781 | + .await | ||
| 782 | + .unwrap(); | ||
| 783 | + for needle in [ | ||
| 784 | + "istanbul", | ||
| 785 | + "İSTANBUL", | ||
| 786 | + "İstanbul", | ||
| 787 | + "ıstanbul", | ||
| 788 | + "ilçe", | ||
| 789 | + "ILCE", | ||
| 790 | + ] { | ||
| 791 | + let (hits, total) = list(&db, None, None, None, None, Some(needle), None, 0) | ||
| 792 | + .await | ||
| 793 | + .unwrap(); | ||
| 794 | + assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); | ||
| 795 | + } | ||
| 796 | + let (miss, total) = list(&db, None, None, None, None, Some("ankara"), None, 0) | ||
| 797 | + .await | ||
| 798 | + .unwrap(); | ||
| 799 | + assert!(miss.is_empty()); | ||
| 800 | + assert_eq!(total, 0); | ||
| 801 | + } | ||
| 802 | +} | ||
src/db/bank_question_image.rsadded+473 -0
| @@ -0,0 +1,473 @@ | |||
| 1 | +//! The `bank_question_image` slot table: the per-slot upsert that pins the | ||
| 2 | +//! template's existence into its own transaction, the page-wide listing, and | ||
| 3 | +//! the choice sweep a non-destructive PATCH runs. Blob I/O stays in the web | ||
| 4 | +//! layer; the pure entity and newtypes in | ||
| 5 | +//! [`crate::domain::bank_question_image`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 8 | + | ||
| 9 | +use crate::database::{Database, transaction_with_retry}; | ||
| 10 | +use crate::domain::bank_question::BankQuestionId; | ||
| 11 | +use crate::domain::bank_question_image::{BankQuestionImage, BankQuestionImageId}; | ||
| 12 | +use crate::domain::exam_question::ChoiceId; | ||
| 13 | +use crate::error::AppError; | ||
| 14 | + | ||
| 15 | +/// What one [`upsert`] transaction returns: the row it | ||
| 16 | +/// stored and the blob name it replaced. Both are arrays because SurrealDB | ||
| 17 | +/// drops an object key valued `NONE` on the way out, while an empty array | ||
| 18 | +/// survives — "nothing was replaced" has to be readable, not missing. | ||
| 19 | +#[derive(SurrealValue)] | ||
| 20 | +struct UpsertOutcome { | ||
| 21 | + stored: Vec<BankQuestionImage>, | ||
| 22 | + replaced: Vec<String>, | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// Create or replace the slot's image row — the deterministic id makes this | ||
| 26 | +/// the whole "one image per slot" story — handing back what it stored plus | ||
| 27 | +/// the blob name it replaced, for the caller to take off disk. | ||
| 28 | +/// | ||
| 29 | +/// Both halves are the transaction's doing. The template's own `points` is | ||
| 30 | +/// moved and put straight back inside it, the way | ||
| 31 | +/// [`crate::db::pool_question::bump_question_and_write`] moves | ||
| 32 | +/// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other | ||
| 33 | +/// int column): that makes the template's *existence* part of this write. | ||
| 34 | +/// A bare `UPSERT` guarded by having read the template first does not | ||
| 35 | +/// survive its delete window — the read sees a row | ||
| 36 | +/// [`crate::db::bank_question::delete`] has removed but | ||
| 37 | +/// not committed, while that delete's image sweep ran on a snapshot | ||
| 38 | +/// predating this row, so both commit and the image outlives the template | ||
| 39 | +/// it hangs on. Nothing could ever read, delete, or sweep it afterwards: | ||
| 40 | +/// every image route goes through the template. Moving the value makes the | ||
| 41 | +/// two transactions touch one key, so the store refuses a side; writing the | ||
| 42 | +/// same value back would be elided and collide with nothing. | ||
| 43 | +/// | ||
| 44 | +/// The replaced blob name comes out of this same transaction rather than a | ||
| 45 | +/// read in front of it (the shape | ||
| 46 | +/// [`crate::db::pool_question::set_image`] has): two | ||
| 47 | +/// uploads to one slot both write this row, so they contend and the loser | ||
| 48 | +/// re-reads the winner's blob name, where two pre-reads both saw the *old* | ||
| 49 | +/// blob and left the loser's fresh one orphaned on disk. | ||
| 50 | +/// | ||
| 51 | +/// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is | ||
| 52 | +/// deterministic per (question, slot) and the table carries no `UNIQUE` | ||
| 53 | +/// index, so the write always resolves onto the row its id names and can | ||
| 54 | +/// never answer "already exists". | ||
| 55 | +pub async fn upsert( | ||
| 56 | + db: &Database, | ||
| 57 | + image: BankQuestionImage, | ||
| 58 | +) -> Result<(BankQuestionImage, Option<String>), AppError> { | ||
| 59 | + // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic | ||
| 60 | + let (question, id) = (image.bank_question.record(), image.id.record()); | ||
| 61 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 62 | + db, | ||
| 63 | + "BEGIN TRANSACTION; | ||
| 64 | + LET $was_points = (SELECT VALUE points FROM ONLY $b); | ||
| 65 | + LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); | ||
| 66 | + IF array::len($bumped) = 0 { THROW 'no_question' }; | ||
| 67 | + UPDATE $b SET points = $was_points; | ||
| 68 | + LET $replaced = (SELECT VALUE file FROM $id); | ||
| 69 | + LET $stored = (UPSERT $id CONTENT $image); | ||
| 70 | + RETURN { stored: $stored, replaced: $replaced }; | ||
| 71 | + COMMIT TRANSACTION;", | ||
| 72 | + &[ | ||
| 73 | + ("b".into(), question.into_value()), | ||
| 74 | + ("id".into(), id.into_value()), | ||
| 75 | + ("image".into(), image.into_value()), | ||
| 76 | + ], | ||
| 77 | + &["no_question"], | ||
| 78 | + ) | ||
| 79 | + .await?; | ||
| 80 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 81 | + // executed" — only the THROW's own slot names the reason. | ||
| 82 | + if errors | ||
| 83 | + .values() | ||
| 84 | + .any(|error| error.to_string().contains("no_question")) | ||
| 85 | + { | ||
| 86 | + return Err(AppError::NotFound); | ||
| 87 | + } | ||
| 88 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 89 | + return Err(error.into()); | ||
| 90 | + } | ||
| 91 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its | ||
| 92 | + // slot follows the statement count rather than a hand-kept number; | ||
| 93 | + // `num_statements` counts BEGIN and COMMIT. | ||
| 94 | + let slot = result.num_statements().saturating_sub(2); | ||
| 95 | + let failed = || AppError::Internal("failed to store bank question image".into()); | ||
| 96 | + let outcome = result | ||
| 97 | + .take::<Vec<UpsertOutcome>>(slot)? | ||
| 98 | + .into_iter() | ||
| 99 | + .next() | ||
| 100 | + .ok_or_else(failed)?; | ||
| 101 | + let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | ||
| 102 | + Ok((stored, outcome.replaced.into_iter().next())) | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +pub async fn read_slot( | ||
| 106 | + db: &Database, | ||
| 107 | + question: &BankQuestionId, | ||
| 108 | + slot: Option<&ChoiceId>, | ||
| 109 | +) -> Result<Option<BankQuestionImage>, AppError> { | ||
| 110 | + Ok(db | ||
| 111 | + .select(BankQuestionImageId::for_slot(question, slot).record()) | ||
| 112 | + .await?) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +pub async fn list_for_question( | ||
| 116 | + db: &Database, | ||
| 117 | + question: &BankQuestionId, | ||
| 118 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 119 | + let mut result = db | ||
| 120 | + .query("SELECT * FROM bank_question_image WHERE bank_question = $b") | ||
| 121 | + .bind(("b", question.record())) | ||
| 122 | + .await? | ||
| 123 | + .check()?; | ||
| 124 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The image rows of several templates in one query — for bucketing onto a | ||
| 128 | +/// listing's *page* (never the whole table: the bank spans the school). | ||
| 129 | +pub async fn list_for_questions( | ||
| 130 | + db: &Database, | ||
| 131 | + questions: &[&BankQuestionId], | ||
| 132 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 133 | + if questions.is_empty() { | ||
| 134 | + return Ok(Vec::new()); | ||
| 135 | + } | ||
| 136 | + let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect(); | ||
| 137 | + let mut result = db | ||
| 138 | + .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") | ||
| 139 | + .bind(("ids", records)) | ||
| 140 | + .await? | ||
| 141 | + .check()?; | ||
| 142 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// Drop the option pictures whose choice is gone — every choice image of | ||
| 146 | +/// the question whose `slot` is *not* in `keep` (the question's own | ||
| 147 | +/// illustration always stays), returning the removed rows so the caller can | ||
| 148 | +/// take their blobs off disk. | ||
| 149 | +/// | ||
| 150 | +/// This is what makes an edit non-destructive: a PATCH that reorders, | ||
| 151 | +/// renames, or drops options passes the surviving choice ids as `keep`, so | ||
| 152 | +/// only the pictures of genuinely removed options go. `keep = &[]` (a text | ||
| 153 | +/// question, or an all-new choice list) still clears the lot. | ||
| 154 | +pub async fn delete_choices_not_in( | ||
| 155 | + db: &Database, | ||
| 156 | + question: &BankQuestionId, | ||
| 157 | + keep: &[ChoiceId], | ||
| 158 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 159 | + let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); | ||
| 160 | + let mut result = db | ||
| 161 | + .query( | ||
| 162 | + "DELETE bank_question_image \ | ||
| 163 | + WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", | ||
| 164 | + ) | ||
| 165 | + .bind(("b", question.record())) | ||
| 166 | + .bind(("keep", keep)) | ||
| 167 | + .await? | ||
| 168 | + .check()?; | ||
| 169 | + Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +pub async fn delete( | ||
| 173 | + db: &Database, | ||
| 174 | + image: BankQuestionImage, | ||
| 175 | +) -> Result<BankQuestionImage, AppError> { | ||
| 176 | + let deleted: Option<BankQuestionImage> = db.delete(image.id.record()).await?; | ||
| 177 | + deleted.ok_or(AppError::NotFound) | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +#[cfg(test)] | ||
| 181 | +mod tests { | ||
| 182 | + use super::*; | ||
| 183 | + use crate::database::Database; | ||
| 184 | + | ||
| 185 | + fn png() -> crate::domain::note_file::FileContentType { | ||
| 186 | + crate::domain::note_file::FileContentType::try_new("image/png").unwrap() | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + /// A real template row: an image write moves its `points` inside its own | ||
| 190 | + /// transaction, so a minted id nothing ever wrote is refused. | ||
| 191 | + async fn a_template(db: &Database) -> BankQuestionId { | ||
| 192 | + let id = BankQuestionId::generate(); | ||
| 193 | + db.query( | ||
| 194 | + "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, | ||
| 195 | + visibility = 'private', created_at = 1", | ||
| 196 | + ) | ||
| 197 | + .bind(("b", id.record())) | ||
| 198 | + .await | ||
| 199 | + .unwrap() | ||
| 200 | + .check() | ||
| 201 | + .unwrap(); | ||
| 202 | + id | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + fn choice_ids() -> Vec<ChoiceId> { | ||
| 206 | + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; | ||
| 207 | + QuestionSpec::try_new( | ||
| 208 | + QuestionKind::try_new("choice").unwrap(), | ||
| 209 | + Some( | ||
| 210 | + ["a", "b", "c"] | ||
| 211 | + .iter() | ||
| 212 | + .map(|l| ChoiceInput { | ||
| 213 | + id: Some((*l).into()), | ||
| 214 | + text: (*l).into(), | ||
| 215 | + }) | ||
| 216 | + .collect(), | ||
| 217 | + ), | ||
| 218 | + Some("a".into()), | ||
| 219 | + &[], | ||
| 220 | + ) | ||
| 221 | + .unwrap() | ||
| 222 | + .into_parts() | ||
| 223 | + .1 | ||
| 224 | + .unwrap() | ||
| 225 | + .iter() | ||
| 226 | + .map(|c| c.get_id().clone()) | ||
| 227 | + .collect() | ||
| 228 | + } | ||
| 229 | + | ||
| 230 | + #[tokio::test] | ||
| 231 | + async fn upsert_replaces_per_slot() { | ||
| 232 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 233 | + let question = a_template(&db).await; | ||
| 234 | + | ||
| 235 | + let (first, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)) | ||
| 236 | + .await | ||
| 237 | + .unwrap(); | ||
| 238 | + assert_eq!(retired, None, "a first upload retires no blob"); | ||
| 239 | + let (second, retired) = upsert(&db, BankQuestionImage::new(&question, None, png(), 5)) | ||
| 240 | + .await | ||
| 241 | + .unwrap(); | ||
| 242 | + // Same slot, same row — the replace swapped the blob pointer, and the | ||
| 243 | + // write itself names the blob the caller must unlink. | ||
| 244 | + assert_ne!(first.get_file(), second.get_file()); | ||
| 245 | + assert_eq!(retired.as_deref(), Some(first.get_file())); | ||
| 246 | + let rows = list_for_question(&db, &question).await.unwrap(); | ||
| 247 | + assert_eq!(rows.len(), 1); | ||
| 248 | + assert_eq!(rows[0].get_size(), 5); | ||
| 249 | + } | ||
| 250 | + | ||
| 251 | + /// The bank half of the non-destructive edit: keeping an option keeps its | ||
| 252 | + /// picture, and only a removed option's picture goes. | ||
| 253 | + #[tokio::test] | ||
| 254 | + async fn only_the_dropped_options_lose_their_pictures() { | ||
| 255 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 256 | + let question = a_template(&db).await; | ||
| 257 | + let ids = choice_ids(); | ||
| 258 | + upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) | ||
| 259 | + .await | ||
| 260 | + .unwrap(); | ||
| 261 | + for id in &ids { | ||
| 262 | + upsert(&db, BankQuestionImage::new(&question, Some(id), png(), 1)) | ||
| 263 | + .await | ||
| 264 | + .unwrap(); | ||
| 265 | + } | ||
| 266 | + | ||
| 267 | + let keep = vec![ids[0].clone(), ids[1].clone()]; | ||
| 268 | + let dropped = delete_choices_not_in(&db, &question, &keep).await.unwrap(); | ||
| 269 | + assert_eq!(dropped.len(), 1); | ||
| 270 | + assert_eq!(dropped[0].get_slot(), Some(&ids[2])); | ||
| 271 | + | ||
| 272 | + let left = list_for_question(&db, &question).await.unwrap(); | ||
| 273 | + assert_eq!(left.len(), 3); | ||
| 274 | + } | ||
| 275 | + | ||
| 276 | + #[tokio::test] | ||
| 277 | + async fn an_empty_keep_set_clears_every_option_picture() { | ||
| 278 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 279 | + let question = a_template(&db).await; | ||
| 280 | + let ids = choice_ids(); | ||
| 281 | + upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) | ||
| 282 | + .await | ||
| 283 | + .unwrap(); | ||
| 284 | + for id in &ids[..2] { | ||
| 285 | + upsert(&db, BankQuestionImage::new(&question, Some(id), png(), 1)) | ||
| 286 | + .await | ||
| 287 | + .unwrap(); | ||
| 288 | + } | ||
| 289 | + | ||
| 290 | + let dropped = delete_choices_not_in(&db, &question, &[]).await.unwrap(); | ||
| 291 | + assert_eq!(dropped.len(), 2); | ||
| 292 | + assert!(dropped.iter().all(|image| image.get_slot().is_some())); | ||
| 293 | + | ||
| 294 | + let left = list_for_question(&db, &question).await.unwrap(); | ||
| 295 | + assert_eq!(left.len(), 1); | ||
| 296 | + assert_eq!(left[0].get_slot(), None); | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + /// The [`crate::db::pool_question`] defect, one domain | ||
| 300 | + /// over: an image written inside its template's delete window must not | ||
| 301 | + /// outlive it. Guarding the write by *reading* the template does not do it | ||
| 302 | + /// — the read sees a row [`crate::db::bank_question::delete`] has removed | ||
| 303 | + /// but not committed, while its `DELETE bank_question_image WHERE | ||
| 304 | + /// bank_question = $b` ran on a snapshot predating this row, so both | ||
| 305 | + /// commit and the image is left pointing at a template that is gone. | ||
| 306 | + /// Nothing can reach it after that: every image route resolves the | ||
| 307 | + /// template first, no boot sweep visits this table, and its blob stays on | ||
| 308 | + /// disk for good. [`upsert`] moves the template's own `points` instead, so | ||
| 309 | + /// the two transactions touch one key and the store refuses a side. | ||
| 310 | + /// | ||
| 311 | + /// The blob half is asserted through the list the delete hands back: that | ||
| 312 | + /// list — never a snapshot read before it — is what the web layer unlinks | ||
| 313 | + /// from, so an image that committed inside the window and is *not* in it is | ||
| 314 | + /// a blob stranded on disk. | ||
| 315 | + /// | ||
| 316 | + /// The window is opened by the schema, not by a lucky interleaving: a | ||
| 317 | + /// `DEFINE EVENT` on `bank_question` fires inside the delete's own | ||
| 318 | + /// transaction the instant the row goes. | ||
| 319 | + /// | ||
| 320 | + /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 321 | + /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 322 | + /// it commits both and answers `Ok` to each, so this passes there on broken | ||
| 323 | + /// code. | ||
| 324 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 325 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 326 | + async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { | ||
| 327 | + let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; | ||
| 328 | + db.query( | ||
| 329 | + "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ | ||
| 330 | + THEN { SLEEP 1s; };", | ||
| 331 | + ) | ||
| 332 | + .await | ||
| 333 | + .unwrap() | ||
| 334 | + .check() | ||
| 335 | + .unwrap(); | ||
| 336 | + | ||
| 337 | + let (mut swept, mut orphans, mut stranded) = (0, 0, 0); | ||
| 338 | + for round in 0..4 { | ||
| 339 | + let question = a_template(&db).await; | ||
| 340 | + let template = crate::db::bank_question::read(&db, &question) | ||
| 341 | + .await | ||
| 342 | + .unwrap() | ||
| 343 | + .unwrap(); | ||
| 344 | + | ||
| 345 | + let drop_it = { | ||
| 346 | + let db = db.clone(); | ||
| 347 | + tokio::spawn(async move { crate::db::bank_question::delete(&db, template).await }) | ||
| 348 | + }; | ||
| 349 | + // The upload starts inside the held window — the template row is | ||
| 350 | + // gone but uncommitted, which is exactly what the handler's | ||
| 351 | + // ownership read believes. | ||
| 352 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 353 | + let child = { | ||
| 354 | + let (db, question) = (db.clone(), question.clone()); | ||
| 355 | + tokio::spawn(async move { | ||
| 356 | + upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await | ||
| 357 | + }) | ||
| 358 | + }; | ||
| 359 | + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 360 | + // A 404 for the upload is a correct answer; the only defect is | ||
| 361 | + // stored state. Neither side may 500 — they contend by design and a | ||
| 362 | + // lost round is re-sent, not reported. | ||
| 363 | + assert!( | ||
| 364 | + !matches!(child, Err(AppError::Db(_))), | ||
| 365 | + "round {round}: a raced upload must be answered, not 500: {child:?}" | ||
| 366 | + ); | ||
| 367 | + assert!( | ||
| 368 | + !matches!(drop_it, Err(AppError::Db(_))), | ||
| 369 | + "round {round}: a raced delete must retry, not 500: {drop_it:?}" | ||
| 370 | + ); | ||
| 371 | + | ||
| 372 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 373 | + if crate::db::bank_question::read(&db, &question) | ||
| 374 | + .await | ||
| 375 | + .unwrap() | ||
| 376 | + .is_none() | ||
| 377 | + { | ||
| 378 | + swept += 1; | ||
| 379 | + orphans += list_for_question(&db, &question).await.unwrap().len(); | ||
| 380 | + if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) | ||
| 381 | + && !images | ||
| 382 | + .iter() | ||
| 383 | + .any(|image| image.get_file() == stored.get_file()) | ||
| 384 | + { | ||
| 385 | + stranded += 1; | ||
| 386 | + } | ||
| 387 | + } | ||
| 388 | + } | ||
| 389 | + eprintln!( | ||
| 390 | + "bank_question::delete raced by an upload: {swept}/4 rounds deleted the template" | ||
| 391 | + ); | ||
| 392 | + assert!( | ||
| 393 | + swept > 0, | ||
| 394 | + "no round ever deleted the template, so the window was never reached" | ||
| 395 | + ); | ||
| 396 | + assert_eq!(orphans, 0, "an image row outlived its template"); | ||
| 397 | + assert_eq!( | ||
| 398 | + stranded, 0, | ||
| 399 | + "an image committed inside the window was swept without being handed back, so its blob stays on disk" | ||
| 400 | + ); | ||
| 401 | + } | ||
| 402 | + | ||
| 403 | + /// Two uploads to one slot must leave exactly one live blob and hand every | ||
| 404 | + /// other one back to be unlinked. Reading the slot's old blob name *before* | ||
| 405 | + /// the write gave both racers the same answer: both retired the same old | ||
| 406 | + /// blob, and the loser's fresh one stayed on disk with nothing naming it. | ||
| 407 | + /// [`upsert`] reads it inside its own transaction instead, so the | ||
| 408 | + /// loser contends on the row it writes and re-reads the winner's name. | ||
| 409 | + /// | ||
| 410 | + /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this | ||
| 411 | + /// table holds the first write open inside its own transaction, so the | ||
| 412 | + /// second reads the slot before the first commits. | ||
| 413 | + /// | ||
| 414 | + /// Real server, and `#[ignore]`d for it, for the reason above: the embedded | ||
| 415 | + /// engine has no write-write conflict detection to make a loser re-read. | ||
| 416 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 417 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 418 | + async fn two_uploads_to_one_slot_leave_no_blob_unretired() { | ||
| 419 | + let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; | ||
| 420 | + db.query( | ||
| 421 | + "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ | ||
| 422 | + THEN { SLEEP 300ms; };", | ||
| 423 | + ) | ||
| 424 | + .await | ||
| 425 | + .unwrap() | ||
| 426 | + .check() | ||
| 427 | + .unwrap(); | ||
| 428 | + | ||
| 429 | + let mut unretired = 0; | ||
| 430 | + for round in 0..3 { | ||
| 431 | + let question = a_template(&db).await; | ||
| 432 | + // A first picture, so both racers have an old blob to retire. | ||
| 433 | + let (original, _) = upsert(&db, BankQuestionImage::new(&question, None, png(), 1)) | ||
| 434 | + .await | ||
| 435 | + .unwrap(); | ||
| 436 | + | ||
| 437 | + let mut writes = Vec::new(); | ||
| 438 | + for size in [2, 3] { | ||
| 439 | + let (db, question) = (db.clone(), question.clone()); | ||
| 440 | + writes.push(tokio::spawn(async move { | ||
| 441 | + upsert(&db, BankQuestionImage::new(&question, None, png(), size)).await | ||
| 442 | + })); | ||
| 443 | + } | ||
| 444 | + let mut written = vec![original.get_file().to_string()]; | ||
| 445 | + let mut retired = Vec::new(); | ||
| 446 | + for write in writes { | ||
| 447 | + let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| { | ||
| 448 | + panic!("round {round}: a raced upload must not 500: {err:?}") | ||
| 449 | + }); | ||
| 450 | + written.push(stored.get_file().to_string()); | ||
| 451 | + retired.extend(replaced); | ||
| 452 | + } | ||
| 453 | + | ||
| 454 | + // Stored state is the whole verdict: exactly one blob is live, and | ||
| 455 | + // every other one this round wrote must have been handed back — | ||
| 456 | + // once. A name written and never returned is a file on disk with | ||
| 457 | + // nothing pointing at it. | ||
| 458 | + let live = read_slot(&db, &question, None).await.unwrap().unwrap(); | ||
| 459 | + assert!( | ||
| 460 | + !retired.iter().any(|name| name == live.get_file()), | ||
| 461 | + "round {round}: the live row's own blob was retired" | ||
| 462 | + ); | ||
| 463 | + unretired += written | ||
| 464 | + .iter() | ||
| 465 | + .filter(|name| *name != live.get_file() && !retired.contains(name)) | ||
| 466 | + .count(); | ||
| 467 | + } | ||
| 468 | + assert_eq!( | ||
| 469 | + unretired, 0, | ||
| 470 | + "a blob was written and never handed back to be unlinked — it stays on disk forever" | ||
| 471 | + ); | ||
| 472 | + } | ||
| 473 | +} | ||
src/db/mod.rsmodified+4 -0
| @@ -2,6 +2,8 @@ | |||
| 2 | 2 | ||
| 3 | pub mod appointment; | 3 | pub mod appointment; |
| 4 | pub mod appointment_slot; | 4 | pub mod appointment_slot; |
| 5 | +pub mod bank_question; | ||
| 6 | +pub mod bank_question_image; | ||
| 5 | pub mod cap; | 7 | pub mod cap; |
| 6 | pub mod class_blueprint; | 8 | pub mod class_blueprint; |
| 7 | pub mod course; | 9 | pub mod course; |
| @@ -15,6 +17,8 @@ pub mod meal_booking; | |||
| 15 | pub mod note; | 17 | pub mod note; |
| 16 | pub mod page; | 18 | pub mod page; |
| 17 | pub mod payment_ledger; | 19 | pub mod payment_ledger; |
| 20 | +pub mod pool_question; | ||
| 18 | pub mod session; | 21 | pub mod session; |
| 19 | pub mod settings; | 22 | pub mod settings; |
| 23 | +pub mod solution; | ||
| 20 | pub mod user; | 24 | pub mod user; |
src/db/pool_question.rsadded+623 -0
| @@ -0,0 +1,623 @@ | |||
| 1 | +//! The `pool_question` table: ask/insert, the two listings, the guarded | ||
| 2 | +//! approve that rides the publish counters along, the pending-only image | ||
| 3 | +//! writes, and the delete that cascades solutions — plus | ||
| 4 | +//! [`bump_question_and_write`], the existence-move every child write goes | ||
| 5 | +//! through. The pure entity and newtypes live in | ||
| 6 | +//! [`crate::domain::pool_question`]; the web layer reaches these through | ||
| 7 | +//! [`crate::service::pool_question`]. | ||
| 8 | + | ||
| 9 | +use surrealdb::types::SurrealValue; | ||
| 10 | + | ||
| 11 | +use crate::constant::{ | ||
| 12 | + POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STATUS_APPROVED, STATUS_PENDING, | ||
| 13 | +}; | ||
| 14 | +use crate::database::{Database, transaction_with_retry}; | ||
| 15 | +use crate::domain::note_file::FileContentType; | ||
| 16 | +use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; | ||
| 17 | +use crate::domain::solution::Solution; | ||
| 18 | +use crate::domain::user::UserId; | ||
| 19 | +use crate::error::AppError; | ||
| 20 | + | ||
| 21 | +/// Move the question's `asked_at` **and** run `statement` — a write to | ||
| 22 | +/// something hanging off a question — in one transaction, handing back the row | ||
| 23 | +/// it returned. `NotFound` means the question is gone and nothing was written. | ||
| 24 | +/// | ||
| 25 | +/// The move is what makes the question's **existence** part of the child's own | ||
| 26 | +/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: | ||
| 27 | +/// the `UPDATE` matches nothing once the row is deleted, and a delete racing | ||
| 28 | +/// this one touches the very key this transaction writes, so the two cannot | ||
| 29 | +/// both commit. Reading the question first does *not* survive that race — the | ||
| 30 | +/// read sees a row [`delete`] has removed but not committed, while its | ||
| 31 | +/// `DELETE solution WHERE question = $q` ran on a snapshot predating this | ||
| 32 | +/// insert, so both commit and the child outlives its question with neither | ||
| 33 | +/// caller told anything. | ||
| 34 | +/// | ||
| 35 | +/// `asked_at` rather than a revision column because this row carries no counter | ||
| 36 | +/// to bump and must not grow one for this alone. It is put back *by captured | ||
| 37 | +/// value* in the same transaction, so nothing outside ever observes the move | ||
| 38 | +/// and the row is byte-identical afterwards (the pool lists order on it). | ||
| 39 | +/// Writing the same value would buy nothing: an `UPDATE` that leaves the | ||
| 40 | +/// document unchanged is elided and never reaches the store's write set, so it | ||
| 41 | +/// collides with nothing. | ||
| 42 | +/// | ||
| 43 | +/// Admissible for [`transaction_with_retry`] as long as `statement` is: the | ||
| 44 | +/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already | ||
| 45 | +/// exists". | ||
| 46 | +pub(crate) async fn bump_question_and_write<T: SurrealValue>( | ||
| 47 | + question: &PoolQuestionId, | ||
| 48 | + statement: &str, | ||
| 49 | + mut bindings: Vec<(String, surrealdb::types::Value)>, | ||
| 50 | + db: &Database, | ||
| 51 | +) -> Result<Option<T>, AppError> { | ||
| 52 | + bindings.push(("q".into(), question.record().into_value())); | ||
| 53 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 54 | + db, | ||
| 55 | + &format!( | ||
| 56 | + "BEGIN TRANSACTION; | ||
| 57 | + LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); | ||
| 58 | + LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); | ||
| 59 | + IF array::len($bumped) = 0 {{ THROW 'no_question' }}; | ||
| 60 | + UPDATE $q SET asked_at = $was_asked; | ||
| 61 | + LET $row = ({statement}); | ||
| 62 | + RETURN $row; | ||
| 63 | + COMMIT TRANSACTION;" | ||
| 64 | + ), | ||
| 65 | + &bindings, | ||
| 66 | + &["no_question"], | ||
| 67 | + ) | ||
| 68 | + .await?; | ||
| 69 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 70 | + // executed" — only the THROW's own slot names the reason. | ||
| 71 | + if errors | ||
| 72 | + .values() | ||
| 73 | + .any(|error| error.to_string().contains("no_question")) | ||
| 74 | + { | ||
| 75 | + return Err(AppError::NotFound); | ||
| 76 | + } | ||
| 77 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 78 | + return Err(error.into()); | ||
| 79 | + } | ||
| 80 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its slot | ||
| 81 | + // follows the statement count rather than a hand-kept number; | ||
| 82 | + // `num_statements` counts BEGIN and COMMIT. | ||
| 83 | + let slot = result.num_statements().saturating_sub(2); | ||
| 84 | + Ok(result.take::<Vec<T>>(slot)?.into_iter().next()) | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> { | ||
| 88 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 89 | + let created: Option<PoolQuestion> = db.create(question.id.record()).content(question).await?; | ||
| 90 | + created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { | ||
| 94 | + Ok(db.select(id.record()).await?) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Every question, newest first — the teacher+ view (approval queue and | ||
| 98 | +/// pool in one list). | ||
| 99 | +pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 100 | + let mut result = db | ||
| 101 | + .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") | ||
| 102 | + .await? | ||
| 103 | + .check()?; | ||
| 104 | + Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// The pool as a non-staff user sees it, newest first: every approved | ||
| 108 | +/// question, plus the caller's own pending ones. | ||
| 109 | +pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 110 | + let mut result = db | ||
| 111 | + .query( | ||
| 112 | + "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ | ||
| 113 | + ORDER BY asked_at DESC, id DESC", | ||
| 114 | + ) | ||
| 115 | + .bind(("approved", STATUS_APPROVED)) | ||
| 116 | + .bind(("usr", user.record())) | ||
| 117 | + .await? | ||
| 118 | + .check()?; | ||
| 119 | + Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// Publish a pending question into the pool, stamping who approved it. | ||
| 123 | +/// The `WHERE status = $pending` guard makes the transition atomic: of two | ||
| 124 | +/// racing approvals exactly one wins, and an approve can never land on a | ||
| 125 | +/// question deleted mid-flight. `None` = the question wasn't pending | ||
| 126 | +/// (already approved, or gone) — the caller sorts out which. | ||
| 127 | +/// | ||
| 128 | +/// Two lifetime badge counters ride that same guard, inside this | ||
| 129 | +/// transaction: the approver's `pool_approved_total` and the *asker's* | ||
| 130 | +/// `pool_published_total`. Both hang off `array::len($done) > 0` — the | ||
| 131 | +/// guard's own verdict — so the pair moves once per real transition and | ||
| 132 | +/// never on a second approve of an already-approved question. | ||
| 133 | +/// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that | ||
| 134 | +/// holds.) The second conjunct is the self-approval rule below. | ||
| 135 | +/// | ||
| 136 | +/// Two rules keep the pair unfarmable, one per side of the transition. | ||
| 137 | +/// | ||
| 138 | +/// The asker is credited at *approval*, not at asking: a bare | ||
| 139 | +/// [`insert`] is self-service and the author can | ||
| 140 | +/// delete their own question and ask again forever, so a counter moved | ||
| 141 | +/// there is farmable. Approval is teacher-gated and one-way, which is why | ||
| 142 | +/// the family is named `pool_published` and not `pool_asked`. That closes | ||
| 143 | +/// the student side. | ||
| 144 | +/// | ||
| 145 | +/// And a *self*-approval — a teacher+ approving a question they asked | ||
| 146 | +/// themselves, which the route deliberately still allows — moves neither | ||
| 147 | +/// counter, hence the `$done[0].asker != $by` half of the condition. It is | ||
| 148 | +/// the same farm from the other end (ask, approve, delete, repeat, with no | ||
| 149 | +/// second person involved), and the two together are why a counter can only | ||
| 150 | +/// move when one person's work was judged by another's. Nothing else about | ||
| 151 | +/// a self-approval changes: same 200, same freeze, same stamp — this skips | ||
| 152 | +/// the credit, not the approval. | ||
| 153 | +/// | ||
| 154 | +/// Re-sent while the store answers "conflict, retry": the guard reads a | ||
| 155 | +/// column a rival approve writes, and both counters sit on user rows every | ||
| 156 | +/// other counter site writes too. Sound to re-send — every statement is an | ||
| 157 | +/// `UPDATE`, none of which can legitimately answer "already exists" — and a | ||
| 158 | +/// lost round aborts having written nothing, increments included. | ||
| 159 | +pub async fn approve( | ||
| 160 | + db: &Database, | ||
| 161 | + id: &PoolQuestionId, | ||
| 162 | + approver: &UserId, | ||
| 163 | +) -> Result<Option<PoolQuestion>, AppError> { | ||
| 164 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 165 | + db, | ||
| 166 | + &format!( | ||
| 167 | + "BEGIN TRANSACTION; | ||
| 168 | + LET $done = (UPDATE $q SET status = $approved, approved_by = $by | ||
| 169 | + WHERE status = $pending RETURN AFTER); | ||
| 170 | + IF array::len($done) > 0 AND $done[0].asker != $by {{ | ||
| 171 | + UPDATE $by SET | ||
| 172 | + {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; | ||
| 173 | + LET $asker = $done[0].asker; | ||
| 174 | + UPDATE $asker SET | ||
| 175 | + {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; | ||
| 176 | + }}; | ||
| 177 | + RETURN $done; | ||
| 178 | + COMMIT TRANSACTION;" | ||
| 179 | + ), | ||
| 180 | + &[ | ||
| 181 | + ("q".into(), id.record().into_value()), | ||
| 182 | + ("approved".into(), STATUS_APPROVED.to_string().into_value()), | ||
| 183 | + ("by".into(), approver.record().into_value()), | ||
| 184 | + ("pending".into(), STATUS_PENDING.to_string().into_value()), | ||
| 185 | + ], | ||
| 186 | + &[], | ||
| 187 | + ) | ||
| 188 | + .await?; | ||
| 189 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 190 | + return Err(error.into()); | ||
| 191 | + } | ||
| 192 | + // The trailing `RETURN` is always the last statement before `COMMIT`, | ||
| 193 | + // so its slot follows the statement count rather than a hand-kept | ||
| 194 | + // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). | ||
| 195 | + let slot = result.num_statements().saturating_sub(2); | ||
| 196 | + Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next()) | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// Point the question at a freshly written image blob. Guarded on | ||
| 200 | +/// `pending` for the same reason approval is: an image landing after | ||
| 201 | +/// approval would put unmoderated bytes in the pool, so an upload that | ||
| 202 | +/// loses the race gets `None` (and the caller takes the orphan blob back | ||
| 203 | +/// off disk). Returns the *before* row — its `image_file` is the replaced | ||
| 204 | +/// blob the caller must remove. | ||
| 205 | +pub async fn set_image( | ||
| 206 | + db: &Database, | ||
| 207 | + id: &PoolQuestionId, | ||
| 208 | + file: &str, | ||
| 209 | + content_type: &FileContentType, | ||
| 210 | + size: i64, | ||
| 211 | +) -> Result<Option<PoolQuestion>, AppError> { | ||
| 212 | + let mut result = db | ||
| 213 | + .query( | ||
| 214 | + "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ | ||
| 215 | + WHERE status = $pending RETURN BEFORE", | ||
| 216 | + ) | ||
| 217 | + .bind(("q", id.record())) | ||
| 218 | + .bind(("file", file.to_string())) | ||
| 219 | + .bind(("ct", content_type.clone())) | ||
| 220 | + .bind(("size", size)) | ||
| 221 | + .bind(("pending", STATUS_PENDING)) | ||
| 222 | + .await? | ||
| 223 | + .check()?; | ||
| 224 | + Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +/// Detach the question's image (pending only, like `set_image`). Returns | ||
| 228 | +/// the *before* row — its `image_file` is the blob the caller must remove. | ||
| 229 | +pub async fn clear_image( | ||
| 230 | + db: &Database, | ||
| 231 | + id: &PoolQuestionId, | ||
| 232 | +) -> Result<Option<PoolQuestion>, AppError> { | ||
| 233 | + let mut result = db | ||
| 234 | + .query( | ||
| 235 | + "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 236 | + WHERE status = $pending RETURN BEFORE", | ||
| 237 | + ) | ||
| 238 | + .bind(("q", id.record())) | ||
| 239 | + .bind(("pending", STATUS_PENDING)) | ||
| 240 | + .await? | ||
| 241 | + .check()?; | ||
| 242 | + Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 243 | +} | ||
| 244 | + | ||
| 245 | +/// Delete the question and its solutions in one transaction, returning | ||
| 246 | +/// the removed rows — the question's *and* the swept solutions' — so the | ||
| 247 | +/// caller can take every image blob off disk (solutions carry photos too, | ||
| 248 | +/// and a row-only sweep would strand theirs forever). | ||
| 249 | +/// | ||
| 250 | +/// Rides the retry because a solution offer now writes this very row | ||
| 251 | +/// ([`bump_question_and_write`]): the two contend by design, and a lost | ||
| 252 | +/// round through a bare `check()` was a 500 for a delete that only had to | ||
| 253 | +/// be re-sent. Admissible — a `DELETE` can never answer "already exists". | ||
| 254 | +pub async fn delete( | ||
| 255 | + db: &Database, | ||
| 256 | + id: &PoolQuestionId, | ||
| 257 | +) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | ||
| 258 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 259 | + db, | ||
| 260 | + "BEGIN TRANSACTION; | ||
| 261 | + DELETE solution WHERE question = $q RETURN BEFORE; | ||
| 262 | + DELETE $q RETURN BEFORE; | ||
| 263 | + COMMIT TRANSACTION;", | ||
| 264 | + &[("q".into(), id.record().into_value())], | ||
| 265 | + &[], | ||
| 266 | + ) | ||
| 267 | + .await?; | ||
| 268 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 269 | + return Err(error.into()); | ||
| 270 | + } | ||
| 271 | + // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. | ||
| 272 | + let solutions = result.take::<Vec<Solution>>(1)?; | ||
| 273 | + Ok(result | ||
| 274 | + .take::<Vec<PoolQuestion>>(2)? | ||
| 275 | + .into_iter() | ||
| 276 | + .next() | ||
| 277 | + .map(|question| (question, solutions))) | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +#[cfg(test)] | ||
| 281 | +mod tests { | ||
| 282 | + use ulid::Ulid; | ||
| 283 | + | ||
| 284 | + use super::*; | ||
| 285 | + use crate::database; | ||
| 286 | + use crate::domain::solution::SolutionBody; | ||
| 287 | + | ||
| 288 | + /// The two counter columns plus a row to carry them: the `user` table is | ||
| 289 | + /// SCHEMAFULL in production, and the counters are `option<int>` there. | ||
| 290 | + async fn a_user(db: &Database) -> UserId { | ||
| 291 | + let user = UserId::from_key(&Ulid::new().to_string()); | ||
| 292 | + db.query(format!( | ||
| 293 | + "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 294 | + DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 295 | + CREATE $usr SET username = $name, password_hash = 'x';" | ||
| 296 | + )) | ||
| 297 | + .bind(("usr", user.record())) | ||
| 298 | + .bind(("name", user.key().to_string())) | ||
| 299 | + .await | ||
| 300 | + .unwrap() | ||
| 301 | + .check() | ||
| 302 | + .unwrap(); | ||
| 303 | + user | ||
| 304 | + } | ||
| 305 | + | ||
| 306 | + /// `(pool_approved_total, pool_published_total)` as stored — absent reads | ||
| 307 | + /// zero, the way `BadgeStats::load` reads it. | ||
| 308 | + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { | ||
| 309 | + let mut result = db | ||
| 310 | + .query(format!( | ||
| 311 | + "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), | ||
| 312 | + ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" | ||
| 313 | + )) | ||
| 314 | + .bind(("usr", user.record())) | ||
| 315 | + .await | ||
| 316 | + .unwrap() | ||
| 317 | + .check() | ||
| 318 | + .unwrap(); | ||
| 319 | + let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | ||
| 320 | + let row = rows.into_iter().next().unwrap_or_default(); | ||
| 321 | + ( | ||
| 322 | + row.first().copied().unwrap_or(0), | ||
| 323 | + row.get(1).copied().unwrap_or(0), | ||
| 324 | + ) | ||
| 325 | + } | ||
| 326 | + | ||
| 327 | + fn question(asker: &UserId) -> PoolQuestion { | ||
| 328 | + use crate::domain::pool_question::{PoolQuestionBody, PoolQuestionTitle}; | ||
| 329 | + PoolQuestion::new( | ||
| 330 | + asker, | ||
| 331 | + PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), | ||
| 332 | + PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), | ||
| 333 | + ) | ||
| 334 | + } | ||
| 335 | + | ||
| 336 | + #[tokio::test] | ||
| 337 | + async fn approval_is_a_one_way_race_safe_transition() { | ||
| 338 | + let db = database::init_mem().await.unwrap(); | ||
| 339 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 340 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 341 | + | ||
| 342 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 343 | + assert_eq!(q.get_status(), STATUS_PENDING); | ||
| 344 | + assert!(q.get_approved_by().is_none()); | ||
| 345 | + | ||
| 346 | + let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); | ||
| 347 | + assert!(approved.is_approved()); | ||
| 348 | + assert_eq!(approved.get_approved_by(), Some(&teacher)); | ||
| 349 | + | ||
| 350 | + // A second approval finds nothing pending. | ||
| 351 | + assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); | ||
| 352 | + // And a missing question approves to None, not an error. | ||
| 353 | + assert!( | ||
| 354 | + approve(&db, &PoolQuestionId::generate(), &teacher) | ||
| 355 | + .await | ||
| 356 | + .unwrap() | ||
| 357 | + .is_none() | ||
| 358 | + ); | ||
| 359 | + } | ||
| 360 | + /// The publish counters ride the guard, so they move exactly once per real | ||
| 361 | + /// transition: the approver's on the approve side, the asker's on the | ||
| 362 | + /// published side, and neither on a second approve of the same question. | ||
| 363 | + #[tokio::test] | ||
| 364 | + async fn approval_moves_both_counters_once_and_only_once() { | ||
| 365 | + let db = database::init_mem().await.unwrap(); | ||
| 366 | + let asker = a_user(&db).await; | ||
| 367 | + let teacher = a_user(&db).await; | ||
| 368 | + | ||
| 369 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 370 | + assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); | ||
| 371 | + | ||
| 372 | + approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); | ||
| 373 | + assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); | ||
| 374 | + assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); | ||
| 375 | + | ||
| 376 | + // The guard finds nothing pending, so neither counter may move — this | ||
| 377 | + // is what stops an approve loop from farming either one. | ||
| 378 | + assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); | ||
| 379 | + assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); | ||
| 380 | + assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); | ||
| 381 | + | ||
| 382 | + // And an approve that lands on nothing at all writes nothing. | ||
| 383 | + assert!( | ||
| 384 | + approve(&db, &PoolQuestionId::generate(), &teacher) | ||
| 385 | + .await | ||
| 386 | + .unwrap() | ||
| 387 | + .is_none() | ||
| 388 | + ); | ||
| 389 | + assert_eq!(counters(&teacher, &db).await, (1, 0)); | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + /// A teacher may ask a question and the route does not bar them from | ||
| 393 | + /// approving it — that still works, unchanged. What it does not do is pay | ||
| 394 | + /// for itself: ask, approve, delete, repeat is the staff-side farm, and | ||
| 395 | + /// neither counter moves when one person is both ends of the transition. | ||
| 396 | + #[tokio::test] | ||
| 397 | + async fn self_approval_still_approves_but_moves_neither_counter() { | ||
| 398 | + let db = database::init_mem().await.unwrap(); | ||
| 399 | + let teacher = a_user(&db).await; | ||
| 400 | + | ||
| 401 | + let q = insert(&db, question(&teacher)).await.unwrap(); | ||
| 402 | + let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); | ||
| 403 | + // The approval itself is untouched: published, stamped, frozen. | ||
| 404 | + assert!(approved.is_approved()); | ||
| 405 | + assert_eq!(approved.get_approved_by(), Some(&teacher)); | ||
| 406 | + assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); | ||
| 407 | + | ||
| 408 | + // And the skip is about the *pair*, not about the teacher: approving | ||
| 409 | + // somebody else's question right after still pays. | ||
| 410 | + let asker = a_user(&db).await; | ||
| 411 | + let other = insert(&db, question(&asker)).await.unwrap(); | ||
| 412 | + approve(&db, other.get_id(), &teacher) | ||
| 413 | + .await | ||
| 414 | + .unwrap() | ||
| 415 | + .unwrap(); | ||
| 416 | + assert_eq!(counters(&teacher, &db).await, (1, 0)); | ||
| 417 | + assert_eq!(counters(&asker, &db).await, (0, 1)); | ||
| 418 | + } | ||
| 419 | + | ||
| 420 | + #[tokio::test] | ||
| 421 | + async fn visibility_hides_others_pending_questions() { | ||
| 422 | + let db = database::init_mem().await.unwrap(); | ||
| 423 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 424 | + let other = UserId::from_key(&Ulid::new().to_string()); | ||
| 425 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 426 | + | ||
| 427 | + let pending = insert(&db, question(&asker)).await.unwrap(); | ||
| 428 | + let published = insert(&db, question(&other)).await.unwrap(); | ||
| 429 | + approve(&db, published.get_id(), &teacher) | ||
| 430 | + .await | ||
| 431 | + .unwrap() | ||
| 432 | + .unwrap(); | ||
| 433 | + | ||
| 434 | + // The asker sees their own pending question plus the pool; a stranger | ||
| 435 | + // sees only the pool; the teacher view (list_all) sees everything. | ||
| 436 | + assert_eq!(list_visible_to(&db, &asker).await.unwrap().len(), 2); | ||
| 437 | + let stranger_view = list_visible_to(&db, &other).await.unwrap(); | ||
| 438 | + assert_eq!(stranger_view.len(), 1); | ||
| 439 | + assert_eq!(stranger_view[0].get_id(), published.get_id()); | ||
| 440 | + assert_eq!(list_all(&db).await.unwrap().len(), 2); | ||
| 441 | + assert!(read(&db, pending.get_id()).await.unwrap().is_some()); | ||
| 442 | + } | ||
| 443 | + | ||
| 444 | + #[tokio::test] | ||
| 445 | + async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { | ||
| 446 | + let db = database::init_mem().await.unwrap(); | ||
| 447 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 448 | + let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 449 | + let png = FileContentType::try_new("image/png").unwrap(); | ||
| 450 | + | ||
| 451 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 452 | + let before = set_image(&db, q.get_id(), "blob_a", &png, 3) | ||
| 453 | + .await | ||
| 454 | + .unwrap() | ||
| 455 | + .unwrap(); | ||
| 456 | + assert!(before.get_image_file().is_none()); | ||
| 457 | + | ||
| 458 | + // A replace reports the old blob for cleanup. | ||
| 459 | + let before = set_image(&db, q.get_id(), "blob_b", &png, 5) | ||
| 460 | + .await | ||
| 461 | + .unwrap() | ||
| 462 | + .unwrap(); | ||
| 463 | + assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 464 | + let stored = read(&db, q.get_id()).await.unwrap().unwrap(); | ||
| 465 | + assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 466 | + assert_eq!(stored.get_image_size(), Some(5)); | ||
| 467 | + | ||
| 468 | + // Clearing reports the detached blob and empties the fields. | ||
| 469 | + let before = clear_image(&db, q.get_id()).await.unwrap().unwrap(); | ||
| 470 | + assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 471 | + assert!( | ||
| 472 | + read(&db, q.get_id()) | ||
| 473 | + .await | ||
| 474 | + .unwrap() | ||
| 475 | + .unwrap() | ||
| 476 | + .get_image_file() | ||
| 477 | + .is_none() | ||
| 478 | + ); | ||
| 479 | + | ||
| 480 | + // Once approved, the image is frozen with the rest of the content. | ||
| 481 | + approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); | ||
| 482 | + assert!( | ||
| 483 | + set_image(&db, q.get_id(), "blob_c", &png, 7) | ||
| 484 | + .await | ||
| 485 | + .unwrap() | ||
| 486 | + .is_none() | ||
| 487 | + ); | ||
| 488 | + assert!(clear_image(&db, q.get_id()).await.unwrap().is_none()); | ||
| 489 | + } | ||
| 490 | + | ||
| 491 | + #[tokio::test] | ||
| 492 | + async fn delete_cascades_solutions_and_returns_the_row() { | ||
| 493 | + let db = database::init_mem().await.unwrap(); | ||
| 494 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 495 | + let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 496 | + | ||
| 497 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 498 | + let offered = crate::db::solution::insert( | ||
| 499 | + &db, | ||
| 500 | + Solution::new( | ||
| 501 | + q.get_id(), | ||
| 502 | + &helper, | ||
| 503 | + SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), | ||
| 504 | + ), | ||
| 505 | + ) | ||
| 506 | + .await | ||
| 507 | + .unwrap(); | ||
| 508 | + | ||
| 509 | + // The swept solutions ride back with the question so the caller can | ||
| 510 | + // take their image blobs off disk. | ||
| 511 | + let (removed, swept) = delete(&db, q.get_id()).await.unwrap().unwrap(); | ||
| 512 | + assert_eq!(removed.get_id(), q.get_id()); | ||
| 513 | + assert_eq!(swept.len(), 1); | ||
| 514 | + assert_eq!(swept[0].get_id(), offered.get_id()); | ||
| 515 | + assert!(read(&db, q.get_id()).await.unwrap().is_none()); | ||
| 516 | + assert!( | ||
| 517 | + crate::db::solution::list_for(&db, q.get_id(), None, 0) | ||
| 518 | + .await | ||
| 519 | + .unwrap() | ||
| 520 | + .0 | ||
| 521 | + .is_empty() | ||
| 522 | + ); | ||
| 523 | + | ||
| 524 | + // Deleting the already-deleted is None, not an error. | ||
| 525 | + assert!(delete(&db, q.get_id()).await.unwrap().is_none()); | ||
| 526 | + } | ||
| 527 | + | ||
| 528 | + /// The [`crate::db::exam_answer`] defect, one domain | ||
| 529 | + /// over: a solution offered inside its question's delete window must not | ||
| 530 | + /// outlive it. Guarding the offer by *reading* the question does not do it | ||
| 531 | + /// — the read sees a row [`delete`] has removed but not committed, while | ||
| 532 | + /// its `DELETE solution WHERE question = $q` ran on a snapshot predating | ||
| 533 | + /// the offer, so both commit and the solution is left pointing at a | ||
| 534 | + /// question that is gone. Nothing can reach it after that: every route to | ||
| 535 | + /// a solution goes through its question, so neither a reader nor a second | ||
| 536 | + /// delete can ever clear it, and its photo stays on disk for good. | ||
| 537 | + /// [`bump_question_and_write`] moves the question's own `asked_at` | ||
| 538 | + /// instead, so the two transactions touch one key and the store refuses | ||
| 539 | + /// one of them. | ||
| 540 | + /// | ||
| 541 | + /// The window is opened by the database, not by a lucky interleaving: a | ||
| 542 | + /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own | ||
| 543 | + /// transaction the instant the row goes, so the `SLEEP` lands exactly | ||
| 544 | + /// between the delete and its cascade every time. | ||
| 545 | + /// | ||
| 546 | + /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 547 | + /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 548 | + /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 549 | + /// broken code. | ||
| 550 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 551 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 552 | + async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { | ||
| 553 | + let (db, _serialized) = database::init_test_server("solution_race").await; | ||
| 554 | + // Hold the delete open for a full second after the row is gone, while | ||
| 555 | + // its cascade still has to run. | ||
| 556 | + db.query( | ||
| 557 | + "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ | ||
| 558 | + THEN { SLEEP 1s; };", | ||
| 559 | + ) | ||
| 560 | + .await | ||
| 561 | + .unwrap() | ||
| 562 | + .check() | ||
| 563 | + .unwrap(); | ||
| 564 | + | ||
| 565 | + let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); | ||
| 566 | + for round in 0..4 { | ||
| 567 | + let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 568 | + let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 569 | + let q = insert(&db, question(&asker)).await.unwrap(); | ||
| 570 | + let id = q.get_id().clone(); | ||
| 571 | + | ||
| 572 | + let drop_it = { | ||
| 573 | + let (db, id) = (db.clone(), id.clone()); | ||
| 574 | + tokio::spawn(async move { delete(&db, &id).await }) | ||
| 575 | + }; | ||
| 576 | + // The offer starts inside the held window — the question row is | ||
| 577 | + // gone but uncommitted, which is exactly what a read believes. | ||
| 578 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 579 | + let child = { | ||
| 580 | + let (db, id) = (db.clone(), id.clone()); | ||
| 581 | + tokio::spawn(async move { | ||
| 582 | + crate::db::solution::insert( | ||
| 583 | + &db, | ||
| 584 | + Solution::new( | ||
| 585 | + &id, | ||
| 586 | + &helper, | ||
| 587 | + SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), | ||
| 588 | + ), | ||
| 589 | + ) | ||
| 590 | + .await | ||
| 591 | + }) | ||
| 592 | + }; | ||
| 593 | + let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 594 | + // A 404 for the offer is a correct answer; the only defect is | ||
| 595 | + // stored state. The delete must not 500 either — it contends with | ||
| 596 | + // the offer by design and a lost round is re-sent, not reported. | ||
| 597 | + assert!( | ||
| 598 | + !matches!(child, Err(AppError::Db(_))), | ||
| 599 | + "round {round}: a raced offer must be answered, not 500: {child:?}" | ||
| 600 | + ); | ||
| 601 | + if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 602 | + delete_500 += 1; | ||
| 603 | + } | ||
| 604 | + | ||
| 605 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 606 | + if read(&db, &id).await.unwrap().is_none() { | ||
| 607 | + swept += 1; | ||
| 608 | + solutions += crate::db::solution::list_for(&db, &id, None, 0) | ||
| 609 | + .await | ||
| 610 | + .unwrap() | ||
| 611 | + .0 | ||
| 612 | + .len(); | ||
| 613 | + } | ||
| 614 | + } | ||
| 615 | + eprintln!("pool_question::delete raced by an offer: {swept}/4 rounds deleted the question"); | ||
| 616 | + assert!( | ||
| 617 | + swept > 0, | ||
| 618 | + "no round ever deleted the question, so the window was never reached" | ||
| 619 | + ); | ||
| 620 | + assert_eq!(solutions, 0, "a solution outlived its question"); | ||
| 621 | + assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); | ||
| 622 | + } | ||
| 623 | +} | ||
src/db/solution.rsadded+386 -0
| @@ -0,0 +1,386 @@ | |||
| 1 | +//! The `solution` table: offers (through the pool question's | ||
| 2 | +//! existence-move), the question-scoped reads and page, the grouped counts, | ||
| 3 | +//! and the unconditional body/image writes of an unmoderated row. The pure | ||
| 4 | +//! entity and newtypes live in [`crate::domain::solution`]; the web layer | ||
| 5 | +//! reaches these through [`crate::service::solution`]. | ||
| 6 | + | ||
| 7 | +use std::collections::HashMap; | ||
| 8 | + | ||
| 9 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 10 | + | ||
| 11 | +use crate::database::Database; | ||
| 12 | +use crate::db::page::PagedList; | ||
| 13 | +use crate::db::pool_question::bump_question_and_write; | ||
| 14 | +use crate::domain::note_file::FileContentType; | ||
| 15 | +use crate::domain::pool_question::PoolQuestionId; | ||
| 16 | +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | + | ||
| 19 | +/// One `GROUP BY question` row of [`counts_for`]. | ||
| 20 | +#[derive(SurrealValue)] | ||
| 21 | +struct SolutionCount { | ||
| 22 | + question: PoolQuestionId, | ||
| 23 | + n: i64, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/// Offer the solution. `NotFound` = the question is gone, and nothing was | ||
| 27 | +/// written: the create rides [`bump_question_and_write`], so the question's | ||
| 28 | +/// existence is a *write* to its row rather than a read the handler made a | ||
| 29 | +/// moment earlier — a bare create landing inside | ||
| 30 | +/// [`crate::db::pool_question::delete`]'s | ||
| 31 | +/// window was swept by nothing and left a solution no route could ever | ||
| 32 | +/// reach or remove (every path to one goes through its question), photo | ||
| 33 | +/// blob included. | ||
| 34 | +/// | ||
| 35 | +/// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call | ||
| 36 | +/// on a table with no `UNIQUE` index, so a re-send cannot answer "already | ||
| 37 | +/// exists" — the one thing the retry could not survive. | ||
| 38 | +pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> { | ||
| 39 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 40 | + let (question, id) = (solution.question.clone(), solution.id.record()); | ||
| 41 | + bump_question_and_write( | ||
| 42 | + &question, | ||
| 43 | + "CREATE $id CONTENT $solution", | ||
| 44 | + vec![ | ||
| 45 | + ("id".into(), id.into_value()), | ||
| 46 | + ("solution".into(), solution.into_value()), | ||
| 47 | + ], | ||
| 48 | + db, | ||
| 49 | + ) | ||
| 50 | + .await? | ||
| 51 | + .ok_or_else(|| AppError::Internal("failed to create solution".into())) | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// Read a solution only if it belongs to `question` — keeps the nested | ||
| 55 | +/// route honest (a solution id under someone else's question 404s). | ||
| 56 | +pub async fn read_for( | ||
| 57 | + db: &Database, | ||
| 58 | + id: &SolutionId, | ||
| 59 | + question: &PoolQuestionId, | ||
| 60 | +) -> Result<Option<Solution>, AppError> { | ||
| 61 | + let solution: Option<Solution> = db.select(id.record()).await?; | ||
| 62 | + Ok(solution.filter(|solution| &solution.question == question)) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +/// The question's solutions, oldest first — a discussion reads downward. | ||
| 66 | +/// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond | ||
| 67 | +/// offers *stable* across re-queries, not insertion-ordered (ULID low bits | ||
| 68 | +/// are random within a millisecond, so same-ms order is arbitrary). | ||
| 69 | +pub async fn list_for( | ||
| 70 | + db: &Database, | ||
| 71 | + question: &PoolQuestionId, | ||
| 72 | + limit: Option<i64>, | ||
| 73 | + offset: i64, | ||
| 74 | +) -> Result<(Vec<Solution>, i64), AppError> { | ||
| 75 | + PagedList::new( | ||
| 76 | + "solution WHERE question = $q", | ||
| 77 | + "ORDER BY offered_at ASC, id ASC", | ||
| 78 | + ) | ||
| 79 | + .bind("q", question.record()) | ||
| 80 | + .run(limit, offset, db) | ||
| 81 | + .await | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// Per-question solution tallies for a page of questions, in one grouped | ||
| 85 | +/// query — a per-row `count()` would cost a query per question. Keys are | ||
| 86 | +/// question record keys; a question with no solutions has no entry, so | ||
| 87 | +/// the caller reads misses as zero. | ||
| 88 | +pub async fn counts_for( | ||
| 89 | + db: &Database, | ||
| 90 | + questions: &[PoolQuestionId], | ||
| 91 | +) -> Result<HashMap<String, i64>, AppError> { | ||
| 92 | + if questions.is_empty() { | ||
| 93 | + return Ok(HashMap::new()); | ||
| 94 | + } | ||
| 95 | + let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect(); | ||
| 96 | + let mut result = db | ||
| 97 | + .query( | ||
| 98 | + "SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question", | ||
| 99 | + ) | ||
| 100 | + .bind(("qs", ids)) | ||
| 101 | + .await? | ||
| 102 | + .check()?; | ||
| 103 | + Ok(result | ||
| 104 | + .take::<Vec<SolutionCount>>(0)? | ||
| 105 | + .into_iter() | ||
| 106 | + .map(|row| (row.question.key().to_string(), row.n)) | ||
| 107 | + .collect()) | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +/// Replace the body. Unconditional (solutions have no moderation state to | ||
| 111 | +/// guard, unlike a question's `pending` gate) — `None` only means the row | ||
| 112 | +/// was deleted mid-flight. Authorship is the web layer's check. | ||
| 113 | +pub async fn set_body( | ||
| 114 | + db: &Database, | ||
| 115 | + id: &SolutionId, | ||
| 116 | + body: &SolutionBody, | ||
| 117 | +) -> Result<Option<Solution>, AppError> { | ||
| 118 | + let mut result = db | ||
| 119 | + .query("UPDATE $s SET body = $b RETURN AFTER") | ||
| 120 | + .bind(("s", id.record())) | ||
| 121 | + .bind(("b", body.clone())) | ||
| 122 | + .await? | ||
| 123 | + .check()?; | ||
| 124 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// Point the solution at a freshly written image blob. Unconditional for | ||
| 128 | +/// the same reason as [`set_body`]. Returns the *before* row — its | ||
| 129 | +/// `image_file` is the replaced blob the caller must remove; `None` means | ||
| 130 | +/// the row was deleted mid-flight (the fresh blob is the caller's orphan | ||
| 131 | +/// to take back off disk). | ||
| 132 | +pub async fn set_image( | ||
| 133 | + db: &Database, | ||
| 134 | + id: &SolutionId, | ||
| 135 | + file: &str, | ||
| 136 | + content_type: &FileContentType, | ||
| 137 | + size: i64, | ||
| 138 | +) -> Result<Option<Solution>, AppError> { | ||
| 139 | + let mut result = db | ||
| 140 | + .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") | ||
| 141 | + .bind(("s", id.record())) | ||
| 142 | + .bind(("file", file.to_string())) | ||
| 143 | + .bind(("ct", content_type.clone())) | ||
| 144 | + .bind(("size", size)) | ||
| 145 | + .await? | ||
| 146 | + .check()?; | ||
| 147 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// Detach the solution's image. Returns the *before* row — its | ||
| 151 | +/// `image_file` is the blob the caller must remove. | ||
| 152 | +pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> { | ||
| 153 | + let mut result = db | ||
| 154 | + .query( | ||
| 155 | + "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 156 | + RETURN BEFORE", | ||
| 157 | + ) | ||
| 158 | + .bind(("s", id.record())) | ||
| 159 | + .await? | ||
| 160 | + .check()?; | ||
| 161 | + Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +pub async fn delete(db: &Database, solution: Solution) -> Result<Solution, AppError> { | ||
| 165 | + let deleted: Option<Solution> = db.delete(solution.id.record()).await?; | ||
| 166 | + deleted.ok_or(AppError::NotFound) | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +#[cfg(test)] | ||
| 170 | +mod tests { | ||
| 171 | + use ulid::Ulid; | ||
| 172 | + | ||
| 173 | + use super::*; | ||
| 174 | + use crate::database; | ||
| 175 | + use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; | ||
| 176 | + use crate::domain::timestamp::Timestamp; | ||
| 177 | + use crate::domain::user::UserId; | ||
| 178 | + | ||
| 179 | + /// A real question row: offering a solution moves its question's | ||
| 180 | + /// `asked_at` (that is what keeps a solution from outliving its question), | ||
| 181 | + /// so a minted id nothing wrote is a 404. | ||
| 182 | + async fn question_row(db: &Database) -> PoolQuestionId { | ||
| 183 | + crate::db::pool_question::insert( | ||
| 184 | + db, | ||
| 185 | + PoolQuestion::new( | ||
| 186 | + &UserId::from_key(&Ulid::new().to_string()), | ||
| 187 | + PoolQuestionTitle::try_new("soru").unwrap(), | ||
| 188 | + PoolQuestionBody::try_new("neden").unwrap(), | ||
| 189 | + ), | ||
| 190 | + ) | ||
| 191 | + .await | ||
| 192 | + .unwrap() | ||
| 193 | + .get_id() | ||
| 194 | + .clone() | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + #[tokio::test] | ||
| 198 | + async fn rows_scope_to_their_question_and_list_oldest_first() { | ||
| 199 | + let db = database::init_mem().await.unwrap(); | ||
| 200 | + let question_a = question_row(&db).await; | ||
| 201 | + let question_b = question_row(&db).await; | ||
| 202 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 203 | + | ||
| 204 | + // Distinct offer times so the assertion pins the real contract — | ||
| 205 | + // older `offered_at` sorts first — not the same-millisecond `id` | ||
| 206 | + // tiebreak, whose random ULID low bits would make the order a coin | ||
| 207 | + // flip (two `now()` reads can land in one millisecond). | ||
| 208 | + let mut first = Solution::new( | ||
| 209 | + &question_a, | ||
| 210 | + &author, | ||
| 211 | + SolutionBody::try_new("Önce türevi al.").unwrap(), | ||
| 212 | + ); | ||
| 213 | + first.offered_at = Timestamp::from_millis(1); | ||
| 214 | + let first = insert(&db, first).await.unwrap(); | ||
| 215 | + let mut second = Solution::new( | ||
| 216 | + &question_a, | ||
| 217 | + &author, | ||
| 218 | + SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), | ||
| 219 | + ); | ||
| 220 | + second.offered_at = Timestamp::from_millis(2); | ||
| 221 | + let second = insert(&db, second).await.unwrap(); | ||
| 222 | + | ||
| 223 | + let (listed, _) = list_for(&db, &question_a, None, 0).await.unwrap(); | ||
| 224 | + assert_eq!(listed.len(), 2); | ||
| 225 | + assert_eq!(listed[0].get_id(), first.get_id()); | ||
| 226 | + assert_eq!(listed[1].get_id(), second.get_id()); | ||
| 227 | + assert!( | ||
| 228 | + list_for(&db, &question_b, None, 0) | ||
| 229 | + .await | ||
| 230 | + .unwrap() | ||
| 231 | + .0 | ||
| 232 | + .is_empty() | ||
| 233 | + ); | ||
| 234 | + | ||
| 235 | + // Readable under its own question, invisible under another. | ||
| 236 | + assert!( | ||
| 237 | + read_for(&db, first.get_id(), &question_a) | ||
| 238 | + .await | ||
| 239 | + .unwrap() | ||
| 240 | + .is_some() | ||
| 241 | + ); | ||
| 242 | + assert!( | ||
| 243 | + read_for(&db, first.get_id(), &question_b) | ||
| 244 | + .await | ||
| 245 | + .unwrap() | ||
| 246 | + .is_none() | ||
| 247 | + ); | ||
| 248 | + | ||
| 249 | + delete(&db, first).await.unwrap(); | ||
| 250 | + assert_eq!( | ||
| 251 | + list_for(&db, &question_a, None, 0).await.unwrap().0.len(), | ||
| 252 | + 1 | ||
| 253 | + ); | ||
| 254 | + } | ||
| 255 | + | ||
| 256 | + #[tokio::test] | ||
| 257 | + async fn image_set_replace_clear_report_the_replaced_blob() { | ||
| 258 | + let db = database::init_mem().await.unwrap(); | ||
| 259 | + let question = question_row(&db).await; | ||
| 260 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 261 | + let png = FileContentType::try_new("image/png").unwrap(); | ||
| 262 | + | ||
| 263 | + let solution = insert( | ||
| 264 | + &db, | ||
| 265 | + Solution::new( | ||
| 266 | + &question, | ||
| 267 | + &author, | ||
| 268 | + SolutionBody::try_new("Grafiği çiz.").unwrap(), | ||
| 269 | + ), | ||
| 270 | + ) | ||
| 271 | + .await | ||
| 272 | + .unwrap(); | ||
| 273 | + | ||
| 274 | + let before = set_image(&db, solution.get_id(), "blob_a", &png, 3) | ||
| 275 | + .await | ||
| 276 | + .unwrap() | ||
| 277 | + .unwrap(); | ||
| 278 | + assert!(before.get_image_file().is_none()); | ||
| 279 | + | ||
| 280 | + // A replace reports the old blob for cleanup. | ||
| 281 | + let before = set_image(&db, solution.get_id(), "blob_b", &png, 5) | ||
| 282 | + .await | ||
| 283 | + .unwrap() | ||
| 284 | + .unwrap(); | ||
| 285 | + assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 286 | + let stored = read_for(&db, solution.get_id(), &question) | ||
| 287 | + .await | ||
| 288 | + .unwrap() | ||
| 289 | + .unwrap(); | ||
| 290 | + assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 291 | + assert_eq!(stored.get_image_size(), Some(5)); | ||
| 292 | + | ||
| 293 | + // Clearing reports the detached blob and empties the fields. | ||
| 294 | + let before = clear_image(&db, solution.get_id()).await.unwrap().unwrap(); | ||
| 295 | + assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 296 | + assert!( | ||
| 297 | + read_for(&db, solution.get_id(), &question) | ||
| 298 | + .await | ||
| 299 | + .unwrap() | ||
| 300 | + .unwrap() | ||
| 301 | + .get_image_file() | ||
| 302 | + .is_none() | ||
| 303 | + ); | ||
| 304 | + | ||
| 305 | + // A row deleted mid-flight surfaces as None, not an error. | ||
| 306 | + let deleted = delete(&db, solution.clone()).await.unwrap(); | ||
| 307 | + assert_eq!(deleted.get_id(), solution.get_id()); | ||
| 308 | + assert!( | ||
| 309 | + set_image(&db, solution.get_id(), "blob_c", &png, 7) | ||
| 310 | + .await | ||
| 311 | + .unwrap() | ||
| 312 | + .is_none() | ||
| 313 | + ); | ||
| 314 | + assert!(clear_image(&db, solution.get_id()).await.unwrap().is_none()); | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + #[tokio::test] | ||
| 318 | + async fn set_body_edits_in_place() { | ||
| 319 | + let db = database::init_mem().await.unwrap(); | ||
| 320 | + let question = question_row(&db).await; | ||
| 321 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 322 | + | ||
| 323 | + let solution = insert( | ||
| 324 | + &db, | ||
| 325 | + Solution::new( | ||
| 326 | + &question, | ||
| 327 | + &author, | ||
| 328 | + SolutionBody::try_new("İlk deneme.").unwrap(), | ||
| 329 | + ), | ||
| 330 | + ) | ||
| 331 | + .await | ||
| 332 | + .unwrap(); | ||
| 333 | + | ||
| 334 | + let edited = set_body( | ||
| 335 | + &db, | ||
| 336 | + solution.get_id(), | ||
| 337 | + &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), | ||
| 338 | + ) | ||
| 339 | + .await | ||
| 340 | + .unwrap() | ||
| 341 | + .unwrap(); | ||
| 342 | + assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); | ||
| 343 | + assert_eq!(edited.get_id(), solution.get_id()); | ||
| 344 | + | ||
| 345 | + // Editing a missing solution is None, not an error. | ||
| 346 | + assert!( | ||
| 347 | + set_body( | ||
| 348 | + &db, | ||
| 349 | + &SolutionId::from_key(&Ulid::new().to_string()), | ||
| 350 | + &SolutionBody::try_new("boş").unwrap(), | ||
| 351 | + ) | ||
| 352 | + .await | ||
| 353 | + .unwrap() | ||
| 354 | + .is_none() | ||
| 355 | + ); | ||
| 356 | + } | ||
| 357 | + | ||
| 358 | + #[tokio::test] | ||
| 359 | + async fn counts_for_groups_per_question() { | ||
| 360 | + let db = database::init_mem().await.unwrap(); | ||
| 361 | + let two = question_row(&db).await; | ||
| 362 | + let one = question_row(&db).await; | ||
| 363 | + let none = question_row(&db).await; | ||
| 364 | + let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 365 | + | ||
| 366 | + for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { | ||
| 367 | + for body in bodies { | ||
| 368 | + insert( | ||
| 369 | + &db, | ||
| 370 | + Solution::new(question, &author, SolutionBody::try_new(body).unwrap()), | ||
| 371 | + ) | ||
| 372 | + .await | ||
| 373 | + .unwrap(); | ||
| 374 | + } | ||
| 375 | + } | ||
| 376 | + | ||
| 377 | + let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()]) | ||
| 378 | + .await | ||
| 379 | + .unwrap(); | ||
| 380 | + assert_eq!(counts.get(two.key()), Some(&2)); | ||
| 381 | + assert_eq!(counts.get(one.key()), Some(&1)); | ||
| 382 | + // No solutions = no entry; the caller reads the miss as zero. | ||
| 383 | + assert_eq!(counts.get(none.key()), None); | ||
| 384 | + assert!(counts_for(&db, &[]).await.unwrap().is_empty()); | ||
| 385 | + } | ||
| 386 | +} | ||
src/domain/bank_question.rsmodified+17 -819
| @@ -6,26 +6,22 @@ | |||
| 6 | //! `ExamQuestion` with its own id, images, and answers; the two never share a | 6 | //! `ExamQuestion` with its own id, images, and answers; the two never share a |
| 7 | //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants | 7 | //! row. The kind-dependent columns satisfy the [`QuestionSpec`] invariants |
| 8 | //! because every write goes through one. | 8 | //! because every write goes through one. |
| 9 | - | 9 | +//! |
| 10 | -use std::collections::HashMap; | 10 | +//! Pure types only: the queries live in [`crate::db::bank_question`], the |
| 11 | +//! PATCH re-derive in [`crate::service::bank_question`]. | ||
| 11 | 12 | ||
| 12 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 13 | 14 | ||
| 14 | -use crate::constant::{ | 15 | +use crate::constant::{BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL}; |
| 15 | - BANK_QUESTION_TABLE, BANK_VISIBILITY_PRIVATE, BANK_VISIBILITY_SCHOOL, USAGE_COUNTS_SQL, | ||
| 16 | -}; | ||
| 17 | -use crate::database::{Database, transaction_with_retry, write_with_retry}; | ||
| 18 | -use crate::domain::bank_question_image::BankQuestionImage; | ||
| 19 | use crate::domain::exam::ExamId; | 16 | use crate::domain::exam::ExamId; |
| 20 | use crate::domain::exam_question::{ | 17 | use crate::domain::exam_question::{ |
| 21 | Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 18 | Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 22 | }; | 19 | }; |
| 23 | use crate::domain::monotonic_id::next_ulid; | 20 | use crate::domain::monotonic_id::next_ulid; |
| 24 | use crate::domain::subject::SubjectId; | 21 | use crate::domain::subject::SubjectId; |
| 25 | -use crate::domain::text_fold::{search_fold, search_fold_sql}; | ||
| 26 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| 27 | use crate::domain::user::UserId; | 23 | use crate::domain::user::UserId; |
| 28 | -use crate::error::{AppError, ValidationError}; | 24 | +use crate::error::ValidationError; |
| 29 | 25 | ||
| 30 | /// Who may see a template. `private` — the owner (and admins) alone; `school` — | 26 | /// Who may see a template. `private` — the owner (and admins) alone; `school` — |
| 31 | /// every teacher. | 27 | /// every teacher. |
| @@ -68,22 +64,6 @@ impl BankVisibility { | |||
| 68 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 64 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 69 | pub struct BankQuestionId(RecordId); | 65 | pub struct BankQuestionId(RecordId); |
| 70 | 66 | ||
| 71 | -/// One `GROUP BY from_bank` row of [`BankQuestion::usage_counts`]. | ||
| 72 | -#[derive(SurrealValue)] | ||
| 73 | -struct UsageCount { | ||
| 74 | - from_bank: BankQuestionId, | ||
| 75 | - n: i64, | ||
| 76 | -} | ||
| 77 | - | ||
| 78 | -/// What one [`BankQuestion::delete`] transaction removed — the template (an | ||
| 79 | -/// empty list once someone else deleted it first) and the image rows swept | ||
| 80 | -/// with it. | ||
| 81 | -#[derive(SurrealValue)] | ||
| 82 | -struct DeleteOutcome { | ||
| 83 | - question: Vec<BankQuestion>, | ||
| 84 | - images: Vec<BankQuestionImage>, | ||
| 85 | -} | ||
| 86 | - | ||
| 87 | impl BankQuestionId { | 67 | impl BankQuestionId { |
| 88 | /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and | 68 | /// A write-ordered id. `list` sorts `id DESC` to mean "newest first", and |
| 89 | /// a random ULID is only millisecond-accurate — templates saved inside one | 69 | /// a random ULID is only millisecond-accurate — templates saved inside one |
| @@ -122,25 +102,25 @@ impl BankQuestionId { | |||
| 122 | /// template would have raised it. | 102 | /// template would have raised it. |
| 123 | #[derive(Debug, Clone, SurrealValue)] | 103 | #[derive(Debug, Clone, SurrealValue)] |
| 124 | pub struct BankQuestion { | 104 | pub struct BankQuestion { |
| 125 | - id: BankQuestionId, | 105 | + pub(crate) id: BankQuestionId, |
| 126 | - owner: UserId, | 106 | + pub(crate) owner: UserId, |
| 127 | /// The origin subject, or `None` once that subject was deleted. | 107 | /// The origin subject, or `None` once that subject was deleted. |
| 128 | /// `#[surreal(default)]` for the same reason `visibility` has one: rows | 108 | /// `#[surreal(default)]` for the same reason `visibility` has one: rows |
| 129 | /// written before the field went optional still decode. | 109 | /// written before the field went optional still decode. |
| 130 | #[surreal(default)] | 110 | #[surreal(default)] |
| 131 | - subject: Option<SubjectId>, | 111 | + pub(crate) subject: Option<SubjectId>, |
| 132 | - text: QuestionText, | 112 | + pub(crate) text: QuestionText, |
| 133 | - kind: QuestionKind, | 113 | + pub(crate) kind: QuestionKind, |
| 134 | - points: QuestionPoints, | 114 | + pub(crate) points: QuestionPoints, |
| 135 | - choices: Option<Vec<Choice>>, | 115 | + pub(crate) choices: Option<Vec<Choice>>, |
| 136 | - correct: Option<ChoiceId>, | 116 | + pub(crate) correct: Option<ChoiceId>, |
| 137 | /// The exam question this template was saved from, if any. | 117 | /// The exam question this template was saved from, if any. |
| 138 | - source_exam: Option<ExamId>, | 118 | + pub(crate) source_exam: Option<ExamId>, |
| 139 | /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile | 119 | /// Who may read it. `#[surreal(default)]` (not serde — that doesn't compile |
| 140 | /// here): rows written before the field existed decode as `private`. | 120 | /// here): rows written before the field existed decode as `private`. |
| 141 | #[surreal(default)] | 121 | #[surreal(default)] |
| 142 | - visibility: BankVisibility, | 122 | + pub(crate) visibility: BankVisibility, |
| 143 | - created_at: Timestamp, | 123 | + pub(crate) created_at: Timestamp, |
| 144 | } | 124 | } |
| 145 | 125 | ||
| 146 | impl BankQuestion { | 126 | impl BankQuestion { |
| @@ -201,328 +181,8 @@ impl BankQuestion { | |||
| 201 | ) | 181 | ) |
| 202 | } | 182 | } |
| 203 | 183 | ||
| 204 | - pub async fn create( | ||
| 205 | - owner: UserId, | ||
| 206 | - subject: SubjectId, | ||
| 207 | - text: QuestionText, | ||
| 208 | - points: QuestionPoints, | ||
| 209 | - spec: QuestionSpec, | ||
| 210 | - db: &Database, | ||
| 211 | - ) -> Result<BankQuestion, AppError> { | ||
| 212 | - Self::insert(owner, subject, text, points, spec, None, db).await | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - /// Like [`Self::create`], but records the origin exam the template was | ||
| 216 | - /// saved from (`POST …/questions/{qid}/to-bank`). | ||
| 217 | - pub async fn create_from_exam( | ||
| 218 | - owner: UserId, | ||
| 219 | - subject: SubjectId, | ||
| 220 | - text: QuestionText, | ||
| 221 | - points: QuestionPoints, | ||
| 222 | - spec: QuestionSpec, | ||
| 223 | - source: ExamId, | ||
| 224 | - db: &Database, | ||
| 225 | - ) -> Result<BankQuestion, AppError> { | ||
| 226 | - Self::insert(owner, subject, text, points, spec, Some(source), db).await | ||
| 227 | - } | ||
| 228 | - | ||
| 229 | - #[allow(clippy::too_many_arguments)] | ||
| 230 | - async fn insert( | ||
| 231 | - owner: UserId, | ||
| 232 | - subject: SubjectId, | ||
| 233 | - text: QuestionText, | ||
| 234 | - points: QuestionPoints, | ||
| 235 | - spec: QuestionSpec, | ||
| 236 | - source_exam: Option<ExamId>, | ||
| 237 | - db: &Database, | ||
| 238 | - ) -> Result<BankQuestion, AppError> { | ||
| 239 | - let question = BankQuestion::from_parts( | ||
| 240 | - BankQuestionId::generate(), | ||
| 241 | - owner, | ||
| 242 | - // Creation always carries a validated subject; only a subject | ||
| 243 | - // delete ever clears it. | ||
| 244 | - Some(subject), | ||
| 245 | - text, | ||
| 246 | - points, | ||
| 247 | - spec, | ||
| 248 | - source_exam, | ||
| 249 | - // Never published on creation — publishing is its own PATCH. | ||
| 250 | - BankVisibility::default(), | ||
| 251 | - Timestamp::now(), | ||
| 252 | - ); | ||
| 253 | - let created: Option<BankQuestion> = | ||
| 254 | - db.create(question.id.record()).content(question).await?; | ||
| 255 | - created.ok_or_else(|| AppError::Internal("failed to create bank question".into())) | ||
| 256 | - } | ||
| 257 | - | ||
| 258 | - pub async fn read( | ||
| 259 | - id: &BankQuestionId, | ||
| 260 | - db: &Database, | ||
| 261 | - ) -> Result<Option<BankQuestion>, AppError> { | ||
| 262 | - Ok(db.select(id.record()).await?) | ||
| 263 | - } | ||
| 264 | - | ||
| 265 | - /// One page of the bank the caller may see, **newest first** (ULID ids sort by | ||
| 266 | - /// creation, so `id DESC` is newest-first) — plus the total row count under | ||
| 267 | - /// the same filters, so a client can page past the window. | ||
| 268 | - /// | ||
| 269 | - /// Every filter is a WHERE clause and the window is a real `LIMIT`/`START`: | ||
| 270 | - /// the old version read the whole table and sliced it in memory, which hid | ||
| 271 | - /// every template past the client's first page. `q` is a case- and | ||
| 272 | - /// diacritic-insensitive fragment of the question text (blank = no text | ||
| 273 | - /// filter): needle and column both go through | ||
| 274 | - /// [`crate::domain::text_fold`], so `istanbul` finds `İSTANBUL` and back. | ||
| 275 | - /// | ||
| 276 | - /// `visible_to` is the security filter, and it is a WHERE clause like every | ||
| 277 | - /// other one — never a post-filter, or `total` would count templates the | ||
| 278 | - /// caller can't have and paging would return short pages of them: | ||
| 279 | - /// `Some(me)` sees the school-published templates plus their own, | ||
| 280 | - /// `None` (admins only) sees everything. | ||
| 281 | - /// | ||
| 282 | - /// `visibility` is the *user's* filter ("only mine" / "shared with the | ||
| 283 | - /// school") and is ANDed on top of that gate, so it can only ever narrow: | ||
| 284 | - /// `school` still hides another teacher's private rows, and `private` | ||
| 285 | - /// intersected with the gate leaves exactly the caller's own drafts. It | ||
| 286 | - /// joins the same `clauses` vec as the rest, so `total` honours it too — | ||
| 287 | - /// a count that ignored it would break paging. | ||
| 288 | - // Flat filter args, like every other `list` here — a builder struct for | ||
| 289 | - // four `Option`s and a window would be more machinery than the call sites. | ||
| 290 | - #[allow(clippy::too_many_arguments)] | ||
| 291 | - pub async fn list( | ||
| 292 | - visible_to: Option<&UserId>, | ||
| 293 | - owner: Option<&UserId>, | ||
| 294 | - subject: Option<&SubjectId>, | ||
| 295 | - visibility: Option<&BankVisibility>, | ||
| 296 | - q: Option<&str>, | ||
| 297 | - limit: Option<i64>, | ||
| 298 | - offset: i64, | ||
| 299 | - db: &Database, | ||
| 300 | - ) -> Result<(Vec<BankQuestion>, i64), AppError> { | ||
| 301 | - let needle = q.map(|q| search_fold(q.trim())).filter(|q| !q.is_empty()); | ||
| 302 | - let mut clauses = Vec::new(); | ||
| 303 | - if visible_to.is_some() { | ||
| 304 | - clauses.push("(visibility = 'school' OR owner = $viewer)"); | ||
| 305 | - } | ||
| 306 | - if visibility.is_some() { | ||
| 307 | - clauses.push("visibility = $visibility"); | ||
| 308 | - } | ||
| 309 | - if owner.is_some() { | ||
| 310 | - clauses.push("owner = $owner"); | ||
| 311 | - } | ||
| 312 | - if subject.is_some() { | ||
| 313 | - clauses.push("subject = $subject"); | ||
| 314 | - } | ||
| 315 | - let text_clause = format!("{} CONTAINS $q", search_fold_sql("text")); | ||
| 316 | - if needle.is_some() { | ||
| 317 | - clauses.push(text_clause.as_str()); | ||
| 318 | - } | ||
| 319 | - let where_clause = if clauses.is_empty() { | ||
| 320 | - "true".to_string() | ||
| 321 | - } else { | ||
| 322 | - clauses.join(" AND ") | ||
| 323 | - }; | ||
| 324 | - // `START` alone (no `LIMIT`) is the unpaged case — `?limit` is opt-in. | ||
| 325 | - let window = match limit { | ||
| 326 | - Some(_) => "LIMIT $limit START $offset", | ||
| 327 | - None => "START $offset", | ||
| 328 | - }; | ||
| 329 | - // The count runs over the *same* WHERE, so `total` can never disagree | ||
| 330 | - // with what paging through the list actually yields. | ||
| 331 | - let mut query = db | ||
| 332 | - .query(format!( | ||
| 333 | - "SELECT * FROM bank_question WHERE {where_clause} ORDER BY id DESC {window}; | ||
| 334 | - SELECT VALUE count() FROM bank_question WHERE {where_clause} GROUP ALL;" | ||
| 335 | - )) | ||
| 336 | - .bind(("offset", offset)); | ||
| 337 | - if let Some(viewer) = visible_to { | ||
| 338 | - query = query.bind(("viewer", viewer.record())); | ||
| 339 | - } | ||
| 340 | - if let Some(visibility) = visibility { | ||
| 341 | - query = query.bind(("visibility", visibility.as_str().to_string())); | ||
| 342 | - } | ||
| 343 | - if let Some(owner) = owner { | ||
| 344 | - query = query.bind(("owner", owner.record())); | ||
| 345 | - } | ||
| 346 | - if let Some(subject) = subject { | ||
| 347 | - query = query.bind(("subject", subject.record())); | ||
| 348 | - } | ||
| 349 | - if let Some(needle) = needle { | ||
| 350 | - query = query.bind(("q", needle)); | ||
| 351 | - } | ||
| 352 | - if let Some(limit) = limit { | ||
| 353 | - query = query.bind(("limit", limit)); | ||
| 354 | - } | ||
| 355 | - let mut result = query.await?.check()?; | ||
| 356 | - let questions = result.take::<Vec<BankQuestion>>(0)?; | ||
| 357 | - // `GROUP ALL` yields no row at all when nothing matched. | ||
| 358 | - let total = result.take::<Vec<i64>>(1)?.first().copied().unwrap_or(0); | ||
| 359 | - Ok((questions, total)) | ||
| 360 | - } | ||
| 361 | - | ||
| 362 | - /// How many exam questions were instantiated from each of `ids` — the | ||
| 363 | - /// `from_bank` side of the provenance link, tallied for a whole page in | ||
| 364 | - /// **one** grouped query (a `count()` per row would be the N+1 this page | ||
| 365 | - /// already had removed once). Keys are template record keys; a template | ||
| 366 | - /// nobody ever used has no entry at all, so the caller reads a miss as | ||
| 367 | - /// zero — and the UI can stay quiet rather than print "0". | ||
| 368 | - /// | ||
| 369 | - /// Counts *questions*, not distinct exams: one exam that inserted the same | ||
| 370 | - /// template twice counts twice, which is what "copies made from this | ||
| 371 | - /// template" means and what the divergence trap is actually about. | ||
| 372 | - pub async fn usage_counts( | ||
| 373 | - ids: &[&BankQuestionId], | ||
| 374 | - db: &Database, | ||
| 375 | - ) -> Result<HashMap<String, i64>, AppError> { | ||
| 376 | - if ids.is_empty() { | ||
| 377 | - return Ok(HashMap::new()); | ||
| 378 | - } | ||
| 379 | - let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect(); | ||
| 380 | - let mut result = db | ||
| 381 | - .query(USAGE_COUNTS_SQL) | ||
| 382 | - .bind(("ids", records)) | ||
| 383 | - .await? | ||
| 384 | - .check()?; | ||
| 385 | - Ok(result | ||
| 386 | - .take::<Vec<UsageCount>>(0)? | ||
| 387 | - .into_iter() | ||
| 388 | - .map(|row| (row.from_bank.key().to_string(), row.n)) | ||
| 389 | - .collect()) | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | - /// Write the editable fields of the template, but only while the row still | ||
| 393 | - /// reads as the snapshot `self` was loaded from — `None` means a concurrent | ||
| 394 | - /// edit (or the subject-delete cascade that clears `subject`) landed inside | ||
| 395 | - /// the handler's read-merge window, so nothing was written: reload, | ||
| 396 | - /// re-merge, retry. This is a genuine read-modify-write — every editable | ||
| 397 | - /// field is re-stated from the snapshot, and the kind/choices/correct trio | ||
| 398 | - /// has to be (a text-only edit re-submits the stored options *with their | ||
| 399 | - /// ids* so each keeps its picture) — so without the compare-and-set the | ||
| 400 | - /// later writer silently reverts the earlier one — and the window is a | ||
| 401 | - /// database round trip wide, which is exactly how far apart two concurrent | ||
| 402 | - /// requests to this one process can sit. | ||
| 403 | - /// | ||
| 404 | - /// Every field the merge re-states is in the guard, which is the same list | ||
| 405 | - /// the `SET` writes. `choices` is compared whole: its objects carry two | ||
| 406 | - /// required string keys, so none is ever dropped for being `NONE` (the trap | ||
| 407 | - /// [`crate::db::settings::save_if_unchanged`] works around). | ||
| 408 | - /// | ||
| 409 | - /// Rides [`write_with_retry`] because an image write now moves this row too | ||
| 410 | - /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]): an | ||
| 411 | - /// upload landing in the same instant makes the store answer "conflict, | ||
| 412 | - /// retry", and a bare `check()` would turn that into a 500 for an edit that | ||
| 413 | - /// only had to be re-sent. A lost round writes nothing, and the guard is | ||
| 414 | - /// re-evaluated on the next one, so a genuine stale merge still comes back | ||
| 415 | - /// as `None`. Admissible: an `UPDATE` can never answer "already exists". | ||
| 416 | - pub async fn update_if_unchanged( | ||
| 417 | - self, | ||
| 418 | - subject: Option<SubjectId>, | ||
| 419 | - text: QuestionText, | ||
| 420 | - points: QuestionPoints, | ||
| 421 | - spec: QuestionSpec, | ||
| 422 | - visibility: BankVisibility, | ||
| 423 | - db: &Database, | ||
| 424 | - ) -> Result<Option<BankQuestion>, AppError> { | ||
| 425 | - let (kind, choices, correct) = spec.into_parts(); | ||
| 426 | - let rows: Vec<BankQuestion> = write_with_retry( | ||
| 427 | - db, | ||
| 428 | - "UPDATE $id SET subject = $subject, text = $text, points = $points, | ||
| 429 | - kind = $kind, choices = $choices, correct = $correct, | ||
| 430 | - visibility = $visibility | ||
| 431 | - WHERE subject = $was_subject AND text = $was_text | ||
| 432 | - AND points = $was_points AND kind = $was_kind | ||
| 433 | - AND choices = $was_choices AND correct = $was_correct | ||
| 434 | - AND visibility = $was_visibility | ||
| 435 | - RETURN AFTER", | ||
| 436 | - &[ | ||
| 437 | - ( | ||
| 438 | - "was_subject".into(), | ||
| 439 | - self.subject.clone().map(|s| s.record()).into_value(), | ||
| 440 | - ), | ||
| 441 | - ("was_text".into(), self.text.clone().into_value()), | ||
| 442 | - ("was_points".into(), self.points.into_value()), | ||
| 443 | - ("was_kind".into(), self.kind.clone().into_value()), | ||
| 444 | - ("was_choices".into(), self.choices.clone().into_value()), | ||
| 445 | - ("was_correct".into(), self.correct.clone().into_value()), | ||
| 446 | - ( | ||
| 447 | - "was_visibility".into(), | ||
| 448 | - self.visibility.clone().into_value(), | ||
| 449 | - ), | ||
| 450 | - ("id".into(), self.id.record().into_value()), | ||
| 451 | - ("subject".into(), subject.map(|s| s.record()).into_value()), | ||
| 452 | - ("text".into(), text.into_value()), | ||
| 453 | - ("points".into(), points.into_value()), | ||
| 454 | - ("kind".into(), kind.into_value()), | ||
| 455 | - ("choices".into(), choices.into_value()), | ||
| 456 | - ("correct".into(), correct.into_value()), | ||
| 457 | - ("visibility".into(), visibility.into_value()), | ||
| 458 | - ], | ||
| 459 | - ) | ||
| 460 | - .await?; | ||
| 461 | - Ok(rows.into_iter().next()) | ||
| 462 | - } | ||
| 463 | - | ||
| 464 | - /// Delete the template and cascade-remove its bank images, so none points | ||
| 465 | - /// at a missing template. Bank rows have no answers. The image rows this | ||
| 466 | - /// actually removed come back with it: the blobs are the web layer's to | ||
| 467 | - /// take off disk, but only for *these* rows — an upload that committed | ||
| 468 | - /// after the caller listed the template's images is swept here too, and a | ||
| 469 | - /// pre-read snapshot would strand its blob for good | ||
| 470 | - /// ([`crate::db::note::delete`]'s story, this domain over). | ||
| 471 | - /// | ||
| 472 | - /// Children first, in one transaction: as two queries, a failure between | ||
| 473 | - /// them left image rows swept under a template that survived, or (the other | ||
| 474 | - /// order) a template gone with its images still there. Rides the retry | ||
| 475 | - /// because an image write now moves this very row | ||
| 476 | - /// ([`crate::domain::bank_question_image::BankQuestionImage::upsert`]) — the | ||
| 477 | - /// two contend by design, and a lost round through a bare `check()` would be | ||
| 478 | - /// a 500 for a delete that only had to be re-sent. Admissible: no `UPDATE` | ||
| 479 | - /// or `DELETE` in here can answer "already exists". | ||
| 480 | - /// | ||
| 481 | - /// Exam questions tied to this template keep living: only their provenance | ||
| 482 | - /// links are cleared, field-scoped (never a whole-row save — the question | ||
| 483 | - /// isn't ours and may be edited concurrently), so nothing can read a link to | ||
| 484 | - /// a template that no longer exists. *Both* directions point at a template, | ||
| 485 | - /// so both are cleared: `from_bank` on the questions instantiated from it, | ||
| 486 | - /// and `banked_as` on the question it was saved out of. | ||
| 487 | - pub async fn delete( | ||
| 488 | - self, | ||
| 489 | - db: &Database, | ||
| 490 | - ) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { | ||
| 491 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 492 | - db, | ||
| 493 | - "BEGIN TRANSACTION; | ||
| 494 | - LET $images = (DELETE bank_question_image WHERE bank_question = $b RETURN BEFORE); | ||
| 495 | - UPDATE exam_question SET from_bank = NONE WHERE from_bank = $b; | ||
| 496 | - UPDATE exam_question SET banked_as = NONE WHERE banked_as = $b; | ||
| 497 | - LET $gone = (DELETE $b RETURN BEFORE); | ||
| 498 | - RETURN { question: $gone, images: $images }; | ||
| 499 | - COMMIT TRANSACTION;", | ||
| 500 | - &[("b".into(), self.id.record().into_value())], | ||
| 501 | - &[], | ||
| 502 | - ) | ||
| 503 | - .await?; | ||
| 504 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 505 | - return Err(error.into()); | ||
| 506 | - } | ||
| 507 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | ||
| 508 | - // slot follows the statement count rather than a hand-kept number; | ||
| 509 | - // `num_statements` counts BEGIN and COMMIT. | ||
| 510 | - let slot = result.num_statements().saturating_sub(2); | ||
| 511 | - let outcome = result | ||
| 512 | - .take::<Vec<DeleteOutcome>>(slot)? | ||
| 513 | - .into_iter() | ||
| 514 | - .next() | ||
| 515 | - .ok_or_else(|| AppError::Internal("failed to delete bank question".into()))?; | ||
| 516 | - let question = outcome | ||
| 517 | - .question | ||
| 518 | - .into_iter() | ||
| 519 | - .next() | ||
| 520 | - .ok_or(AppError::NotFound)?; | ||
| 521 | - Ok((question, outcome.images)) | ||
| 522 | - } | ||
| 523 | - | ||
| 524 | #[allow(clippy::too_many_arguments)] | 184 | #[allow(clippy::too_many_arguments)] |
| 525 | - fn from_parts( | 185 | + pub(crate) fn from_parts( |
| 526 | id: BankQuestionId, | 186 | id: BankQuestionId, |
| 527 | owner: UserId, | 187 | owner: UserId, |
| 528 | subject: Option<SubjectId>, | 188 | subject: Option<SubjectId>, |
| @@ -554,472 +214,10 @@ impl BankQuestion { | |||
| 554 | mod tests { | 214 | mod tests { |
| 555 | use super::*; | 215 | use super::*; |
| 556 | 216 | ||
| 557 | - fn spec() -> QuestionSpec { | ||
| 558 | - use crate::domain::exam_question::ChoiceInput; | ||
| 559 | - QuestionSpec::try_new( | ||
| 560 | - QuestionKind::try_new("choice").unwrap(), | ||
| 561 | - Some(vec![ | ||
| 562 | - ChoiceInput { | ||
| 563 | - id: Some("a".into()), | ||
| 564 | - text: "yes".into(), | ||
| 565 | - }, | ||
| 566 | - ChoiceInput { | ||
| 567 | - id: Some("b".into()), | ||
| 568 | - text: "no".into(), | ||
| 569 | - }, | ||
| 570 | - ]), | ||
| 571 | - Some("b".into()), | ||
| 572 | - &[], | ||
| 573 | - ) | ||
| 574 | - .unwrap() | ||
| 575 | - } | ||
| 576 | - | ||
| 577 | - /// A row stored before `visibility` existed has no such key — it must decode | ||
| 578 | - /// as `private`, the safe value. Asserted on the decoder itself, so no | ||
| 579 | - /// schema DEFAULT can paper over it: a `school` default here would publish | ||
| 580 | - /// every pre-existing template in the school at once. | ||
| 581 | - #[tokio::test] | ||
| 582 | - async fn a_row_without_the_field_decodes_private() { | ||
| 583 | - use surrealdb::types::Value; | ||
| 584 | - | ||
| 585 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 586 | - let question = BankQuestion::create( | ||
| 587 | - UserId::generate(), | ||
| 588 | - SubjectId::generate(), | ||
| 589 | - QuestionText::try_new("q").unwrap(), | ||
| 590 | - QuestionPoints::try_new(1).unwrap(), | ||
| 591 | - spec(), | ||
| 592 | - &db, | ||
| 593 | - ) | ||
| 594 | - .await | ||
| 595 | - .unwrap(); | ||
| 596 | - assert_eq!(question.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 597 | - | ||
| 598 | - let mut stored = question.into_value(); | ||
| 599 | - let Value::Object(ref mut map) = stored else { | ||
| 600 | - panic!("a bank question serializes to an object"); | ||
| 601 | - }; | ||
| 602 | - assert!(map.remove("visibility").is_some()); | ||
| 603 | - let old = BankQuestion::from_value(stored).unwrap(); | ||
| 604 | - assert_eq!(old.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 605 | - assert!(!old.get_visibility().is_school()); | ||
| 606 | - } | ||
| 607 | - | ||
| 608 | - /// The visibility gate is a WHERE clause, so `total` counts exactly what the | ||
| 609 | - /// page can contain — never someone else's private templates. | ||
| 610 | - #[tokio::test] | ||
| 611 | - async fn list_hides_private_templates_from_others() { | ||
| 612 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 613 | - let owner = UserId::generate(); | ||
| 614 | - let other = UserId::generate(); | ||
| 615 | - let private = BankQuestion::create( | ||
| 616 | - owner.clone(), | ||
| 617 | - SubjectId::generate(), | ||
| 618 | - QuestionText::try_new("secret").unwrap(), | ||
| 619 | - QuestionPoints::try_new(1).unwrap(), | ||
| 620 | - spec(), | ||
| 621 | - &db, | ||
| 622 | - ) | ||
| 623 | - .await | ||
| 624 | - .unwrap(); | ||
| 625 | - let published = BankQuestion::create( | ||
| 626 | - owner.clone(), | ||
| 627 | - SubjectId::generate(), | ||
| 628 | - QuestionText::try_new("shared").unwrap(), | ||
| 629 | - QuestionPoints::try_new(1).unwrap(), | ||
| 630 | - spec(), | ||
| 631 | - &db, | ||
| 632 | - ) | ||
| 633 | - .await | ||
| 634 | - .unwrap(); | ||
| 635 | - let subject = published.get_subject().cloned(); | ||
| 636 | - published | ||
| 637 | - .update_if_unchanged( | ||
| 638 | - subject, | ||
| 639 | - QuestionText::try_new("shared").unwrap(), | ||
| 640 | - QuestionPoints::try_new(1).unwrap(), | ||
| 641 | - spec(), | ||
| 642 | - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), | ||
| 643 | - &db, | ||
| 644 | - ) | ||
| 645 | - .await | ||
| 646 | - .unwrap(); | ||
| 647 | - | ||
| 648 | - // The stranger sees the published one alone, and `total` agrees. | ||
| 649 | - let (items, total) = BankQuestion::list(Some(&other), None, None, None, None, None, 0, &db) | ||
| 650 | - .await | ||
| 651 | - .unwrap(); | ||
| 652 | - assert_eq!((items.len(), total), (1, 1)); | ||
| 653 | - assert_eq!(items[0].get_text().as_str(), "shared"); | ||
| 654 | - // The owner sees both; an admin (`None`) too. | ||
| 655 | - let (items, total) = BankQuestion::list(Some(&owner), None, None, None, None, None, 0, &db) | ||
| 656 | - .await | ||
| 657 | - .unwrap(); | ||
| 658 | - assert_eq!((items.len(), total), (2, 2)); | ||
| 659 | - let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) | ||
| 660 | - .await | ||
| 661 | - .unwrap(); | ||
| 662 | - assert_eq!((items.len(), total), (2, 2)); | ||
| 663 | - // An explicit `owner=` filter can't widen the gate. | ||
| 664 | - let (items, total) = | ||
| 665 | - BankQuestion::list(Some(&other), Some(&owner), None, None, None, None, 0, &db) | ||
| 666 | - .await | ||
| 667 | - .unwrap(); | ||
| 668 | - assert_eq!((items.len(), total), (1, 1)); | ||
| 669 | - assert_eq!(private.get_visibility().as_str(), BANK_VISIBILITY_PRIVATE); | ||
| 670 | - } | ||
| 671 | - | ||
| 672 | - /// The bite test for the compare-and-set that replaced the writer lease of | ||
| 673 | - /// `BANK_LOCK` on the PATCH path: a merge built on a snapshot the row has | ||
| 674 | - /// since moved past must be refused, not written — otherwise it reverts | ||
| 675 | - /// whatever landed in between. Asserts the *stored* row, never a race | ||
| 676 | - /// outcome: the in-memory engine can drop one of two concurrent writes and | ||
| 677 | - /// still answer `Ok`. | ||
| 678 | - #[tokio::test] | ||
| 679 | - async fn a_merge_built_on_a_stale_snapshot_is_refused() { | ||
| 680 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 681 | - let owner = UserId::generate(); | ||
| 682 | - let stale = BankQuestion::create( | ||
| 683 | - owner, | ||
| 684 | - SubjectId::generate(), | ||
| 685 | - QuestionText::try_new("first").unwrap(), | ||
| 686 | - QuestionPoints::try_new(1).unwrap(), | ||
| 687 | - spec(), | ||
| 688 | - &db, | ||
| 689 | - ) | ||
| 690 | - .await | ||
| 691 | - .unwrap(); | ||
| 692 | - // Somebody else's edit lands on the row this snapshot came from. | ||
| 693 | - let landed = stale | ||
| 694 | - .clone() | ||
| 695 | - .update_if_unchanged( | ||
| 696 | - None, | ||
| 697 | - QuestionText::try_new("theirs").unwrap(), | ||
| 698 | - QuestionPoints::try_new(2).unwrap(), | ||
| 699 | - spec(), | ||
| 700 | - BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), | ||
| 701 | - &db, | ||
| 702 | - ) | ||
| 703 | - .await | ||
| 704 | - .unwrap(); | ||
| 705 | - assert!(landed.is_some(), "the first write is on a fresh snapshot"); | ||
| 706 | - | ||
| 707 | - let refused = stale | ||
| 708 | - .update_if_unchanged( | ||
| 709 | - None, | ||
| 710 | - QuestionText::try_new("mine").unwrap(), | ||
| 711 | - QuestionPoints::try_new(3).unwrap(), | ||
| 712 | - spec(), | ||
| 713 | - BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(), | ||
| 714 | - &db, | ||
| 715 | - ) | ||
| 716 | - .await | ||
| 717 | - .unwrap(); | ||
| 718 | - assert!(refused.is_none(), "a stale merge must not be written"); | ||
| 719 | - let stored = BankQuestion::read(landed.unwrap().get_id(), &db) | ||
| 720 | - .await | ||
| 721 | - .unwrap() | ||
| 722 | - .unwrap(); | ||
| 723 | - assert_eq!(stored.get_text().as_str(), "theirs"); | ||
| 724 | - assert_eq!(stored.get_points().as_i64(), 2); | ||
| 725 | - } | ||
| 726 | - | ||
| 727 | - /// The `visibility` filter ANDs onto the security gate, so it narrows and | ||
| 728 | - /// never widens: a stranger asking for `school` still can't see a private | ||
| 729 | - /// row, and `private` means "my own drafts" for everyone but an admin. | ||
| 730 | - #[tokio::test] | ||
| 731 | - async fn visibility_filter_narrows_never_widens() { | ||
| 732 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 733 | - let owner = UserId::generate(); | ||
| 734 | - let other = UserId::generate(); | ||
| 735 | - let mine = |text: &str| { | ||
| 736 | - BankQuestion::create( | ||
| 737 | - owner.clone(), | ||
| 738 | - SubjectId::generate(), | ||
| 739 | - QuestionText::try_new(text).unwrap(), | ||
| 740 | - QuestionPoints::try_new(1).unwrap(), | ||
| 741 | - spec(), | ||
| 742 | - &db, | ||
| 743 | - ) | ||
| 744 | - }; | ||
| 745 | - mine("draft").await.unwrap(); | ||
| 746 | - let published = mine("shared").await.unwrap(); | ||
| 747 | - let subject = published.get_subject().cloned(); | ||
| 748 | - published | ||
| 749 | - .update_if_unchanged( | ||
| 750 | - subject, | ||
| 751 | - QuestionText::try_new("shared").unwrap(), | ||
| 752 | - QuestionPoints::try_new(1).unwrap(), | ||
| 753 | - spec(), | ||
| 754 | - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), | ||
| 755 | - &db, | ||
| 756 | - ) | ||
| 757 | - .await | ||
| 758 | - .unwrap(); | ||
| 759 | - let private = BankVisibility::try_new(BANK_VISIBILITY_PRIVATE).unwrap(); | ||
| 760 | - let school = BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(); | ||
| 761 | - | ||
| 762 | - // Owner: `private` = their drafts, `school` = the published one. | ||
| 763 | - let (items, total) = | ||
| 764 | - BankQuestion::list(Some(&owner), None, None, Some(&private), None, None, 0, &db) | ||
| 765 | - .await | ||
| 766 | - .unwrap(); | ||
| 767 | - assert_eq!((items.len(), total), (1, 1)); | ||
| 768 | - assert_eq!(items[0].get_text().as_str(), "draft"); | ||
| 769 | - let (items, total) = | ||
| 770 | - BankQuestion::list(Some(&owner), None, None, Some(&school), None, None, 0, &db) | ||
| 771 | - .await | ||
| 772 | - .unwrap(); | ||
| 773 | - assert_eq!((items.len(), total), (1, 1)); | ||
| 774 | - assert_eq!(items[0].get_text().as_str(), "shared"); | ||
| 775 | - // A stranger's `private` is empty — never someone else's draft. | ||
| 776 | - let (items, total) = | ||
| 777 | - BankQuestion::list(Some(&other), None, None, Some(&private), None, None, 0, &db) | ||
| 778 | - .await | ||
| 779 | - .unwrap(); | ||
| 780 | - assert!(items.is_empty()); | ||
| 781 | - assert_eq!(total, 0); | ||
| 782 | - // …and their `school` stops at the published one, gate intact. | ||
| 783 | - let (items, total) = | ||
| 784 | - BankQuestion::list(Some(&other), None, None, Some(&school), None, None, 0, &db) | ||
| 785 | - .await | ||
| 786 | - .unwrap(); | ||
| 787 | - assert_eq!((items.len(), total), (1, 1)); | ||
| 788 | - // Composes with the other filters: right owner, wrong visibility. | ||
| 789 | - let (items, total) = BankQuestion::list( | ||
| 790 | - Some(&owner), | ||
| 791 | - Some(&owner), | ||
| 792 | - None, | ||
| 793 | - Some(&school), | ||
| 794 | - Some("draft"), | ||
| 795 | - None, | ||
| 796 | - 0, | ||
| 797 | - &db, | ||
| 798 | - ) | ||
| 799 | - .await | ||
| 800 | - .unwrap(); | ||
| 801 | - assert!(items.is_empty()); | ||
| 802 | - assert_eq!(total, 0); | ||
| 803 | - } | ||
| 804 | - | ||
| 805 | - /// The whole page's tally in one grouped statement: right number per | ||
| 806 | - /// template, unused templates absent (so the UI prints nothing rather than | ||
| 807 | - /// "0"), and questions authored by hand never counted. | ||
| 808 | - #[tokio::test] | ||
| 809 | - async fn usage_counts_tallies_a_page_in_one_statement() { | ||
| 810 | - // One statement, so a page costs one round trip — a `;` here would mean | ||
| 811 | - // the per-row N+1 crept back in. | ||
| 812 | - assert!( | ||
| 813 | - !USAGE_COUNTS_SQL.contains(';'), | ||
| 814 | - "usage_counts must be one statement" | ||
| 815 | - ); | ||
| 816 | - | ||
| 817 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 818 | - let owner = UserId::generate(); | ||
| 819 | - let template = |text: &str| { | ||
| 820 | - BankQuestion::create( | ||
| 821 | - owner.clone(), | ||
| 822 | - SubjectId::generate(), | ||
| 823 | - QuestionText::try_new(text).unwrap(), | ||
| 824 | - QuestionPoints::try_new(1).unwrap(), | ||
| 825 | - spec(), | ||
| 826 | - &db, | ||
| 827 | - ) | ||
| 828 | - }; | ||
| 829 | - let used_twice = template("twice").await.unwrap(); | ||
| 830 | - let used_once = template("once").await.unwrap(); | ||
| 831 | - let unused = template("never").await.unwrap(); | ||
| 832 | - | ||
| 833 | - // Real exam rows: instantiating a template moves the exam's counter | ||
| 834 | - // (what keeps a question from outliving its exam), so a minted id | ||
| 835 | - // nothing wrote is a 404. | ||
| 836 | - let exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | ||
| 837 | - let other_exam = crate::db::exam::published_exam(&db).await.get_id().clone(); | ||
| 838 | - // A real subject row: an exam question claims a reference on its | ||
| 839 | - // subject, so a minted id it never wrote would be refused. | ||
| 840 | - let subject = crate::domain::subject::Subject::create( | ||
| 841 | - &crate::db::course::a_test_course(&db).await, | ||
| 842 | - crate::domain::subject::SubjectName::try_new("topic").unwrap(), | ||
| 843 | - crate::domain::subject::SubjectDescription::try_new("").unwrap(), | ||
| 844 | - &db, | ||
| 845 | - ) | ||
| 846 | - .await | ||
| 847 | - .unwrap(); | ||
| 848 | - async fn instantiate( | ||
| 849 | - exam: &ExamId, | ||
| 850 | - subject: &SubjectId, | ||
| 851 | - source: &BankQuestion, | ||
| 852 | - db: &Database, | ||
| 853 | - ) { | ||
| 854 | - crate::db::exam_question::create_from_bank( | ||
| 855 | - db, | ||
| 856 | - exam, | ||
| 857 | - subject.clone(), | ||
| 858 | - source.get_text().clone(), | ||
| 859 | - source.get_points(), | ||
| 860 | - source.spec(), | ||
| 861 | - source.get_id().clone(), | ||
| 862 | - ) | ||
| 863 | - .await | ||
| 864 | - .unwrap(); | ||
| 865 | - } | ||
| 866 | - // Two copies of the same template, in two different exams. | ||
| 867 | - instantiate(&exam, subject.get_id(), &used_twice, &db).await; | ||
| 868 | - instantiate(&other_exam, subject.get_id(), &used_twice, &db).await; | ||
| 869 | - instantiate(&exam, subject.get_id(), &used_once, &db).await; | ||
| 870 | - // A hand-authored question has no `from_bank` and must not be tallied. | ||
| 871 | - crate::db::exam_question::create( | ||
| 872 | - &db, | ||
| 873 | - &exam, | ||
| 874 | - subject.get_id().clone(), | ||
| 875 | - QuestionText::try_new("mine").unwrap(), | ||
| 876 | - QuestionPoints::try_new(1).unwrap(), | ||
| 877 | - spec(), | ||
| 878 | - ) | ||
| 879 | - .await | ||
| 880 | - .unwrap(); | ||
| 881 | - | ||
| 882 | - let ids = [used_twice.get_id(), used_once.get_id(), unused.get_id()]; | ||
| 883 | - let counts = BankQuestion::usage_counts(&ids, &db).await.unwrap(); | ||
| 884 | - assert_eq!(counts.get(used_twice.get_id().key()).copied(), Some(2)); | ||
| 885 | - assert_eq!(counts.get(used_once.get_id().key()).copied(), Some(1)); | ||
| 886 | - assert_eq!( | ||
| 887 | - counts.get(unused.get_id().key()), | ||
| 888 | - None, | ||
| 889 | - "unused stays absent" | ||
| 890 | - ); | ||
| 891 | - assert_eq!(counts.len(), 2); | ||
| 892 | - | ||
| 893 | - // A template outside the page is never counted into it. | ||
| 894 | - let narrow = BankQuestion::usage_counts(&[used_once.get_id()], &db) | ||
| 895 | - .await | ||
| 896 | - .unwrap(); | ||
| 897 | - assert_eq!(narrow.len(), 1); | ||
| 898 | - assert_eq!(narrow.get(used_once.get_id().key()).copied(), Some(1)); | ||
| 899 | - // An empty page asks nothing at all. | ||
| 900 | - assert!( | ||
| 901 | - BankQuestion::usage_counts(&[], &db) | ||
| 902 | - .await | ||
| 903 | - .unwrap() | ||
| 904 | - .is_empty() | ||
| 905 | - ); | ||
| 906 | - } | ||
| 907 | - | ||
| 908 | #[test] | 217 | #[test] |
| 909 | fn visibility_rejects_anything_else() { | 218 | fn visibility_rejects_anything_else() { |
| 910 | assert!(BankVisibility::try_new("public").is_err()); | 219 | assert!(BankVisibility::try_new("public").is_err()); |
| 911 | assert!(BankVisibility::try_new("").is_err()); | 220 | assert!(BankVisibility::try_new("").is_err()); |
| 912 | assert!(BankVisibility::try_new("school").unwrap().is_school()); | 221 | assert!(BankVisibility::try_new("school").unwrap().is_school()); |
| 913 | } | 222 | } |
| 914 | - | ||
| 915 | - #[tokio::test] | ||
| 916 | - async fn list_is_school_wide() { | ||
| 917 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 918 | - for _ in 0..2 { | ||
| 919 | - BankQuestion::create( | ||
| 920 | - UserId::generate(), | ||
| 921 | - SubjectId::generate(), | ||
| 922 | - QuestionText::try_new("q").unwrap(), | ||
| 923 | - QuestionPoints::try_new(1).unwrap(), | ||
| 924 | - spec(), | ||
| 925 | - &db, | ||
| 926 | - ) | ||
| 927 | - .await | ||
| 928 | - .unwrap(); | ||
| 929 | - } | ||
| 930 | - // Different owners, yet both listed. | ||
| 931 | - let (items, total) = BankQuestion::list(None, None, None, None, None, None, 0, &db) | ||
| 932 | - .await | ||
| 933 | - .unwrap(); | ||
| 934 | - assert_eq!(items.len(), 2); | ||
| 935 | - assert_eq!(total, 2); | ||
| 936 | - } | ||
| 937 | - | ||
| 938 | - /// The window is SQL, not an in-memory slice, and `total` ignores it. | ||
| 939 | - #[tokio::test] | ||
| 940 | - async fn list_pages_newest_first_and_filters_text() { | ||
| 941 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 942 | - let owner = UserId::generate(); | ||
| 943 | - for i in 0..5 { | ||
| 944 | - BankQuestion::create( | ||
| 945 | - owner.clone(), | ||
| 946 | - SubjectId::generate(), | ||
| 947 | - QuestionText::try_new(&format!("question {i}")).unwrap(), | ||
| 948 | - QuestionPoints::try_new(1).unwrap(), | ||
| 949 | - spec(), | ||
| 950 | - &db, | ||
| 951 | - ) | ||
| 952 | - .await | ||
| 953 | - .unwrap(); | ||
| 954 | - } | ||
| 955 | - let (page, total) = BankQuestion::list(None, None, None, None, None, Some(2), 0, &db) | ||
| 956 | - .await | ||
| 957 | - .unwrap(); | ||
| 958 | - assert_eq!(total, 5); | ||
| 959 | - assert_eq!(page.len(), 2); | ||
| 960 | - // Newest first: the last-created row leads. | ||
| 961 | - assert_eq!(page[0].get_text().as_str(), "question 4"); | ||
| 962 | - // The tail is reachable by offset. | ||
| 963 | - let (tail, _) = BankQuestion::list(None, None, None, None, None, Some(2), 4, &db) | ||
| 964 | - .await | ||
| 965 | - .unwrap(); | ||
| 966 | - assert_eq!(tail[0].get_text().as_str(), "question 0"); | ||
| 967 | - // Text filter runs in SQL, case-insensitively, and narrows `total`. | ||
| 968 | - let (hits, total) = | ||
| 969 | - BankQuestion::list(None, None, None, None, Some("QUESTION 3"), None, 0, &db) | ||
| 970 | - .await | ||
| 971 | - .unwrap(); | ||
| 972 | - assert_eq!((hits.len(), total), (1, 1)); | ||
| 973 | - // Owner filter with nobody's templates. | ||
| 974 | - let (none, total) = BankQuestion::list( | ||
| 975 | - None, | ||
| 976 | - Some(&UserId::generate()), | ||
| 977 | - None, | ||
| 978 | - None, | ||
| 979 | - None, | ||
| 980 | - None, | ||
| 981 | - 0, | ||
| 982 | - &db, | ||
| 983 | - ) | ||
| 984 | - .await | ||
| 985 | - .unwrap(); | ||
| 986 | - assert!(none.is_empty()); | ||
| 987 | - assert_eq!(total, 0); | ||
| 988 | - } | ||
| 989 | - | ||
| 990 | - /// Turkish `İ`/`ı` must not split the search into two disjoint halves. | ||
| 991 | - #[tokio::test] | ||
| 992 | - async fn list_text_filter_folds_turkish_casing() { | ||
| 993 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 994 | - BankQuestion::create( | ||
| 995 | - UserId::generate(), | ||
| 996 | - SubjectId::generate(), | ||
| 997 | - QuestionText::try_new("İSTANBUL kaç ilçeye ayrılır?").unwrap(), | ||
| 998 | - QuestionPoints::try_new(1).unwrap(), | ||
| 999 | - spec(), | ||
| 1000 | - &db, | ||
| 1001 | - ) | ||
| 1002 | - .await | ||
| 1003 | - .unwrap(); | ||
| 1004 | - for needle in [ | ||
| 1005 | - "istanbul", | ||
| 1006 | - "İSTANBUL", | ||
| 1007 | - "İstanbul", | ||
| 1008 | - "ıstanbul", | ||
| 1009 | - "ilçe", | ||
| 1010 | - "ILCE", | ||
| 1011 | - ] { | ||
| 1012 | - let (hits, total) = | ||
| 1013 | - BankQuestion::list(None, None, None, None, Some(needle), None, 0, &db) | ||
| 1014 | - .await | ||
| 1015 | - .unwrap(); | ||
| 1016 | - assert_eq!((hits.len(), total), (1, 1), "needle {needle} missed"); | ||
| 1017 | - } | ||
| 1018 | - let (miss, total) = | ||
| 1019 | - BankQuestion::list(None, None, None, None, Some("ankara"), None, 0, &db) | ||
| 1020 | - .await | ||
| 1021 | - .unwrap(); | ||
| 1022 | - assert!(miss.is_empty()); | ||
| 1023 | - assert_eq!(total, 0); | ||
| 1024 | - } | ||
| 1025 | } | 223 | } |
src/domain/bank_question_image.rsmodified+17 -458
| @@ -8,18 +8,17 @@ | |||
| 8 | //! `file` — a fresh server-generated ULID per upload. The row id is | 8 | //! `file` — a fresh server-generated ULID per upload. The row id is |
| 9 | //! *deterministic* per (question, slot), so "one image per slot" holds by | 9 | //! *deterministic* per (question, slot), so "one image per slot" holds by |
| 10 | //! construction and a replace is a plain UPSERT. The web layer owns the blob | 10 | //! construction and a replace is a plain UPSERT. The web layer owns the blob |
| 11 | -//! I/O and its ordering; this module owns the rows. | 11 | +//! I/O and its ordering; the queries live in |
| 12 | +//! [`crate::db::bank_question_image`]. | ||
| 12 | 13 | ||
| 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 14 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 14 | use ulid::Ulid; | 15 | use ulid::Ulid; |
| 15 | 16 | ||
| 16 | use crate::constant::BANK_QUESTION_IMAGE_TABLE; | 17 | use crate::constant::BANK_QUESTION_IMAGE_TABLE; |
| 17 | -use crate::database::{Database, transaction_with_retry}; | ||
| 18 | use crate::domain::bank_question::BankQuestionId; | 18 | use crate::domain::bank_question::BankQuestionId; |
| 19 | use crate::domain::exam_question::ChoiceId; | 19 | use crate::domain::exam_question::ChoiceId; |
| 20 | use crate::domain::key; | 20 | use crate::domain::key; |
| 21 | use crate::domain::note_file::FileContentType; | 21 | use crate::domain::note_file::FileContentType; |
| 22 | -use crate::error::AppError; | ||
| 23 | 22 | ||
| 24 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 23 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 25 | pub struct BankQuestionImageId(RecordId); | 24 | pub struct BankQuestionImageId(RecordId); |
| @@ -48,31 +47,22 @@ impl BankQuestionImageId { | |||
| 48 | 47 | ||
| 49 | #[derive(Debug, Clone, SurrealValue)] | 48 | #[derive(Debug, Clone, SurrealValue)] |
| 50 | pub struct BankQuestionImage { | 49 | pub struct BankQuestionImage { |
| 51 | - id: BankQuestionImageId, | 50 | + pub(crate) id: BankQuestionImageId, |
| 52 | - bank_question: BankQuestionId, | 51 | + pub(crate) bank_question: BankQuestionId, |
| 53 | /// `NONE` = the question's illustration; otherwise the id of the option | 52 | /// `NONE` = the question's illustration; otherwise the id of the option |
| 54 | /// this picture belongs to. | 53 | /// this picture belongs to. |
| 55 | - slot: Option<ChoiceId>, | 54 | + pub(crate) slot: Option<ChoiceId>, |
| 56 | /// The blob's on-disk name — a fresh ULID every upload. | 55 | /// The blob's on-disk name — a fresh ULID every upload. |
| 57 | - file: String, | 56 | + pub(crate) file: String, |
| 58 | - content_type: FileContentType, | 57 | + pub(crate) content_type: FileContentType, |
| 59 | - size: i64, | 58 | + pub(crate) size: i64, |
| 60 | -} | ||
| 61 | - | ||
| 62 | -/// What one [`BankQuestionImage::upsert`] transaction returns: the row it | ||
| 63 | -/// stored and the blob name it replaced. Both are arrays because SurrealDB | ||
| 64 | -/// drops an object key valued `NONE` on the way out, while an empty array | ||
| 65 | -/// survives — "nothing was replaced" has to be readable, not missing. | ||
| 66 | -#[derive(SurrealValue)] | ||
| 67 | -struct UpsertOutcome { | ||
| 68 | - stored: Vec<BankQuestionImage>, | ||
| 69 | - replaced: Vec<String>, | ||
| 70 | } | 59 | } |
| 71 | 60 | ||
| 72 | impl BankQuestionImage { | 61 | impl BankQuestionImage { |
| 73 | /// Assemble a row (fresh blob name generated here) without persisting it. | 62 | /// Assemble a row (fresh blob name generated here) without persisting it. |
| 74 | /// The caller writes the blob under [`Self::get_file`] first, then calls | 63 | /// The caller writes the blob under [`Self::get_file`] first, then calls |
| 75 | - /// [`Self::upsert`] — so a stored row always points at a real blob. | 64 | + /// [`crate::db::bank_question_image::upsert`] — so a stored row always |
| 65 | + /// points at a real blob. | ||
| 76 | pub fn new( | 66 | pub fn new( |
| 77 | question: &BankQuestionId, | 67 | question: &BankQuestionId, |
| 78 | slot: Option<&ChoiceId>, | 68 | slot: Option<&ChoiceId>, |
| @@ -89,6 +79,10 @@ impl BankQuestionImage { | |||
| 89 | } | 79 | } |
| 90 | } | 80 | } |
| 91 | 81 | ||
| 82 | + pub fn get_id(&self) -> &BankQuestionImageId { | ||
| 83 | + &self.id | ||
| 84 | + } | ||
| 85 | + | ||
| 92 | pub fn get_bank_question(&self) -> &BankQuestionId { | 86 | pub fn get_bank_question(&self) -> &BankQuestionId { |
| 93 | &self.bank_question | 87 | &self.bank_question |
| 94 | } | 88 | } |
| @@ -108,187 +102,14 @@ impl BankQuestionImage { | |||
| 108 | pub fn get_size(&self) -> i64 { | 102 | pub fn get_size(&self) -> i64 { |
| 109 | self.size | 103 | self.size |
| 110 | } | 104 | } |
| 111 | - | ||
| 112 | - /// Create or replace the slot's image row — the deterministic id makes this | ||
| 113 | - /// the whole "one image per slot" story — handing back what it stored plus | ||
| 114 | - /// the blob name it replaced, for the caller to take off disk. | ||
| 115 | - /// | ||
| 116 | - /// Both halves are the transaction's doing. The template's own `points` is | ||
| 117 | - /// moved and put straight back inside it, the way | ||
| 118 | - /// [`crate::domain::pool_question::bump_question_and_write`] moves | ||
| 119 | - /// `asked_at` (`created_at` is `READONLY`, so the move goes on the one other | ||
| 120 | - /// int column): that makes the template's *existence* part of this write. | ||
| 121 | - /// A bare `UPSERT` guarded by having read the template first does not | ||
| 122 | - /// survive its delete window — the read sees a row | ||
| 123 | - /// [`crate::domain::bank_question::BankQuestion::delete`] has removed but | ||
| 124 | - /// not committed, while that delete's image sweep ran on a snapshot | ||
| 125 | - /// predating this row, so both commit and the image outlives the template | ||
| 126 | - /// it hangs on. Nothing could ever read, delete, or sweep it afterwards: | ||
| 127 | - /// every image route goes through the template. Moving the value makes the | ||
| 128 | - /// two transactions touch one key, so the store refuses a side; writing the | ||
| 129 | - /// same value back would be elided and collide with nothing. | ||
| 130 | - /// | ||
| 131 | - /// The replaced blob name comes out of this same transaction rather than a | ||
| 132 | - /// read in front of it (the shape | ||
| 133 | - /// [`crate::domain::pool_question::PoolQuestion::set_image`] has): two | ||
| 134 | - /// uploads to one slot both write this row, so they contend and the loser | ||
| 135 | - /// re-reads the winner's blob name, where two pre-reads both saw the *old* | ||
| 136 | - /// blob and left the loser's fresh one orphaned on disk. | ||
| 137 | - /// | ||
| 138 | - /// Admissible for [`transaction_with_retry`]: the `UPSERT`'s id is | ||
| 139 | - /// deterministic per (question, slot) and the table carries no `UNIQUE` | ||
| 140 | - /// index, so the write always resolves onto the row its id names and can | ||
| 141 | - /// never answer "already exists". | ||
| 142 | - pub async fn upsert( | ||
| 143 | - self, | ||
| 144 | - db: &Database, | ||
| 145 | - ) -> Result<(BankQuestionImage, Option<String>), AppError> { | ||
| 146 | - // whole-row-save-ok: self is built in place, never read back, and the slot id is deterministic | ||
| 147 | - let (question, id) = (self.bank_question.record(), self.id.record()); | ||
| 148 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 149 | - db, | ||
| 150 | - "BEGIN TRANSACTION; | ||
| 151 | - LET $was_points = (SELECT VALUE points FROM ONLY $b); | ||
| 152 | - LET $bumped = (UPDATE $b SET points = points + 1 RETURN VALUE id); | ||
| 153 | - IF array::len($bumped) = 0 { THROW 'no_question' }; | ||
| 154 | - UPDATE $b SET points = $was_points; | ||
| 155 | - LET $replaced = (SELECT VALUE file FROM $id); | ||
| 156 | - LET $stored = (UPSERT $id CONTENT $image); | ||
| 157 | - RETURN { stored: $stored, replaced: $replaced }; | ||
| 158 | - COMMIT TRANSACTION;", | ||
| 159 | - &[ | ||
| 160 | - ("b".into(), question.into_value()), | ||
| 161 | - ("id".into(), id.into_value()), | ||
| 162 | - ("image".into(), self.into_value()), | ||
| 163 | - ], | ||
| 164 | - &["no_question"], | ||
| 165 | - ) | ||
| 166 | - .await?; | ||
| 167 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 168 | - // executed" — only the THROW's own slot names the reason. | ||
| 169 | - if errors | ||
| 170 | - .values() | ||
| 171 | - .any(|error| error.to_string().contains("no_question")) | ||
| 172 | - { | ||
| 173 | - return Err(AppError::NotFound); | ||
| 174 | - } | ||
| 175 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 176 | - return Err(error.into()); | ||
| 177 | - } | ||
| 178 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its | ||
| 179 | - // slot follows the statement count rather than a hand-kept number; | ||
| 180 | - // `num_statements` counts BEGIN and COMMIT. | ||
| 181 | - let slot = result.num_statements().saturating_sub(2); | ||
| 182 | - let failed = || AppError::Internal("failed to store bank question image".into()); | ||
| 183 | - let outcome = result | ||
| 184 | - .take::<Vec<UpsertOutcome>>(slot)? | ||
| 185 | - .into_iter() | ||
| 186 | - .next() | ||
| 187 | - .ok_or_else(failed)?; | ||
| 188 | - let stored = outcome.stored.into_iter().next().ok_or_else(failed)?; | ||
| 189 | - Ok((stored, outcome.replaced.into_iter().next())) | ||
| 190 | - } | ||
| 191 | - | ||
| 192 | - pub async fn read_slot( | ||
| 193 | - question: &BankQuestionId, | ||
| 194 | - slot: Option<&ChoiceId>, | ||
| 195 | - db: &Database, | ||
| 196 | - ) -> Result<Option<BankQuestionImage>, AppError> { | ||
| 197 | - Ok(db | ||
| 198 | - .select(BankQuestionImageId::for_slot(question, slot).record()) | ||
| 199 | - .await?) | ||
| 200 | - } | ||
| 201 | - | ||
| 202 | - pub async fn list_for_question( | ||
| 203 | - question: &BankQuestionId, | ||
| 204 | - db: &Database, | ||
| 205 | - ) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 206 | - let mut result = db | ||
| 207 | - .query("SELECT * FROM bank_question_image WHERE bank_question = $b") | ||
| 208 | - .bind(("b", question.record())) | ||
| 209 | - .await? | ||
| 210 | - .check()?; | ||
| 211 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 212 | - } | ||
| 213 | - | ||
| 214 | - /// The image rows of several templates in one query — for bucketing onto a | ||
| 215 | - /// listing's *page* (never the whole table: the bank spans the school). | ||
| 216 | - pub async fn list_for_questions( | ||
| 217 | - questions: &[&BankQuestionId], | ||
| 218 | - db: &Database, | ||
| 219 | - ) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 220 | - if questions.is_empty() { | ||
| 221 | - return Ok(Vec::new()); | ||
| 222 | - } | ||
| 223 | - let records: Vec<RecordId> = questions.iter().map(|q| q.record()).collect(); | ||
| 224 | - let mut result = db | ||
| 225 | - .query("SELECT * FROM bank_question_image WHERE bank_question IN $ids") | ||
| 226 | - .bind(("ids", records)) | ||
| 227 | - .await? | ||
| 228 | - .check()?; | ||
| 229 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 230 | - } | ||
| 231 | - | ||
| 232 | - /// Drop the option pictures whose choice is gone — every choice image of | ||
| 233 | - /// the question whose `slot` is *not* in `keep` (the question's own | ||
| 234 | - /// illustration always stays), returning the removed rows so the caller can | ||
| 235 | - /// take their blobs off disk. | ||
| 236 | - /// | ||
| 237 | - /// This is what makes an edit non-destructive: a PATCH that reorders, | ||
| 238 | - /// renames, or drops options passes the surviving choice ids as `keep`, so | ||
| 239 | - /// only the pictures of genuinely removed options go. `keep = &[]` (a text | ||
| 240 | - /// question, or an all-new choice list) still clears the lot. | ||
| 241 | - pub async fn delete_choices_not_in( | ||
| 242 | - question: &BankQuestionId, | ||
| 243 | - keep: &[ChoiceId], | ||
| 244 | - db: &Database, | ||
| 245 | - ) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 246 | - let keep: Vec<String> = keep.iter().map(|id| id.as_str().to_string()).collect(); | ||
| 247 | - let mut result = db | ||
| 248 | - .query( | ||
| 249 | - "DELETE bank_question_image \ | ||
| 250 | - WHERE bank_question = $b AND slot != NONE AND slot NOT IN $keep RETURN BEFORE", | ||
| 251 | - ) | ||
| 252 | - .bind(("b", question.record())) | ||
| 253 | - .bind(("keep", keep)) | ||
| 254 | - .await? | ||
| 255 | - .check()?; | ||
| 256 | - Ok(result.take::<Vec<BankQuestionImage>>(0)?) | ||
| 257 | - } | ||
| 258 | - | ||
| 259 | - pub async fn delete(self, db: &Database) -> Result<BankQuestionImage, AppError> { | ||
| 260 | - let deleted: Option<BankQuestionImage> = db.delete(self.id.record()).await?; | ||
| 261 | - deleted.ok_or(AppError::NotFound) | ||
| 262 | - } | ||
| 263 | } | 105 | } |
| 264 | 106 | ||
| 265 | #[cfg(test)] | 107 | #[cfg(test)] |
| 266 | mod tests { | 108 | mod tests { |
| 267 | use super::*; | 109 | use super::*; |
| 268 | - use crate::domain::bank_question::BankQuestion; | ||
| 269 | - use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; | ||
| 270 | - | ||
| 271 | - fn png() -> FileContentType { | ||
| 272 | - FileContentType::try_new("image/png").unwrap() | ||
| 273 | - } | ||
| 274 | - | ||
| 275 | - /// A real template row: an image write moves its `points` inside its own | ||
| 276 | - /// transaction, so a minted id nothing ever wrote is refused. | ||
| 277 | - async fn a_template(db: &Database) -> BankQuestionId { | ||
| 278 | - let id = BankQuestionId::generate(); | ||
| 279 | - db.query( | ||
| 280 | - "CREATE $b SET owner = user:u, text = 'soru', kind = 'text', points = 5, | ||
| 281 | - visibility = 'private', created_at = 1", | ||
| 282 | - ) | ||
| 283 | - .bind(("b", id.record())) | ||
| 284 | - .await | ||
| 285 | - .unwrap() | ||
| 286 | - .check() | ||
| 287 | - .unwrap(); | ||
| 288 | - id | ||
| 289 | - } | ||
| 290 | 110 | ||
| 291 | fn choice_ids() -> Vec<ChoiceId> { | 111 | fn choice_ids() -> Vec<ChoiceId> { |
| 112 | + use crate::domain::exam_question::{ChoiceInput, QuestionKind, QuestionSpec}; | ||
| 292 | QuestionSpec::try_new( | 113 | QuestionSpec::try_new( |
| 293 | QuestionKind::try_new("choice").unwrap(), | 114 | QuestionKind::try_new("choice").unwrap(), |
| 294 | Some( | 115 | Some( |
| @@ -312,8 +133,8 @@ mod tests { | |||
| 312 | .collect() | 133 | .collect() |
| 313 | } | 134 | } |
| 314 | 135 | ||
| 315 | - #[tokio::test] | 136 | + #[test] |
| 316 | - async fn for_slot_keys_by_question_and_choice_id() { | 137 | + fn for_slot_keys_by_question_and_choice_id() { |
| 317 | let question = BankQuestionId::from_key("abc"); | 138 | let question = BankQuestionId::from_key("abc"); |
| 318 | let ids = choice_ids(); | 139 | let ids = choice_ids(); |
| 319 | assert_eq!( | 140 | assert_eq!( |
| @@ -330,266 +151,4 @@ mod tests { | |||
| 330 | BankQuestionImageId::for_slot(&question, Some(&ids[1])) | 151 | BankQuestionImageId::for_slot(&question, Some(&ids[1])) |
| 331 | ); | 152 | ); |
| 332 | } | 153 | } |
| 333 | - | ||
| 334 | - #[tokio::test] | ||
| 335 | - async fn upsert_replaces_per_slot() { | ||
| 336 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 337 | - let question = a_template(&db).await; | ||
| 338 | - | ||
| 339 | - let (first, retired) = BankQuestionImage::new(&question, None, png(), 3) | ||
| 340 | - .upsert(&db) | ||
| 341 | - .await | ||
| 342 | - .unwrap(); | ||
| 343 | - assert_eq!(retired, None, "a first upload retires no blob"); | ||
| 344 | - let (second, retired) = BankQuestionImage::new(&question, None, png(), 5) | ||
| 345 | - .upsert(&db) | ||
| 346 | - .await | ||
| 347 | - .unwrap(); | ||
| 348 | - // Same slot, same row — the replace swapped the blob pointer, and the | ||
| 349 | - // write itself names the blob the caller must unlink. | ||
| 350 | - assert_ne!(first.get_file(), second.get_file()); | ||
| 351 | - assert_eq!(retired.as_deref(), Some(first.get_file())); | ||
| 352 | - let rows = BankQuestionImage::list_for_question(&question, &db) | ||
| 353 | - .await | ||
| 354 | - .unwrap(); | ||
| 355 | - assert_eq!(rows.len(), 1); | ||
| 356 | - assert_eq!(rows[0].get_size(), 5); | ||
| 357 | - } | ||
| 358 | - | ||
| 359 | - /// The bank half of the non-destructive edit: keeping an option keeps its | ||
| 360 | - /// picture, and only a removed option's picture goes. | ||
| 361 | - #[tokio::test] | ||
| 362 | - async fn only_the_dropped_options_lose_their_pictures() { | ||
| 363 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 364 | - let question = a_template(&db).await; | ||
| 365 | - let ids = choice_ids(); | ||
| 366 | - BankQuestionImage::new(&question, None, png(), 1) | ||
| 367 | - .upsert(&db) | ||
| 368 | - .await | ||
| 369 | - .unwrap(); | ||
| 370 | - for id in &ids { | ||
| 371 | - BankQuestionImage::new(&question, Some(id), png(), 1) | ||
| 372 | - .upsert(&db) | ||
| 373 | - .await | ||
| 374 | - .unwrap(); | ||
| 375 | - } | ||
| 376 | - | ||
| 377 | - let keep = vec![ids[0].clone(), ids[1].clone()]; | ||
| 378 | - let dropped = BankQuestionImage::delete_choices_not_in(&question, &keep, &db) | ||
| 379 | - .await | ||
| 380 | - .unwrap(); | ||
| 381 | - assert_eq!(dropped.len(), 1); | ||
| 382 | - assert_eq!(dropped[0].get_slot(), Some(&ids[2])); | ||
| 383 | - | ||
| 384 | - let left = BankQuestionImage::list_for_question(&question, &db) | ||
| 385 | - .await | ||
| 386 | - .unwrap(); | ||
| 387 | - assert_eq!(left.len(), 3); | ||
| 388 | - } | ||
| 389 | - | ||
| 390 | - #[tokio::test] | ||
| 391 | - async fn an_empty_keep_set_clears_every_option_picture() { | ||
| 392 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 393 | - let question = a_template(&db).await; | ||
| 394 | - let ids = choice_ids(); | ||
| 395 | - BankQuestionImage::new(&question, None, png(), 1) | ||
| 396 | - .upsert(&db) | ||
| 397 | - .await | ||
| 398 | - .unwrap(); | ||
| 399 | - for id in &ids[..2] { | ||
| 400 | - BankQuestionImage::new(&question, Some(id), png(), 1) | ||
| 401 | - .upsert(&db) | ||
| 402 | - .await | ||
| 403 | - .unwrap(); | ||
| 404 | - } | ||
| 405 | - | ||
| 406 | - let dropped = BankQuestionImage::delete_choices_not_in(&question, &[], &db) | ||
| 407 | - .await | ||
| 408 | - .unwrap(); | ||
| 409 | - assert_eq!(dropped.len(), 2); | ||
| 410 | - assert!(dropped.iter().all(|image| image.get_slot().is_some())); | ||
| 411 | - | ||
| 412 | - let left = BankQuestionImage::list_for_question(&question, &db) | ||
| 413 | - .await | ||
| 414 | - .unwrap(); | ||
| 415 | - assert_eq!(left.len(), 1); | ||
| 416 | - assert_eq!(left[0].get_slot(), None); | ||
| 417 | - } | ||
| 418 | - | ||
| 419 | - /// The [`crate::domain::pool_question::PoolQuestion`] defect, one domain | ||
| 420 | - /// over: an image written inside its template's delete window must not | ||
| 421 | - /// outlive it. Guarding the write by *reading* the template does not do it | ||
| 422 | - /// — the read sees a row [`BankQuestion::delete`] has removed but not | ||
| 423 | - /// committed, while its `DELETE bank_question_image WHERE bank_question = | ||
| 424 | - /// $b` ran on a snapshot predating this row, so both commit and the image | ||
| 425 | - /// is left pointing at a template that is gone. Nothing can reach it after | ||
| 426 | - /// that: every image route resolves the template first, no boot sweep | ||
| 427 | - /// visits this table, and its blob stays on disk for good. [`Self::upsert`] | ||
| 428 | - /// moves the template's own `points` instead, so the two transactions touch | ||
| 429 | - /// one key and the store refuses a side. | ||
| 430 | - /// | ||
| 431 | - /// The blob half is asserted through the list the delete hands back: that | ||
| 432 | - /// list — never a snapshot read before it — is what the web layer unlinks | ||
| 433 | - /// from, so an image that committed inside the window and is *not* in it is | ||
| 434 | - /// a blob stranded on disk. | ||
| 435 | - /// | ||
| 436 | - /// The window is opened by the schema, not by a lucky interleaving: a | ||
| 437 | - /// `DEFINE EVENT` on `bank_question` fires inside the delete's own | ||
| 438 | - /// transaction the instant the row goes. | ||
| 439 | - /// | ||
| 440 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 441 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 442 | - /// it commits both and answers `Ok` to each, so this passes there on broken | ||
| 443 | - /// code. | ||
| 444 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 445 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 446 | - async fn an_image_written_inside_a_delete_window_never_outlives_its_template() { | ||
| 447 | - let (db, _serialized) = crate::database::init_test_server("bank_image_race").await; | ||
| 448 | - db.query( | ||
| 449 | - "DEFINE EVENT hold_the_window ON TABLE bank_question WHEN $event = 'DELETE' \ | ||
| 450 | - THEN { SLEEP 1s; };", | ||
| 451 | - ) | ||
| 452 | - .await | ||
| 453 | - .unwrap() | ||
| 454 | - .check() | ||
| 455 | - .unwrap(); | ||
| 456 | - | ||
| 457 | - let (mut swept, mut orphans, mut stranded) = (0, 0, 0); | ||
| 458 | - for round in 0..4 { | ||
| 459 | - let question = a_template(&db).await; | ||
| 460 | - let template = BankQuestion::read(&question, &db).await.unwrap().unwrap(); | ||
| 461 | - | ||
| 462 | - let drop_it = { | ||
| 463 | - let db = db.clone(); | ||
| 464 | - tokio::spawn(async move { template.delete(&db).await }) | ||
| 465 | - }; | ||
| 466 | - // The upload starts inside the held window — the template row is | ||
| 467 | - // gone but uncommitted, which is exactly what the handler's | ||
| 468 | - // ownership read believes. | ||
| 469 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 470 | - let child = { | ||
| 471 | - let (db, question) = (db.clone(), question.clone()); | ||
| 472 | - tokio::spawn(async move { | ||
| 473 | - BankQuestionImage::new(&question, None, png(), 3) | ||
| 474 | - .upsert(&db) | ||
| 475 | - .await | ||
| 476 | - }) | ||
| 477 | - }; | ||
| 478 | - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 479 | - // A 404 for the upload is a correct answer; the only defect is | ||
| 480 | - // stored state. Neither side may 500 — they contend by design and a | ||
| 481 | - // lost round is re-sent, not reported. | ||
| 482 | - assert!( | ||
| 483 | - !matches!(child, Err(AppError::Db(_))), | ||
| 484 | - "round {round}: a raced upload must be answered, not 500: {child:?}" | ||
| 485 | - ); | ||
| 486 | - assert!( | ||
| 487 | - !matches!(drop_it, Err(AppError::Db(_))), | ||
| 488 | - "round {round}: a raced delete must retry, not 500: {drop_it:?}" | ||
| 489 | - ); | ||
| 490 | - | ||
| 491 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 492 | - if BankQuestion::read(&question, &db).await.unwrap().is_none() { | ||
| 493 | - swept += 1; | ||
| 494 | - orphans += BankQuestionImage::list_for_question(&question, &db) | ||
| 495 | - .await | ||
| 496 | - .unwrap() | ||
| 497 | - .len(); | ||
| 498 | - if let (Ok((stored, _)), Ok((_, images))) = (&child, &drop_it) | ||
| 499 | - && !images | ||
| 500 | - .iter() | ||
| 501 | - .any(|image| image.get_file() == stored.get_file()) | ||
| 502 | - { | ||
| 503 | - stranded += 1; | ||
| 504 | - } | ||
| 505 | - } | ||
| 506 | - } | ||
| 507 | - eprintln!("BankQuestion::delete raced by an upload: {swept}/4 rounds deleted the template"); | ||
| 508 | - assert!( | ||
| 509 | - swept > 0, | ||
| 510 | - "no round ever deleted the template, so the window was never reached" | ||
| 511 | - ); | ||
| 512 | - assert_eq!(orphans, 0, "an image row outlived its template"); | ||
| 513 | - assert_eq!( | ||
| 514 | - stranded, 0, | ||
| 515 | - "an image committed inside the window was swept without being handed back, so its blob stays on disk" | ||
| 516 | - ); | ||
| 517 | - } | ||
| 518 | - | ||
| 519 | - /// Two uploads to one slot must leave exactly one live blob and hand every | ||
| 520 | - /// other one back to be unlinked. Reading the slot's old blob name *before* | ||
| 521 | - /// the write gave both racers the same answer: both retired the same old | ||
| 522 | - /// blob, and the loser's fresh one stayed on disk with nothing naming it. | ||
| 523 | - /// [`Self::upsert`] reads it inside its own transaction instead, so the | ||
| 524 | - /// loser contends on the row it writes and re-reads the winner's name. | ||
| 525 | - /// | ||
| 526 | - /// The overlap is forced rather than hoped for: a `DEFINE EVENT` on this | ||
| 527 | - /// table holds the first write open inside its own transaction, so the | ||
| 528 | - /// second reads the slot before the first commits. | ||
| 529 | - /// | ||
| 530 | - /// Real server, and `#[ignore]`d for it, for the reason above: the embedded | ||
| 531 | - /// engine has no write-write conflict detection to make a loser re-read. | ||
| 532 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 533 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 534 | - async fn two_uploads_to_one_slot_leave_no_blob_unretired() { | ||
| 535 | - let (db, _serialized) = crate::database::init_test_server("bank_image_replace").await; | ||
| 536 | - db.query( | ||
| 537 | - "DEFINE EVENT hold_the_write ON TABLE bank_question_image WHEN true \ | ||
| 538 | - THEN { SLEEP 300ms; };", | ||
| 539 | - ) | ||
| 540 | - .await | ||
| 541 | - .unwrap() | ||
| 542 | - .check() | ||
| 543 | - .unwrap(); | ||
| 544 | - | ||
| 545 | - let mut unretired = 0; | ||
| 546 | - for round in 0..3 { | ||
| 547 | - let question = a_template(&db).await; | ||
| 548 | - // A first picture, so both racers have an old blob to retire. | ||
| 549 | - let (original, _) = BankQuestionImage::new(&question, None, png(), 1) | ||
| 550 | - .upsert(&db) | ||
| 551 | - .await | ||
| 552 | - .unwrap(); | ||
| 553 | - | ||
| 554 | - let mut writes = Vec::new(); | ||
| 555 | - for size in [2, 3] { | ||
| 556 | - let (db, question) = (db.clone(), question.clone()); | ||
| 557 | - writes.push(tokio::spawn(async move { | ||
| 558 | - BankQuestionImage::new(&question, None, png(), size) | ||
| 559 | - .upsert(&db) | ||
| 560 | - .await | ||
| 561 | - })); | ||
| 562 | - } | ||
| 563 | - let mut written = vec![original.get_file().to_string()]; | ||
| 564 | - let mut retired = Vec::new(); | ||
| 565 | - for write in writes { | ||
| 566 | - let (stored, replaced) = write.await.unwrap().unwrap_or_else(|err| { | ||
| 567 | - panic!("round {round}: a raced upload must not 500: {err:?}") | ||
| 568 | - }); | ||
| 569 | - written.push(stored.get_file().to_string()); | ||
| 570 | - retired.extend(replaced); | ||
| 571 | - } | ||
| 572 | - | ||
| 573 | - // Stored state is the whole verdict: exactly one blob is live, and | ||
| 574 | - // every other one this round wrote must have been handed back — | ||
| 575 | - // once. A name written and never returned is a file on disk with | ||
| 576 | - // nothing pointing at it. | ||
| 577 | - let live = BankQuestionImage::read_slot(&question, None, &db) | ||
| 578 | - .await | ||
| 579 | - .unwrap() | ||
| 580 | - .unwrap(); | ||
| 581 | - assert!( | ||
| 582 | - !retired.iter().any(|name| name == live.get_file()), | ||
| 583 | - "round {round}: the live row's own blob was retired" | ||
| 584 | - ); | ||
| 585 | - unretired += written | ||
| 586 | - .iter() | ||
| 587 | - .filter(|name| *name != live.get_file() && !retired.contains(name)) | ||
| 588 | - .count(); | ||
| 589 | - } | ||
| 590 | - assert_eq!( | ||
| 591 | - unretired, 0, | ||
| 592 | - "a blob was written and never handed back to be unlinked — it stays on disk forever" | ||
| 593 | - ); | ||
| 594 | - } | ||
| 595 | } | 154 | } |
src/domain/pomodoro.rsmodified+1 -1
| @@ -146,7 +146,7 @@ impl PomodoroSession { | |||
| 146 | /// They move only for a stint that **counts**, which is | 146 | /// They move only for a stint that **counts**, which is |
| 147 | /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most | 147 | /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most |
| 148 | /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this | 148 | /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this |
| 149 | - /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] | 149 | + /// is the farm [`crate::db::pool_question::approve`] |
| 150 | /// argues about from the other end: finishing is self-service, one stint is | 150 | /// argues about from the other end: finishing is self-service, one stint is |
| 151 | /// two requests and no second person, so a counter moved once per | 151 | /// two requests and no second person, so a counter moved once per |
| 152 | /// round-trip is farmable — two hundred pairs inside the rate limit bought | 152 | /// round-trip is farmable — two hundred pairs inside the rate limit bought |
src/domain/pool_question.rsmodified+17 -668
| @@ -8,95 +8,29 @@ | |||
| 8 | //! the row as metadata (`image_*`); the bytes live on disk under | 8 | //! the row as metadata (`image_*`); the bytes live on disk under |
| 9 | //! [`crate::config::Config::files_path`] in a file named by `image_file` — a | 9 | //! [`crate::config::Config::files_path`] in a file named by `image_file` — a |
| 10 | //! fresh server-generated ULID per upload. The web layer owns the blob I/O; | 10 | //! fresh server-generated ULID per upload. The web layer owns the blob I/O; |
| 11 | -//! this module owns the rows. | 11 | +//! the queries live in [`crate::db::pool_question`], the workflows in |
| 12 | +//! [`crate::service::pool_question`]. | ||
| 12 | 13 | ||
| 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 14 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 14 | 15 | ||
| 15 | use crate::constant::{ | 16 | use crate::constant::{ |
| 16 | - MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_APPROVED_TOTAL_FIELD, | 17 | + MAX_POOL_QUESTION_BODY_LEN, MAX_POOL_QUESTION_TITLE_LEN, POOL_QUESTION_TABLE, STATUS_APPROVED, |
| 17 | - POOL_PUBLISHED_TOTAL_FIELD, POOL_QUESTION_TABLE, STATUS_APPROVED, STATUS_PENDING, | 18 | + STATUS_PENDING, |
| 18 | }; | 19 | }; |
| 19 | -use crate::database::{Database, transaction_with_retry}; | ||
| 20 | use crate::domain::monotonic_id::next_ulid; | 20 | use crate::domain::monotonic_id::next_ulid; |
| 21 | use crate::domain::note_file::FileContentType; | 21 | use crate::domain::note_file::FileContentType; |
| 22 | -use crate::domain::solution::Solution; | ||
| 23 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| 24 | use crate::domain::user::UserId; | 23 | use crate::domain::user::UserId; |
| 25 | -use crate::error::{AppError, ValidationError}; | 24 | +use crate::error::ValidationError; |
| 26 | use crate::validate::validate_required; | 25 | use crate::validate::validate_required; |
| 27 | 26 | ||
| 28 | -/// Move the question's `asked_at` **and** run `statement` — a write to | ||
| 29 | -/// something hanging off a question — in one transaction, handing back the row | ||
| 30 | -/// it returned. `NotFound` means the question is gone and nothing was written. | ||
| 31 | -/// | ||
| 32 | -/// The move is what makes the question's **existence** part of the child's own | ||
| 33 | -/// write, the way [`crate::domain::menu::bump_menu_and_write`] does for a menu: | ||
| 34 | -/// the `UPDATE` matches nothing once the row is deleted, and a delete racing | ||
| 35 | -/// this one touches the very key this transaction writes, so the two cannot | ||
| 36 | -/// both commit. Reading the question first does *not* survive that race — the | ||
| 37 | -/// read sees a row [`PoolQuestion::delete`] has removed but not committed, | ||
| 38 | -/// while its `DELETE solution WHERE question = $q` ran on a snapshot predating | ||
| 39 | -/// this insert, so both commit and the child outlives its question with neither | ||
| 40 | -/// caller told anything. | ||
| 41 | -/// | ||
| 42 | -/// `asked_at` rather than a revision column because this row carries no counter | ||
| 43 | -/// to bump and must not grow one for this alone. It is put back *by captured | ||
| 44 | -/// value* in the same transaction, so nothing outside ever observes the move | ||
| 45 | -/// and the row is byte-identical afterwards (the pool lists order on it). | ||
| 46 | -/// Writing the same value would buy nothing: an `UPDATE` that leaves the | ||
| 47 | -/// document unchanged is elided and never reaches the store's write set, so it | ||
| 48 | -/// collides with nothing. | ||
| 49 | -/// | ||
| 50 | -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the | ||
| 51 | -/// `UPDATE`s, `SELECT`, `IF`/`THROW` and `RETURN` can never answer "already | ||
| 52 | -/// exists". | ||
| 53 | -pub(crate) async fn bump_question_and_write<T: SurrealValue>( | ||
| 54 | - question: &PoolQuestionId, | ||
| 55 | - statement: &str, | ||
| 56 | - mut bindings: Vec<(String, surrealdb::types::Value)>, | ||
| 57 | - db: &Database, | ||
| 58 | -) -> Result<Option<T>, AppError> { | ||
| 59 | - bindings.push(("q".into(), question.record().into_value())); | ||
| 60 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 61 | - db, | ||
| 62 | - &format!( | ||
| 63 | - "BEGIN TRANSACTION; | ||
| 64 | - LET $was_asked = (SELECT VALUE asked_at FROM ONLY $q); | ||
| 65 | - LET $bumped = (UPDATE $q SET asked_at = asked_at + 1 RETURN VALUE id); | ||
| 66 | - IF array::len($bumped) = 0 {{ THROW 'no_question' }}; | ||
| 67 | - UPDATE $q SET asked_at = $was_asked; | ||
| 68 | - LET $row = ({statement}); | ||
| 69 | - RETURN $row; | ||
| 70 | - COMMIT TRANSACTION;" | ||
| 71 | - ), | ||
| 72 | - &bindings, | ||
| 73 | - &["no_question"], | ||
| 74 | - ) | ||
| 75 | - .await?; | ||
| 76 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 77 | - // executed" — only the THROW's own slot names the reason. | ||
| 78 | - if errors | ||
| 79 | - .values() | ||
| 80 | - .any(|error| error.to_string().contains("no_question")) | ||
| 81 | - { | ||
| 82 | - return Err(AppError::NotFound); | ||
| 83 | - } | ||
| 84 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 85 | - return Err(error.into()); | ||
| 86 | - } | ||
| 87 | - // The trailing `RETURN` is the last statement before `COMMIT`, so its slot | ||
| 88 | - // follows the statement count rather than a hand-kept number; | ||
| 89 | - // `num_statements` counts BEGIN and COMMIT. | ||
| 90 | - let slot = result.num_statements().saturating_sub(2); | ||
| 91 | - Ok(result.take::<Vec<T>>(slot)?.into_iter().next()) | ||
| 92 | -} | ||
| 93 | - | ||
| 94 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 27 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 95 | pub struct PoolQuestionId(RecordId); | 28 | pub struct PoolQuestionId(RecordId); |
| 96 | 29 | ||
| 97 | impl PoolQuestionId { | 30 | impl PoolQuestionId { |
| 98 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 31 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 99 | - /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break ([`PoolQuestion::list_all`]), | 32 | + /// the pool sorts `asked_at DESC, id DESC` and the id *is* the tie-break |
| 33 | + /// ([`crate::db::pool_question::list_all`]), | ||
| 100 | /// and a random low half scrambles rows minted in the same millisecond. | 34 | /// and a random low half scrambles rows minted in the same millisecond. |
| 101 | pub fn generate() -> Self { | 35 | pub fn generate() -> Self { |
| 102 | Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) | 36 | Self(RecordId::new(POOL_QUESTION_TABLE, next_ulid().to_string())) |
| @@ -148,18 +82,18 @@ impl PoolQuestionBody { | |||
| 148 | 82 | ||
| 149 | #[derive(Debug, Clone, SurrealValue)] | 83 | #[derive(Debug, Clone, SurrealValue)] |
| 150 | pub struct PoolQuestion { | 84 | pub struct PoolQuestion { |
| 151 | - id: PoolQuestionId, | 85 | + pub(crate) id: PoolQuestionId, |
| 152 | - asker: UserId, | 86 | + pub(crate) asker: UserId, |
| 153 | - title: PoolQuestionTitle, | 87 | + pub(crate) title: PoolQuestionTitle, |
| 154 | - body: PoolQuestionBody, | 88 | + pub(crate) body: PoolQuestionBody, |
| 155 | - status: String, | 89 | + pub(crate) status: String, |
| 156 | - asked_at: Timestamp, | 90 | + pub(crate) asked_at: Timestamp, |
| 157 | - approved_by: Option<UserId>, | 91 | + pub(crate) approved_by: Option<UserId>, |
| 158 | /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | 92 | /// The photo's on-disk blob name — a fresh ULID every upload; `None` when |
| 159 | /// the question carries no image. | 93 | /// the question carries no image. |
| 160 | - image_file: Option<String>, | 94 | + pub(crate) image_file: Option<String>, |
| 161 | - image_content_type: Option<FileContentType>, | 95 | + pub(crate) image_content_type: Option<FileContentType>, |
| 162 | - image_size: Option<i64>, | 96 | + pub(crate) image_size: Option<i64>, |
| 163 | } | 97 | } |
| 164 | 98 | ||
| 165 | impl PoolQuestion { | 99 | impl PoolQuestion { |
| @@ -221,589 +155,4 @@ impl PoolQuestion { | |||
| 221 | pub fn get_image_size(&self) -> Option<i64> { | 155 | pub fn get_image_size(&self) -> Option<i64> { |
| 222 | self.image_size | 156 | self.image_size |
| 223 | } | 157 | } |
| 224 | - | ||
| 225 | - pub async fn insert(self, db: &Database) -> Result<PoolQuestion, AppError> { | ||
| 226 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 227 | - let created: Option<PoolQuestion> = db.create(self.id.record()).content(self).await?; | ||
| 228 | - created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) | ||
| 229 | - } | ||
| 230 | - | ||
| 231 | - pub async fn read( | ||
| 232 | - id: &PoolQuestionId, | ||
| 233 | - db: &Database, | ||
| 234 | - ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 235 | - Ok(db.select(id.record()).await?) | ||
| 236 | - } | ||
| 237 | - | ||
| 238 | - /// Every question, newest first — the teacher+ view (approval queue and | ||
| 239 | - /// pool in one list). | ||
| 240 | - pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 241 | - let mut result = db | ||
| 242 | - .query("SELECT * FROM pool_question ORDER BY asked_at DESC, id DESC") | ||
| 243 | - .await? | ||
| 244 | - .check()?; | ||
| 245 | - Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 246 | - } | ||
| 247 | - | ||
| 248 | - /// The pool as a non-staff user sees it, newest first: every approved | ||
| 249 | - /// question, plus the caller's own pending ones. | ||
| 250 | - pub async fn list_visible_to( | ||
| 251 | - user: &UserId, | ||
| 252 | - db: &Database, | ||
| 253 | - ) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 254 | - let mut result = db | ||
| 255 | - .query( | ||
| 256 | - "SELECT * FROM pool_question WHERE status = $approved OR asker = $usr \ | ||
| 257 | - ORDER BY asked_at DESC, id DESC", | ||
| 258 | - ) | ||
| 259 | - .bind(("approved", STATUS_APPROVED)) | ||
| 260 | - .bind(("usr", user.record())) | ||
| 261 | - .await? | ||
| 262 | - .check()?; | ||
| 263 | - Ok(result.take::<Vec<PoolQuestion>>(0)?) | ||
| 264 | - } | ||
| 265 | - | ||
| 266 | - /// Publish a pending question into the pool, stamping who approved it. | ||
| 267 | - /// The `WHERE status = $pending` guard makes the transition atomic: of two | ||
| 268 | - /// racing approvals exactly one wins, and an approve can never land on a | ||
| 269 | - /// question deleted mid-flight. `None` = the question wasn't pending | ||
| 270 | - /// (already approved, or gone) — the caller sorts out which. | ||
| 271 | - /// | ||
| 272 | - /// Two lifetime badge counters ride that same guard, inside this | ||
| 273 | - /// transaction: the approver's `pool_approved_total` and the *asker's* | ||
| 274 | - /// `pool_published_total`. Both hang off `array::len($done) > 0` — the | ||
| 275 | - /// guard's own verdict — so the pair moves once per real transition and | ||
| 276 | - /// never on a second approve of an already-approved question. | ||
| 277 | - /// (`count ?? 0 > 0` misparses here; `array::len` is the spelling that | ||
| 278 | - /// holds.) The second conjunct is the self-approval rule below. | ||
| 279 | - /// | ||
| 280 | - /// Two rules keep the pair unfarmable, one per side of the transition. | ||
| 281 | - /// | ||
| 282 | - /// The asker is credited at *approval*, not at asking: a bare | ||
| 283 | - /// [`insert`](PoolQuestion::insert) is self-service and the author can | ||
| 284 | - /// delete their own question and ask again forever, so a counter moved | ||
| 285 | - /// there is farmable. Approval is teacher-gated and one-way, which is why | ||
| 286 | - /// the family is named `pool_published` and not `pool_asked`. That closes | ||
| 287 | - /// the student side. | ||
| 288 | - /// | ||
| 289 | - /// And a *self*-approval — a teacher+ approving a question they asked | ||
| 290 | - /// themselves, which the route deliberately still allows — moves neither | ||
| 291 | - /// counter, hence the `$done[0].asker != $by` half of the condition. It is | ||
| 292 | - /// the same farm from the other end (ask, approve, delete, repeat, with no | ||
| 293 | - /// second person involved), and the two together are why a counter can only | ||
| 294 | - /// move when one person's work was judged by another's. Nothing else about | ||
| 295 | - /// a self-approval changes: same 200, same freeze, same stamp — this skips | ||
| 296 | - /// the credit, not the approval. | ||
| 297 | - /// | ||
| 298 | - /// Re-sent while the store answers "conflict, retry": the guard reads a | ||
| 299 | - /// column a rival approve writes, and both counters sit on user rows every | ||
| 300 | - /// other counter site writes too. Sound to re-send — every statement is an | ||
| 301 | - /// `UPDATE`, none of which can legitimately answer "already exists" — and a | ||
| 302 | - /// lost round aborts having written nothing, increments included. | ||
| 303 | - pub async fn approve( | ||
| 304 | - id: &PoolQuestionId, | ||
| 305 | - approver: &UserId, | ||
| 306 | - db: &Database, | ||
| 307 | - ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 308 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 309 | - db, | ||
| 310 | - &format!( | ||
| 311 | - "BEGIN TRANSACTION; | ||
| 312 | - LET $done = (UPDATE $q SET status = $approved, approved_by = $by | ||
| 313 | - WHERE status = $pending RETURN AFTER); | ||
| 314 | - IF array::len($done) > 0 AND $done[0].asker != $by {{ | ||
| 315 | - UPDATE $by SET | ||
| 316 | - {POOL_APPROVED_TOTAL_FIELD} = ({POOL_APPROVED_TOTAL_FIELD} ?? 0) + 1; | ||
| 317 | - LET $asker = $done[0].asker; | ||
| 318 | - UPDATE $asker SET | ||
| 319 | - {POOL_PUBLISHED_TOTAL_FIELD} = ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0) + 1; | ||
| 320 | - }}; | ||
| 321 | - RETURN $done; | ||
| 322 | - COMMIT TRANSACTION;" | ||
| 323 | - ), | ||
| 324 | - &[ | ||
| 325 | - ("q".into(), id.record().into_value()), | ||
| 326 | - ("approved".into(), STATUS_APPROVED.to_string().into_value()), | ||
| 327 | - ("by".into(), approver.record().into_value()), | ||
| 328 | - ("pending".into(), STATUS_PENDING.to_string().into_value()), | ||
| 329 | - ], | ||
| 330 | - &[], | ||
| 331 | - ) | ||
| 332 | - .await?; | ||
| 333 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 334 | - return Err(error.into()); | ||
| 335 | - } | ||
| 336 | - // The trailing `RETURN` is always the last statement before `COMMIT`, | ||
| 337 | - // so its slot follows the statement count rather than a hand-kept | ||
| 338 | - // number (`num_statements` counts `BEGIN` and `COMMIT` too, hence -2). | ||
| 339 | - let slot = result.num_statements().saturating_sub(2); | ||
| 340 | - Ok(result.take::<Vec<PoolQuestion>>(slot)?.into_iter().next()) | ||
| 341 | - } | ||
| 342 | - | ||
| 343 | - /// Point the question at a freshly written image blob. Guarded on | ||
| 344 | - /// `pending` for the same reason approval is: an image landing after | ||
| 345 | - /// approval would put unmoderated bytes in the pool, so an upload that | ||
| 346 | - /// loses the race gets `None` (and the caller takes the orphan blob back | ||
| 347 | - /// off disk). Returns the *before* row — its `image_file` is the replaced | ||
| 348 | - /// blob the caller must remove. | ||
| 349 | - pub async fn set_image( | ||
| 350 | - id: &PoolQuestionId, | ||
| 351 | - file: &str, | ||
| 352 | - content_type: &FileContentType, | ||
| 353 | - size: i64, | ||
| 354 | - db: &Database, | ||
| 355 | - ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 356 | - let mut result = db | ||
| 357 | - .query( | ||
| 358 | - "UPDATE $q SET image_file = $file, image_content_type = $ct, image_size = $size \ | ||
| 359 | - WHERE status = $pending RETURN BEFORE", | ||
| 360 | - ) | ||
| 361 | - .bind(("q", id.record())) | ||
| 362 | - .bind(("file", file.to_string())) | ||
| 363 | - .bind(("ct", content_type.clone())) | ||
| 364 | - .bind(("size", size)) | ||
| 365 | - .bind(("pending", STATUS_PENDING)) | ||
| 366 | - .await? | ||
| 367 | - .check()?; | ||
| 368 | - Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 369 | - } | ||
| 370 | - | ||
| 371 | - /// Detach the question's image (pending only, like `set_image`). Returns | ||
| 372 | - /// the *before* row — its `image_file` is the blob the caller must remove. | ||
| 373 | - pub async fn clear_image( | ||
| 374 | - id: &PoolQuestionId, | ||
| 375 | - db: &Database, | ||
| 376 | - ) -> Result<Option<PoolQuestion>, AppError> { | ||
| 377 | - let mut result = db | ||
| 378 | - .query( | ||
| 379 | - "UPDATE $q SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 380 | - WHERE status = $pending RETURN BEFORE", | ||
| 381 | - ) | ||
| 382 | - .bind(("q", id.record())) | ||
| 383 | - .bind(("pending", STATUS_PENDING)) | ||
| 384 | - .await? | ||
| 385 | - .check()?; | ||
| 386 | - Ok(result.take::<Vec<PoolQuestion>>(0)?.into_iter().next()) | ||
| 387 | - } | ||
| 388 | - | ||
| 389 | - /// Delete the question and its solutions in one transaction, returning | ||
| 390 | - /// the removed rows — the question's *and* the swept solutions' — so the | ||
| 391 | - /// caller can take every image blob off disk (solutions carry photos too, | ||
| 392 | - /// and a row-only sweep would strand theirs forever). | ||
| 393 | - /// | ||
| 394 | - /// Rides the retry because a solution offer now writes this very row | ||
| 395 | - /// ([`bump_question_and_write`]): the two contend by design, and a lost | ||
| 396 | - /// round through a bare `check()` was a 500 for a delete that only had to | ||
| 397 | - /// be re-sent. Admissible — a `DELETE` can never answer "already exists". | ||
| 398 | - pub async fn delete( | ||
| 399 | - id: &PoolQuestionId, | ||
| 400 | - db: &Database, | ||
| 401 | - ) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | ||
| 402 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 403 | - db, | ||
| 404 | - "BEGIN TRANSACTION; | ||
| 405 | - DELETE solution WHERE question = $q RETURN BEFORE; | ||
| 406 | - DELETE $q RETURN BEFORE; | ||
| 407 | - COMMIT TRANSACTION;", | ||
| 408 | - &[("q".into(), id.record().into_value())], | ||
| 409 | - &[], | ||
| 410 | - ) | ||
| 411 | - .await?; | ||
| 412 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 413 | - return Err(error.into()); | ||
| 414 | - } | ||
| 415 | - // Slots count BEGIN: the solution sweep is slot 1, the question slot 2. | ||
| 416 | - let solutions = result.take::<Vec<Solution>>(1)?; | ||
| 417 | - Ok(result | ||
| 418 | - .take::<Vec<PoolQuestion>>(2)? | ||
| 419 | - .into_iter() | ||
| 420 | - .next() | ||
| 421 | - .map(|question| (question, solutions))) | ||
| 422 | - } | ||
| 423 | -} | ||
| 424 | - | ||
| 425 | -#[cfg(test)] | ||
| 426 | -mod tests { | ||
| 427 | - use ulid::Ulid; | ||
| 428 | - | ||
| 429 | - use super::*; | ||
| 430 | - use crate::database; | ||
| 431 | - use crate::domain::solution::{Solution, SolutionBody}; | ||
| 432 | - | ||
| 433 | - /// The two counter columns plus a row to carry them: the `user` table is | ||
| 434 | - /// SCHEMAFULL in production, and the counters are `option<int>` there. | ||
| 435 | - async fn a_user(db: &Database) -> UserId { | ||
| 436 | - let user = UserId::from_key(&Ulid::new().to_string()); | ||
| 437 | - db.query(format!( | ||
| 438 | - "DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 439 | - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 440 | - CREATE $usr SET username = $name, password_hash = 'x';" | ||
| 441 | - )) | ||
| 442 | - .bind(("usr", user.record())) | ||
| 443 | - .bind(("name", user.key().to_string())) | ||
| 444 | - .await | ||
| 445 | - .unwrap() | ||
| 446 | - .check() | ||
| 447 | - .unwrap(); | ||
| 448 | - user | ||
| 449 | - } | ||
| 450 | - | ||
| 451 | - /// `(pool_approved_total, pool_published_total)` as stored — absent reads | ||
| 452 | - /// zero, the way `BadgeStats::load` reads it. | ||
| 453 | - async fn counters(user: &UserId, db: &Database) -> (i64, i64) { | ||
| 454 | - let mut result = db | ||
| 455 | - .query(format!( | ||
| 456 | - "SELECT VALUE [({POOL_APPROVED_TOTAL_FIELD} ?? 0), | ||
| 457 | - ({POOL_PUBLISHED_TOTAL_FIELD} ?? 0)] FROM $usr" | ||
| 458 | - )) | ||
| 459 | - .bind(("usr", user.record())) | ||
| 460 | - .await | ||
| 461 | - .unwrap() | ||
| 462 | - .check() | ||
| 463 | - .unwrap(); | ||
| 464 | - let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | ||
| 465 | - let row = rows.into_iter().next().unwrap_or_default(); | ||
| 466 | - ( | ||
| 467 | - row.first().copied().unwrap_or(0), | ||
| 468 | - row.get(1).copied().unwrap_or(0), | ||
| 469 | - ) | ||
| 470 | - } | ||
| 471 | - | ||
| 472 | - fn question(asker: &UserId) -> PoolQuestion { | ||
| 473 | - PoolQuestion::new( | ||
| 474 | - asker, | ||
| 475 | - PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), | ||
| 476 | - PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), | ||
| 477 | - ) | ||
| 478 | - } | ||
| 479 | - | ||
| 480 | - #[tokio::test] | ||
| 481 | - async fn approval_is_a_one_way_race_safe_transition() { | ||
| 482 | - let db = database::init_mem().await.unwrap(); | ||
| 483 | - let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 484 | - let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 485 | - | ||
| 486 | - let q = question(&asker).insert(&db).await.unwrap(); | ||
| 487 | - assert_eq!(q.get_status(), STATUS_PENDING); | ||
| 488 | - assert!(q.get_approved_by().is_none()); | ||
| 489 | - | ||
| 490 | - let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 491 | - .await | ||
| 492 | - .unwrap() | ||
| 493 | - .unwrap(); | ||
| 494 | - assert!(approved.is_approved()); | ||
| 495 | - assert_eq!(approved.get_approved_by(), Some(&teacher)); | ||
| 496 | - | ||
| 497 | - // A second approval finds nothing pending. | ||
| 498 | - assert!( | ||
| 499 | - PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 500 | - .await | ||
| 501 | - .unwrap() | ||
| 502 | - .is_none() | ||
| 503 | - ); | ||
| 504 | - // And a missing question approves to None, not an error. | ||
| 505 | - assert!( | ||
| 506 | - PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) | ||
| 507 | - .await | ||
| 508 | - .unwrap() | ||
| 509 | - .is_none() | ||
| 510 | - ); | ||
| 511 | - } | ||
| 512 | - | ||
| 513 | - /// The publish counters ride the guard, so they move exactly once per real | ||
| 514 | - /// transition: the approver's on the approve side, the asker's on the | ||
| 515 | - /// published side, and neither on a second approve of the same question. | ||
| 516 | - #[tokio::test] | ||
| 517 | - async fn approval_moves_both_counters_once_and_only_once() { | ||
| 518 | - let db = database::init_mem().await.unwrap(); | ||
| 519 | - let asker = a_user(&db).await; | ||
| 520 | - let teacher = a_user(&db).await; | ||
| 521 | - | ||
| 522 | - let q = question(&asker).insert(&db).await.unwrap(); | ||
| 523 | - assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); | ||
| 524 | - | ||
| 525 | - PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 526 | - .await | ||
| 527 | - .unwrap() | ||
| 528 | - .unwrap(); | ||
| 529 | - assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); | ||
| 530 | - assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); | ||
| 531 | - | ||
| 532 | - // The guard finds nothing pending, so neither counter may move — this | ||
| 533 | - // is what stops an approve loop from farming either one. | ||
| 534 | - assert!( | ||
| 535 | - PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 536 | - .await | ||
| 537 | - .unwrap() | ||
| 538 | - .is_none() | ||
| 539 | - ); | ||
| 540 | - assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); | ||
| 541 | - assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); | ||
| 542 | - | ||
| 543 | - // And an approve that lands on nothing at all writes nothing. | ||
| 544 | - assert!( | ||
| 545 | - PoolQuestion::approve(&PoolQuestionId::generate(), &teacher, &db) | ||
| 546 | - .await | ||
| 547 | - .unwrap() | ||
| 548 | - .is_none() | ||
| 549 | - ); | ||
| 550 | - assert_eq!(counters(&teacher, &db).await, (1, 0)); | ||
| 551 | - } | ||
| 552 | - | ||
| 553 | - /// A teacher may ask a question and the route does not bar them from | ||
| 554 | - /// approving it — that still works, unchanged. What it does not do is pay | ||
| 555 | - /// for itself: ask, approve, delete, repeat is the staff-side farm, and | ||
| 556 | - /// neither counter moves when one person is both ends of the transition. | ||
| 557 | - #[tokio::test] | ||
| 558 | - async fn self_approval_still_approves_but_moves_neither_counter() { | ||
| 559 | - let db = database::init_mem().await.unwrap(); | ||
| 560 | - let teacher = a_user(&db).await; | ||
| 561 | - | ||
| 562 | - let q = question(&teacher).insert(&db).await.unwrap(); | ||
| 563 | - let approved = PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 564 | - .await | ||
| 565 | - .unwrap() | ||
| 566 | - .unwrap(); | ||
| 567 | - // The approval itself is untouched: published, stamped, frozen. | ||
| 568 | - assert!(approved.is_approved()); | ||
| 569 | - assert_eq!(approved.get_approved_by(), Some(&teacher)); | ||
| 570 | - assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); | ||
| 571 | - | ||
| 572 | - // And the skip is about the *pair*, not about the teacher: approving | ||
| 573 | - // somebody else's question right after still pays. | ||
| 574 | - let asker = a_user(&db).await; | ||
| 575 | - let other = question(&asker).insert(&db).await.unwrap(); | ||
| 576 | - PoolQuestion::approve(other.get_id(), &teacher, &db) | ||
| 577 | - .await | ||
| 578 | - .unwrap() | ||
| 579 | - .unwrap(); | ||
| 580 | - assert_eq!(counters(&teacher, &db).await, (1, 0)); | ||
| 581 | - assert_eq!(counters(&asker, &db).await, (0, 1)); | ||
| 582 | - } | ||
| 583 | - | ||
| 584 | - #[tokio::test] | ||
| 585 | - async fn visibility_hides_others_pending_questions() { | ||
| 586 | - let db = database::init_mem().await.unwrap(); | ||
| 587 | - let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 588 | - let other = UserId::from_key(&Ulid::new().to_string()); | ||
| 589 | - let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 590 | - | ||
| 591 | - let pending = question(&asker).insert(&db).await.unwrap(); | ||
| 592 | - let published = question(&other).insert(&db).await.unwrap(); | ||
| 593 | - PoolQuestion::approve(published.get_id(), &teacher, &db) | ||
| 594 | - .await | ||
| 595 | - .unwrap() | ||
| 596 | - .unwrap(); | ||
| 597 | - | ||
| 598 | - // The asker sees their own pending question plus the pool; a stranger | ||
| 599 | - // sees only the pool; the teacher view (list_all) sees everything. | ||
| 600 | - assert_eq!( | ||
| 601 | - PoolQuestion::list_visible_to(&asker, &db) | ||
| 602 | - .await | ||
| 603 | - .unwrap() | ||
| 604 | - .len(), | ||
| 605 | - 2 | ||
| 606 | - ); | ||
| 607 | - let stranger_view = PoolQuestion::list_visible_to(&other, &db).await.unwrap(); | ||
| 608 | - assert_eq!(stranger_view.len(), 1); | ||
| 609 | - assert_eq!(stranger_view[0].get_id(), published.get_id()); | ||
| 610 | - assert_eq!(PoolQuestion::list_all(&db).await.unwrap().len(), 2); | ||
| 611 | - assert!( | ||
| 612 | - PoolQuestion::read(pending.get_id(), &db) | ||
| 613 | - .await | ||
| 614 | - .unwrap() | ||
| 615 | - .is_some() | ||
| 616 | - ); | ||
| 617 | - } | ||
| 618 | - | ||
| 619 | - #[tokio::test] | ||
| 620 | - async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { | ||
| 621 | - let db = database::init_mem().await.unwrap(); | ||
| 622 | - let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 623 | - let teacher = UserId::from_key(&Ulid::new().to_string()); | ||
| 624 | - let png = FileContentType::try_new("image/png").unwrap(); | ||
| 625 | - | ||
| 626 | - let q = question(&asker).insert(&db).await.unwrap(); | ||
| 627 | - let before = PoolQuestion::set_image(q.get_id(), "blob_a", &png, 3, &db) | ||
| 628 | - .await | ||
| 629 | - .unwrap() | ||
| 630 | - .unwrap(); | ||
| 631 | - assert!(before.get_image_file().is_none()); | ||
| 632 | - | ||
| 633 | - // A replace reports the old blob for cleanup. | ||
| 634 | - let before = PoolQuestion::set_image(q.get_id(), "blob_b", &png, 5, &db) | ||
| 635 | - .await | ||
| 636 | - .unwrap() | ||
| 637 | - .unwrap(); | ||
| 638 | - assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 639 | - let stored = PoolQuestion::read(q.get_id(), &db).await.unwrap().unwrap(); | ||
| 640 | - assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 641 | - assert_eq!(stored.get_image_size(), Some(5)); | ||
| 642 | - | ||
| 643 | - // Clearing reports the detached blob and empties the fields. | ||
| 644 | - let before = PoolQuestion::clear_image(q.get_id(), &db) | ||
| 645 | - .await | ||
| 646 | - .unwrap() | ||
| 647 | - .unwrap(); | ||
| 648 | - assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 649 | - assert!( | ||
| 650 | - PoolQuestion::read(q.get_id(), &db) | ||
| 651 | - .await | ||
| 652 | - .unwrap() | ||
| 653 | - .unwrap() | ||
| 654 | - .get_image_file() | ||
| 655 | - .is_none() | ||
| 656 | - ); | ||
| 657 | - | ||
| 658 | - // Once approved, the image is frozen with the rest of the content. | ||
| 659 | - PoolQuestion::approve(q.get_id(), &teacher, &db) | ||
| 660 | - .await | ||
| 661 | - .unwrap() | ||
| 662 | - .unwrap(); | ||
| 663 | - assert!( | ||
| 664 | - PoolQuestion::set_image(q.get_id(), "blob_c", &png, 7, &db) | ||
| 665 | - .await | ||
| 666 | - .unwrap() | ||
| 667 | - .is_none() | ||
| 668 | - ); | ||
| 669 | - assert!( | ||
| 670 | - PoolQuestion::clear_image(q.get_id(), &db) | ||
| 671 | - .await | ||
| 672 | - .unwrap() | ||
| 673 | - .is_none() | ||
| 674 | - ); | ||
| 675 | - } | ||
| 676 | - | ||
| 677 | - #[tokio::test] | ||
| 678 | - async fn delete_cascades_solutions_and_returns_the_row() { | ||
| 679 | - let db = database::init_mem().await.unwrap(); | ||
| 680 | - let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 681 | - let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 682 | - | ||
| 683 | - let q = question(&asker).insert(&db).await.unwrap(); | ||
| 684 | - let offered = Solution::new( | ||
| 685 | - q.get_id(), | ||
| 686 | - &helper, | ||
| 687 | - SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), | ||
| 688 | - ) | ||
| 689 | - .insert(&db) | ||
| 690 | - .await | ||
| 691 | - .unwrap(); | ||
| 692 | - | ||
| 693 | - // The swept solutions ride back with the question so the caller can | ||
| 694 | - // take their image blobs off disk. | ||
| 695 | - let (removed, swept) = PoolQuestion::delete(q.get_id(), &db) | ||
| 696 | - .await | ||
| 697 | - .unwrap() | ||
| 698 | - .unwrap(); | ||
| 699 | - assert_eq!(removed.get_id(), q.get_id()); | ||
| 700 | - assert_eq!(swept.len(), 1); | ||
| 701 | - assert_eq!(swept[0].get_id(), offered.get_id()); | ||
| 702 | - assert!(PoolQuestion::read(q.get_id(), &db).await.unwrap().is_none()); | ||
| 703 | - assert!( | ||
| 704 | - Solution::list_for(q.get_id(), None, 0, &db) | ||
| 705 | - .await | ||
| 706 | - .unwrap() | ||
| 707 | - .0 | ||
| 708 | - .is_empty() | ||
| 709 | - ); | ||
| 710 | - | ||
| 711 | - // Deleting the already-deleted is None, not an error. | ||
| 712 | - assert!( | ||
| 713 | - PoolQuestion::delete(q.get_id(), &db) | ||
| 714 | - .await | ||
| 715 | - .unwrap() | ||
| 716 | - .is_none() | ||
| 717 | - ); | ||
| 718 | - } | ||
| 719 | - | ||
| 720 | - /// The [`crate::domain::exam_answer::ExamAnswer::save`] defect, one domain | ||
| 721 | - /// over: a solution offered inside its question's delete window must not | ||
| 722 | - /// outlive it. Guarding the offer by *reading* the question does not do it | ||
| 723 | - /// — the read sees a row [`PoolQuestion::delete`] has removed but not | ||
| 724 | - /// committed, while its `DELETE solution WHERE question = $q` ran on a | ||
| 725 | - /// snapshot predating the offer, so both commit and the solution is left | ||
| 726 | - /// pointing at a question that is gone. Nothing can reach it after that: | ||
| 727 | - /// every route to a solution goes through its question, so neither a | ||
| 728 | - /// reader nor a second delete can ever clear it, and its photo stays on | ||
| 729 | - /// disk for good. [`bump_question_and_write`] moves the question's own | ||
| 730 | - /// `asked_at` instead, so the two transactions touch one key and the store | ||
| 731 | - /// refuses one of them. | ||
| 732 | - /// | ||
| 733 | - /// The window is opened by the database, not by a lucky interleaving: a | ||
| 734 | - /// `DEFINE EVENT` on `pool_question` fires *inside* the delete's own | ||
| 735 | - /// transaction the instant the row goes, so the `SLEEP` lands exactly | ||
| 736 | - /// between the delete and its cascade every time. | ||
| 737 | - /// | ||
| 738 | - /// Real server, and `#[ignore]`d for it: the subject *is* the store's | ||
| 739 | - /// conflict detection, which `init_mem`'s embedded engine does not have — | ||
| 740 | - /// it commits both writes and answers `Ok` to each, so this passes there on | ||
| 741 | - /// broken code. | ||
| 742 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 743 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 744 | - async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { | ||
| 745 | - let (db, _serialized) = database::init_test_server("solution_race").await; | ||
| 746 | - // Hold the delete open for a full second after the row is gone, while | ||
| 747 | - // its cascade still has to run. | ||
| 748 | - db.query( | ||
| 749 | - "DEFINE EVENT hold_the_window ON TABLE pool_question WHEN $event = 'DELETE' \ | ||
| 750 | - THEN { SLEEP 1s; };", | ||
| 751 | - ) | ||
| 752 | - .await | ||
| 753 | - .unwrap() | ||
| 754 | - .check() | ||
| 755 | - .unwrap(); | ||
| 756 | - | ||
| 757 | - let (mut solutions, mut swept, mut delete_500) = (0, 0, 0); | ||
| 758 | - for round in 0..4 { | ||
| 759 | - let asker = UserId::from_key(&Ulid::new().to_string()); | ||
| 760 | - let helper = UserId::from_key(&Ulid::new().to_string()); | ||
| 761 | - let q = question(&asker).insert(&db).await.unwrap(); | ||
| 762 | - let id = q.get_id().clone(); | ||
| 763 | - | ||
| 764 | - let drop_it = { | ||
| 765 | - let (db, id) = (db.clone(), id.clone()); | ||
| 766 | - tokio::spawn(async move { PoolQuestion::delete(&id, &db).await }) | ||
| 767 | - }; | ||
| 768 | - // The offer starts inside the held window — the question row is | ||
| 769 | - // gone but uncommitted, which is exactly what a read believes. | ||
| 770 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 771 | - let child = { | ||
| 772 | - let (db, id) = (db.clone(), id.clone()); | ||
| 773 | - tokio::spawn(async move { | ||
| 774 | - Solution::new( | ||
| 775 | - &id, | ||
| 776 | - &helper, | ||
| 777 | - SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), | ||
| 778 | - ) | ||
| 779 | - .insert(&db) | ||
| 780 | - .await | ||
| 781 | - }) | ||
| 782 | - }; | ||
| 783 | - let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); | ||
| 784 | - // A 404 for the offer is a correct answer; the only defect is | ||
| 785 | - // stored state. The delete must not 500 either — it contends with | ||
| 786 | - // the offer by design and a lost round is re-sent, not reported. | ||
| 787 | - assert!( | ||
| 788 | - !matches!(child, Err(AppError::Db(_))), | ||
| 789 | - "round {round}: a raced offer must be answered, not 500: {child:?}" | ||
| 790 | - ); | ||
| 791 | - if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 792 | - delete_500 += 1; | ||
| 793 | - } | ||
| 794 | - | ||
| 795 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 796 | - if PoolQuestion::read(&id, &db).await.unwrap().is_none() { | ||
| 797 | - swept += 1; | ||
| 798 | - solutions += Solution::list_for(&id, None, 0, &db).await.unwrap().0.len(); | ||
| 799 | - } | ||
| 800 | - } | ||
| 801 | - eprintln!("PoolQuestion::delete raced by an offer: {swept}/4 rounds deleted the question"); | ||
| 802 | - assert!( | ||
| 803 | - swept > 0, | ||
| 804 | - "no round ever deleted the question, so the window was never reached" | ||
| 805 | - ); | ||
| 806 | - assert_eq!(solutions, 0, "a solution outlived its question"); | ||
| 807 | - assert_eq!(delete_500, 0, "a raced delete must retry, not 500"); | ||
| 808 | - } | ||
| 809 | } | 158 | } |
src/domain/solution.rsmodified+16 -380
| @@ -5,21 +5,18 @@ | |||
| 5 | //! Like a question, a solution may carry one photo (`image_*` metadata on the | 5 | //! Like a question, a solution may carry one photo (`image_*` metadata on the |
| 6 | //! row, bytes on disk under a server-generated ULID) — but unlike a question | 6 | //! row, bytes on disk under a server-generated ULID) — but unlike a question |
| 7 | //! it has no moderation state, so its author may edit the body and swap the | 7 | //! it has no moderation state, so its author may edit the body and swap the |
| 8 | -//! photo at any time; there is nothing to freeze. | 8 | +//! photo at any time; there is nothing to freeze. The queries live in |
| 9 | - | 9 | +//! [`crate::db::solution`], the funnels in [`crate::service::solution`]. |
| 10 | -use std::collections::HashMap; | ||
| 11 | 10 | ||
| 12 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 11 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 13 | 12 | ||
| 14 | use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; | 13 | use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE}; |
| 15 | -use crate::database::Database; | ||
| 16 | use crate::domain::monotonic_id::next_ulid; | 14 | use crate::domain::monotonic_id::next_ulid; |
| 17 | use crate::domain::note_file::FileContentType; | 15 | use crate::domain::note_file::FileContentType; |
| 18 | -use crate::db::page::PagedList; | 16 | +use crate::domain::pool_question::PoolQuestionId; |
| 19 | -use crate::domain::pool_question::{PoolQuestionId, bump_question_and_write}; | ||
| 20 | use crate::domain::timestamp::Timestamp; | 17 | use crate::domain::timestamp::Timestamp; |
| 21 | use crate::domain::user::UserId; | 18 | use crate::domain::user::UserId; |
| 22 | -use crate::error::{AppError, ValidationError}; | 19 | +use crate::error::ValidationError; |
| 23 | use crate::validate::validate_required; | 20 | use crate::validate::validate_required; |
| 24 | 21 | ||
| 25 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -27,7 +24,8 @@ pub struct SolutionId(RecordId); | |||
| 27 | 24 | ||
| 28 | impl SolutionId { | 25 | impl SolutionId { |
| 29 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 26 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 30 | - /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break ([`Solution::list_for_question`]), | 27 | + /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break |
| 28 | + /// ([`crate::db::solution::list_for`]), | ||
| 31 | /// and a random low half scrambles rows minted in the same millisecond. | 29 | /// and a random low half scrambles rows minted in the same millisecond. |
| 32 | pub fn generate() -> Self { | 30 | pub fn generate() -> Self { |
| 33 | Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) | 31 | Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string())) |
| @@ -65,23 +63,16 @@ impl SolutionBody { | |||
| 65 | 63 | ||
| 66 | #[derive(Debug, Clone, SurrealValue)] | 64 | #[derive(Debug, Clone, SurrealValue)] |
| 67 | pub struct Solution { | 65 | pub struct Solution { |
| 68 | - id: SolutionId, | 66 | + pub(crate) id: SolutionId, |
| 69 | - question: PoolQuestionId, | 67 | + pub(crate) question: PoolQuestionId, |
| 70 | - author: UserId, | 68 | + pub(crate) author: UserId, |
| 71 | - body: SolutionBody, | 69 | + pub(crate) body: SolutionBody, |
| 72 | - offered_at: Timestamp, | 70 | + pub(crate) offered_at: Timestamp, |
| 73 | /// The photo's on-disk blob name — a fresh ULID every upload; `None` when | 71 | /// The photo's on-disk blob name — a fresh ULID every upload; `None` when |
| 74 | /// the solution carries no image. | 72 | /// the solution carries no image. |
| 75 | - image_file: Option<String>, | 73 | + pub(crate) image_file: Option<String>, |
| 76 | - image_content_type: Option<FileContentType>, | 74 | + pub(crate) image_content_type: Option<FileContentType>, |
| 77 | - image_size: Option<i64>, | 75 | + pub(crate) image_size: Option<i64>, |
| 78 | -} | ||
| 79 | - | ||
| 80 | -/// One `GROUP BY question` row of [`Solution::counts_for`]. | ||
| 81 | -#[derive(SurrealValue)] | ||
| 82 | -struct SolutionCount { | ||
| 83 | - question: PoolQuestionId, | ||
| 84 | - n: i64, | ||
| 85 | } | 76 | } |
| 86 | 77 | ||
| 87 | impl Solution { | 78 | impl Solution { |
| @@ -129,369 +120,14 @@ impl Solution { | |||
| 129 | pub fn get_image_size(&self) -> Option<i64> { | 120 | pub fn get_image_size(&self) -> Option<i64> { |
| 130 | self.image_size | 121 | self.image_size |
| 131 | } | 122 | } |
| 132 | - | ||
| 133 | - /// Offer the solution. `NotFound` = the question is gone, and nothing was | ||
| 134 | - /// written: the create rides [`bump_question_and_write`], so the question's | ||
| 135 | - /// existence is a *write* to its row rather than a read the handler made a | ||
| 136 | - /// moment earlier — a bare create landing inside | ||
| 137 | - /// [`PoolQuestion::delete`](crate::domain::pool_question::PoolQuestion::delete)'s | ||
| 138 | - /// window was swept by nothing and left a solution no route could ever | ||
| 139 | - /// reach or remove (every path to one goes through its question), photo | ||
| 140 | - /// blob included. | ||
| 141 | - /// | ||
| 142 | - /// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call | ||
| 143 | - /// on a table with no `UNIQUE` index, so a re-send cannot answer "already | ||
| 144 | - /// exists" — the one thing the retry could not survive. | ||
| 145 | - pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { | ||
| 146 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 147 | - let (question, id) = (self.question.clone(), self.id.record()); | ||
| 148 | - bump_question_and_write( | ||
| 149 | - &question, | ||
| 150 | - "CREATE $id CONTENT $solution", | ||
| 151 | - vec![ | ||
| 152 | - ("id".into(), id.into_value()), | ||
| 153 | - ("solution".into(), self.into_value()), | ||
| 154 | - ], | ||
| 155 | - db, | ||
| 156 | - ) | ||
| 157 | - .await? | ||
| 158 | - .ok_or_else(|| AppError::Internal("failed to create solution".into())) | ||
| 159 | - } | ||
| 160 | - | ||
| 161 | - /// Read a solution only if it belongs to `question` — keeps the nested | ||
| 162 | - /// route honest (a solution id under someone else's question 404s). | ||
| 163 | - pub async fn read_for( | ||
| 164 | - id: &SolutionId, | ||
| 165 | - question: &PoolQuestionId, | ||
| 166 | - db: &Database, | ||
| 167 | - ) -> Result<Option<Solution>, AppError> { | ||
| 168 | - let solution: Option<Solution> = db.select(id.record()).await?; | ||
| 169 | - Ok(solution.filter(|solution| &solution.question == question)) | ||
| 170 | - } | ||
| 171 | - | ||
| 172 | - /// The question's solutions, oldest first — a discussion reads downward. | ||
| 173 | - /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond | ||
| 174 | - /// offers *stable* across re-queries, not insertion-ordered (ULID low bits | ||
| 175 | - /// are random within a millisecond, so same-ms order is arbitrary). | ||
| 176 | - pub async fn list_for( | ||
| 177 | - question: &PoolQuestionId, | ||
| 178 | - limit: Option<i64>, | ||
| 179 | - offset: i64, | ||
| 180 | - db: &Database, | ||
| 181 | - ) -> Result<(Vec<Solution>, i64), AppError> { | ||
| 182 | - PagedList::new( | ||
| 183 | - "solution WHERE question = $q", | ||
| 184 | - "ORDER BY offered_at ASC, id ASC", | ||
| 185 | - ) | ||
| 186 | - .bind("q", question.record()) | ||
| 187 | - .run(limit, offset, db) | ||
| 188 | - .await | ||
| 189 | - } | ||
| 190 | - | ||
| 191 | - /// Per-question solution tallies for a page of questions, in one grouped | ||
| 192 | - /// query — a per-row `count()` would cost a query per question. Keys are | ||
| 193 | - /// question record keys; a question with no solutions has no entry, so | ||
| 194 | - /// the caller reads misses as zero. | ||
| 195 | - pub async fn counts_for( | ||
| 196 | - questions: &[PoolQuestionId], | ||
| 197 | - db: &Database, | ||
| 198 | - ) -> Result<HashMap<String, i64>, AppError> { | ||
| 199 | - if questions.is_empty() { | ||
| 200 | - return Ok(HashMap::new()); | ||
| 201 | - } | ||
| 202 | - let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect(); | ||
| 203 | - let mut result = db | ||
| 204 | - .query("SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question") | ||
| 205 | - .bind(("qs", ids)) | ||
| 206 | - .await? | ||
| 207 | - .check()?; | ||
| 208 | - Ok(result | ||
| 209 | - .take::<Vec<SolutionCount>>(0)? | ||
| 210 | - .into_iter() | ||
| 211 | - .map(|row| (row.question.key().to_string(), row.n)) | ||
| 212 | - .collect()) | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - /// Replace the body. Unconditional (solutions have no moderation state to | ||
| 216 | - /// guard, unlike a question's `pending` gate) — `None` only means the row | ||
| 217 | - /// was deleted mid-flight. Authorship is the web layer's check. | ||
| 218 | - pub async fn set_body( | ||
| 219 | - id: &SolutionId, | ||
| 220 | - body: &SolutionBody, | ||
| 221 | - db: &Database, | ||
| 222 | - ) -> Result<Option<Solution>, AppError> { | ||
| 223 | - let mut result = db | ||
| 224 | - .query("UPDATE $s SET body = $b RETURN AFTER") | ||
| 225 | - .bind(("s", id.record())) | ||
| 226 | - .bind(("b", body.clone())) | ||
| 227 | - .await? | ||
| 228 | - .check()?; | ||
| 229 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 230 | - } | ||
| 231 | - | ||
| 232 | - /// Point the solution at a freshly written image blob. Unconditional for | ||
| 233 | - /// the same reason as [`Self::set_body`]. Returns the *before* row — its | ||
| 234 | - /// `image_file` is the replaced blob the caller must remove; `None` means | ||
| 235 | - /// the row was deleted mid-flight (the fresh blob is the caller's orphan | ||
| 236 | - /// to take back off disk). | ||
| 237 | - pub async fn set_image( | ||
| 238 | - id: &SolutionId, | ||
| 239 | - file: &str, | ||
| 240 | - content_type: &FileContentType, | ||
| 241 | - size: i64, | ||
| 242 | - db: &Database, | ||
| 243 | - ) -> Result<Option<Solution>, AppError> { | ||
| 244 | - let mut result = db | ||
| 245 | - .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE") | ||
| 246 | - .bind(("s", id.record())) | ||
| 247 | - .bind(("file", file.to_string())) | ||
| 248 | - .bind(("ct", content_type.clone())) | ||
| 249 | - .bind(("size", size)) | ||
| 250 | - .await? | ||
| 251 | - .check()?; | ||
| 252 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 253 | - } | ||
| 254 | - | ||
| 255 | - /// Detach the solution's image. Returns the *before* row — its | ||
| 256 | - /// `image_file` is the blob the caller must remove. | ||
| 257 | - pub async fn clear_image(id: &SolutionId, db: &Database) -> Result<Option<Solution>, AppError> { | ||
| 258 | - let mut result = db | ||
| 259 | - .query( | ||
| 260 | - "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \ | ||
| 261 | - RETURN BEFORE", | ||
| 262 | - ) | ||
| 263 | - .bind(("s", id.record())) | ||
| 264 | - .await? | ||
| 265 | - .check()?; | ||
| 266 | - Ok(result.take::<Vec<Solution>>(0)?.into_iter().next()) | ||
| 267 | - } | ||
| 268 | - | ||
| 269 | - pub async fn delete(self, db: &Database) -> Result<Solution, AppError> { | ||
| 270 | - let deleted: Option<Solution> = db.delete(self.id.record()).await?; | ||
| 271 | - deleted.ok_or(AppError::NotFound) | ||
| 272 | - } | ||
| 273 | } | 123 | } |
| 274 | 124 | ||
| 275 | #[cfg(test)] | 125 | #[cfg(test)] |
| 276 | mod tests { | 126 | mod tests { |
| 277 | - use ulid::Ulid; | ||
| 278 | - | ||
| 279 | use super::*; | 127 | use super::*; |
| 280 | 128 | ||
| 281 | - /// A real question row: offering a solution moves its question's | 129 | + #[test] |
| 282 | - /// `asked_at` (that is what keeps a solution from outliving its question), | 130 | + fn body_rules() { |
| 283 | - /// so a minted id nothing wrote is a 404. | ||
| 284 | - async fn question_row(db: &Database) -> PoolQuestionId { | ||
| 285 | - use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle}; | ||
| 286 | - PoolQuestion::new( | ||
| 287 | - &UserId::from_key(&Ulid::new().to_string()), | ||
| 288 | - PoolQuestionTitle::try_new("soru").unwrap(), | ||
| 289 | - PoolQuestionBody::try_new("neden").unwrap(), | ||
| 290 | - ) | ||
| 291 | - .insert(db) | ||
| 292 | - .await | ||
| 293 | - .unwrap() | ||
| 294 | - .get_id() | ||
| 295 | - .clone() | ||
| 296 | - } | ||
| 297 | - | ||
| 298 | - #[tokio::test] | ||
| 299 | - async fn rows_scope_to_their_question_and_list_oldest_first() { | ||
| 300 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 301 | - let question_a = question_row(&db).await; | ||
| 302 | - let question_b = question_row(&db).await; | ||
| 303 | - let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 304 | - | ||
| 305 | - // Distinct offer times so the assertion pins the real contract — | ||
| 306 | - // older `offered_at` sorts first — not the same-millisecond `id` | ||
| 307 | - // tiebreak, whose random ULID low bits would make the order a coin | ||
| 308 | - // flip (two `now()` reads can land in one millisecond). | ||
| 309 | - let mut first = Solution::new( | ||
| 310 | - &question_a, | ||
| 311 | - &author, | ||
| 312 | - SolutionBody::try_new("Önce türevi al.").unwrap(), | ||
| 313 | - ); | ||
| 314 | - first.offered_at = Timestamp::from_millis(1); | ||
| 315 | - let first = first.insert(&db).await.unwrap(); | ||
| 316 | - let mut second = Solution::new( | ||
| 317 | - &question_a, | ||
| 318 | - &author, | ||
| 319 | - SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(), | ||
| 320 | - ); | ||
| 321 | - second.offered_at = Timestamp::from_millis(2); | ||
| 322 | - let second = second.insert(&db).await.unwrap(); | ||
| 323 | - | ||
| 324 | - let (listed, _) = Solution::list_for(&question_a, None, 0, &db).await.unwrap(); | ||
| 325 | - assert_eq!(listed.len(), 2); | ||
| 326 | - assert_eq!(listed[0].get_id(), first.get_id()); | ||
| 327 | - assert_eq!(listed[1].get_id(), second.get_id()); | ||
| 328 | - assert!( | ||
| 329 | - Solution::list_for(&question_b, None, 0, &db) | ||
| 330 | - .await | ||
| 331 | - .unwrap() | ||
| 332 | - .0 | ||
| 333 | - .is_empty() | ||
| 334 | - ); | ||
| 335 | - | ||
| 336 | - // Readable under its own question, invisible under another. | ||
| 337 | - assert!( | ||
| 338 | - Solution::read_for(first.get_id(), &question_a, &db) | ||
| 339 | - .await | ||
| 340 | - .unwrap() | ||
| 341 | - .is_some() | ||
| 342 | - ); | ||
| 343 | - assert!( | ||
| 344 | - Solution::read_for(first.get_id(), &question_b, &db) | ||
| 345 | - .await | ||
| 346 | - .unwrap() | ||
| 347 | - .is_none() | ||
| 348 | - ); | ||
| 349 | - | ||
| 350 | - first.delete(&db).await.unwrap(); | ||
| 351 | - assert_eq!( | ||
| 352 | - Solution::list_for(&question_a, None, 0, &db) | ||
| 353 | - .await | ||
| 354 | - .unwrap() | ||
| 355 | - .0 | ||
| 356 | - .len(), | ||
| 357 | - 1 | ||
| 358 | - ); | ||
| 359 | - } | ||
| 360 | - | ||
| 361 | - #[tokio::test] | ||
| 362 | - async fn image_set_replace_clear_report_the_replaced_blob() { | ||
| 363 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 364 | - let question = question_row(&db).await; | ||
| 365 | - let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 366 | - let png = FileContentType::try_new("image/png").unwrap(); | ||
| 367 | - | ||
| 368 | - let solution = Solution::new( | ||
| 369 | - &question, | ||
| 370 | - &author, | ||
| 371 | - SolutionBody::try_new("Grafiği çiz.").unwrap(), | ||
| 372 | - ) | ||
| 373 | - .insert(&db) | ||
| 374 | - .await | ||
| 375 | - .unwrap(); | ||
| 376 | - | ||
| 377 | - let before = Solution::set_image(solution.get_id(), "blob_a", &png, 3, &db) | ||
| 378 | - .await | ||
| 379 | - .unwrap() | ||
| 380 | - .unwrap(); | ||
| 381 | - assert!(before.get_image_file().is_none()); | ||
| 382 | - | ||
| 383 | - // A replace reports the old blob for cleanup. | ||
| 384 | - let before = Solution::set_image(solution.get_id(), "blob_b", &png, 5, &db) | ||
| 385 | - .await | ||
| 386 | - .unwrap() | ||
| 387 | - .unwrap(); | ||
| 388 | - assert_eq!(before.get_image_file(), Some("blob_a")); | ||
| 389 | - let stored = Solution::read_for(solution.get_id(), &question, &db) | ||
| 390 | - .await | ||
| 391 | - .unwrap() | ||
| 392 | - .unwrap(); | ||
| 393 | - assert_eq!(stored.get_image_file(), Some("blob_b")); | ||
| 394 | - assert_eq!(stored.get_image_size(), Some(5)); | ||
| 395 | - | ||
| 396 | - // Clearing reports the detached blob and empties the fields. | ||
| 397 | - let before = Solution::clear_image(solution.get_id(), &db) | ||
| 398 | - .await | ||
| 399 | - .unwrap() | ||
| 400 | - .unwrap(); | ||
| 401 | - assert_eq!(before.get_image_file(), Some("blob_b")); | ||
| 402 | - assert!( | ||
| 403 | - Solution::read_for(solution.get_id(), &question, &db) | ||
| 404 | - .await | ||
| 405 | - .unwrap() | ||
| 406 | - .unwrap() | ||
| 407 | - .get_image_file() | ||
| 408 | - .is_none() | ||
| 409 | - ); | ||
| 410 | - | ||
| 411 | - // A row deleted mid-flight surfaces as None, not an error. | ||
| 412 | - solution.clone().delete(&db).await.unwrap(); | ||
| 413 | - assert!( | ||
| 414 | - Solution::set_image(solution.get_id(), "blob_c", &png, 7, &db) | ||
| 415 | - .await | ||
| 416 | - .unwrap() | ||
| 417 | - .is_none() | ||
| 418 | - ); | ||
| 419 | - assert!( | ||
| 420 | - Solution::clear_image(solution.get_id(), &db) | ||
| 421 | - .await | ||
| 422 | - .unwrap() | ||
| 423 | - .is_none() | ||
| 424 | - ); | ||
| 425 | - } | ||
| 426 | - | ||
| 427 | - #[tokio::test] | ||
| 428 | - async fn set_body_edits_in_place() { | ||
| 429 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 430 | - let question = question_row(&db).await; | ||
| 431 | - let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 432 | - | ||
| 433 | - let solution = Solution::new( | ||
| 434 | - &question, | ||
| 435 | - &author, | ||
| 436 | - SolutionBody::try_new("İlk deneme.").unwrap(), | ||
| 437 | - ) | ||
| 438 | - .insert(&db) | ||
| 439 | - .await | ||
| 440 | - .unwrap(); | ||
| 441 | - | ||
| 442 | - let edited = Solution::set_body( | ||
| 443 | - solution.get_id(), | ||
| 444 | - &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(), | ||
| 445 | - &db, | ||
| 446 | - ) | ||
| 447 | - .await | ||
| 448 | - .unwrap() | ||
| 449 | - .unwrap(); | ||
| 450 | - assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm."); | ||
| 451 | - assert_eq!(edited.get_id(), solution.get_id()); | ||
| 452 | - | ||
| 453 | - // Editing a missing solution is None, not an error. | ||
| 454 | - assert!( | ||
| 455 | - Solution::set_body( | ||
| 456 | - &SolutionId::generate(), | ||
| 457 | - &SolutionBody::try_new("boş").unwrap(), | ||
| 458 | - &db, | ||
| 459 | - ) | ||
| 460 | - .await | ||
| 461 | - .unwrap() | ||
| 462 | - .is_none() | ||
| 463 | - ); | ||
| 464 | - } | ||
| 465 | - | ||
| 466 | - #[tokio::test] | ||
| 467 | - async fn counts_for_groups_per_question() { | ||
| 468 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 469 | - let two = question_row(&db).await; | ||
| 470 | - let one = question_row(&db).await; | ||
| 471 | - let none = question_row(&db).await; | ||
| 472 | - let author = UserId::from_key(&Ulid::new().to_string()); | ||
| 473 | - | ||
| 474 | - for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] { | ||
| 475 | - for body in bodies { | ||
| 476 | - Solution::new(question, &author, SolutionBody::try_new(body).unwrap()) | ||
| 477 | - .insert(&db) | ||
| 478 | - .await | ||
| 479 | - .unwrap(); | ||
| 480 | - } | ||
| 481 | - } | ||
| 482 | - | ||
| 483 | - let counts = Solution::counts_for(&[two.clone(), one.clone(), none.clone()], &db) | ||
| 484 | - .await | ||
| 485 | - .unwrap(); | ||
| 486 | - assert_eq!(counts.get(two.key()), Some(&2)); | ||
| 487 | - assert_eq!(counts.get(one.key()), Some(&1)); | ||
| 488 | - // No solutions = no entry; the caller reads the miss as zero. | ||
| 489 | - assert_eq!(counts.get(none.key()), None); | ||
| 490 | - assert!(Solution::counts_for(&[], &db).await.unwrap().is_empty()); | ||
| 491 | - } | ||
| 492 | - | ||
| 493 | - #[tokio::test] | ||
| 494 | - async fn body_rules() { | ||
| 495 | assert!(SolutionBody::try_new("").is_err()); | 131 | assert!(SolutionBody::try_new("").is_err()); |
| 496 | assert!(SolutionBody::try_new(" ").is_err()); | 132 | assert!(SolutionBody::try_new(" ").is_err()); |
| 497 | assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err()); | 133 | assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err()); |
src/service/bank_question.rsadded+178 -0
| @@ -0,0 +1,178 @@ | |||
| 1 | +//! Bank-question workflows: the PATCH re-derive — the merge (set / clear / | ||
| 2 | +//! keep per field) re-judged against a fresh read every retry round, with the | ||
| 3 | +//! kind/choices/correct trio re-validated as a unit — plus the read, list, | ||
| 4 | +//! create, usage-tally, and delete funnels the web layer goes through. The | ||
| 5 | +//! queries and their transactions live in [`crate::db::bank_question`]; the | ||
| 6 | +//! pure entity and newtypes in [`crate::domain::bank_question`]. | ||
| 7 | + | ||
| 8 | +use std::collections::HashMap; | ||
| 9 | + | ||
| 10 | +use crate::constant::CAS_UPDATE_RETRIES; | ||
| 11 | +use crate::database::Database; | ||
| 12 | +use crate::db::bank_question; | ||
| 13 | +use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | ||
| 14 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 15 | +use crate::domain::exam::ExamId; | ||
| 16 | +use crate::domain::exam_question::{ | ||
| 17 | + Choice, ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | ||
| 18 | +}; | ||
| 19 | +use crate::domain::subject::SubjectId; | ||
| 20 | +use crate::domain::user::UserId; | ||
| 21 | +use crate::error::AppError; | ||
| 22 | + | ||
| 23 | +pub async fn read(db: &Database, id: &BankQuestionId) -> Result<Option<BankQuestion>, AppError> { | ||
| 24 | + bank_question::read(db, id).await | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +pub async fn create( | ||
| 28 | + db: &Database, | ||
| 29 | + owner: UserId, | ||
| 30 | + subject: SubjectId, | ||
| 31 | + text: QuestionText, | ||
| 32 | + points: QuestionPoints, | ||
| 33 | + spec: QuestionSpec, | ||
| 34 | +) -> Result<BankQuestion, AppError> { | ||
| 35 | + bank_question::create(db, owner, subject, text, points, spec).await | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Like [`create`], but records the origin exam the template was saved from | ||
| 39 | +/// (`POST …/questions/{qid}/to-bank`). | ||
| 40 | +pub async fn create_from_exam( | ||
| 41 | + db: &Database, | ||
| 42 | + owner: UserId, | ||
| 43 | + subject: SubjectId, | ||
| 44 | + text: QuestionText, | ||
| 45 | + points: QuestionPoints, | ||
| 46 | + spec: QuestionSpec, | ||
| 47 | + source: ExamId, | ||
| 48 | +) -> Result<BankQuestion, AppError> { | ||
| 49 | + bank_question::create_from_exam(db, owner, subject, text, points, spec, source).await | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// One page of the bank the caller may see, plus the total under the same | ||
| 53 | +/// filters — the visibility gate is a WHERE clause inside, never a post-filter. | ||
| 54 | +#[allow(clippy::too_many_arguments)] | ||
| 55 | +pub async fn list( | ||
| 56 | + db: &Database, | ||
| 57 | + visible_to: Option<&UserId>, | ||
| 58 | + owner: Option<&UserId>, | ||
| 59 | + subject: Option<&SubjectId>, | ||
| 60 | + visibility: Option<&BankVisibility>, | ||
| 61 | + q: Option<&str>, | ||
| 62 | + limit: Option<i64>, | ||
| 63 | + offset: i64, | ||
| 64 | +) -> Result<(Vec<BankQuestion>, i64), AppError> { | ||
| 65 | + bank_question::list(db, visible_to, owner, subject, visibility, q, limit, offset).await | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// How many exam questions were instantiated from each of `ids`, in one | ||
| 69 | +/// grouped query for the whole page. | ||
| 70 | +pub async fn usage_counts( | ||
| 71 | + db: &Database, | ||
| 72 | + ids: &[&BankQuestionId], | ||
| 73 | +) -> Result<HashMap<String, i64>, AppError> { | ||
| 74 | + bank_question::usage_counts(db, ids).await | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +/// A `PATCH /bank-questions/{bid}` request after field validation: every | ||
| 78 | +/// value the request *sets* is already validated (text, points, and kind by | ||
| 79 | +/// their newtypes; the submitted choices as `ChoiceInput`s; the subject by | ||
| 80 | +/// the web's existence read). What is *kept* — and whether the merged | ||
| 81 | +/// kind/choices/correct trio is a legal question — are the update's own | ||
| 82 | +/// decisions, re-derived against a fresh read every retry round, so they live | ||
| 83 | +/// here and not in the web layer. `choices`/`correct` carry the web DTO's | ||
| 84 | +/// set-or-clear spelling (`Some(None)` = explicit `null`). | ||
| 85 | +pub struct BankQuestionPatch { | ||
| 86 | + pub subject: Option<SubjectId>, | ||
| 87 | + pub text: Option<QuestionText>, | ||
| 88 | + pub points: Option<QuestionPoints>, | ||
| 89 | + pub kind: Option<QuestionKind>, | ||
| 90 | + pub choices: Option<Option<Vec<ChoiceInput>>>, | ||
| 91 | + pub correct: Option<Option<String>>, | ||
| 92 | + pub visibility: Option<BankVisibility>, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Re-derive and save the template: merge the patch over a fresh read, | ||
| 96 | +/// re-validate the kind-dependent fields as a unit, and land the whole merge | ||
| 97 | +/// with the compare-and-set — retried while the row keeps moving under the | ||
| 98 | +/// snapshot. Concurrent PATCHes of one template no longer queue behind each | ||
| 99 | +/// other: the lost update they used to cause is refused by the guard, and the | ||
| 100 | +/// next round re-merges over what actually landed. | ||
| 101 | +pub async fn update( | ||
| 102 | + db: &Database, | ||
| 103 | + id: &BankQuestionId, | ||
| 104 | + patch: &BankQuestionPatch, | ||
| 105 | +) -> Result<BankQuestion, AppError> { | ||
| 106 | + let mut left = CAS_UPDATE_RETRIES; | ||
| 107 | + loop { | ||
| 108 | + let question = bank_question::read(db, id) | ||
| 109 | + .await? | ||
| 110 | + .ok_or(AppError::NotFound)?; | ||
| 111 | + // Omitted keeps the stored subject — which may already be `None`, cleared | ||
| 112 | + // by that subject's delete. | ||
| 113 | + let subject = match &patch.subject { | ||
| 114 | + Some(subject) => Some(subject.clone()), | ||
| 115 | + None => question.get_subject().cloned(), | ||
| 116 | + }; | ||
| 117 | + let text = patch | ||
| 118 | + .text | ||
| 119 | + .clone() | ||
| 120 | + .unwrap_or_else(|| question.get_text().clone()); | ||
| 121 | + let points = patch.points.unwrap_or_else(|| question.get_points()); | ||
| 122 | + let kind = patch | ||
| 123 | + .kind | ||
| 124 | + .clone() | ||
| 125 | + .unwrap_or_else(|| question.get_kind().clone()); | ||
| 126 | + // Merge the kind-dependent fields (set / clear / keep per field), then | ||
| 127 | + // re-validate them as a unit — a PATCH can't leave a half-question behind. | ||
| 128 | + // Omitting `choices` re-submits the stored options *with their ids*, so a | ||
| 129 | + // text-only edit keeps every identity (and every picture) untouched. | ||
| 130 | + let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec(); | ||
| 131 | + let choices = match &patch.choices { | ||
| 132 | + Some(update) => update.clone(), | ||
| 133 | + None => question.get_choices().map(|stored| { | ||
| 134 | + stored | ||
| 135 | + .iter() | ||
| 136 | + .map(|choice| ChoiceInput { | ||
| 137 | + id: Some(choice.get_id().as_str().to_string()), | ||
| 138 | + text: choice.get_text().as_str().to_string(), | ||
| 139 | + }) | ||
| 140 | + .collect() | ||
| 141 | + }), | ||
| 142 | + }; | ||
| 143 | + let correct = patch | ||
| 144 | + .correct | ||
| 145 | + .clone() | ||
| 146 | + .unwrap_or_else(|| question.get_correct().map(|id| id.as_str().to_string())); | ||
| 147 | + let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; | ||
| 148 | + let visibility = patch | ||
| 149 | + .visibility | ||
| 150 | + .clone() | ||
| 151 | + .unwrap_or_else(|| question.get_visibility().clone()); | ||
| 152 | + | ||
| 153 | + if let Some(updated) = bank_question::update_if_unchanged( | ||
| 154 | + db, question, subject, text, points, spec, visibility, | ||
| 155 | + ) | ||
| 156 | + .await? | ||
| 157 | + { | ||
| 158 | + return Ok(updated); | ||
| 159 | + } | ||
| 160 | + // The row moved under the snapshot every gate above judged: re-read and | ||
| 161 | + // re-merge, so both edits land instead of the later reverting the earlier. | ||
| 162 | + left -= 1; | ||
| 163 | + if left == 0 { | ||
| 164 | + return Err(AppError::Conflict( | ||
| 165 | + "the template kept changing underneath this update — try again", | ||
| 166 | + )); | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/// Delete the template and cascade-remove its image rows; the swept rows come | ||
| 172 | +/// back with it, and their blob files are the web layer's to unlink. | ||
| 173 | +pub async fn delete( | ||
| 174 | + db: &Database, | ||
| 175 | + target: BankQuestion, | ||
| 176 | +) -> Result<(BankQuestion, Vec<BankQuestionImage>), AppError> { | ||
| 177 | + bank_question::delete(db, target).await | ||
| 178 | +} | ||
src/service/bank_question_image.rsadded+63 -0
| @@ -0,0 +1,63 @@ | |||
| 1 | +//! Bank-question image funnels: the per-slot upsert, the slot/page reads, the | ||
| 2 | +//! choice sweep a non-destructive PATCH runs, and the single-row delete. The | ||
| 3 | +//! queries and their transactions live in | ||
| 4 | +//! [`crate::db::bank_question_image`]; the blob files themselves stay the web | ||
| 5 | +//! layer's to write and unlink. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::bank_question_image; | ||
| 9 | +use crate::domain::bank_question::BankQuestionId; | ||
| 10 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 11 | +use crate::domain::exam_question::ChoiceId; | ||
| 12 | +use crate::error::AppError; | ||
| 13 | + | ||
| 14 | +/// Create or replace the slot's image row, handing back what it stored plus | ||
| 15 | +/// the blob name it replaced, for the caller to take off disk. | ||
| 16 | +pub async fn upsert( | ||
| 17 | + db: &Database, | ||
| 18 | + image: BankQuestionImage, | ||
| 19 | +) -> Result<(BankQuestionImage, Option<String>), AppError> { | ||
| 20 | + bank_question_image::upsert(db, image).await | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +pub async fn read_slot( | ||
| 24 | + db: &Database, | ||
| 25 | + question: &BankQuestionId, | ||
| 26 | + slot: Option<&ChoiceId>, | ||
| 27 | +) -> Result<Option<BankQuestionImage>, AppError> { | ||
| 28 | + bank_question_image::read_slot(db, question, slot).await | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +pub async fn list_for_question( | ||
| 32 | + db: &Database, | ||
| 33 | + question: &BankQuestionId, | ||
| 34 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 35 | + bank_question_image::list_for_question(db, question).await | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The image rows of several templates in one query — for bucketing onto a | ||
| 39 | +/// listing's *page*. | ||
| 40 | +pub async fn list_for_questions( | ||
| 41 | + db: &Database, | ||
| 42 | + questions: &[&BankQuestionId], | ||
| 43 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 44 | + bank_question_image::list_for_questions(db, questions).await | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// Drop the option pictures whose choice is gone — every choice image of | ||
| 48 | +/// the question whose `slot` is *not* in `keep` — returning the removed rows | ||
| 49 | +/// so the caller can take their blobs off disk. | ||
| 50 | +pub async fn delete_choices_not_in( | ||
| 51 | + db: &Database, | ||
| 52 | + question: &BankQuestionId, | ||
| 53 | + keep: &[ChoiceId], | ||
| 54 | +) -> Result<Vec<BankQuestionImage>, AppError> { | ||
| 55 | + bank_question_image::delete_choices_not_in(db, question, keep).await | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +pub async fn delete( | ||
| 59 | + db: &Database, | ||
| 60 | + image: BankQuestionImage, | ||
| 61 | +) -> Result<BankQuestionImage, AppError> { | ||
| 62 | + bank_question_image::delete(db, image).await | ||
| 63 | +} | ||
src/service/mod.rsmodified+4 -0
| @@ -3,6 +3,8 @@ | |||
| 3 | 3 | ||
| 4 | pub mod appointment; | 4 | pub mod appointment; |
| 5 | pub mod appointment_slot; | 5 | pub mod appointment_slot; |
| 6 | +pub mod bank_question; | ||
| 7 | +pub mod bank_question_image; | ||
| 6 | pub mod class_blueprint; | 8 | pub mod class_blueprint; |
| 7 | pub mod course; | 9 | pub mod course; |
| 8 | pub mod course_session; | 10 | pub mod course_session; |
| @@ -13,6 +15,8 @@ pub mod exam_question; | |||
| 13 | pub mod meal_booking; | 15 | pub mod meal_booking; |
| 14 | pub mod note; | 16 | pub mod note; |
| 15 | pub mod payment_ledger; | 17 | pub mod payment_ledger; |
| 18 | +pub mod pool_question; | ||
| 16 | pub mod session; | 19 | pub mod session; |
| 17 | pub mod settings; | 20 | pub mod settings; |
| 21 | +pub mod solution; | ||
| 18 | pub mod user; | 22 | pub mod user; |
src/service/pool_question.rsadded+86 -0
| @@ -0,0 +1,86 @@ | |||
| 1 | +//! Pool-question funnels: ask, the two listings, the approve with its | ||
| 2 | +//! 409-vs-404 split, the pending-only image writes, and the delete whose | ||
| 3 | +//! swept solutions ride back for the web layer's blob cleanup. The queries | ||
| 4 | +//! and their transactions live in [`crate::db::pool_question`]; the pure | ||
| 5 | +//! entity and newtypes in [`crate::domain::pool_question`]. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::pool_question; | ||
| 9 | +use crate::domain::note_file::FileContentType; | ||
| 10 | +use crate::domain::pool_question::{PoolQuestion, PoolQuestionId}; | ||
| 11 | +use crate::domain::solution::Solution; | ||
| 12 | +use crate::domain::user::UserId; | ||
| 13 | +use crate::error::AppError; | ||
| 14 | + | ||
| 15 | +pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> { | ||
| 16 | + pool_question::insert(db, question).await | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { | ||
| 20 | + pool_question::read(db, id).await | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// Every question, newest first — the teacher+ view (approval queue and | ||
| 24 | +/// pool in one list). | ||
| 25 | +pub async fn list_all(db: &Database) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 26 | + pool_question::list_all(db).await | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// The pool as a non-staff user sees it, newest first: every approved | ||
| 30 | +/// question, plus the caller's own pending ones. | ||
| 31 | +pub async fn list_visible_to(db: &Database, user: &UserId) -> Result<Vec<PoolQuestion>, AppError> { | ||
| 32 | + pool_question::list_visible_to(db, user).await | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// Approve a pending question, stamping `approver`. A `None` from the | ||
| 36 | +/// guarded write is ambiguous — already approved, or gone — so this sorts it | ||
| 37 | +/// out with a read: the question missing is a 404, anything else is the 409 | ||
| 38 | +/// the route's second approve answers. | ||
| 39 | +pub async fn approve( | ||
| 40 | + db: &Database, | ||
| 41 | + id: &PoolQuestionId, | ||
| 42 | + approver: &UserId, | ||
| 43 | +) -> Result<PoolQuestion, AppError> { | ||
| 44 | + match pool_question::approve(db, id, approver).await? { | ||
| 45 | + Some(question) => Ok(question), | ||
| 46 | + // Nothing was pending under that id: either it's already approved | ||
| 47 | + // (409) or it never existed / was deleted (404). | ||
| 48 | + None => { | ||
| 49 | + if pool_question::read(db, id).await?.is_none() { | ||
| 50 | + return Err(AppError::NotFound); | ||
| 51 | + } | ||
| 52 | + Err(AppError::Conflict("the question is already approved")) | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// Point the question at a freshly written image blob; `None` means the | ||
| 58 | +/// question was approved or deleted mid-upload (the fresh blob is the | ||
| 59 | +/// caller's orphan to take back off disk). | ||
| 60 | +pub async fn set_image( | ||
| 61 | + db: &Database, | ||
| 62 | + id: &PoolQuestionId, | ||
| 63 | + file: &str, | ||
| 64 | + content_type: &FileContentType, | ||
| 65 | + size: i64, | ||
| 66 | +) -> Result<Option<PoolQuestion>, AppError> { | ||
| 67 | + pool_question::set_image(db, id, file, content_type, size).await | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// Detach the question's image (pending only, like [`set_image`]); `None` | ||
| 71 | +/// means the question is no longer pending. | ||
| 72 | +pub async fn clear_image( | ||
| 73 | + db: &Database, | ||
| 74 | + id: &PoolQuestionId, | ||
| 75 | +) -> Result<Option<PoolQuestion>, AppError> { | ||
| 76 | + pool_question::clear_image(db, id).await | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// Delete the question and cascade its solutions; the removed rows come back | ||
| 80 | +/// so the web layer can take every image blob off disk. | ||
| 81 | +pub async fn delete( | ||
| 82 | + db: &Database, | ||
| 83 | + id: &PoolQuestionId, | ||
| 84 | +) -> Result<Option<(PoolQuestion, Vec<Solution>)>, AppError> { | ||
| 85 | + pool_question::delete(db, id).await | ||
| 86 | +} | ||
src/service/solution.rsadded+80 -0
| @@ -0,0 +1,80 @@ | |||
| 1 | +//! Solution funnels: the offer (through the question's existence-move), the | ||
| 2 | +//! question-scoped read and page, the grouped counts, and the unconditional | ||
| 3 | +//! body/image writes of an unmoderated row. The queries live in | ||
| 4 | +//! [`crate::db::solution`]; the pure entity and newtypes in | ||
| 5 | +//! [`crate::domain::solution`]. | ||
| 6 | + | ||
| 7 | +use std::collections::HashMap; | ||
| 8 | + | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::db::solution; | ||
| 11 | +use crate::domain::note_file::FileContentType; | ||
| 12 | +use crate::domain::pool_question::PoolQuestionId; | ||
| 13 | +use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | ||
| 14 | +use crate::error::AppError; | ||
| 15 | + | ||
| 16 | +/// Offer the solution; `NotFound` = the question is gone, and nothing was | ||
| 17 | +/// written. | ||
| 18 | +pub async fn insert(db: &Database, offer: Solution) -> Result<Solution, AppError> { | ||
| 19 | + solution::insert(db, offer).await | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +/// Read a solution only if it belongs to `question` — keeps the nested | ||
| 23 | +/// route honest (a solution id under someone else's question 404s). | ||
| 24 | +pub async fn read_for( | ||
| 25 | + db: &Database, | ||
| 26 | + id: &SolutionId, | ||
| 27 | + question: &PoolQuestionId, | ||
| 28 | +) -> Result<Option<Solution>, AppError> { | ||
| 29 | + solution::read_for(db, id, question).await | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/// The question's solutions, oldest first. | ||
| 33 | +pub async fn list_for( | ||
| 34 | + db: &Database, | ||
| 35 | + question: &PoolQuestionId, | ||
| 36 | + limit: Option<i64>, | ||
| 37 | + offset: i64, | ||
| 38 | +) -> Result<(Vec<Solution>, i64), AppError> { | ||
| 39 | + solution::list_for(db, question, limit, offset).await | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// Per-question solution tallies for a page of questions, in one grouped | ||
| 43 | +/// query. | ||
| 44 | +pub async fn counts_for( | ||
| 45 | + db: &Database, | ||
| 46 | + questions: &[PoolQuestionId], | ||
| 47 | +) -> Result<HashMap<String, i64>, AppError> { | ||
| 48 | + solution::counts_for(db, questions).await | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Replace the body; `None` only means the row was deleted mid-flight. | ||
| 52 | +pub async fn set_body( | ||
| 53 | + db: &Database, | ||
| 54 | + id: &SolutionId, | ||
| 55 | + body: &SolutionBody, | ||
| 56 | +) -> Result<Option<Solution>, AppError> { | ||
| 57 | + solution::set_body(db, id, body).await | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// Point the solution at a freshly written image blob; the *before* row names | ||
| 61 | +/// the replaced blob the caller must remove. | ||
| 62 | +pub async fn set_image( | ||
| 63 | + db: &Database, | ||
| 64 | + id: &SolutionId, | ||
| 65 | + file: &str, | ||
| 66 | + content_type: &FileContentType, | ||
| 67 | + size: i64, | ||
| 68 | +) -> Result<Option<Solution>, AppError> { | ||
| 69 | + solution::set_image(db, id, file, content_type, size).await | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/// Detach the solution's image; the *before* row names the blob the caller | ||
| 73 | +/// must remove. | ||
| 74 | +pub async fn clear_image(db: &Database, id: &SolutionId) -> Result<Option<Solution>, AppError> { | ||
| 75 | + solution::clear_image(db, id).await | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +pub async fn delete(db: &Database, target: Solution) -> Result<Solution, AppError> { | ||
| 79 | + solution::delete(db, target).await | ||
| 80 | +} | ||
src/web/bank_questions.rsmodified+75 -89
| @@ -25,17 +25,19 @@ use utoipa::{IntoParams, ToSchema}; | |||
| 25 | use utoipa_axum::router::OpenApiRouter; | 25 | use utoipa_axum::router::OpenApiRouter; |
| 26 | use utoipa_axum::routes; | 26 | use utoipa_axum::routes; |
| 27 | 27 | ||
| 28 | -use crate::constant::{CAS_UPDATE_RETRIES, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | 28 | +use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 29 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | 29 | use crate::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; |
| 30 | use crate::domain::bank_question_image::BankQuestionImage; | 30 | use crate::domain::bank_question_image::BankQuestionImage; |
| 31 | use crate::domain::exam_question::{ | 31 | use crate::domain::exam_question::{ |
| 32 | - Choice, ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 32 | + ChoiceId, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 33 | }; | 33 | }; |
| 34 | use crate::domain::note_file::FileContentType; | 34 | use crate::domain::note_file::FileContentType; |
| 35 | use crate::domain::role::Role; | 35 | use crate::domain::role::Role; |
| 36 | use crate::domain::subject::{Subject, SubjectId}; | 36 | use crate::domain::subject::{Subject, SubjectId}; |
| 37 | use crate::domain::user::{User, UserId}; | 37 | use crate::domain::user::{User, UserId}; |
| 38 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 38 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 39 | +use crate::service::bank_question; | ||
| 40 | +use crate::service::bank_question_image; | ||
| 39 | use crate::state::AppState; | 41 | use crate::state::AppState; |
| 40 | 42 | ||
| 41 | use super::dto::person_map; | 43 | use super::dto::person_map; |
| @@ -309,7 +311,7 @@ async fn bank_images_by_question( | |||
| 309 | db: &crate::database::Database, | 311 | db: &crate::database::Database, |
| 310 | ) -> Result<HashMap<String, Vec<BankQuestionImage>>, AppError> { | 312 | ) -> Result<HashMap<String, Vec<BankQuestionImage>>, AppError> { |
| 311 | let mut buckets: HashMap<String, Vec<BankQuestionImage>> = HashMap::new(); | 313 | let mut buckets: HashMap<String, Vec<BankQuestionImage>> = HashMap::new(); |
| 312 | - for image in BankQuestionImage::list_for_questions(questions, db).await? { | 314 | + for image in bank_question_image::list_for_questions(db, questions).await? { |
| 313 | buckets | 315 | buckets |
| 314 | .entry(image.get_bank_question().key().to_string()) | 316 | .entry(image.get_bank_question().key().to_string()) |
| 315 | .or_default() | 317 | .or_default() |
| @@ -338,7 +340,7 @@ impl BankImageMeta { | |||
| 338 | 340 | ||
| 339 | /// The template, or a 404. | 341 | /// The template, or a 404. |
| 340 | async fn question_or_404(st: &AppState, bid: &str) -> Result<BankQuestion, AppError> { | 342 | async fn question_or_404(st: &AppState, bid: &str) -> Result<BankQuestion, AppError> { |
| 341 | - BankQuestion::read(&BankQuestionId::from_key(bid), &st.db) | 343 | + bank_question::read(&st.db, &BankQuestionId::from_key(bid)) |
| 342 | .await? | 344 | .await? |
| 343 | .ok_or(AppError::NotFound) | 345 | .ok_or(AppError::NotFound) |
| 344 | } | 346 | } |
| @@ -419,7 +421,10 @@ pub(crate) async fn store_image( | |||
| 419 | ) -> Result<BankQuestionImage, AppError> { | 421 | ) -> Result<BankQuestionImage, AppError> { |
| 420 | let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); | 422 | let image = BankQuestionImage::new(question, slot, content_type, data.len() as i64); |
| 421 | let file = image.get_file().to_string(); | 423 | let file = image.get_file().to_string(); |
| 422 | - store_blob(st, &file, data, || async { image.upsert(&st.db).await }).await | 424 | + store_blob(st, &file, data, || async { |
| 425 | + bank_question_image::upsert(&st.db, image).await | ||
| 426 | + }) | ||
| 427 | + .await | ||
| 423 | } | 428 | } |
| 424 | 429 | ||
| 425 | /// Add a template to the bank. Requires teacher+. `subject_id` is origin | 430 | /// Add a template to the bank. Requires teacher+. `subject_id` is origin |
| @@ -459,7 +464,7 @@ async fn create_question( | |||
| 459 | &[], | 464 | &[], |
| 460 | )?; | 465 | )?; |
| 461 | let question = | 466 | let question = |
| 462 | - BankQuestion::create(user.get_id().clone(), subject, text, points, spec, &st.db).await?; | 467 | + bank_question::create(&st.db, user.get_id().clone(), subject, text, points, spec).await?; |
| 463 | Ok(( | 468 | Ok(( |
| 464 | StatusCode::CREATED, | 469 | StatusCode::CREATED, |
| 465 | Json(BankQuestionResponse::new(&question, &[])), | 470 | Json(BankQuestionResponse::new(&question, &[])), |
| @@ -515,7 +520,8 @@ async fn list_questions( | |||
| 515 | let viewer = (!user.get_role().at_least(Role::Admin)).then(|| user.get_id().clone()); | 520 | let viewer = (!user.get_role().at_least(Role::Admin)).then(|| user.get_id().clone()); |
| 516 | // Filters, order, and window are all SQL — `total` comes from a count over | 521 | // Filters, order, and window are all SQL — `total` comes from a count over |
| 517 | // the same WHERE, so a client can page past the first window. | 522 | // the same WHERE, so a client can page past the first window. |
| 518 | - let (questions, total) = BankQuestion::list( | 523 | + let (questions, total) = bank_question::list( |
| 524 | + &st.db, | ||
| 519 | viewer.as_ref(), | 525 | viewer.as_ref(), |
| 520 | owner.as_ref(), | 526 | owner.as_ref(), |
| 521 | subject.as_ref(), | 527 | subject.as_ref(), |
| @@ -523,7 +529,6 @@ async fn list_questions( | |||
| 523 | filter.q.as_deref(), | 529 | filter.q.as_deref(), |
| 524 | limit, | 530 | limit, |
| 525 | offset, | 531 | offset, |
| 526 | - &st.db, | ||
| 527 | ) | 532 | ) |
| 528 | .await?; | 533 | .await?; |
| 529 | 534 | ||
| @@ -533,7 +538,7 @@ async fn list_questions( | |||
| 533 | let ids: Vec<&BankQuestionId> = questions.iter().map(BankQuestion::get_id).collect(); | 538 | let ids: Vec<&BankQuestionId> = questions.iter().map(BankQuestion::get_id).collect(); |
| 534 | let buckets = bank_images_by_question(&ids, &st.db).await?; | 539 | let buckets = bank_images_by_question(&ids, &st.db).await?; |
| 535 | // One grouped query for the whole page — never a count per row. | 540 | // One grouped query for the whole page — never a count per row. |
| 536 | - let used = BankQuestion::usage_counts(&ids, &st.db).await?; | 541 | + let used = bank_question::usage_counts(&st.db, &ids).await?; |
| 537 | let subject_ids: Vec<&SubjectId> = questions | 542 | let subject_ids: Vec<&SubjectId> = questions |
| 538 | .iter() | 543 | .iter() |
| 539 | .filter_map(BankQuestion::get_subject) | 544 | .filter_map(BankQuestion::get_subject) |
| @@ -596,7 +601,7 @@ async fn get_question( | |||
| 596 | Path(bid): Path<String>, | 601 | Path(bid): Path<String>, |
| 597 | ) -> Result<Json<BankQuestionResponse>, AppError> { | 602 | ) -> Result<Json<BankQuestionResponse>, AppError> { |
| 598 | let question = visible_question(&st, &user, &bid).await?; | 603 | let question = visible_question(&st, &user, &bid).await?; |
| 599 | - let images = BankQuestionImage::list_for_question(question.get_id(), &st.db).await?; | 604 | + let images = bank_question_image::list_for_question(&st.db, question.get_id()).await?; |
| 600 | Ok(Json(BankQuestionResponse::new(&question, &images))) | 605 | Ok(Json(BankQuestionResponse::new(&question, &images))) |
| 601 | } | 606 | } |
| 602 | 607 | ||
| @@ -636,62 +641,38 @@ async fn update_question( | |||
| 636 | Path(bid): Path<String>, | 641 | Path(bid): Path<String>, |
| 637 | Json(req): Json<UpdateBankQuestion>, | 642 | Json(req): Json<UpdateBankQuestion>, |
| 638 | ) -> Result<Json<BankQuestionResponse>, AppError> { | 643 | ) -> Result<Json<BankQuestionResponse>, AppError> { |
| 639 | - // Read, merge and write again while the row keeps moving underneath: the | 644 | + // Authz first (404 invisible, 403 not the owner), then the fields the |
| 640 | - // guarded write refuses on a snapshot that has gone stale, so both edits | 645 | + // request sets are validated right here; the read-merge-retry loop that |
| 641 | - // land instead of the later one reverting the earlier. | 646 | + // lands them lives in the service, which re-reads and re-merges while the |
| 642 | - let mut left = CAS_UPDATE_RETRIES; | 647 | + // row keeps moving underneath — its guarded write refuses on a snapshot |
| 643 | - let updated = loop { | 648 | + // that has gone stale, so both edits land instead of the later one |
| 644 | - let question = owned_question(&st, &user, &bid).await?; | 649 | + // reverting the earlier. |
| 645 | - // Omitted keeps the stored subject — which may already be `None`, cleared | 650 | + owned_question(&st, &user, &bid).await?; |
| 646 | - // by that subject's delete. | 651 | + let patch = bank_question::BankQuestionPatch { |
| 647 | - let subject = match req.subject_id { | 652 | + subject: match req.subject_id { |
| 648 | Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), | 653 | Some(ref subject_id) => Some(subject_must_exist(subject_id, &st.db).await?), |
| 649 | - None => question.get_subject().cloned(), | 654 | + None => None, |
| 650 | - }; | 655 | + }, |
| 651 | - let text = match req.text { | 656 | + text: match req.text { |
| 652 | - Some(ref text) => QuestionText::try_new(text)?, | 657 | + Some(ref text) => Some(QuestionText::try_new(text)?), |
| 653 | - None => question.get_text().clone(), | 658 | + None => None, |
| 654 | - }; | 659 | + }, |
| 655 | - let points = match req.points { | 660 | + points: req.points.map(QuestionPoints::try_new).transpose()?, |
| 656 | - Some(points) => QuestionPoints::try_new(points)?, | 661 | + kind: match req.kind { |
| 657 | - None => question.get_points(), | 662 | + Some(ref kind) => Some(QuestionKind::try_new(kind)?), |
| 658 | - }; | 663 | + None => None, |
| 659 | - // Merge the kind-dependent fields (set / clear / keep per field), then | 664 | + }, |
| 660 | - // re-validate them as a unit — a PATCH can't leave a half-question behind. | 665 | + // Set-or-clear spelling: omitting `choices` keeps the stored options |
| 661 | - let kind = match req.kind { | 666 | + // (re-submitted with their ids, so a text-only edit keeps every |
| 662 | - Some(ref kind) => QuestionKind::try_new(kind)?, | 667 | + // picture), resolved against a fresh read every retry round. |
| 663 | - None => question.get_kind().clone(), | 668 | + choices: req.choices.map(ChoiceBody::into_inputs), |
| 664 | - }; | 669 | + correct: req.correct, |
| 665 | - // Omitting `choices` re-submits the stored options *with their ids*, so a | 670 | + visibility: match req.visibility { |
| 666 | - // text-only edit keeps every identity (and every picture) untouched. | 671 | + Some(ref visibility) => Some(BankVisibility::try_new(visibility)?), |
| 667 | - let choices = match req.choices.clone() { | 672 | + None => None, |
| 668 | - Some(update) => ChoiceBody::into_inputs(update), | 673 | + }, |
| 669 | - None => ChoiceBody::from_stored(question.get_choices()), | ||
| 670 | - }; | ||
| 671 | - let correct = match req.correct.clone() { | ||
| 672 | - Some(update) => update, | ||
| 673 | - None => question.get_correct().map(|id| id.as_str().to_string()), | ||
| 674 | - }; | ||
| 675 | - let stored: Vec<Choice> = question.get_choices().unwrap_or_default().to_vec(); | ||
| 676 | - let spec = QuestionSpec::try_new(kind, choices, correct, &stored)?; | ||
| 677 | - let visibility = match req.visibility { | ||
| 678 | - Some(ref visibility) => BankVisibility::try_new(visibility)?, | ||
| 679 | - None => question.get_visibility().clone(), | ||
| 680 | - }; | ||
| 681 | - | ||
| 682 | - if let Some(updated) = question | ||
| 683 | - .update_if_unchanged(subject, text, points, spec, visibility, &st.db) | ||
| 684 | - .await? | ||
| 685 | - { | ||
| 686 | - break updated; | ||
| 687 | - } | ||
| 688 | - left -= 1; | ||
| 689 | - if left == 0 { | ||
| 690 | - return Err(AppError::Conflict( | ||
| 691 | - "the template kept changing underneath this update — try again", | ||
| 692 | - )); | ||
| 693 | - } | ||
| 694 | }; | 674 | }; |
| 675 | + let updated = bank_question::update(&st.db, &BankQuestionId::from_key(&bid), &patch).await?; | ||
| 695 | let bid = updated.get_id().clone(); | 676 | let bid = updated.get_id().clone(); |
| 696 | // Only the options that are actually *gone* lose their pictures — an option | 677 | // Only the options that are actually *gone* lose their pictures — an option |
| 697 | // that survives the edit keeps its image wherever it moved in the list. | 678 | // that survives the edit keeps its image wherever it moved in the list. |
| @@ -701,10 +682,10 @@ async fn update_question( | |||
| 701 | .iter() | 682 | .iter() |
| 702 | .map(|choice| choice.get_id().clone()) | 683 | .map(|choice| choice.get_id().clone()) |
| 703 | .collect(); | 684 | .collect(); |
| 704 | - for image in BankQuestionImage::delete_choices_not_in(&bid, &keep, &st.db).await? { | 685 | + for image in bank_question_image::delete_choices_not_in(&st.db, &bid, &keep).await? { |
| 705 | remove_blob(&st.files_path, image.get_file()).await; | 686 | remove_blob(&st.files_path, image.get_file()).await; |
| 706 | } | 687 | } |
| 707 | - let images = BankQuestionImage::list_for_question(updated.get_id(), &st.db).await?; | 688 | + let images = bank_question_image::list_for_question(&st.db, updated.get_id()).await?; |
| 708 | Ok(Json(BankQuestionResponse::new(&updated, &images))) | 689 | Ok(Json(BankQuestionResponse::new(&updated, &images))) |
| 709 | } | 690 | } |
| 710 | 691 | ||
| @@ -733,7 +714,7 @@ async fn delete_question( | |||
| 733 | // in between strands at worst an unreachable blob. The blobs come from what | 714 | // in between strands at worst an unreachable blob. The blobs come from what |
| 734 | // the delete *swept*, never a list read before it: an upload that landed in | 715 | // the delete *swept*, never a list read before it: an upload that landed in |
| 735 | // between is swept too, and its blob would be stranded for good. | 716 | // between is swept too, and its blob would be stranded for good. |
| 736 | - let (_, images) = question.delete(&st.db).await?; | 717 | + let (_, images) = bank_question::delete(&st.db, question).await?; |
| 737 | for image in &images { | 718 | for image in &images { |
| 738 | remove_blob(&st.files_path, image.get_file()).await; | 719 | remove_blob(&st.files_path, image.get_file()).await; |
| 739 | } | 720 | } |
| @@ -800,7 +781,7 @@ async fn get_question_image( | |||
| 800 | Path(bid): Path<String>, | 781 | Path(bid): Path<String>, |
| 801 | ) -> Result<Response, AppError> { | 782 | ) -> Result<Response, AppError> { |
| 802 | let question = visible_question(&st, &user, &bid).await?; | 783 | let question = visible_question(&st, &user, &bid).await?; |
| 803 | - let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) | 784 | + let image = bank_question_image::read_slot(&st.db, question.get_id(), None) |
| 804 | .await? | 785 | .await? |
| 805 | .ok_or(AppError::NotFound)?; | 786 | .ok_or(AppError::NotFound)?; |
| 806 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await | 787 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
| @@ -826,10 +807,10 @@ async fn delete_question_image( | |||
| 826 | Path(bid): Path<String>, | 807 | Path(bid): Path<String>, |
| 827 | ) -> Result<StatusCode, AppError> { | 808 | ) -> Result<StatusCode, AppError> { |
| 828 | let question = owned_question(&st, &user, &bid).await?; | 809 | let question = owned_question(&st, &user, &bid).await?; |
| 829 | - let image = BankQuestionImage::read_slot(question.get_id(), None, &st.db) | 810 | + let image = bank_question_image::read_slot(&st.db, question.get_id(), None) |
| 830 | .await? | 811 | .await? |
| 831 | .ok_or(AppError::NotFound)?; | 812 | .ok_or(AppError::NotFound)?; |
| 832 | - let image = image.delete(&st.db).await?; | 813 | + let image = bank_question_image::delete(&st.db, image).await?; |
| 833 | remove_blob(&st.files_path, image.get_file()).await; | 814 | remove_blob(&st.files_path, image.get_file()).await; |
| 834 | Ok(StatusCode::NO_CONTENT) | 815 | Ok(StatusCode::NO_CONTENT) |
| 835 | } | 816 | } |
| @@ -896,7 +877,7 @@ async fn get_choice_image( | |||
| 896 | ) -> Result<Response, AppError> { | 877 | ) -> Result<Response, AppError> { |
| 897 | let question = visible_question(&st, &user, &bid).await?; | 878 | let question = visible_question(&st, &user, &bid).await?; |
| 898 | let slot = bank_choice_slot(&question, &choice_id)?; | 879 | let slot = bank_choice_slot(&question, &choice_id)?; |
| 899 | - let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) | 880 | + let image = bank_question_image::read_slot(&st.db, question.get_id(), Some(&slot)) |
| 900 | .await? | 881 | .await? |
| 901 | .ok_or(AppError::NotFound)?; | 882 | .ok_or(AppError::NotFound)?; |
| 902 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await | 883 | serve_inline_blob(&st.files_path, image.get_file(), image.get_content_type()).await |
| @@ -926,10 +907,10 @@ async fn delete_choice_image( | |||
| 926 | ) -> Result<StatusCode, AppError> { | 907 | ) -> Result<StatusCode, AppError> { |
| 927 | let question = owned_question(&st, &user, &bid).await?; | 908 | let question = owned_question(&st, &user, &bid).await?; |
| 928 | let slot = bank_choice_slot(&question, &choice_id)?; | 909 | let slot = bank_choice_slot(&question, &choice_id)?; |
| 929 | - let image = BankQuestionImage::read_slot(question.get_id(), Some(&slot), &st.db) | 910 | + let image = bank_question_image::read_slot(&st.db, question.get_id(), Some(&slot)) |
| 930 | .await? | 911 | .await? |
| 931 | .ok_or(AppError::NotFound)?; | 912 | .ok_or(AppError::NotFound)?; |
| 932 | - let image = image.delete(&st.db).await?; | 913 | + let image = bank_question_image::delete(&st.db, image).await?; |
| 933 | remove_blob(&st.files_path, image.get_file()).await; | 914 | remove_blob(&st.files_path, image.get_file()).await; |
| 934 | Ok(StatusCode::NO_CONTENT) | 915 | Ok(StatusCode::NO_CONTENT) |
| 935 | } | 916 | } |
| @@ -951,7 +932,10 @@ mod tests { | |||
| 951 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) | 932 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 952 | .await | 933 | .await |
| 953 | .unwrap(); | 934 | .unwrap(); |
| 954 | - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 | 935 | + crate::service::user::set_role(db, user.get_id(), role) |
| 936 | + .await | ||
| 937 | + .unwrap() | ||
| 938 | + .0 | ||
| 955 | } | 939 | } |
| 956 | 940 | ||
| 957 | /// Every bank route is `RequireTeacher` today, so this is pinned at the | 941 | /// Every bank route is `RequireTeacher` today, so this is pinned at the |
| @@ -961,13 +945,13 @@ mod tests { | |||
| 961 | async fn demoted_owner_loses_their_own_template() { | 945 | async fn demoted_owner_loses_their_own_template() { |
| 962 | let db = init_mem().await.unwrap(); | 946 | let db = init_mem().await.unwrap(); |
| 963 | let owner = user("ogretmen", Role::Teacher, &db).await; | 947 | let owner = user("ogretmen", Role::Teacher, &db).await; |
| 964 | - let question = BankQuestion::create( | 948 | + let question = bank_question::create( |
| 949 | + &db, | ||
| 965 | owner.get_id().clone(), | 950 | owner.get_id().clone(), |
| 966 | SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), | 951 | SubjectId::from_key("01TESTSUBJECTAAAAAAAAAAAAA"), |
| 967 | QuestionText::try_new("2 + 2 = ?").unwrap(), | 952 | QuestionText::try_new("2 + 2 = ?").unwrap(), |
| 968 | QuestionPoints::try_new(1).unwrap(), | 953 | QuestionPoints::try_new(1).unwrap(), |
| 969 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), | 954 | QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), |
| 970 | - &db, | ||
| 971 | ) | 955 | ) |
| 972 | .await | 956 | .await |
| 973 | .unwrap(); | 957 | .unwrap(); |
| @@ -1008,19 +992,21 @@ mod tests { | |||
| 1008 | 992 | ||
| 1009 | // The bank is teacher+ end to end, so a school-wide row is no way in | 993 | // The bank is teacher+ end to end, so a school-wide row is no way in |
| 1010 | // either. | 994 | // either. |
| 1011 | - let question = question | 995 | + let question = bank_question::update( |
| 1012 | - .update_if_unchanged( | 996 | + &db, |
| 1013 | - None, | 997 | + question.get_id(), |
| 1014 | - QuestionText::try_new("2 + 2 = ?").unwrap(), | 998 | + &bank_question::BankQuestionPatch { |
| 1015 | - QuestionPoints::try_new(1).unwrap(), | 999 | + subject: None, |
| 1016 | - QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]) | 1000 | + text: None, |
| 1017 | - .unwrap(), | 1001 | + points: None, |
| 1018 | - BankVisibility::try_new("school").unwrap(), | 1002 | + kind: None, |
| 1019 | - &db, | 1003 | + choices: None, |
| 1020 | - ) | 1004 | + correct: None, |
| 1021 | - .await | 1005 | + visibility: Some(BankVisibility::try_new("school").unwrap()), |
| 1022 | - .unwrap() | 1006 | + }, |
| 1023 | - .expect("nothing raced this update"); | 1007 | + ) |
| 1008 | + .await | ||
| 1009 | + .unwrap(); | ||
| 1024 | let student = user("ogrenci", Role::Student, &db).await; | 1010 | let student = user("ogrenci", Role::Student, &db).await; |
| 1025 | assert!(!can_see(&question, &student)); | 1011 | assert!(!can_see(&question, &student)); |
| 1026 | assert!(can_see(&question, &admin)); | 1012 | assert!(can_see(&question, &admin)); |
src/web/exams/mod.rsmodified+0 -2
| @@ -14,8 +14,6 @@ use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | |||
| 14 | use crate::database::Database; | 14 | use crate::database::Database; |
| 15 | use crate::domain::answer_image::AnswerImage; | 15 | use crate::domain::answer_image::AnswerImage; |
| 16 | use crate::domain::badge; | 16 | use crate::domain::badge; |
| 17 | -use crate::domain::bank_question::{BankQuestion, BankQuestionId}; | ||
| 18 | -use crate::domain::bank_question_image::BankQuestionImage; | ||
| 19 | 17 | ||
| 20 | use crate::domain::exam::{ | 18 | use crate::domain::exam::{ |
| 21 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle, | 19 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, ExamTitle, |
src/web/exams/questions.rsmodified+12 -8
| @@ -1,5 +1,9 @@ | |||
| 1 | use super::*; | 1 | use super::*; |
| 2 | 2 | ||
| 3 | +use crate::domain::bank_question::BankQuestionId; | ||
| 4 | +use crate::domain::bank_question_image::BankQuestionImage; | ||
| 5 | +use crate::service::bank_question; | ||
| 6 | +use crate::service::bank_question_image; | ||
| 3 | use crate::service::exam_question; | 7 | use crate::service::exam_question; |
| 4 | 8 | ||
| 5 | // ---- questions -------------------------------------------------------------- | 9 | // ---- questions -------------------------------------------------------------- |
| @@ -477,7 +481,7 @@ pub(crate) async fn question_from_bank( | |||
| 477 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; | 481 | exam_question::ensure_questions_editable(exam.get_id(), &st.db).await?; |
| 478 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | 482 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; |
| 479 | 483 | ||
| 480 | - let template = BankQuestion::read(&BankQuestionId::from_key(&bid), &st.db) | 484 | + let template = bank_question::read(&st.db, &BankQuestionId::from_key(&bid)) |
| 481 | .await? | 485 | .await? |
| 482 | .ok_or(AppError::NotFound)?; | 486 | .ok_or(AppError::NotFound)?; |
| 483 | // A template the caller may not see is a 404, exactly as it is on the bank's | 487 | // 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( | |||
| 503 | // The copy is all-or-nothing: any mid-loop failure rolls back the fresh | 507 | // The copy is all-or-nothing: any mid-loop failure rolls back the fresh |
| 504 | // question row (its cascade drops the copied image rows) and the blobs | 508 | // question row (its cascade drops the copied image rows) and the blobs |
| 505 | // written so far, leaving the source and destination untouched. | 509 | // written so far, leaving the source and destination untouched. |
| 506 | - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | 510 | + let sources = bank_question_image::list_for_question(&st.db, template.get_id()).await?; |
| 507 | let mut copied: Vec<String> = Vec::new(); | 511 | let mut copied: Vec<String> = Vec::new(); |
| 508 | for source in &sources { | 512 | for source in &sources { |
| 509 | let step = async { | 513 | let step = async { |
| @@ -615,7 +619,7 @@ pub(crate) async fn question_refresh_from_bank( | |||
| 615 | reason: "this question did not come from a bank template", | 619 | reason: "this question did not come from a bank template", |
| 616 | })); | 620 | })); |
| 617 | }; | 621 | }; |
| 618 | - let template = BankQuestion::read(&source, &st.db) | 622 | + let template = bank_question::read(&st.db, &source) |
| 619 | .await? | 623 | .await? |
| 620 | .ok_or(AppError::NotFound)?; | 624 | .ok_or(AppError::NotFound)?; |
| 621 | if !crate::web::bank_questions::can_see(&template, &user) { | 625 | if !crate::web::bank_questions::can_see(&template, &user) { |
| @@ -627,7 +631,7 @@ pub(crate) async fn question_refresh_from_bank( | |||
| 627 | // question untouched, since a half-applied refresh has no old content left | 631 | // question untouched, since a half-applied refresh has no old content left |
| 628 | // to roll back to. Bounded — at most one illustration plus ten option | 632 | // to roll back to. Bounded — at most one illustration plus ten option |
| 629 | // pictures, each under the school's file cap. | 633 | // pictures, each under the school's file cap. |
| 630 | - let sources = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | 634 | + let sources = bank_question_image::list_for_question(&st.db, template.get_id()).await?; |
| 631 | let mut incoming: Vec<(&BankQuestionImage, Vec<u8>)> = Vec::with_capacity(sources.len()); | 635 | let mut incoming: Vec<(&BankQuestionImage, Vec<u8>)> = Vec::with_capacity(sources.len()); |
| 632 | for source in &sources { | 636 | for source in &sources { |
| 633 | let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) | 637 | let bytes = tokio::fs::read(blob_path(&st.files_path, source.get_file())) |
| @@ -735,14 +739,14 @@ pub(crate) async fn question_to_bank( | |||
| 735 | 739 | ||
| 736 | // `create_from_exam` mints its own id and insert (the funnel), fed the | 740 | // `create_from_exam` mints its own id and insert (the funnel), fed the |
| 737 | // question's fields plus the origin exam it was saved off. | 741 | // question's fields plus the origin exam it was saved off. |
| 738 | - let template = BankQuestion::create_from_exam( | 742 | + let template = bank_question::create_from_exam( |
| 743 | + &st.db, | ||
| 739 | user.get_id().clone(), | 744 | user.get_id().clone(), |
| 740 | question.get_subject().clone(), | 745 | question.get_subject().clone(), |
| 741 | question.get_text().clone(), | 746 | question.get_text().clone(), |
| 742 | question.get_points(), | 747 | question.get_points(), |
| 743 | question.spec(), | 748 | question.spec(), |
| 744 | exam.get_id().clone(), | 749 | exam.get_id().clone(), |
| 745 | - &st.db, | ||
| 746 | ) | 750 | ) |
| 747 | .await?; | 751 | .await?; |
| 748 | 752 | ||
| @@ -778,7 +782,7 @@ pub(crate) async fn question_to_bank( | |||
| 778 | for file in &copied { | 782 | for file in &copied { |
| 779 | remove_blob(&st.files_path, file).await; | 783 | remove_blob(&st.files_path, file).await; |
| 780 | } | 784 | } |
| 781 | - let _ = template.delete(&st.db).await; | 785 | + let _ = bank_question::delete(&st.db, template).await; |
| 782 | return Err(err); | 786 | return Err(err); |
| 783 | } | 787 | } |
| 784 | } | 788 | } |
| @@ -806,7 +810,7 @@ pub(crate) async fn question_to_bank( | |||
| 806 | ); | 810 | ); |
| 807 | } | 811 | } |
| 808 | 812 | ||
| 809 | - let images = BankQuestionImage::list_for_question(template.get_id(), &st.db).await?; | 813 | + let images = bank_question_image::list_for_question(&st.db, template.get_id()).await?; |
| 810 | Ok(( | 814 | Ok(( |
| 811 | StatusCode::CREATED, | 815 | StatusCode::CREATED, |
| 812 | Json(BankQuestionResponse::new(&template, &images)), | 816 | Json(BankQuestionResponse::new(&template, &images)), |
src/web/questions.rsmodified+24 -30
| @@ -27,6 +27,8 @@ use crate::domain::role::Role; | |||
| 27 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; | 27 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 28 | use crate::domain::user::User; | 28 | use crate::domain::user::User; |
| 29 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 29 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 30 | +use crate::service::pool_question; | ||
| 31 | +use crate::service::solution; | ||
| 30 | use crate::state::AppState; | 32 | use crate::state::AppState; |
| 31 | 33 | ||
| 32 | use super::{ | 34 | use super::{ |
| @@ -88,7 +90,7 @@ fn ensure_asker_editable(question: &PoolQuestion, user: &User) -> Result<(), App | |||
| 88 | } | 90 | } |
| 89 | 91 | ||
| 90 | async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppError> { | 92 | async fn question_or_404(st: &AppState, id: &str) -> Result<PoolQuestion, AppError> { |
| 91 | - PoolQuestion::read(&PoolQuestionId::from_key(id), &st.db) | 93 | + pool_question::read(&st.db, &PoolQuestionId::from_key(id)) |
| 92 | .await? | 94 | .await? |
| 93 | .ok_or(AppError::NotFound) | 95 | .ok_or(AppError::NotFound) |
| 94 | } | 96 | } |
| @@ -227,7 +229,7 @@ async fn question_responses( | |||
| 227 | .iter() | 229 | .iter() |
| 228 | .map(|question| question.get_id().clone()) | 230 | .map(|question| question.get_id().clone()) |
| 229 | .collect(); | 231 | .collect(); |
| 230 | - let counts = Solution::counts_for(&question_ids, &st.db).await?; | 232 | + let counts = solution::counts_for(&st.db, &question_ids).await?; |
| 231 | Ok(questions | 233 | Ok(questions |
| 232 | .iter() | 234 | .iter() |
| 233 | .map(|question| { | 235 | .map(|question| { |
| @@ -266,9 +268,8 @@ async fn ask_question( | |||
| 266 | } | 268 | } |
| 267 | let title = PoolQuestionTitle::try_new(&req.title)?; | 269 | let title = PoolQuestionTitle::try_new(&req.title)?; |
| 268 | let body = PoolQuestionBody::try_new(&req.body)?; | 270 | let body = PoolQuestionBody::try_new(&req.body)?; |
| 269 | - let question = PoolQuestion::new(user.get_id(), title, body) | 271 | + let question = |
| 270 | - .insert(&st.db) | 272 | + pool_question::insert(&st.db, PoolQuestion::new(user.get_id(), title, body)).await?; |
| 271 | - .await?; | ||
| 272 | let responses = question_responses(std::slice::from_ref(&question), &st).await?; | 273 | let responses = question_responses(std::slice::from_ref(&question), &st).await?; |
| 273 | let response = responses | 274 | let response = responses |
| 274 | .into_iter() | 275 | .into_iter() |
| @@ -311,9 +312,9 @@ async fn list_questions( | |||
| 311 | } | 312 | } |
| 312 | 313 | ||
| 313 | let mut questions = if user.get_role().at_least(Role::Teacher) { | 314 | let mut questions = if user.get_role().at_least(Role::Teacher) { |
| 314 | - PoolQuestion::list_all(&st.db).await? | 315 | + pool_question::list_all(&st.db).await? |
| 315 | } else { | 316 | } else { |
| 316 | - PoolQuestion::list_visible_to(user.get_id(), &st.db).await? | 317 | + pool_question::list_visible_to(&st.db, user.get_id()).await? |
| 317 | }; | 318 | }; |
| 318 | if let Some(ref status) = filter.status { | 319 | if let Some(ref status) = filter.status { |
| 319 | questions.retain(|question| question.get_status() == status); | 320 | questions.retain(|question| question.get_status() == status); |
| @@ -377,17 +378,8 @@ async fn approve_question( | |||
| 377 | RequireTeacher(user): RequireTeacher, | 378 | RequireTeacher(user): RequireTeacher, |
| 378 | Path(id): Path<String>, | 379 | Path(id): Path<String>, |
| 379 | ) -> Result<Json<PoolQuestionResponse>, AppError> { | 380 | ) -> Result<Json<PoolQuestionResponse>, AppError> { |
| 380 | - let approved = | 381 | + let question = |
| 381 | - PoolQuestion::approve(&PoolQuestionId::from_key(&id), user.get_id(), &st.db).await?; | 382 | + pool_question::approve(&st.db, &PoolQuestionId::from_key(&id), user.get_id()).await?; |
| 382 | - let question = match approved { | ||
| 383 | - Some(question) => question, | ||
| 384 | - // Nothing was pending under that id: either it's already approved | ||
| 385 | - // (409) or it never existed / was deleted (404). | ||
| 386 | - None => { | ||
| 387 | - question_or_404(&st, &id).await?; | ||
| 388 | - return Err(AppError::Conflict("the question is already approved")); | ||
| 389 | - } | ||
| 390 | - }; | ||
| 391 | // Both counters moved inside the approval's own transaction; the badges | 383 | // Both counters moved inside the approval's own transaction; the badges |
| 392 | // they may have earned are a decoration on top of it. Losing one to a | 384 | // they may have earned are a decoration on top of it. Losing one to a |
| 393 | // transient database error must never fail the approval behind it, and the | 385 | // transient database error must never fail the approval behind it, and the |
| @@ -435,7 +427,7 @@ async fn delete_question( | |||
| 435 | "only the asker or a teacher+ may delete a question", | 427 | "only the asker or a teacher+ may delete a question", |
| 436 | )); | 428 | )); |
| 437 | } | 429 | } |
| 438 | - let (removed, swept) = PoolQuestion::delete(question.get_id(), &st.db) | 430 | + let (removed, swept) = pool_question::delete(&st.db, question.get_id()) |
| 439 | .await? | 431 | .await? |
| 440 | .ok_or(AppError::NotFound)?; | 432 | .ok_or(AppError::NotFound)?; |
| 441 | // Rows went first (in one transaction); now every blob they pointed at — | 433 | // Rows went first (in one transaction); now every blob they pointed at — |
| @@ -493,7 +485,7 @@ async fn upload_image( | |||
| 493 | 485 | ||
| 494 | let file = ulid::Ulid::new().to_string(); | 486 | let file = ulid::Ulid::new().to_string(); |
| 495 | store_blob(&st, &file, &upload.data, || async { | 487 | store_blob(&st, &file, &upload.data, || async { |
| 496 | - match PoolQuestion::set_image(question.get_id(), &file, &upload.content_type, size, &st.db) | 488 | + match pool_question::set_image(&st.db, question.get_id(), &file, &upload.content_type, size) |
| 497 | .await? | 489 | .await? |
| 498 | { | 490 | { |
| 499 | // The guarded UPDATE found the question still pending: point-of-truth | 491 | // The guarded UPDATE found the question still pending: point-of-truth |
| @@ -569,7 +561,7 @@ async fn delete_image( | |||
| 569 | if question.get_image_file().is_none() { | 561 | if question.get_image_file().is_none() { |
| 570 | return Err(AppError::NotFound); | 562 | return Err(AppError::NotFound); |
| 571 | } | 563 | } |
| 572 | - let before = PoolQuestion::clear_image(question.get_id(), &st.db) | 564 | + let before = pool_question::clear_image(&st.db, question.get_id()) |
| 573 | .await? | 565 | .await? |
| 574 | .ok_or(AppError::Conflict("the question is no longer pending"))?; | 566 | .ok_or(AppError::Conflict("the question is no longer pending"))?; |
| 575 | if let Some(file) = before.get_image_file() { | 567 | if let Some(file) = before.get_image_file() { |
| @@ -591,7 +583,7 @@ async fn visible_solution( | |||
| 591 | ) -> Result<Solution, AppError> { | 583 | ) -> Result<Solution, AppError> { |
| 592 | let question = question_or_404(st, id).await?; | 584 | let question = question_or_404(st, id).await?; |
| 593 | ensure_visible(&question, user)?; | 585 | ensure_visible(&question, user)?; |
| 594 | - Solution::read_for(&SolutionId::from_key(sid), question.get_id(), &st.db) | 586 | + solution::read_for(&st.db, &SolutionId::from_key(sid), question.get_id()) |
| 595 | .await? | 587 | .await? |
| 596 | .ok_or(AppError::NotFound) | 588 | .ok_or(AppError::NotFound) |
| 597 | } | 589 | } |
| @@ -648,9 +640,11 @@ async fn offer_solution( | |||
| 648 | )); | 640 | )); |
| 649 | } | 641 | } |
| 650 | let body = SolutionBody::try_new(&req.body)?; | 642 | let body = SolutionBody::try_new(&req.body)?; |
| 651 | - let solution = Solution::new(question.get_id(), user.get_id(), body) | 643 | + let solution = solution::insert( |
| 652 | - .insert(&st.db) | 644 | + &st.db, |
| 653 | - .await?; | 645 | + Solution::new(question.get_id(), user.get_id(), body), |
| 646 | + ) | ||
| 647 | + .await?; | ||
| 654 | let people = person_map([user.get_id().clone()], &st.db).await?; | 648 | let people = person_map([user.get_id().clone()], &st.db).await?; |
| 655 | Ok(( | 649 | Ok(( |
| 656 | StatusCode::CREATED, | 650 | StatusCode::CREATED, |
| @@ -683,7 +677,7 @@ async fn list_solutions( | |||
| 683 | let (limit, offset) = page.resolve()?; | 677 | let (limit, offset) = page.resolve()?; |
| 684 | let question = question_or_404(&st, &id).await?; | 678 | let question = question_or_404(&st, &id).await?; |
| 685 | ensure_visible(&question, &user)?; | 679 | ensure_visible(&question, &user)?; |
| 686 | - let (solutions, total) = Solution::list_for(question.get_id(), limit, offset, &st.db).await?; | 680 | + let (solutions, total) = solution::list_for(&st.db, question.get_id(), limit, offset).await?; |
| 687 | let slice = solutions.as_slice(); | 681 | let slice = solutions.as_slice(); |
| 688 | let people = person_map( | 682 | let people = person_map( |
| 689 | slice.iter().map(|solution| solution.get_author().clone()), | 683 | slice.iter().map(|solution| solution.get_author().clone()), |
| @@ -728,7 +722,7 @@ async fn delete_solution( | |||
| 728 | } | 722 | } |
| 729 | // Row first, blob after — a crash in between strands at worst an | 723 | // Row first, blob after — a crash in between strands at worst an |
| 730 | // unreachable file. | 724 | // unreachable file. |
| 731 | - let deleted = solution.delete(&st.db).await?; | 725 | + let deleted = solution::delete(&st.db, solution).await?; |
| 732 | if let Some(file) = deleted.get_image_file() { | 726 | if let Some(file) = deleted.get_image_file() { |
| 733 | remove_blob(&st.files_path, file).await; | 727 | remove_blob(&st.files_path, file).await; |
| 734 | } | 728 | } |
| @@ -767,7 +761,7 @@ async fn edit_solution( | |||
| 767 | ) -> Result<Json<SolutionResponse>, AppError> { | 761 | ) -> Result<Json<SolutionResponse>, AppError> { |
| 768 | let solution = author_solution(&st, &user, &id, &sid).await?; | 762 | let solution = author_solution(&st, &user, &id, &sid).await?; |
| 769 | let body = SolutionBody::try_new(&req.body)?; | 763 | let body = SolutionBody::try_new(&req.body)?; |
| 770 | - let updated = Solution::set_body(solution.get_id(), &body, &st.db) | 764 | + let updated = solution::set_body(&st.db, solution.get_id(), &body) |
| 771 | .await? | 765 | .await? |
| 772 | .ok_or(AppError::NotFound)?; | 766 | .ok_or(AppError::NotFound)?; |
| 773 | let people = person_map([user.get_id().clone()], &st.db).await?; | 767 | let people = person_map([user.get_id().clone()], &st.db).await?; |
| @@ -817,7 +811,7 @@ async fn upload_solution_image( | |||
| 817 | 811 | ||
| 818 | let file = ulid::Ulid::new().to_string(); | 812 | let file = ulid::Ulid::new().to_string(); |
| 819 | store_blob(&st, &file, &upload.data, || async { | 813 | store_blob(&st, &file, &upload.data, || async { |
| 820 | - match Solution::set_image(solution.get_id(), &file, &upload.content_type, size, &st.db) | 814 | + match solution::set_image(&st.db, solution.get_id(), &file, &upload.content_type, size) |
| 821 | .await? | 815 | .await? |
| 822 | { | 816 | { |
| 823 | // Row write done; the replaced blob (if any) comes off disk. | 817 | // Row write done; the replaced blob (if any) comes off disk. |
| @@ -896,7 +890,7 @@ async fn delete_solution_image( | |||
| 896 | if solution.get_image_file().is_none() { | 890 | if solution.get_image_file().is_none() { |
| 897 | return Err(AppError::NotFound); | 891 | return Err(AppError::NotFound); |
| 898 | } | 892 | } |
| 899 | - let before = Solution::clear_image(solution.get_id(), &st.db) | 893 | + let before = solution::clear_image(&st.db, solution.get_id()) |
| 900 | .await? | 894 | .await? |
| 901 | .ok_or(AppError::NotFound)?; | 895 | .ok_or(AppError::NotFound)?; |
| 902 | if let Some(file) = before.get_image_file() { | 896 | if let Some(file) = before.get_image_file() { |
tests/integration.rsmodified+15 -14
| @@ -20670,7 +20670,8 @@ async fn linking_the_banked_template_does_not_clobber_a_concurrent_edit() { | |||
| 20670 | /// A whole-row save from the stale struct would resurrect the dead exam link. | 20670 | /// A whole-row save from the stale struct would resurrect the dead exam link. |
| 20671 | #[tokio::test] | 20671 | #[tokio::test] |
| 20672 | async fn a_bank_patch_does_not_clobber_a_concurrent_write() { | 20672 | async fn a_bank_patch_does_not_clobber_a_concurrent_write() { |
| 20673 | - use hezarfen_backend::domain::bank_question::{BankQuestion, BankQuestionId, BankVisibility}; | 20673 | + use hezarfen_backend::db::bank_question::{read, update_if_unchanged}; |
| 20674 | + use hezarfen_backend::domain::bank_question::{BankQuestionId, BankVisibility}; | ||
| 20674 | use hezarfen_backend::domain::exam_question::{ | 20675 | use hezarfen_backend::domain::exam_question::{ |
| 20675 | QuestionKind, QuestionPoints, QuestionSpec, QuestionText, | 20676 | QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 20676 | }; | 20677 | }; |
| @@ -20702,7 +20703,7 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { | |||
| 20702 | 20703 | ||
| 20703 | // The handler's read, then the exam delete lands mid-window and clears the | 20704 | // The handler's read, then the exam delete lands mid-window and clears the |
| 20704 | // template's `source_exam`. | 20705 | // template's `source_exam`. |
| 20705 | - let stale = BankQuestion::read(&BankQuestionId::from_key(&bid), &db) | 20706 | + let stale = read(&db, &BankQuestionId::from_key(&bid)) |
| 20706 | .await | 20707 | .await |
| 20707 | .unwrap() | 20708 | .unwrap() |
| 20708 | .expect("template exists"); | 20709 | .expect("template exists"); |
| @@ -20718,18 +20719,18 @@ async fn a_bank_patch_does_not_clobber_a_concurrent_write() { | |||
| 20718 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); | 20719 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 20719 | 20720 | ||
| 20720 | // The stale struct writes its own fields only. | 20721 | // The stale struct writes its own fields only. |
| 20721 | - let updated = stale | 20722 | + let updated = update_if_unchanged( |
| 20722 | - .update_if_unchanged( | 20723 | + &db, |
| 20723 | - None, | 20724 | + stale, |
| 20724 | - QuestionText::try_new("edited").unwrap(), | 20725 | + None, |
| 20725 | - QuestionPoints::try_new(7).unwrap(), | 20726 | + QuestionText::try_new("edited").unwrap(), |
| 20726 | - QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), | 20727 | + QuestionPoints::try_new(7).unwrap(), |
| 20727 | - BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), | 20728 | + QuestionSpec::try_new(QuestionKind::try_new("text").unwrap(), None, None, &[]).unwrap(), |
| 20728 | - &db, | 20729 | + BankVisibility::try_new(BANK_VISIBILITY_SCHOOL).unwrap(), |
| 20729 | - ) | 20730 | + ) |
| 20730 | - .await | 20731 | + .await |
| 20731 | - .expect("update ran") | 20732 | + .expect("update ran") |
| 20732 | - .expect("update written — the exam delete touched no compared column"); | 20733 | + .expect("update written — the exam delete touched no compared column"); |
| 20733 | assert_eq!(updated.get_text().as_str(), "edited"); | 20734 | assert_eq!(updated.get_text().as_str(), "edited"); |
| 20734 | assert!( | 20735 | assert!( |
| 20735 | updated.get_source_exam().is_none(), | 20736 | updated.get_source_exam().is_none(), |
tests/regress_bank_images.rsmodified+5 -16
| @@ -29,6 +29,7 @@ use axum::http::StatusCode; | |||
| 29 | use common::{create_course, create_subject, id_of, login_as, send}; | 29 | use common::{create_course, create_subject, id_of, login_as, send}; |
| 30 | use hezarfen_backend::build_router; | 30 | use hezarfen_backend::build_router; |
| 31 | use hezarfen_backend::database::Database; | 31 | use hezarfen_backend::database::Database; |
| 32 | +use hezarfen_backend::db::bank_question_image::{list_for_question, upsert}; | ||
| 32 | use hezarfen_backend::domain::bank_question::BankQuestionId; | 33 | use hezarfen_backend::domain::bank_question::BankQuestionId; |
| 33 | use hezarfen_backend::domain::bank_question_image::BankQuestionImage; | 34 | use hezarfen_backend::domain::bank_question_image::BankQuestionImage; |
| 34 | use hezarfen_backend::domain::note_file::FileContentType; | 35 | use hezarfen_backend::domain::note_file::FileContentType; |
| @@ -136,9 +137,7 @@ async fn an_image_write_under_a_missing_template_is_refused() { | |||
| 136 | assert_eq!(dropped.status, StatusCode::NO_CONTENT); | 137 | assert_eq!(dropped.status, StatusCode::NO_CONTENT); |
| 137 | 138 | ||
| 138 | let question = BankQuestionId::from_key(&bid); | 139 | let question = BankQuestionId::from_key(&bid); |
| 139 | - let refused = BankQuestionImage::new(&question, None, png(), 3) | 140 | + let refused = upsert(&db, BankQuestionImage::new(&question, None, png(), 3)).await; |
| 140 | - .upsert(&db) | ||
| 141 | - .await; | ||
| 142 | assert!( | 141 | assert!( |
| 143 | matches!(refused, Err(AppError::NotFound)), | 142 | matches!(refused, Err(AppError::NotFound)), |
| 144 | "a slot write under a deleted template must be refused: {refused:?}" | 143 | "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() { | |||
| 146 | // Stored state is the verdict — a refusal that still wrote the row would be | 145 | // Stored state is the verdict — a refusal that still wrote the row would be |
| 147 | // the very defect this pins. | 146 | // the very defect this pins. |
| 148 | assert!( | 147 | assert!( |
| 149 | - BankQuestionImage::list_for_question(&question, &db) | 148 | + list_for_question(&db, &question).await.unwrap().is_empty(), |
| 150 | - .await | ||
| 151 | - .unwrap() | ||
| 152 | - .is_empty(), | ||
| 153 | "the refused write left an orphan row" | 149 | "the refused write left an orphan row" |
| 154 | ); | 150 | ); |
| 155 | } | 151 | } |
| @@ -180,9 +176,7 @@ async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() { | |||
| 180 | "a replace retires the blob it replaced: {after:?}" | 176 | "a replace retires the blob it replaced: {after:?}" |
| 181 | ); | 177 | ); |
| 182 | let question = BankQuestionId::from_key(&bid); | 178 | let question = BankQuestionId::from_key(&bid); |
| 183 | - let rows = BankQuestionImage::list_for_question(&question, &db) | 179 | + let rows = list_for_question(&db, &question).await.unwrap(); |
| 184 | - .await | ||
| 185 | - .unwrap(); | ||
| 186 | assert_eq!(rows.len(), 1, "one row per slot"); | 180 | assert_eq!(rows.len(), 1, "one row per slot"); |
| 187 | assert_eq!( | 181 | assert_eq!( |
| 188 | after, | 182 | after, |
| @@ -204,10 +198,5 @@ async fn a_replace_retires_one_blob_and_a_delete_takes_the_rest() { | |||
| 204 | "the delete left a blob behind: {:?}", | 198 | "the delete left a blob behind: {:?}", |
| 205 | blobs(&files) | 199 | blobs(&files) |
| 206 | ); | 200 | ); |
| 207 | - assert!( | 201 | + assert!(list_for_question(&db, &question).await.unwrap().is_empty()); |
| 208 | - BankQuestionImage::list_for_question(&question, &db) | ||
| 209 | - .await | ||
| 210 | - .unwrap() | ||
| 211 | - .is_empty() | ||
| 212 | - ); | ||
| 213 | } | 202 | } |