forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBe2d0e43Ahmet Kaan Gümüş2 months ago397 commits

solution.rs386 lines, 13.4 KiBHistoryRawDownload
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
7use std::collections::HashMap;
8
9use surrealdb::types::{RecordId, SurrealValue};
10
11use crate::database::Database;
12use crate::db::page::PagedList;
13use crate::db::pool_question::bump_question_and_write;
14use crate::domain::note_file::FileContentType;
15use crate::domain::pool_question::PoolQuestionId;
16use crate::domain::solution::{Solution, SolutionBody, SolutionId};
17use crate::error::AppError;
18
19/// One `GROUP BY question` row of [`counts_for`].
20#[derive(SurrealValue)]
21struct 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.
38pub 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).
56pub 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).
69pub 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.
88pub 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.
113pub 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).
132pub 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.
152pub 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
164pub 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)]
170mod 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}