forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBebffd41Ahmet Kaan Gümüş2 months ago509 commits

solution.rs499 lines, 17.6 KiBHistoryRawDownload
1//! The `solution` table: offers (their question's existence enforced by the
2//! real foreign key), the question-scoped read 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
7use std::collections::HashMap;
8
9use crate::database::{Database, tx_with_retry};
10use crate::db::page::PagedList;
11use crate::domain::note_file::FileContentType;
12use crate::domain::pool_question::PoolQuestionId;
13use crate::domain::solution::{Solution, SolutionBody, SolutionId};
14use crate::domain::timestamp::Timestamp;
15use crate::domain::user::UserId;
16use crate::error::AppError;
17
18/// Offer the solution. `NotFound` = the question is gone, and nothing was
19/// written: the insert's foreign key (`solution_question_fkey`) refuses an
20/// orphan the old existence-move transaction spent five statements dodging —
21/// a bare create landing inside
22/// [`crate::db::pool_question::delete`]'s window used to be swept by
23/// nothing and left a solution no route could ever reach or remove (every
24/// path to one goes through its question), photo blob included.
25///
26/// The author's own foreign key never fires in practice (the request
27/// carries a live session user) and stays a database error if it ever does;
28/// only the question's key maps to the 404.
29pub async fn insert(db: &Database, solution: Solution) -> Result<Solution, AppError> {
30 match sqlx::query_as!(
31 Solution,
32 r#"INSERT INTO solution (id, question, author, body, offered_at)
33 VALUES ($1, $2, $3, $4, $5)
34 RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId",
35 author AS "author: UserId", body AS "body: SolutionBody",
36 offered_at AS "offered_at: Timestamp""#,
37 solution.id.uuid(),
38 solution.question.uuid(),
39 solution.author.uuid(),
40 solution.body.as_str(),
41 solution.offered_at.as_millis(),
42 )
43 .fetch_one(db)
44 .await
45 {
46 Ok(row) => Ok(row),
47 Err(err) if is_question_gone(&err) => Err(AppError::NotFound),
48 Err(err) => Err(err.into()),
49 }
50}
51
52/// Did this insert fail on the *question* foreign key — the parent-gone
53/// refusal — rather than some unrelated database fault?
54fn is_question_gone(err: &sqlx::Error) -> bool {
55 err.as_database_error().and_then(|db| db.constraint()) == Some("solution_question_fkey")
56}
57
58/// Read a solution only if it belongs to `question` — keeps the nested
59/// route honest (a solution id under someone else's question 404s).
60pub async fn read_for(
61 db: &Database,
62 id: &SolutionId,
63 question: &PoolQuestionId,
64) -> Result<Option<Solution>, AppError> {
65 let row = sqlx::query_as!(
66 Solution,
67 r#"SELECT id AS "id: SolutionId", question AS "question: PoolQuestionId",
68 author AS "author: UserId", body AS "body: SolutionBody",
69 offered_at AS "offered_at: Timestamp"
70 FROM solution WHERE id = $1 AND question = $2"#,
71 id.uuid(),
72 question.uuid()
73 )
74 .fetch_optional(db)
75 .await?;
76 Ok(row)
77}
78
79/// The question's solutions, oldest first — a discussion reads downward.
80/// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond
81/// offers *stable* across re-queries (the ids are write-ordered UUIDv7, so
82/// same-ms rows still sort by mint order).
83pub async fn list_for(
84 db: &Database,
85 question: &PoolQuestionId,
86 limit: Option<i64>,
87 offset: i64,
88) -> Result<(Vec<Solution>, i64), AppError> {
89 // `.uuid()` feeds the builder its raw bind value — exact, typed.
90 PagedList::new(
91 "solution WHERE question = $1",
92 "ORDER BY offered_at ASC, id ASC",
93 )
94 .bind(question.uuid())
95 .run(limit, offset, db)
96 .await
97}
98
99/// Per-question solution tallies for a page of questions, in one grouped
100/// query — a per-row `count()` would cost a query per question. Keys are
101/// the questions' wire keys; a question with no solutions has no entry, so
102/// the caller reads misses as zero.
103pub async fn counts_for(
104 db: &Database,
105 questions: &[PoolQuestionId],
106) -> Result<HashMap<String, i64>, AppError> {
107 if questions.is_empty() {
108 return Ok(HashMap::new());
109 }
110 let ids: Vec<uuid::Uuid> = questions.iter().map(|id| id.uuid()).collect();
111 let rows = sqlx::query!(
112 r#"SELECT question AS "question: PoolQuestionId", count(*) AS n
113 FROM solution
114 WHERE question = ANY($1)
115 GROUP BY question"#,
116 &ids,
117 )
118 .fetch_all(db)
119 .await?;
120 Ok(rows
121 .into_iter()
122 .map(|row| (row.question.key(), row.n.unwrap_or(0)))
123 .collect())
124}
125
126/// Replace the body. Unconditional (solutions have no moderation state to
127/// guard, unlike a question's `pending` gate) — `None` only means the row
128/// was deleted mid-flight. Authorship is the web layer's check.
129pub async fn set_body(
130 db: &Database,
131 id: &SolutionId,
132 body: &SolutionBody,
133) -> Result<Option<Solution>, AppError> {
134 let row = sqlx::query_as!(
135 Solution,
136 r#"UPDATE solution SET body = $2 WHERE id = $1
137 RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId",
138 author AS "author: UserId", body AS "body: SolutionBody",
139 offered_at AS "offered_at: Timestamp""#,
140 id.uuid(),
141 body.as_str()
142 )
143 .fetch_optional(db)
144 .await?;
145 Ok(row)
146}
147
148/// Point the solution at a freshly written image blob. Unconditional for
149/// the same reason as [`set_body`]. `Ok(None)` means the row was deleted
150/// mid-flight (the fresh blob is the caller's orphan to take back off
151/// disk); `Ok(Some(replaced))` names the blob this upload displaced — the
152/// caller's to remove, `None` inside when nothing was there before.
153///
154/// The photo is its own row in `solution_image` (the child-table shape of
155/// `question_image`), so the write is that row's upsert; the parent's
156/// `FOR UPDATE` row lock still makes the before-read and the write one
157/// switch, so two racing uploads can never both be told they replaced the
158/// same blob — the loser re-reads the winner's blob name, the discipline
159/// `crate::db::question_image::upsert` documents.
160pub async fn set_image(
161 db: &Database,
162 id: &SolutionId,
163 file: &str,
164 content_type: &FileContentType,
165 size: i64,
166) -> Result<Option<Option<String>>, AppError> {
167 // Owned captures (`Send` rule of `tx_with_retry` closures).
168 let id = *id;
169 let file = file.to_owned();
170 let content_type = content_type.clone();
171 tx_with_retry(db, false, async move |tx| {
172 let before = sqlx::query!(
173 r#"SELECT id FROM solution WHERE id = $1 FOR UPDATE"#,
174 id.uuid()
175 )
176 .fetch_optional(&mut *tx)
177 .await?;
178 if before.is_none() {
179 return Ok(None);
180 }
181 let replaced = sqlx::query_scalar!(
182 r#"SELECT file FROM solution_image WHERE solution = $1"#,
183 id.uuid()
184 )
185 .fetch_optional(&mut *tx)
186 .await?;
187 sqlx::query!(
188 r#"INSERT INTO solution_image (solution, file, content_type, size)
189 VALUES ($1, $2, $3, $4)
190 ON CONFLICT (solution) DO UPDATE
191 SET file = EXCLUDED.file, content_type = EXCLUDED.content_type,
192 size = EXCLUDED.size"#,
193 id.uuid(),
194 file,
195 content_type.as_str(),
196 size,
197 )
198 .execute(&mut *tx)
199 .await?;
200 Ok(Some(replaced))
201 })
202 .await
203}
204
205/// Detach the solution's image. `Ok(None)` = the row was deleted mid-flight;
206/// `Ok(Some(detached))` names the blob the caller removes — `None` inside
207/// when the solution carried no image (the route answers that 404).
208pub async fn clear_image(
209 db: &Database,
210 id: &SolutionId,
211) -> Result<Option<Option<String>>, AppError> {
212 // Owned capture (`Send` rule of `tx_with_retry` closures).
213 let id = *id;
214 tx_with_retry(db, false, async move |tx| {
215 let before = sqlx::query!(
216 r#"SELECT id FROM solution WHERE id = $1 FOR UPDATE"#,
217 id.uuid()
218 )
219 .fetch_optional(&mut *tx)
220 .await?;
221 if before.is_none() {
222 return Ok(None);
223 }
224 let detached = sqlx::query_scalar!(
225 r#"DELETE FROM solution_image WHERE solution = $1 RETURNING file"#,
226 id.uuid()
227 )
228 .fetch_optional(&mut *tx)
229 .await?;
230 Ok(Some(detached))
231 })
232 .await
233}
234
235/// Delete a solution, returning the row plus the blob name of the photo it
236/// carried (the caller's disk-GC list — one entry at most). The photo row
237/// goes first: its foreign key is `NO ACTION`, so it cannot outlive being
238/// pointed at, and its file name is read on the way out, under the same
239/// transaction — a photo uploaded by a racing `set_image` loses the row
240/// lock to this delete and comes back as the caller's orphan.
241pub async fn delete(
242 db: &Database,
243 solution: Solution,
244) -> Result<Option<(Solution, Option<String>)>, AppError> {
245 // Owned capture (`Send` rule of `tx_with_retry` closures).
246 let id = *solution.get_id();
247 tx_with_retry(db, false, async move |tx| {
248 let image = sqlx::query_scalar!(
249 r#"DELETE FROM solution_image WHERE solution = $1 RETURNING file"#,
250 id.uuid()
251 )
252 .fetch_optional(&mut *tx)
253 .await?;
254 let deleted = sqlx::query_as!(
255 Solution,
256 r#"DELETE FROM solution WHERE id = $1
257 RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId",
258 author AS "author: UserId", body AS "body: SolutionBody",
259 offered_at AS "offered_at: Timestamp""#,
260 id.uuid()
261 )
262 .fetch_optional(&mut *tx)
263 .await?;
264 Ok(deleted.map(|deleted| (deleted, image)))
265 })
266 .await
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272 use crate::database;
273 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};
274 use crate::domain::timestamp::Timestamp;
275 use crate::domain::user::UserId;
276
277 /// A real `app_user` row: askers and authors are foreign keys now.
278 async fn a_person(db: &Database, label: &str) -> UserId {
279 let user = UserId::generate();
280 sqlx::query(
281 "INSERT INTO app_user (id, username, created_at) \
282 VALUES ($1, $2, 0)",
283 )
284 .bind(user.uuid())
285 .bind(format!("{label}-{}", &user.key()[30..]))
286 .execute(db)
287 .await
288 .unwrap();
289 user
290 }
291
292 /// A real question row: offering a solution moves its question's
293 /// `asked_at` (that is what keeps a solution from outliving its question),
294 /// so a minted id nothing wrote is a 404.
295 async fn question_row(db: &Database) -> PoolQuestionId {
296 let asker = a_person(db, "asker").await;
297 *crate::db::pool_question::insert(
298 db,
299 PoolQuestion::new(
300 &asker,
301 PoolQuestionTitle::try_new("soru").unwrap(),
302 PoolQuestionBody::try_new("neden").unwrap(),
303 ),
304 )
305 .await
306 .unwrap()
307 .get_id()
308 }
309
310 #[tokio::test]
311 async fn rows_scope_to_their_question_and_list_oldest_first() {
312 let (db, _leases) = database::init_test_db().await;
313 let question_a = question_row(&db).await;
314 let question_b = question_row(&db).await;
315 let author = a_person(&db, "author").await;
316
317 // Distinct offer times so the assertion pins the real contract —
318 // older `offered_at` sorts first — not the same-millisecond `id`
319 // tiebreak, whose random ULID low bits would make the order a coin
320 // flip (two `now()` reads can land in one millisecond).
321 let mut first = Solution::new(
322 &question_a,
323 &author,
324 SolutionBody::try_new("Önce türevi al.").unwrap(),
325 );
326 first.offered_at = Timestamp::from_millis(1);
327 let first = insert(&db, first).await.unwrap();
328 let mut second = Solution::new(
329 &question_a,
330 &author,
331 SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(),
332 );
333 second.offered_at = Timestamp::from_millis(2);
334 let second = insert(&db, second).await.unwrap();
335
336 let (listed, _) = list_for(&db, &question_a, None, 0).await.unwrap();
337 assert_eq!(listed.len(), 2);
338 assert_eq!(listed[0].get_id(), first.get_id());
339 assert_eq!(listed[1].get_id(), second.get_id());
340 assert!(
341 list_for(&db, &question_b, None, 0)
342 .await
343 .unwrap()
344 .0
345 .is_empty()
346 );
347
348 // Readable under its own question, invisible under another.
349 assert!(
350 read_for(&db, first.get_id(), &question_a)
351 .await
352 .unwrap()
353 .is_some()
354 );
355 assert!(
356 read_for(&db, first.get_id(), &question_b)
357 .await
358 .unwrap()
359 .is_none()
360 );
361
362 let first_id = *first.get_id();
363 let (deleted, image) = delete(&db, first).await.unwrap().unwrap();
364 assert_eq!(deleted.get_id(), &first_id);
365 assert!(image.is_none());
366 assert_eq!(
367 list_for(&db, &question_a, None, 0).await.unwrap().0.len(),
368 1
369 );
370 }
371
372 #[tokio::test]
373 async fn image_set_replace_clear_report_the_replaced_blob() {
374 let (db, _leases) = database::init_test_db().await;
375 let question = question_row(&db).await;
376 let author = a_person(&db, "author").await;
377 let png = FileContentType::try_new("image/png").unwrap();
378
379 let solution = insert(
380 &db,
381 Solution::new(
382 &question,
383 &author,
384 SolutionBody::try_new("Grafiği çiz.").unwrap(),
385 ),
386 )
387 .await
388 .unwrap();
389
390 let replaced = set_image(&db, solution.get_id(), "blob_a", &png, 3)
391 .await
392 .unwrap()
393 .unwrap();
394 assert!(replaced.is_none());
395
396 // A replace reports the old blob for cleanup.
397 let replaced = set_image(&db, solution.get_id(), "blob_b", &png, 5)
398 .await
399 .unwrap()
400 .unwrap();
401 assert_eq!(replaced.as_deref(), Some("blob_a"));
402 let stored = crate::db::solution_image::read(&db, solution.get_id())
403 .await
404 .unwrap()
405 .unwrap();
406 assert_eq!(stored.get_file(), "blob_b");
407 assert_eq!(stored.get_size(), 5);
408
409 // Clearing reports the detached blob and drops the row.
410 let detached = clear_image(&db, solution.get_id()).await.unwrap().unwrap();
411 assert_eq!(detached.as_deref(), Some("blob_b"));
412 assert!(
413 crate::db::solution_image::read(&db, solution.get_id())
414 .await
415 .unwrap()
416 .is_none()
417 );
418
419 // A row deleted mid-flight surfaces as None, not an error.
420 let (deleted, image) = delete(&db, solution.clone()).await.unwrap().unwrap();
421 assert_eq!(deleted.get_id(), solution.get_id());
422 assert!(image.is_none());
423 assert!(
424 set_image(&db, solution.get_id(), "blob_c", &png, 7)
425 .await
426 .unwrap()
427 .is_none()
428 );
429 assert!(clear_image(&db, solution.get_id()).await.unwrap().is_none());
430 }
431
432 #[tokio::test]
433 async fn set_body_edits_in_place() {
434 let (db, _leases) = database::init_test_db().await;
435 let question = question_row(&db).await;
436 let author = a_person(&db, "author").await;
437
438 let solution = insert(
439 &db,
440 Solution::new(
441 &question,
442 &author,
443 SolutionBody::try_new("İlk deneme.").unwrap(),
444 ),
445 )
446 .await
447 .unwrap();
448
449 let edited = set_body(
450 &db,
451 solution.get_id(),
452 &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(),
453 )
454 .await
455 .unwrap()
456 .unwrap();
457 assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm.");
458 assert_eq!(edited.get_id(), solution.get_id());
459
460 // Editing a missing solution is None, not an error.
461 assert!(
462 set_body(
463 &db,
464 &SolutionId::from_key(&uuid::Uuid::now_v7().to_string()),
465 &SolutionBody::try_new("boş").unwrap(),
466 )
467 .await
468 .unwrap()
469 .is_none()
470 );
471 }
472
473 #[tokio::test]
474 async fn counts_for_groups_per_question() {
475 let (db, _leases) = database::init_test_db().await;
476 let two = question_row(&db).await;
477 let one = question_row(&db).await;
478 let none = question_row(&db).await;
479 let author = a_person(&db, "author").await;
480
481 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {
482 for body in bodies {
483 insert(
484 &db,
485 Solution::new(question, &author, SolutionBody::try_new(body).unwrap()),
486 )
487 .await
488 .unwrap();
489 }
490 }
491
492 let counts = counts_for(&db, &[two, one, none]).await.unwrap();
493 assert_eq!(counts.get(two.key().as_str()), Some(&2));
494 assert_eq!(counts.get(one.key().as_str()), Some(&1));
495 // No solutions = no entry; the caller reads the miss as zero.
496 assert_eq!(counts.get(none.key().as_str()), None);
497 assert!(counts_for(&db, &[]).await.unwrap().is_empty());
498 }
499}