forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

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

pool_question.rs796 lines, 32.2 KiBHistoryRawDownload
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. The pure entity and
4//! newtypes live in [`crate::domain::pool_question`]; the web layer reaches
5//! these through [`crate::service::pool_question`].
6
7use crate::constant::{STATUS_APPROVED, STATUS_PENDING};
8use crate::database::{Database, tx_with_retry};
9use crate::db::page::{PagedList, Param};
10use crate::domain::note_file::FileContentType;
11use crate::domain::pool_question::{
12 PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle,
13};
14use crate::domain::solution::{Solution, SolutionBody, SolutionId};
15use crate::domain::timestamp::Timestamp;
16use crate::domain::user::UserId;
17use crate::error::AppError;
18
19pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> {
20 let row = sqlx::query_as!(
21 PoolQuestion,
22 r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at)
23 VALUES ($1, $2, $3, $4, $5, $6)
24 RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId",
25 title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
26 status, asked_at AS "asked_at: Timestamp",
27 approved_by AS "approved_by: UserId""#,
28 question.id.uuid(),
29 question.asker.uuid(),
30 question.title.as_str(),
31 question.body.as_str(),
32 question.status,
33 question.asked_at.as_millis(),
34 )
35 .fetch_one(db)
36 .await?;
37 Ok(row)
38}
39
40pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> {
41 let row = sqlx::query_as!(
42 PoolQuestion,
43 r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId",
44 title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
45 status, asked_at AS "asked_at: Timestamp",
46 approved_by AS "approved_by: UserId"
47 FROM pool_question WHERE id = $1"#,
48 id.uuid()
49 )
50 .fetch_optional(db)
51 .await?;
52 Ok(row)
53}
54
55/// One page of the question list, newest first — plus the `total` count of
56/// every row under the *same* filters, so a client can page past the window.
57///
58/// `viewer` is the security gate, and it is a WHERE clause, never a
59/// post-filter: `None` (teacher+ only) sees every row — the approval queue
60/// and the pool together; `Some(me)` sees every `approved` question plus
61/// their own pending ones. `status` is the caller's filter, ANDed on top of
62/// that gate so it can only ever narrow: `pending` for a student is exactly
63/// their own unapproved questions, `approved` the pool, and for teacher+
64/// `pending` is the approval queue. Gate and filter share one statement pair
65/// ([`PagedList`]: the shape is runtime-conditional, that builder's named
66/// exemption from the compile-time macros), so a `pending` request never
67/// loads the approved pool into a `Vec` first and `total` can never disagree
68/// with what paging through the list actually yields.
69pub async fn list(
70 db: &Database,
71 viewer: Option<&UserId>,
72 status: Option<&str>,
73 limit: Option<i64>,
74 offset: i64,
75) -> Result<(Vec<PoolQuestion>, i64), AppError> {
76 let mut clauses: Vec<String> = Vec::new();
77 let mut binds: Vec<Param> = Vec::new();
78 if let Some(viewer) = viewer {
79 binds.push(Param::Text(STATUS_APPROVED.to_string()));
80 let pool_arm = format!("status = ${}", binds.len());
81 binds.push(Param::Uuid(viewer.uuid()));
82 let own_arm = format!("asker = ${}", binds.len());
83 clauses.push(format!("({pool_arm} OR {own_arm})"));
84 }
85 if let Some(status) = status {
86 binds.push(Param::Text(status.to_string()));
87 clauses.push(format!("status = ${}", binds.len()));
88 }
89 let from_where = if clauses.is_empty() {
90 "pool_question WHERE true".to_string()
91 } else {
92 format!("pool_question WHERE {}", clauses.join(" AND "))
93 };
94 let mut page = PagedList::new(from_where, "ORDER BY asked_at DESC, id DESC");
95 for bind in binds {
96 page = page.bind(bind);
97 }
98 page.run(limit, offset, db).await
99}
100
101/// Publish a pending question into the pool, stamping who approved it.
102/// The `WHERE status = 'pending'` guard makes the transition atomic: of two
103/// racing approvals exactly one wins, and an approve can never land on a
104/// question deleted mid-flight. `None` = the question wasn't pending
105/// (already approved, or gone) — the caller sorts out which.
106///
107/// Two lifetime badge counters ride that same guard inside this
108/// transaction: the approver's `pool_approved_total` and the *asker's*
109/// `pool_published_total`. Both move only when the guard's own verdict
110/// landed, so the pair moves once per real transition and never on a second
111/// approve of an already-approved question.
112///
113/// Two rules keep the pair unfarmable, one per side of the transition.
114///
115/// The asker is credited at *approval*, not at asking: a bare
116/// [`insert`] is self-service and the author can
117/// delete their own question and ask again forever, so a counter moved
118/// there is farmable. Approval is teacher-gated and one-way, which is why
119/// the family is named `pool_published` and not `pool_asked`. That closes
120/// the student side.
121///
122/// And a *self*-approval — a teacher+ approving a question they asked
123/// themselves, which the route deliberately still allows — moves neither
124/// counter. It is the same farm from the other end (ask, approve, delete,
125/// repeat, with no second person involved), and the two together are why a
126/// counter can only move when one person's work was judged by another's.
127/// Nothing else about a self-approval changes: same 200, same freeze, same
128/// stamp — this skips the credit, not the approval.
129///
130/// Rides the retry loop because the counter bumps lock user rows every
131/// other counter site writes too; a deadlock between two approvals takes a
132/// round and lands the next attempt.
133pub async fn approve(
134 db: &Database,
135 id: &PoolQuestionId,
136 approver: &UserId,
137) -> Result<Option<PoolQuestion>, AppError> {
138 let id = *id;
139 let approver = *approver;
140 tx_with_retry(db, false, async move |tx| {
141 let approved = sqlx::query_as!(
142 PoolQuestion,
143 r#"UPDATE pool_question SET status = $2, approved_by = $3
144 WHERE id = $1 AND status = $4
145 RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId",
146 title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
147 status, asked_at AS "asked_at: Timestamp",
148 approved_by AS "approved_by: UserId""#,
149 id.uuid(),
150 STATUS_APPROVED,
151 approver.uuid(),
152 STATUS_PENDING,
153 )
154 .fetch_optional(&mut *tx)
155 .await?;
156 if let Some(question) = &approved
157 && question.asker != approver
158 {
159 // The counter columns are NOT NULL DEFAULT 0 — the old
160 // absent-reads-as-zero coalesce is gone with the schema.
161 sqlx::query!(
162 "UPDATE app_user SET pool_approved_total = pool_approved_total + 1
163 WHERE id = $1",
164 approver.uuid()
165 )
166 .execute(&mut *tx)
167 .await?;
168 sqlx::query!(
169 "UPDATE app_user SET pool_published_total = pool_published_total + 1
170 WHERE id = $1",
171 question.asker.uuid()
172 )
173 .execute(&mut *tx)
174 .await?;
175 }
176 Ok(approved)
177 })
178 .await
179}
180
181/// Point the question at a freshly written image blob. Guarded on `pending`
182/// for the same reason approval is: an image landing after approval would
183/// put unmoderated bytes in the pool, so an upload that loses the race gets
184/// `Ok(None)` (and the caller takes the orphan blob back off disk).
185/// `Ok(Some(replaced))` names the blob this upload displaced — the caller's
186/// to remove, `None` inside when nothing was there before.
187///
188/// The photo is its own row in `pool_question_image` (the child-table shape
189/// of `question_image`), so the write is that row's upsert; the parent's
190/// `FOR UPDATE` row lock still makes the pending check and the write one
191/// switch — a racing approve either predates this transaction's snapshot or
192/// waits on the lock, so a fresh image can never straddle an approval. The
193/// replaced name is read *inside the same transaction*, not by the caller
194/// before it: two uploads to one question both write this row, so they
195/// contend on it and the loser re-reads the winner's blob name — the
196/// discipline `crate::db::question_image::upsert` documents.
197pub async fn set_image(
198 db: &Database,
199 id: &PoolQuestionId,
200 file: &str,
201 content_type: &FileContentType,
202 size: i64,
203) -> Result<Option<Option<String>>, AppError> {
204 let id = *id;
205 let file = file.to_owned();
206 let content_type = content_type.clone();
207 tx_with_retry(db, false, async move |tx| {
208 let before = sqlx::query!(
209 r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#,
210 id.uuid()
211 )
212 .fetch_optional(&mut *tx)
213 .await?;
214 let Some(before) = before else {
215 return Ok(None);
216 };
217 if before.status != STATUS_PENDING {
218 return Ok(None);
219 }
220 let replaced = sqlx::query_scalar!(
221 r#"SELECT file FROM pool_question_image WHERE question = $1"#,
222 id.uuid()
223 )
224 .fetch_optional(&mut *tx)
225 .await?;
226 sqlx::query!(
227 r#"INSERT INTO pool_question_image (question, file, content_type, size)
228 VALUES ($1, $2, $3, $4)
229 ON CONFLICT (question) DO UPDATE
230 SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
231 size = EXCLUDED.size"#,
232 id.uuid(),
233 file,
234 content_type.as_str(),
235 size,
236 )
237 .execute(&mut *tx)
238 .await?;
239 Ok(Some(replaced))
240 })
241 .await
242}
243
244/// Detach the question's image (pending only, like [`set_image`]).
245/// `Ok(None)` = the question is gone or no longer pending;
246/// `Ok(Some(detached))` names the blob the caller removes — `None` inside
247/// when the question carried no image (the route answers that 404).
248pub async fn clear_image(
249 db: &Database,
250 id: &PoolQuestionId,
251) -> Result<Option<Option<String>>, AppError> {
252 let id = *id;
253 tx_with_retry(db, false, async move |tx| {
254 let before = sqlx::query!(
255 r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#,
256 id.uuid()
257 )
258 .fetch_optional(&mut *tx)
259 .await?;
260 let Some(before) = before else {
261 return Ok(None);
262 };
263 if before.status != STATUS_PENDING {
264 return Ok(None);
265 }
266 let detached = sqlx::query_scalar!(
267 r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#,
268 id.uuid()
269 )
270 .fetch_optional(&mut *tx)
271 .await?;
272 Ok(Some(detached))
273 })
274 .await
275}
276
277/// What [`delete`] took with the question: the rows ride back for their
278/// ids, and `image_files` is the caller's disk-GC list — the question's
279/// photo and every swept solution's.
280#[derive(Debug)]
281pub struct Deleted {
282 pub question: PoolQuestion,
283 pub solutions: Vec<Solution>,
284 pub image_files: Vec<String>,
285}
286
287/// Delete the question and its solutions in one transaction, returning the
288/// removed rows plus every image blob key the two kinds of rows named, so
289/// the caller can take every blob off disk (solutions carry photos too, and
290/// a row-only sweep would strand theirs forever).
291///
292/// Children before the parent, so the foreign keys never refuse the parent
293/// delete — the photo rows first (they name their parents), then the
294/// solutions, then the question. `cascade = true` because a solution offer
295/// committing inside this window makes the parent delete answer 23503 — a
296/// mid-cascade race the retry loop re-runs, sweeping the latecomer with it.
297/// That foreign key is also what keeps a solution from outliving its
298/// question on the insert side, so the old existence-move transaction is
299/// simply gone.
300pub async fn delete(db: &Database, id: &PoolQuestionId) -> Result<Option<Deleted>, AppError> {
301 let id = *id;
302 tx_with_retry(db, true, async move |tx| {
303 let solution_files = sqlx::query_scalar!(
304 r#"DELETE FROM solution_image si
305 USING solution s
306 WHERE si.solution = s.id AND s.question = $1
307 RETURNING si.file"#,
308 id.uuid()
309 )
310 .fetch_all(&mut *tx)
311 .await?;
312 let solutions = sqlx::query_as!(
313 Solution,
314 r#"DELETE FROM solution WHERE question = $1
315 RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId",
316 author AS "author: UserId", body AS "body: SolutionBody",
317 offered_at AS "offered_at: Timestamp""#,
318 id.uuid()
319 )
320 .fetch_all(&mut *tx)
321 .await?;
322 let question_file = sqlx::query_scalar!(
323 r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#,
324 id.uuid()
325 )
326 .fetch_optional(&mut *tx)
327 .await?;
328 let question = sqlx::query_as!(
329 PoolQuestion,
330 r#"DELETE FROM pool_question WHERE id = $1
331 RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId",
332 title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody",
333 status, asked_at AS "asked_at: Timestamp",
334 approved_by AS "approved_by: UserId""#,
335 id.uuid()
336 )
337 .fetch_optional(&mut *tx)
338 .await?;
339 Ok(question.map(|question| {
340 let mut image_files = solution_files;
341 image_files.extend(question_file);
342 Deleted {
343 question,
344 solutions,
345 image_files,
346 }
347 }))
348 })
349 .await
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355 use crate::database;
356 use crate::domain::solution::SolutionBody;
357 use sqlx::Row as _;
358
359 /// A real `app_user` row: the asker and the approver are foreign keys on
360 /// the question, and the counters are plain `NOT NULL DEFAULT 0` columns.
361 async fn a_user(db: &Database) -> UserId {
362 let user = UserId::generate();
363 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
364 .bind(user.uuid())
365 .bind(format!("u{}", &user.key()[30..]))
366 .execute(db)
367 .await
368 .unwrap();
369 user
370 }
371
372 /// `(pool_approved_total, pool_published_total)` as stored — the columns
373 /// read zero on a fresh row, the way `BadgeStats::load` reads them.
374 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
375 let row = sqlx::query(
376 "SELECT pool_approved_total, pool_published_total \
377 FROM app_user WHERE id = $1",
378 )
379 .bind(user.uuid())
380 .fetch_one(db)
381 .await
382 .unwrap();
383 (
384 row.try_get::<i64, _>(0).unwrap(),
385 row.try_get::<i64, _>(1).unwrap(),
386 )
387 }
388
389 fn question(asker: &UserId) -> PoolQuestion {
390 use crate::domain::pool_question::{PoolQuestionBody, PoolQuestionTitle};
391 PoolQuestion::new(
392 asker,
393 PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(),
394 PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(),
395 )
396 }
397
398 #[tokio::test]
399 async fn approval_is_a_one_way_race_safe_transition() {
400 let (db, _leases) = database::init_test_db().await;
401 let asker = a_user(&db).await;
402 let teacher = a_user(&db).await;
403
404 let q = insert(&db, question(&asker)).await.unwrap();
405 assert_eq!(q.get_status(), STATUS_PENDING);
406 assert!(q.get_approved_by().is_none());
407
408 let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap();
409 assert!(approved.is_approved());
410 assert_eq!(approved.get_approved_by(), Some(&teacher));
411
412 // A second approval finds nothing pending.
413 assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none());
414 // And a missing question approves to None, not an error.
415 assert!(
416 approve(&db, &PoolQuestionId::generate(), &teacher)
417 .await
418 .unwrap()
419 .is_none()
420 );
421 }
422 /// The publish counters ride the guard, so they move exactly once per real
423 /// transition: the approver's on the approve side, the asker's on the
424 /// published side, and neither on a second approve of the same question.
425 #[tokio::test]
426 async fn approval_moves_both_counters_once_and_only_once() {
427 let (db, _leases) = database::init_test_db().await;
428 let asker = a_user(&db).await;
429 let teacher = a_user(&db).await;
430
431 let q = insert(&db, question(&asker)).await.unwrap();
432 assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero");
433
434 approve(&db, q.get_id(), &teacher).await.unwrap().unwrap();
435 assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver");
436 assert_eq!(counters(&asker, &db).await, (0, 1), "the asker");
437
438 // The guard finds nothing pending, so neither counter may move — this
439 // is what stops an approve loop from farming either one.
440 assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none());
441 assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve");
442 assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish");
443
444 // And an approve that lands on nothing at all writes nothing.
445 assert!(
446 approve(&db, &PoolQuestionId::generate(), &teacher)
447 .await
448 .unwrap()
449 .is_none()
450 );
451 assert_eq!(counters(&teacher, &db).await, (1, 0));
452 }
453
454 /// A teacher may ask a question and the route does not bar them from
455 /// approving it — that still works, unchanged. What it does not do is pay
456 /// for itself: ask, approve, delete, repeat is the staff-side farm, and
457 /// neither counter moves when one person is both ends of the transition.
458 #[tokio::test]
459 async fn self_approval_still_approves_but_moves_neither_counter() {
460 let (db, _leases) = database::init_test_db().await;
461 let teacher = a_user(&db).await;
462
463 let q = insert(&db, question(&teacher)).await.unwrap();
464 let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap();
465 // The approval itself is untouched: published, stamped, frozen.
466 assert!(approved.is_approved());
467 assert_eq!(approved.get_approved_by(), Some(&teacher));
468 assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit");
469
470 // And the skip is about the *pair*, not about the teacher: approving
471 // somebody else's question right after still pays.
472 let asker = a_user(&db).await;
473 let other = insert(&db, question(&asker)).await.unwrap();
474 approve(&db, other.get_id(), &teacher)
475 .await
476 .unwrap()
477 .unwrap();
478 assert_eq!(counters(&teacher, &db).await, (1, 0));
479 assert_eq!(counters(&asker, &db).await, (0, 1));
480 }
481
482 #[tokio::test]
483 async fn visibility_hides_others_pending_questions() {
484 let (db, _leases) = database::init_test_db().await;
485 let asker = a_user(&db).await;
486 let other = a_user(&db).await;
487 let teacher = a_user(&db).await;
488
489 let pending = insert(&db, question(&asker)).await.unwrap();
490 let published = insert(&db, question(&other)).await.unwrap();
491 approve(&db, published.get_id(), &teacher)
492 .await
493 .unwrap()
494 .unwrap();
495
496 // The asker sees their own pending question plus the pool; a stranger
497 // sees only the pool; the teacher view (viewer = None) sees everything.
498 let (asker_view, total) = list(&db, Some(&asker), None, None, 0).await.unwrap();
499 assert_eq!(asker_view.len(), 2);
500 assert_eq!(total, 2);
501 let (stranger_view, total) = list(&db, Some(&other), None, None, 0).await.unwrap();
502 assert_eq!(stranger_view.len(), 1);
503 assert_eq!(total, 1);
504 assert_eq!(stranger_view[0].get_id(), published.get_id());
505 let (everything, total) = list(&db, None, None, None, 0).await.unwrap();
506 assert_eq!(everything.len(), 2);
507 assert_eq!(total, 2);
508 assert!(read(&db, pending.get_id()).await.unwrap().is_some());
509 }
510
511 /// The status filter rides the same WHERE as the visibility gate: a
512 /// student's `pending` page is exactly their own unapproved questions —
513 /// another student's pending one exists but is not in it — and `total`
514 /// is the filtered count. Teacher+ `pending` is the whole approval
515 /// queue, and the window applies after the filter.
516 #[tokio::test]
517 async fn status_filter_narrows_within_the_visibility_gate() {
518 let (db, _leases) = database::init_test_db().await;
519 let asker = a_user(&db).await;
520 let other = a_user(&db).await;
521 let teacher = a_user(&db).await;
522
523 let mine_pending = insert(&db, question(&asker)).await.unwrap();
524 let theirs_pending = insert(&db, question(&other)).await.unwrap();
525 let mine_pool = insert(&db, question(&asker)).await.unwrap();
526 approve(&db, mine_pool.get_id(), &teacher).await.unwrap().unwrap();
527 let theirs_pool = insert(&db, question(&other)).await.unwrap();
528 approve(&db, theirs_pool.get_id(), &teacher).await.unwrap().unwrap();
529
530 // Student, pending: their own queue only.
531 let (items, total) =
532 list(&db, Some(&asker), Some(STATUS_PENDING), None, 0).await.unwrap();
533 assert_eq!(items.len(), 1);
534 assert_eq!(total, 1);
535 assert_eq!(items[0].get_id(), mine_pending.get_id());
536 assert_ne!(items[0].get_id(), theirs_pending.get_id());
537
538 // Student, approved: the pool (their gate already was pool + own).
539 let (items, total) =
540 list(&db, Some(&asker), Some(STATUS_APPROVED), None, 0).await.unwrap();
541 assert_eq!(items.len(), 2);
542 assert_eq!(total, 2);
543
544 // Teacher+, pending: the full approval queue, whoever asked.
545 let (items, total) = list(&db, None, Some(STATUS_PENDING), None, 0).await.unwrap();
546 assert_eq!(items.len(), 2);
547 assert_eq!(total, 2);
548
549 // A paged pending request counts the filtered set, not the page.
550 let (items, total) =
551 list(&db, None, Some(STATUS_PENDING), Some(1), 0).await.unwrap();
552 assert_eq!(items.len(), 1);
553 assert_eq!(total, 2);
554 }
555
556 #[tokio::test]
557 async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() {
558 let (db, _leases) = database::init_test_db().await;
559 let asker = a_user(&db).await;
560 let teacher = a_user(&db).await;
561 let png = FileContentType::try_new("image/png").unwrap();
562
563 let q = insert(&db, question(&asker)).await.unwrap();
564 let replaced = set_image(&db, q.get_id(), "blob_a", &png, 3)
565 .await
566 .unwrap()
567 .unwrap();
568 assert!(replaced.is_none());
569
570 // A replace reports the old blob for cleanup.
571 let replaced = set_image(&db, q.get_id(), "blob_b", &png, 5)
572 .await
573 .unwrap()
574 .unwrap();
575 assert_eq!(replaced.as_deref(), Some("blob_a"));
576 let stored = crate::db::pool_question_image::read(&db, q.get_id())
577 .await
578 .unwrap()
579 .unwrap();
580 assert_eq!(stored.get_file(), "blob_b");
581 assert_eq!(stored.get_size(), 5);
582
583 // Clearing reports the detached blob and drops the row.
584 let detached = clear_image(&db, q.get_id()).await.unwrap().unwrap();
585 assert_eq!(detached.as_deref(), Some("blob_b"));
586 assert!(
587 crate::db::pool_question_image::read(&db, q.get_id())
588 .await
589 .unwrap()
590 .is_none()
591 );
592
593 // Once approved, the image is frozen with the rest of the content.
594 approve(&db, q.get_id(), &teacher).await.unwrap().unwrap();
595 assert!(
596 set_image(&db, q.get_id(), "blob_c", &png, 7)
597 .await
598 .unwrap()
599 .is_none()
600 );
601 assert!(clear_image(&db, q.get_id()).await.unwrap().is_none());
602 }
603
604 #[tokio::test]
605 async fn delete_cascades_solutions_and_returns_the_row() {
606 let (db, _leases) = database::init_test_db().await;
607 let asker = a_user(&db).await;
608 let helper = a_user(&db).await;
609 let png = FileContentType::try_new("image/png").unwrap();
610
611 let q = insert(&db, question(&asker)).await.unwrap();
612 let offered = crate::db::solution::insert(
613 &db,
614 Solution::new(
615 q.get_id(),
616 &helper,
617 SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(),
618 ),
619 )
620 .await
621 .unwrap();
622 // Photos on both rows: their blob names must ride out with the
623 // delete, or the files strand on disk forever.
624 set_image(&db, q.get_id(), "q_blob", &png, 1)
625 .await
626 .unwrap()
627 .unwrap();
628 crate::db::solution::set_image(&db, offered.get_id(), "s_blob", &png, 2)
629 .await
630 .unwrap()
631 .unwrap();
632
633 // The swept solutions ride back with the question so the caller can
634 // take every image blob off disk.
635 let removed = delete(&db, q.get_id()).await.unwrap().unwrap();
636 assert_eq!(removed.question.get_id(), q.get_id());
637 assert_eq!(removed.solutions.len(), 1);
638 assert_eq!(removed.solutions[0].get_id(), offered.get_id());
639 assert_eq!(removed.image_files.len(), 2);
640 assert!(removed.image_files.contains(&"q_blob".to_string()));
641 assert!(removed.image_files.contains(&"s_blob".to_string()));
642 assert!(read(&db, q.get_id()).await.unwrap().is_none());
643 assert!(
644 crate::db::solution::list_for(&db, q.get_id(), None, 0)
645 .await
646 .unwrap()
647 .0
648 .is_empty()
649 );
650
651 // Deleting the already-deleted is None, not an error.
652 assert!(delete(&db, q.get_id()).await.unwrap().is_none());
653 }
654
655 /// The [`crate::db::exam_answer`] defect, one domain
656 /// over: a solution offered inside its question's delete window must not
657 /// outlive it. Guarding the offer by *reading* the question does not do it
658 /// — the read sees a row [`delete`] has removed but not committed, while
659 /// its `DELETE solution WHERE question = $q` ran on a snapshot predating
660 /// the offer, so both commit and the solution is left pointing at a
661 /// question that is gone. Nothing can reach it after that: every route to
662 /// a solution goes through its question, so neither a reader nor a second
663 /// delete can ever clear it, and its photo stays on disk for good.
664 /// [`bump_question_and_write`] moves the question's own `asked_at`
665 /// instead, so the two transactions touch one key and the store refuses
666 /// one of them.
667 /// The offer writes the question row too (its `solution_count`), so the
668 /// two transactions touch one row and Postgres refuses one of them.
669 /// Both orders are forced by awaiting one side to completion before the
670 /// other starts. A barrier is a coin toss under load, and a run where the
671 /// delete loses every overlapped round has still proved the invariant.
672 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
673 async fn a_solution_offered_inside_a_delete_never_outlives_its_question() {
674 let (db, _leases) = database::init_test_db().await;
675
676 async fn offer(
677 db: &Database,
678 id: &PoolQuestionId,
679 helper: &UserId,
680 ) -> Result<Solution, AppError> {
681 crate::db::solution::insert(
682 db,
683 Solution::new(
684 id,
685 helper,
686 SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(),
687 ),
688 )
689 .await
690 }
691
692 async fn solutions(db: &Database, id: &PoolQuestionId) -> usize {
693 crate::db::solution::list_for(db, id, None, 0)
694 .await
695 .unwrap()
696 .0
697 .len()
698 }
699
700 // Delete-first: the question is gone before the offer starts.
701 {
702 let asker = a_user(&db).await;
703 let helper = a_user(&db).await;
704 let q = insert(&db, question(&asker)).await.unwrap();
705 let id = *q.get_id();
706 let dropped = delete(&db, &id).await;
707 assert!(
708 !matches!(dropped, Err(AppError::Db(_))),
709 "delete-first: a delete must be answered, not 500: {dropped:?}"
710 );
711 assert!(
712 read(&db, &id).await.unwrap().is_none(),
713 "delete-first: the question is still there after delete: {dropped:?}"
714 );
715 let child = offer(&db, &id, &helper).await;
716 assert!(
717 !matches!(child, Err(AppError::Db(_))),
718 "delete-first: an offer must be answered, not 500: {child:?}"
719 );
720 assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question");
721 }
722
723 // Write-first: the offer lands, then the delete sweeps it.
724 {
725 let asker = a_user(&db).await;
726 let helper = a_user(&db).await;
727 let q = insert(&db, question(&asker)).await.unwrap();
728 let id = *q.get_id();
729 let child = offer(&db, &id, &helper).await;
730 assert!(
731 child.is_ok(),
732 "write-first: the offer must land before the delete: {child:?}"
733 );
734 let dropped = delete(&db, &id).await;
735 assert!(
736 !matches!(dropped, Err(AppError::Db(_))),
737 "write-first: a delete must be answered, not 500: {dropped:?}"
738 );
739 assert!(
740 read(&db, &id).await.unwrap().is_none(),
741 "write-first: the question is still there"
742 );
743 assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question");
744 }
745
746 // Overlapped rounds. Delete may lose every one of them.
747 let mut swept = 0;
748 for round in 0..4 {
749 let asker = a_user(&db).await;
750 let helper = a_user(&db).await;
751 let q = insert(&db, question(&asker)).await.unwrap();
752 let id = *q.get_id();
753
754 let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2));
755 let drop_it = {
756 let (db, id, gate) = (db.clone(), id, gate.clone());
757 tokio::spawn(async move {
758 gate.wait().await;
759 delete(&db, &id).await
760 })
761 };
762 let child = {
763 let (db, id, helper, gate) = (db.clone(), id, helper, gate);
764 tokio::spawn(async move {
765 gate.wait().await;
766 offer(&db, &id, &helper).await
767 })
768 };
769 let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap());
770 assert!(
771 !matches!(child, Err(AppError::Db(_))),
772 "round {round}: a raced offer must be answered, not 500: {child:?}"
773 );
774 assert!(
775 !matches!(drop_it, Err(AppError::Db(_))),
776 "round {round}: a raced delete must be answered, not 500: {drop_it:?}"
777 );
778
779 if read(&db, &id).await.unwrap().is_none() {
780 swept += 1;
781 assert_eq!(
782 solutions(&db, &id).await,
783 0,
784 "round {round}: a solution outlived its question"
785 );
786 } else if drop_it.is_ok() {
787 panic!(
788 "round {round}: the delete reported success but the question is still there"
789 );
790 }
791 }
792 eprintln!(
793 "pool_question::delete raced by an offer: {swept}/4 concurrent rounds deleted the question"
794 );
795 }
796}