forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

solution.rs472 lines, 16.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", 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 ulid::Ulid;
258
259 use super::*;
260 use crate::database;
261 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};
262 use crate::domain::timestamp::Timestamp;
263 use crate::domain::user::UserId;
264
265 /// A real question row: offering a solution moves its question's
266 /// `asked_at` (that is what keeps a solution from outliving its question),
267 /// so a minted id nothing wrote is a 404.
268 async fn question_row(db: &Database) -> PoolQuestionId {
269 crate::db::pool_question::insert(
270 db,
271 PoolQuestion::new(
272 &UserId::from_key(&Ulid::generate().to_string()),
273 PoolQuestionTitle::try_new("soru").unwrap(),
274 PoolQuestionBody::try_new("neden").unwrap(),
275 ),
276 )
277 .await
278 .unwrap()
279 .get_id()
280 .clone()
281 }
282
283 #[tokio::test]
284 async fn rows_scope_to_their_question_and_list_oldest_first() {
285 let db = database::init_mem().await.unwrap();
286 let question_a = question_row(&db).await;
287 let question_b = question_row(&db).await;
288 let author = UserId::from_key(&Ulid::generate().to_string());
289
290 // Distinct offer times so the assertion pins the real contract —
291 // older `offered_at` sorts first — not the same-millisecond `id`
292 // tiebreak, whose random ULID low bits would make the order a coin
293 // flip (two `now()` reads can land in one millisecond).
294 let mut first = Solution::new(
295 &question_a,
296 &author,
297 SolutionBody::try_new("Önce türevi al.").unwrap(),
298 );
299 first.offered_at = Timestamp::from_millis(1);
300 let first = insert(&db, first).await.unwrap();
301 let mut second = Solution::new(
302 &question_a,
303 &author,
304 SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(),
305 );
306 second.offered_at = Timestamp::from_millis(2);
307 let second = insert(&db, second).await.unwrap();
308
309 let (listed, _) = list_for(&db, &question_a, None, 0).await.unwrap();
310 assert_eq!(listed.len(), 2);
311 assert_eq!(listed[0].get_id(), first.get_id());
312 assert_eq!(listed[1].get_id(), second.get_id());
313 assert!(
314 list_for(&db, &question_b, None, 0)
315 .await
316 .unwrap()
317 .0
318 .is_empty()
319 );
320
321 // Readable under its own question, invisible under another.
322 assert!(
323 read_for(&db, first.get_id(), &question_a)
324 .await
325 .unwrap()
326 .is_some()
327 );
328 assert!(
329 read_for(&db, first.get_id(), &question_b)
330 .await
331 .unwrap()
332 .is_none()
333 );
334
335 delete(&db, first).await.unwrap();
336 assert_eq!(
337 list_for(&db, &question_a, None, 0).await.unwrap().0.len(),
338 1
339 );
340 }
341
342 #[tokio::test]
343 async fn image_set_replace_clear_report_the_replaced_blob() {
344 let db = database::init_mem().await.unwrap();
345 let question = question_row(&db).await;
346 let author = UserId::from_key(&Ulid::generate().to_string());
347 let png = FileContentType::try_new("image/png").unwrap();
348
349 let solution = insert(
350 &db,
351 Solution::new(
352 &question,
353 &author,
354 SolutionBody::try_new("Grafiği çiz.").unwrap(),
355 ),
356 )
357 .await
358 .unwrap();
359
360 let before = set_image(&db, solution.get_id(), "blob_a", &png, 3)
361 .await
362 .unwrap()
363 .unwrap();
364 assert!(before.get_image_file().is_none());
365
366 // A replace reports the old blob for cleanup.
367 let before = set_image(&db, solution.get_id(), "blob_b", &png, 5)
368 .await
369 .unwrap()
370 .unwrap();
371 assert_eq!(before.get_image_file(), Some("blob_a"));
372 let stored = read_for(&db, solution.get_id(), &question)
373 .await
374 .unwrap()
375 .unwrap();
376 assert_eq!(stored.get_image_file(), Some("blob_b"));
377 assert_eq!(stored.get_image_size(), Some(5));
378
379 // Clearing reports the detached blob and empties the fields.
380 let before = clear_image(&db, solution.get_id()).await.unwrap().unwrap();
381 assert_eq!(before.get_image_file(), Some("blob_b"));
382 assert!(
383 read_for(&db, solution.get_id(), &question)
384 .await
385 .unwrap()
386 .unwrap()
387 .get_image_file()
388 .is_none()
389 );
390
391 // A row deleted mid-flight surfaces as None, not an error.
392 let deleted = delete(&db, solution.clone()).await.unwrap();
393 assert_eq!(deleted.get_id(), solution.get_id());
394 assert!(
395 set_image(&db, solution.get_id(), "blob_c", &png, 7)
396 .await
397 .unwrap()
398 .is_none()
399 );
400 assert!(clear_image(&db, solution.get_id()).await.unwrap().is_none());
401 }
402
403 #[tokio::test]
404 async fn set_body_edits_in_place() {
405 let db = database::init_mem().await.unwrap();
406 let question = question_row(&db).await;
407 let author = UserId::from_key(&Ulid::generate().to_string());
408
409 let solution = insert(
410 &db,
411 Solution::new(
412 &question,
413 &author,
414 SolutionBody::try_new("İlk deneme.").unwrap(),
415 ),
416 )
417 .await
418 .unwrap();
419
420 let edited = set_body(
421 &db,
422 solution.get_id(),
423 &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(),
424 )
425 .await
426 .unwrap()
427 .unwrap();
428 assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm.");
429 assert_eq!(edited.get_id(), solution.get_id());
430
431 // Editing a missing solution is None, not an error.
432 assert!(
433 set_body(
434 &db,
435 &SolutionId::from_key(&Ulid::generate().to_string()),
436 &SolutionBody::try_new("boş").unwrap(),
437 )
438 .await
439 .unwrap()
440 .is_none()
441 );
442 }
443
444 #[tokio::test]
445 async fn counts_for_groups_per_question() {
446 let db = database::init_mem().await.unwrap();
447 let two = question_row(&db).await;
448 let one = question_row(&db).await;
449 let none = question_row(&db).await;
450 let author = UserId::from_key(&Ulid::generate().to_string());
451
452 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {
453 for body in bodies {
454 insert(
455 &db,
456 Solution::new(question, &author, SolutionBody::try_new(body).unwrap()),
457 )
458 .await
459 .unwrap();
460 }
461 }
462
463 let counts = counts_for(&db, &[two.clone(), one.clone(), none.clone()])
464 .await
465 .unwrap();
466 assert_eq!(counts.get(two.key()), Some(&2));
467 assert_eq!(counts.get(one.key()), Some(&1));
468 // No solutions = no entry; the caller reads the miss as zero.
469 assert_eq!(counts.get(none.key()), None);
470 assert!(counts_for(&db, &[]).await.unwrap().is_empty());
471 }
472}