forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

solution.rs505 lines, 17.2 KiBHistoryRawDownload
1//! A solution offered on an approved pool question (see
2//! [`crate::domain::pool_question`]). Anyone in the school — student or staff
3//! — may offer one; rows list oldest first, reading as a discussion thread.
4//! Solutions die with their question (the question delete cascades here).
5//! Like a question, a solution may carry one photo (`image_*` metadata on the
6//! row, bytes on disk under a server-generated ULID) — but unlike a question
7//! it has no moderation state, so its author may edit the body and swap the
8//! photo at any time; there is nothing to freeze.
9
10use std::collections::HashMap;
11
12use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
13
14use crate::constant::{MAX_SOLUTION_BODY_LEN, SOLUTION_TABLE};
15use crate::database::Database;
16use crate::domain::monotonic_id::next_ulid;
17use crate::domain::note_file::FileContentType;
18use crate::db::page::PagedList;
19use crate::domain::pool_question::{PoolQuestionId, bump_question_and_write};
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::UserId;
22use crate::error::{AppError, ValidationError};
23use crate::validate::validate_required;
24
25#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
26pub struct SolutionId(RecordId);
27
28impl SolutionId {
29 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
30 /// solutions sort `offered_at ASC, id ASC` and the id *is* the tie-break ([`Solution::list_for_question`]),
31 /// and a random low half scrambles rows minted in the same millisecond.
32 pub fn generate() -> Self {
33 Self(RecordId::new(SOLUTION_TABLE, next_ulid().to_string()))
34 }
35
36 pub fn from_key(key: &str) -> Self {
37 Self(RecordId::new(SOLUTION_TABLE, key))
38 }
39
40 pub fn record(&self) -> RecordId {
41 self.0.clone()
42 }
43
44 pub fn key(&self) -> &str {
45 match &self.0.key {
46 RecordIdKey::String(key) => key,
47 _ => "",
48 }
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
53pub struct SolutionBody(String);
54
55impl SolutionBody {
56 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
57 validate_required("body", value, MAX_SOLUTION_BODY_LEN)?;
58 Ok(Self(value.to_string()))
59 }
60
61 pub fn as_str(&self) -> &str {
62 &self.0
63 }
64}
65
66#[derive(Debug, Clone, SurrealValue)]
67pub struct Solution {
68 id: SolutionId,
69 question: PoolQuestionId,
70 author: UserId,
71 body: SolutionBody,
72 offered_at: Timestamp,
73 /// The photo's on-disk blob name — a fresh ULID every upload; `None` when
74 /// the solution carries no image.
75 image_file: Option<String>,
76 image_content_type: Option<FileContentType>,
77 image_size: Option<i64>,
78}
79
80/// One `GROUP BY question` row of [`Solution::counts_for`].
81#[derive(SurrealValue)]
82struct SolutionCount {
83 question: PoolQuestionId,
84 n: i64,
85}
86
87impl Solution {
88 pub fn new(question: &PoolQuestionId, author: &UserId, body: SolutionBody) -> Self {
89 Self {
90 id: SolutionId::generate(),
91 question: question.clone(),
92 author: author.clone(),
93 body,
94 offered_at: Timestamp::now(),
95 image_file: None,
96 image_content_type: None,
97 image_size: None,
98 }
99 }
100
101 pub fn get_id(&self) -> &SolutionId {
102 &self.id
103 }
104
105 pub fn get_question(&self) -> &PoolQuestionId {
106 &self.question
107 }
108
109 pub fn get_author(&self) -> &UserId {
110 &self.author
111 }
112
113 pub fn get_body(&self) -> &SolutionBody {
114 &self.body
115 }
116
117 pub fn get_offered_at(&self) -> Timestamp {
118 self.offered_at
119 }
120
121 pub fn get_image_file(&self) -> Option<&str> {
122 self.image_file.as_deref()
123 }
124
125 pub fn get_image_content_type(&self) -> Option<&FileContentType> {
126 self.image_content_type.as_ref()
127 }
128
129 pub fn get_image_size(&self) -> Option<i64> {
130 self.image_size
131 }
132
133 /// Offer the solution. `NotFound` = the question is gone, and nothing was
134 /// written: the create rides [`bump_question_and_write`], so the question's
135 /// existence is a *write* to its row rather than a read the handler made a
136 /// moment earlier — a bare create landing inside
137 /// [`PoolQuestion::delete`](crate::domain::pool_question::PoolQuestion::delete)'s
138 /// window was swept by nothing and left a solution no route could ever
139 /// reach or remove (every path to one goes through its question), photo
140 /// blob included.
141 ///
142 /// Re-sendable despite the `CREATE`: `$id` is a ULID minted once per call
143 /// on a table with no `UNIQUE` index, so a re-send cannot answer "already
144 /// exists" — the one thing the retry could not survive.
145 pub async fn insert(self, db: &Database) -> Result<Solution, AppError> {
146 // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber
147 let (question, id) = (self.question.clone(), self.id.record());
148 bump_question_and_write(
149 &question,
150 "CREATE $id CONTENT $solution",
151 vec![
152 ("id".into(), id.into_value()),
153 ("solution".into(), self.into_value()),
154 ],
155 db,
156 )
157 .await?
158 .ok_or_else(|| AppError::Internal("failed to create solution".into()))
159 }
160
161 /// Read a solution only if it belongs to `question` — keeps the nested
162 /// route honest (a solution id under someone else's question 404s).
163 pub async fn read_for(
164 id: &SolutionId,
165 question: &PoolQuestionId,
166 db: &Database,
167 ) -> Result<Option<Solution>, AppError> {
168 let solution: Option<Solution> = db.select(id.record()).await?;
169 Ok(solution.filter(|solution| &solution.question == question))
170 }
171
172 /// The question's solutions, oldest first — a discussion reads downward.
173 /// Ordered by `offered_at`; the `id` tiebreak only makes same-millisecond
174 /// offers *stable* across re-queries, not insertion-ordered (ULID low bits
175 /// are random within a millisecond, so same-ms order is arbitrary).
176 pub async fn list_for(
177 question: &PoolQuestionId,
178 limit: Option<i64>,
179 offset: i64,
180 db: &Database,
181 ) -> Result<(Vec<Solution>, i64), AppError> {
182 PagedList::new(
183 "solution WHERE question = $q",
184 "ORDER BY offered_at ASC, id ASC",
185 )
186 .bind("q", question.record())
187 .run(limit, offset, db)
188 .await
189 }
190
191 /// Per-question solution tallies for a page of questions, in one grouped
192 /// query — a per-row `count()` would cost a query per question. Keys are
193 /// question record keys; a question with no solutions has no entry, so
194 /// the caller reads misses as zero.
195 pub async fn counts_for(
196 questions: &[PoolQuestionId],
197 db: &Database,
198 ) -> Result<HashMap<String, i64>, AppError> {
199 if questions.is_empty() {
200 return Ok(HashMap::new());
201 }
202 let ids: Vec<RecordId> = questions.iter().map(|question| question.record()).collect();
203 let mut result = db
204 .query("SELECT question, count() AS n FROM solution WHERE question IN $qs GROUP BY question")
205 .bind(("qs", ids))
206 .await?
207 .check()?;
208 Ok(result
209 .take::<Vec<SolutionCount>>(0)?
210 .into_iter()
211 .map(|row| (row.question.key().to_string(), row.n))
212 .collect())
213 }
214
215 /// Replace the body. Unconditional (solutions have no moderation state to
216 /// guard, unlike a question's `pending` gate) — `None` only means the row
217 /// was deleted mid-flight. Authorship is the web layer's check.
218 pub async fn set_body(
219 id: &SolutionId,
220 body: &SolutionBody,
221 db: &Database,
222 ) -> Result<Option<Solution>, AppError> {
223 let mut result = db
224 .query("UPDATE $s SET body = $b RETURN AFTER")
225 .bind(("s", id.record()))
226 .bind(("b", body.clone()))
227 .await?
228 .check()?;
229 Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
230 }
231
232 /// Point the solution at a freshly written image blob. Unconditional for
233 /// the same reason as [`Self::set_body`]. Returns the *before* row — its
234 /// `image_file` is the replaced blob the caller must remove; `None` means
235 /// the row was deleted mid-flight (the fresh blob is the caller's orphan
236 /// to take back off disk).
237 pub async fn set_image(
238 id: &SolutionId,
239 file: &str,
240 content_type: &FileContentType,
241 size: i64,
242 db: &Database,
243 ) -> Result<Option<Solution>, AppError> {
244 let mut result = db
245 .query("UPDATE $s SET image_file = $file, image_content_type = $ct, image_size = $size RETURN BEFORE")
246 .bind(("s", id.record()))
247 .bind(("file", file.to_string()))
248 .bind(("ct", content_type.clone()))
249 .bind(("size", size))
250 .await?
251 .check()?;
252 Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
253 }
254
255 /// Detach the solution's image. Returns the *before* row — its
256 /// `image_file` is the blob the caller must remove.
257 pub async fn clear_image(id: &SolutionId, db: &Database) -> Result<Option<Solution>, AppError> {
258 let mut result = db
259 .query(
260 "UPDATE $s SET image_file = NONE, image_content_type = NONE, image_size = NONE \
261 RETURN BEFORE",
262 )
263 .bind(("s", id.record()))
264 .await?
265 .check()?;
266 Ok(result.take::<Vec<Solution>>(0)?.into_iter().next())
267 }
268
269 pub async fn delete(self, db: &Database) -> Result<Solution, AppError> {
270 let deleted: Option<Solution> = db.delete(self.id.record()).await?;
271 deleted.ok_or(AppError::NotFound)
272 }
273}
274
275#[cfg(test)]
276mod tests {
277 use ulid::Ulid;
278
279 use super::*;
280
281 /// A real question row: offering a solution moves its question's
282 /// `asked_at` (that is what keeps a solution from outliving its question),
283 /// so a minted id nothing wrote is a 404.
284 async fn question_row(db: &Database) -> PoolQuestionId {
285 use crate::domain::pool_question::{PoolQuestion, PoolQuestionBody, PoolQuestionTitle};
286 PoolQuestion::new(
287 &UserId::from_key(&Ulid::new().to_string()),
288 PoolQuestionTitle::try_new("soru").unwrap(),
289 PoolQuestionBody::try_new("neden").unwrap(),
290 )
291 .insert(db)
292 .await
293 .unwrap()
294 .get_id()
295 .clone()
296 }
297
298 #[tokio::test]
299 async fn rows_scope_to_their_question_and_list_oldest_first() {
300 let db = crate::database::init_mem().await.unwrap();
301 let question_a = question_row(&db).await;
302 let question_b = question_row(&db).await;
303 let author = UserId::from_key(&Ulid::new().to_string());
304
305 // Distinct offer times so the assertion pins the real contract —
306 // older `offered_at` sorts first — not the same-millisecond `id`
307 // tiebreak, whose random ULID low bits would make the order a coin
308 // flip (two `now()` reads can land in one millisecond).
309 let mut first = Solution::new(
310 &question_a,
311 &author,
312 SolutionBody::try_new("Önce türevi al.").unwrap(),
313 );
314 first.offered_at = Timestamp::from_millis(1);
315 let first = first.insert(&db).await.unwrap();
316 let mut second = Solution::new(
317 &question_a,
318 &author,
319 SolutionBody::try_new("Ya da tablo yöntemi.").unwrap(),
320 );
321 second.offered_at = Timestamp::from_millis(2);
322 let second = second.insert(&db).await.unwrap();
323
324 let (listed, _) = Solution::list_for(&question_a, None, 0, &db).await.unwrap();
325 assert_eq!(listed.len(), 2);
326 assert_eq!(listed[0].get_id(), first.get_id());
327 assert_eq!(listed[1].get_id(), second.get_id());
328 assert!(
329 Solution::list_for(&question_b, None, 0, &db)
330 .await
331 .unwrap()
332 .0
333 .is_empty()
334 );
335
336 // Readable under its own question, invisible under another.
337 assert!(
338 Solution::read_for(first.get_id(), &question_a, &db)
339 .await
340 .unwrap()
341 .is_some()
342 );
343 assert!(
344 Solution::read_for(first.get_id(), &question_b, &db)
345 .await
346 .unwrap()
347 .is_none()
348 );
349
350 first.delete(&db).await.unwrap();
351 assert_eq!(
352 Solution::list_for(&question_a, None, 0, &db)
353 .await
354 .unwrap()
355 .0
356 .len(),
357 1
358 );
359 }
360
361 #[tokio::test]
362 async fn image_set_replace_clear_report_the_replaced_blob() {
363 let db = crate::database::init_mem().await.unwrap();
364 let question = question_row(&db).await;
365 let author = UserId::from_key(&Ulid::new().to_string());
366 let png = FileContentType::try_new("image/png").unwrap();
367
368 let solution = Solution::new(
369 &question,
370 &author,
371 SolutionBody::try_new("Grafiği çiz.").unwrap(),
372 )
373 .insert(&db)
374 .await
375 .unwrap();
376
377 let before = Solution::set_image(solution.get_id(), "blob_a", &png, 3, &db)
378 .await
379 .unwrap()
380 .unwrap();
381 assert!(before.get_image_file().is_none());
382
383 // A replace reports the old blob for cleanup.
384 let before = Solution::set_image(solution.get_id(), "blob_b", &png, 5, &db)
385 .await
386 .unwrap()
387 .unwrap();
388 assert_eq!(before.get_image_file(), Some("blob_a"));
389 let stored = Solution::read_for(solution.get_id(), &question, &db)
390 .await
391 .unwrap()
392 .unwrap();
393 assert_eq!(stored.get_image_file(), Some("blob_b"));
394 assert_eq!(stored.get_image_size(), Some(5));
395
396 // Clearing reports the detached blob and empties the fields.
397 let before = Solution::clear_image(solution.get_id(), &db)
398 .await
399 .unwrap()
400 .unwrap();
401 assert_eq!(before.get_image_file(), Some("blob_b"));
402 assert!(
403 Solution::read_for(solution.get_id(), &question, &db)
404 .await
405 .unwrap()
406 .unwrap()
407 .get_image_file()
408 .is_none()
409 );
410
411 // A row deleted mid-flight surfaces as None, not an error.
412 solution.clone().delete(&db).await.unwrap();
413 assert!(
414 Solution::set_image(solution.get_id(), "blob_c", &png, 7, &db)
415 .await
416 .unwrap()
417 .is_none()
418 );
419 assert!(
420 Solution::clear_image(solution.get_id(), &db)
421 .await
422 .unwrap()
423 .is_none()
424 );
425 }
426
427 #[tokio::test]
428 async fn set_body_edits_in_place() {
429 let db = crate::database::init_mem().await.unwrap();
430 let question = question_row(&db).await;
431 let author = UserId::from_key(&Ulid::new().to_string());
432
433 let solution = Solution::new(
434 &question,
435 &author,
436 SolutionBody::try_new("İlk deneme.").unwrap(),
437 )
438 .insert(&db)
439 .await
440 .unwrap();
441
442 let edited = Solution::set_body(
443 solution.get_id(),
444 &SolutionBody::try_new("Düzeltilmiş çözüm.").unwrap(),
445 &db,
446 )
447 .await
448 .unwrap()
449 .unwrap();
450 assert_eq!(edited.get_body().as_str(), "Düzeltilmiş çözüm.");
451 assert_eq!(edited.get_id(), solution.get_id());
452
453 // Editing a missing solution is None, not an error.
454 assert!(
455 Solution::set_body(
456 &SolutionId::generate(),
457 &SolutionBody::try_new("boş").unwrap(),
458 &db,
459 )
460 .await
461 .unwrap()
462 .is_none()
463 );
464 }
465
466 #[tokio::test]
467 async fn counts_for_groups_per_question() {
468 let db = crate::database::init_mem().await.unwrap();
469 let two = question_row(&db).await;
470 let one = question_row(&db).await;
471 let none = question_row(&db).await;
472 let author = UserId::from_key(&Ulid::new().to_string());
473
474 for (question, bodies) in [(&two, vec!["a", "b"]), (&one, vec!["c"])] {
475 for body in bodies {
476 Solution::new(question, &author, SolutionBody::try_new(body).unwrap())
477 .insert(&db)
478 .await
479 .unwrap();
480 }
481 }
482
483 let counts = Solution::counts_for(&[two.clone(), one.clone(), none.clone()], &db)
484 .await
485 .unwrap();
486 assert_eq!(counts.get(two.key()), Some(&2));
487 assert_eq!(counts.get(one.key()), Some(&1));
488 // No solutions = no entry; the caller reads the miss as zero.
489 assert_eq!(counts.get(none.key()), None);
490 assert!(Solution::counts_for(&[], &db).await.unwrap().is_empty());
491 }
492
493 #[tokio::test]
494 async fn body_rules() {
495 assert!(SolutionBody::try_new("").is_err());
496 assert!(SolutionBody::try_new(" ").is_err());
497 assert!(SolutionBody::try_new(&"x".repeat(10_001)).is_err());
498 assert_eq!(
499 SolutionBody::try_new("Kısmi integrasyon.")
500 .unwrap()
501 .as_str(),
502 "Kısmi integrasyon."
503 );
504 }
505}