forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB914d095Ahmet Kaan Gümüş2 months ago454 commits

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