| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use crate::constant::{STATUS_APPROVED, STATUS_PENDING}; |
| 8 | use crate::database::{Database, tx_with_retry}; |
| 9 | use crate::db::page::{PagedList, Param}; |
| 10 | use crate::domain::note_file::FileContentType; |
| 11 | use crate::domain::pool_question::{ |
| 12 | PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, |
| 13 | }; |
| 14 | use crate::domain::solution::{Solution, SolutionBody, SolutionId}; |
| 15 | use crate::domain::timestamp::Timestamp; |
| 16 | use crate::domain::user::UserId; |
| 17 | use crate::error::AppError; |
| 18 | |
| 19 | pub async fn insert(db: &Database, question: PoolQuestion) -> Result<PoolQuestion, AppError> { |
| 20 | let row = sqlx::query_as!( |
| 21 | PoolQuestion, |
| 22 | r#"INSERT INTO pool_question (id, asker, title, body, status, asked_at) |
| 23 | VALUES ($1, $2, $3, $4, $5, $6) |
| 24 | RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 25 | title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 26 | status, asked_at AS "asked_at: Timestamp", |
| 27 | approved_by AS "approved_by: UserId""#, |
| 28 | question.id.uuid(), |
| 29 | question.asker.uuid(), |
| 30 | question.title.as_str(), |
| 31 | question.body.as_str(), |
| 32 | question.status, |
| 33 | question.asked_at.as_millis(), |
| 34 | ) |
| 35 | .fetch_one(db) |
| 36 | .await?; |
| 37 | Ok(row) |
| 38 | } |
| 39 | |
| 40 | pub async fn read(db: &Database, id: &PoolQuestionId) -> Result<Option<PoolQuestion>, AppError> { |
| 41 | let row = sqlx::query_as!( |
| 42 | PoolQuestion, |
| 43 | r#"SELECT id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 44 | title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 45 | status, asked_at AS "asked_at: Timestamp", |
| 46 | approved_by AS "approved_by: UserId" |
| 47 | FROM pool_question WHERE id = $1"#, |
| 48 | id.uuid() |
| 49 | ) |
| 50 | .fetch_optional(db) |
| 51 | .await?; |
| 52 | Ok(row) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | pub async fn list( |
| 70 | db: &Database, |
| 71 | viewer: Option<&UserId>, |
| 72 | status: Option<&str>, |
| 73 | limit: Option<i64>, |
| 74 | offset: i64, |
| 75 | ) -> Result<(Vec<PoolQuestion>, i64), AppError> { |
| 76 | let mut clauses: Vec<String> = Vec::new(); |
| 77 | let mut binds: Vec<Param> = Vec::new(); |
| 78 | if let Some(viewer) = viewer { |
| 79 | binds.push(Param::Text(STATUS_APPROVED.to_string())); |
| 80 | let pool_arm = format!("status = ${}", binds.len()); |
| 81 | binds.push(Param::Uuid(viewer.uuid())); |
| 82 | let own_arm = format!("asker = ${}", binds.len()); |
| 83 | clauses.push(format!("({pool_arm} OR {own_arm})")); |
| 84 | } |
| 85 | if let Some(status) = status { |
| 86 | binds.push(Param::Text(status.to_string())); |
| 87 | clauses.push(format!("status = ${}", binds.len())); |
| 88 | } |
| 89 | let from_where = if clauses.is_empty() { |
| 90 | "pool_question WHERE true".to_string() |
| 91 | } else { |
| 92 | format!("pool_question WHERE {}", clauses.join(" AND ")) |
| 93 | }; |
| 94 | let mut page = PagedList::new(from_where, "ORDER BY asked_at DESC, id DESC"); |
| 95 | for bind in binds { |
| 96 | page = page.bind(bind); |
| 97 | } |
| 98 | page.run(limit, offset, db).await |
| 99 | } |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | pub async fn approve( |
| 134 | db: &Database, |
| 135 | id: &PoolQuestionId, |
| 136 | approver: &UserId, |
| 137 | ) -> Result<Option<PoolQuestion>, AppError> { |
| 138 | let id = *id; |
| 139 | let approver = *approver; |
| 140 | tx_with_retry(db, false, async move |tx| { |
| 141 | let approved = sqlx::query_as!( |
| 142 | PoolQuestion, |
| 143 | r#"UPDATE pool_question SET status = $2, approved_by = $3 |
| 144 | WHERE id = $1 AND status = $4 |
| 145 | RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 146 | title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 147 | status, asked_at AS "asked_at: Timestamp", |
| 148 | approved_by AS "approved_by: UserId""#, |
| 149 | id.uuid(), |
| 150 | STATUS_APPROVED, |
| 151 | approver.uuid(), |
| 152 | STATUS_PENDING, |
| 153 | ) |
| 154 | .fetch_optional(&mut *tx) |
| 155 | .await?; |
| 156 | if let Some(question) = &approved |
| 157 | && question.asker != approver |
| 158 | { |
| 159 | |
| 160 | |
| 161 | sqlx::query!( |
| 162 | "UPDATE app_user SET pool_approved_total = pool_approved_total + 1 |
| 163 | WHERE id = $1", |
| 164 | approver.uuid() |
| 165 | ) |
| 166 | .execute(&mut *tx) |
| 167 | .await?; |
| 168 | sqlx::query!( |
| 169 | "UPDATE app_user SET pool_published_total = pool_published_total + 1 |
| 170 | WHERE id = $1", |
| 171 | question.asker.uuid() |
| 172 | ) |
| 173 | .execute(&mut *tx) |
| 174 | .await?; |
| 175 | } |
| 176 | Ok(approved) |
| 177 | }) |
| 178 | .await |
| 179 | } |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | pub async fn set_image( |
| 198 | db: &Database, |
| 199 | id: &PoolQuestionId, |
| 200 | file: &str, |
| 201 | content_type: &FileContentType, |
| 202 | size: i64, |
| 203 | ) -> Result<Option<Option<String>>, AppError> { |
| 204 | let id = *id; |
| 205 | let file = file.to_owned(); |
| 206 | let content_type = content_type.clone(); |
| 207 | tx_with_retry(db, false, async move |tx| { |
| 208 | let before = sqlx::query!( |
| 209 | r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#, |
| 210 | id.uuid() |
| 211 | ) |
| 212 | .fetch_optional(&mut *tx) |
| 213 | .await?; |
| 214 | let Some(before) = before else { |
| 215 | return Ok(None); |
| 216 | }; |
| 217 | if before.status != STATUS_PENDING { |
| 218 | return Ok(None); |
| 219 | } |
| 220 | let replaced = sqlx::query_scalar!( |
| 221 | r#"SELECT file FROM pool_question_image WHERE question = $1"#, |
| 222 | id.uuid() |
| 223 | ) |
| 224 | .fetch_optional(&mut *tx) |
| 225 | .await?; |
| 226 | sqlx::query!( |
| 227 | r#"INSERT INTO pool_question_image (question, file, content_type, size) |
| 228 | VALUES ($1, $2, $3, $4) |
| 229 | ON CONFLICT (question) DO UPDATE |
| 230 | SET file = EXCLUDED.file, content_type = EXCLUDED.content_type, |
| 231 | size = EXCLUDED.size"#, |
| 232 | id.uuid(), |
| 233 | file, |
| 234 | content_type.as_str(), |
| 235 | size, |
| 236 | ) |
| 237 | .execute(&mut *tx) |
| 238 | .await?; |
| 239 | Ok(Some(replaced)) |
| 240 | }) |
| 241 | .await |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | pub async fn clear_image( |
| 249 | db: &Database, |
| 250 | id: &PoolQuestionId, |
| 251 | ) -> Result<Option<Option<String>>, AppError> { |
| 252 | let id = *id; |
| 253 | tx_with_retry(db, false, async move |tx| { |
| 254 | let before = sqlx::query!( |
| 255 | r#"SELECT status FROM pool_question WHERE id = $1 FOR UPDATE"#, |
| 256 | id.uuid() |
| 257 | ) |
| 258 | .fetch_optional(&mut *tx) |
| 259 | .await?; |
| 260 | let Some(before) = before else { |
| 261 | return Ok(None); |
| 262 | }; |
| 263 | if before.status != STATUS_PENDING { |
| 264 | return Ok(None); |
| 265 | } |
| 266 | let detached = sqlx::query_scalar!( |
| 267 | r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#, |
| 268 | id.uuid() |
| 269 | ) |
| 270 | .fetch_optional(&mut *tx) |
| 271 | .await?; |
| 272 | Ok(Some(detached)) |
| 273 | }) |
| 274 | .await |
| 275 | } |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | #[derive(Debug)] |
| 281 | pub struct Deleted { |
| 282 | pub question: PoolQuestion, |
| 283 | pub solutions: Vec<Solution>, |
| 284 | pub image_files: Vec<String>, |
| 285 | } |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | pub async fn delete(db: &Database, id: &PoolQuestionId) -> Result<Option<Deleted>, AppError> { |
| 301 | let id = *id; |
| 302 | tx_with_retry(db, true, async move |tx| { |
| 303 | let solution_files = sqlx::query_scalar!( |
| 304 | r#"DELETE FROM solution_image si |
| 305 | USING solution s |
| 306 | WHERE si.solution = s.id AND s.question = $1 |
| 307 | RETURNING si.file"#, |
| 308 | id.uuid() |
| 309 | ) |
| 310 | .fetch_all(&mut *tx) |
| 311 | .await?; |
| 312 | let solutions = sqlx::query_as!( |
| 313 | Solution, |
| 314 | r#"DELETE FROM solution WHERE question = $1 |
| 315 | RETURNING id AS "id: SolutionId", question AS "question: PoolQuestionId", |
| 316 | author AS "author: UserId", body AS "body: SolutionBody", |
| 317 | offered_at AS "offered_at: Timestamp""#, |
| 318 | id.uuid() |
| 319 | ) |
| 320 | .fetch_all(&mut *tx) |
| 321 | .await?; |
| 322 | let question_file = sqlx::query_scalar!( |
| 323 | r#"DELETE FROM pool_question_image WHERE question = $1 RETURNING file"#, |
| 324 | id.uuid() |
| 325 | ) |
| 326 | .fetch_optional(&mut *tx) |
| 327 | .await?; |
| 328 | let question = sqlx::query_as!( |
| 329 | PoolQuestion, |
| 330 | r#"DELETE FROM pool_question WHERE id = $1 |
| 331 | RETURNING id AS "id: PoolQuestionId", asker AS "asker: UserId", |
| 332 | title AS "title: PoolQuestionTitle", body AS "body: PoolQuestionBody", |
| 333 | status, asked_at AS "asked_at: Timestamp", |
| 334 | approved_by AS "approved_by: UserId""#, |
| 335 | id.uuid() |
| 336 | ) |
| 337 | .fetch_optional(&mut *tx) |
| 338 | .await?; |
| 339 | Ok(question.map(|question| { |
| 340 | let mut image_files = solution_files; |
| 341 | image_files.extend(question_file); |
| 342 | Deleted { |
| 343 | question, |
| 344 | solutions, |
| 345 | image_files, |
| 346 | } |
| 347 | })) |
| 348 | }) |
| 349 | .await |
| 350 | } |
| 351 | |
| 352 | #[cfg(test)] |
| 353 | mod tests { |
| 354 | use super::*; |
| 355 | use crate::database; |
| 356 | use crate::domain::solution::SolutionBody; |
| 357 | use sqlx::Row as _; |
| 358 | |
| 359 | |
| 360 | |
| 361 | async fn a_user(db: &Database) -> UserId { |
| 362 | let user = UserId::generate(); |
| 363 | sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)") |
| 364 | .bind(user.uuid()) |
| 365 | .bind(format!("u{}", &user.key()[30..])) |
| 366 | .execute(db) |
| 367 | .await |
| 368 | .unwrap(); |
| 369 | user |
| 370 | } |
| 371 | |
| 372 | |
| 373 | |
| 374 | async fn counters(user: &UserId, db: &Database) -> (i64, i64) { |
| 375 | let row = sqlx::query( |
| 376 | "SELECT pool_approved_total, pool_published_total \ |
| 377 | FROM app_user WHERE id = $1", |
| 378 | ) |
| 379 | .bind(user.uuid()) |
| 380 | .fetch_one(db) |
| 381 | .await |
| 382 | .unwrap(); |
| 383 | ( |
| 384 | row.try_get::<i64, _>(0).unwrap(), |
| 385 | row.try_get::<i64, _>(1).unwrap(), |
| 386 | ) |
| 387 | } |
| 388 | |
| 389 | fn question(asker: &UserId) -> PoolQuestion { |
| 390 | use crate::domain::pool_question::{PoolQuestionBody, PoolQuestionTitle}; |
| 391 | PoolQuestion::new( |
| 392 | asker, |
| 393 | PoolQuestionTitle::try_new("Bu integral nasıl çözülür?").unwrap(), |
| 394 | PoolQuestionBody::try_new("∫x·eˣ dx adım adım?").unwrap(), |
| 395 | ) |
| 396 | } |
| 397 | |
| 398 | #[tokio::test] |
| 399 | async fn approval_is_a_one_way_race_safe_transition() { |
| 400 | let (db, _leases) = database::init_test_db().await; |
| 401 | let asker = a_user(&db).await; |
| 402 | let teacher = a_user(&db).await; |
| 403 | |
| 404 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 405 | assert_eq!(q.get_status(), STATUS_PENDING); |
| 406 | assert!(q.get_approved_by().is_none()); |
| 407 | |
| 408 | let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); |
| 409 | assert!(approved.is_approved()); |
| 410 | assert_eq!(approved.get_approved_by(), Some(&teacher)); |
| 411 | |
| 412 | |
| 413 | assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); |
| 414 | |
| 415 | assert!( |
| 416 | approve(&db, &PoolQuestionId::generate(), &teacher) |
| 417 | .await |
| 418 | .unwrap() |
| 419 | .is_none() |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | |
| 424 | |
| 425 | #[tokio::test] |
| 426 | async fn approval_moves_both_counters_once_and_only_once() { |
| 427 | let (db, _leases) = database::init_test_db().await; |
| 428 | let asker = a_user(&db).await; |
| 429 | let teacher = a_user(&db).await; |
| 430 | |
| 431 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 432 | assert_eq!(counters(&asker, &db).await, (0, 0), "absent reads zero"); |
| 433 | |
| 434 | approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); |
| 435 | assert_eq!(counters(&teacher, &db).await, (1, 0), "the approver"); |
| 436 | assert_eq!(counters(&asker, &db).await, (0, 1), "the asker"); |
| 437 | |
| 438 | |
| 439 | |
| 440 | assert!(approve(&db, q.get_id(), &teacher).await.unwrap().is_none()); |
| 441 | assert_eq!(counters(&teacher, &db).await, (1, 0), "still one approve"); |
| 442 | assert_eq!(counters(&asker, &db).await, (0, 1), "still one publish"); |
| 443 | |
| 444 | |
| 445 | assert!( |
| 446 | approve(&db, &PoolQuestionId::generate(), &teacher) |
| 447 | .await |
| 448 | .unwrap() |
| 449 | .is_none() |
| 450 | ); |
| 451 | assert_eq!(counters(&teacher, &db).await, (1, 0)); |
| 452 | } |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | #[tokio::test] |
| 459 | async fn self_approval_still_approves_but_moves_neither_counter() { |
| 460 | let (db, _leases) = database::init_test_db().await; |
| 461 | let teacher = a_user(&db).await; |
| 462 | |
| 463 | let q = insert(&db, question(&teacher)).await.unwrap(); |
| 464 | let approved = approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); |
| 465 | |
| 466 | assert!(approved.is_approved()); |
| 467 | assert_eq!(approved.get_approved_by(), Some(&teacher)); |
| 468 | assert_eq!(counters(&teacher, &db).await, (0, 0), "no self-credit"); |
| 469 | |
| 470 | |
| 471 | |
| 472 | let asker = a_user(&db).await; |
| 473 | let other = insert(&db, question(&asker)).await.unwrap(); |
| 474 | approve(&db, other.get_id(), &teacher) |
| 475 | .await |
| 476 | .unwrap() |
| 477 | .unwrap(); |
| 478 | assert_eq!(counters(&teacher, &db).await, (1, 0)); |
| 479 | assert_eq!(counters(&asker, &db).await, (0, 1)); |
| 480 | } |
| 481 | |
| 482 | #[tokio::test] |
| 483 | async fn visibility_hides_others_pending_questions() { |
| 484 | let (db, _leases) = database::init_test_db().await; |
| 485 | let asker = a_user(&db).await; |
| 486 | let other = a_user(&db).await; |
| 487 | let teacher = a_user(&db).await; |
| 488 | |
| 489 | let pending = insert(&db, question(&asker)).await.unwrap(); |
| 490 | let published = insert(&db, question(&other)).await.unwrap(); |
| 491 | approve(&db, published.get_id(), &teacher) |
| 492 | .await |
| 493 | .unwrap() |
| 494 | .unwrap(); |
| 495 | |
| 496 | |
| 497 | |
| 498 | let (asker_view, total) = list(&db, Some(&asker), None, None, 0).await.unwrap(); |
| 499 | assert_eq!(asker_view.len(), 2); |
| 500 | assert_eq!(total, 2); |
| 501 | let (stranger_view, total) = list(&db, Some(&other), None, None, 0).await.unwrap(); |
| 502 | assert_eq!(stranger_view.len(), 1); |
| 503 | assert_eq!(total, 1); |
| 504 | assert_eq!(stranger_view[0].get_id(), published.get_id()); |
| 505 | let (everything, total) = list(&db, None, None, None, 0).await.unwrap(); |
| 506 | assert_eq!(everything.len(), 2); |
| 507 | assert_eq!(total, 2); |
| 508 | assert!(read(&db, pending.get_id()).await.unwrap().is_some()); |
| 509 | } |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | #[tokio::test] |
| 517 | async fn status_filter_narrows_within_the_visibility_gate() { |
| 518 | let (db, _leases) = database::init_test_db().await; |
| 519 | let asker = a_user(&db).await; |
| 520 | let other = a_user(&db).await; |
| 521 | let teacher = a_user(&db).await; |
| 522 | |
| 523 | let mine_pending = insert(&db, question(&asker)).await.unwrap(); |
| 524 | let theirs_pending = insert(&db, question(&other)).await.unwrap(); |
| 525 | let mine_pool = insert(&db, question(&asker)).await.unwrap(); |
| 526 | approve(&db, mine_pool.get_id(), &teacher).await.unwrap().unwrap(); |
| 527 | let theirs_pool = insert(&db, question(&other)).await.unwrap(); |
| 528 | approve(&db, theirs_pool.get_id(), &teacher).await.unwrap().unwrap(); |
| 529 | |
| 530 | |
| 531 | let (items, total) = |
| 532 | list(&db, Some(&asker), Some(STATUS_PENDING), None, 0).await.unwrap(); |
| 533 | assert_eq!(items.len(), 1); |
| 534 | assert_eq!(total, 1); |
| 535 | assert_eq!(items[0].get_id(), mine_pending.get_id()); |
| 536 | assert_ne!(items[0].get_id(), theirs_pending.get_id()); |
| 537 | |
| 538 | |
| 539 | let (items, total) = |
| 540 | list(&db, Some(&asker), Some(STATUS_APPROVED), None, 0).await.unwrap(); |
| 541 | assert_eq!(items.len(), 2); |
| 542 | assert_eq!(total, 2); |
| 543 | |
| 544 | |
| 545 | let (items, total) = list(&db, None, Some(STATUS_PENDING), None, 0).await.unwrap(); |
| 546 | assert_eq!(items.len(), 2); |
| 547 | assert_eq!(total, 2); |
| 548 | |
| 549 | |
| 550 | let (items, total) = |
| 551 | list(&db, None, Some(STATUS_PENDING), Some(1), 0).await.unwrap(); |
| 552 | assert_eq!(items.len(), 1); |
| 553 | assert_eq!(total, 2); |
| 554 | } |
| 555 | |
| 556 | #[tokio::test] |
| 557 | async fn image_attaches_only_while_pending_and_reports_the_replaced_blob() { |
| 558 | let (db, _leases) = database::init_test_db().await; |
| 559 | let asker = a_user(&db).await; |
| 560 | let teacher = a_user(&db).await; |
| 561 | let png = FileContentType::try_new("image/png").unwrap(); |
| 562 | |
| 563 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 564 | let replaced = set_image(&db, q.get_id(), "blob_a", &png, 3) |
| 565 | .await |
| 566 | .unwrap() |
| 567 | .unwrap(); |
| 568 | assert!(replaced.is_none()); |
| 569 | |
| 570 | |
| 571 | let replaced = set_image(&db, q.get_id(), "blob_b", &png, 5) |
| 572 | .await |
| 573 | .unwrap() |
| 574 | .unwrap(); |
| 575 | assert_eq!(replaced.as_deref(), Some("blob_a")); |
| 576 | let stored = crate::db::pool_question_image::read(&db, q.get_id()) |
| 577 | .await |
| 578 | .unwrap() |
| 579 | .unwrap(); |
| 580 | assert_eq!(stored.get_file(), "blob_b"); |
| 581 | assert_eq!(stored.get_size(), 5); |
| 582 | |
| 583 | |
| 584 | let detached = clear_image(&db, q.get_id()).await.unwrap().unwrap(); |
| 585 | assert_eq!(detached.as_deref(), Some("blob_b")); |
| 586 | assert!( |
| 587 | crate::db::pool_question_image::read(&db, q.get_id()) |
| 588 | .await |
| 589 | .unwrap() |
| 590 | .is_none() |
| 591 | ); |
| 592 | |
| 593 | |
| 594 | approve(&db, q.get_id(), &teacher).await.unwrap().unwrap(); |
| 595 | assert!( |
| 596 | set_image(&db, q.get_id(), "blob_c", &png, 7) |
| 597 | .await |
| 598 | .unwrap() |
| 599 | .is_none() |
| 600 | ); |
| 601 | assert!(clear_image(&db, q.get_id()).await.unwrap().is_none()); |
| 602 | } |
| 603 | |
| 604 | #[tokio::test] |
| 605 | async fn delete_cascades_solutions_and_returns_the_row() { |
| 606 | let (db, _leases) = database::init_test_db().await; |
| 607 | let asker = a_user(&db).await; |
| 608 | let helper = a_user(&db).await; |
| 609 | let png = FileContentType::try_new("image/png").unwrap(); |
| 610 | |
| 611 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 612 | let offered = crate::db::solution::insert( |
| 613 | &db, |
| 614 | Solution::new( |
| 615 | q.get_id(), |
| 616 | &helper, |
| 617 | SolutionBody::try_new("Kısmi integrasyon uygula.").unwrap(), |
| 618 | ), |
| 619 | ) |
| 620 | .await |
| 621 | .unwrap(); |
| 622 | |
| 623 | |
| 624 | set_image(&db, q.get_id(), "q_blob", &png, 1) |
| 625 | .await |
| 626 | .unwrap() |
| 627 | .unwrap(); |
| 628 | crate::db::solution::set_image(&db, offered.get_id(), "s_blob", &png, 2) |
| 629 | .await |
| 630 | .unwrap() |
| 631 | .unwrap(); |
| 632 | |
| 633 | |
| 634 | |
| 635 | let removed = delete(&db, q.get_id()).await.unwrap().unwrap(); |
| 636 | assert_eq!(removed.question.get_id(), q.get_id()); |
| 637 | assert_eq!(removed.solutions.len(), 1); |
| 638 | assert_eq!(removed.solutions[0].get_id(), offered.get_id()); |
| 639 | assert_eq!(removed.image_files.len(), 2); |
| 640 | assert!(removed.image_files.contains(&"q_blob".to_string())); |
| 641 | assert!(removed.image_files.contains(&"s_blob".to_string())); |
| 642 | assert!(read(&db, q.get_id()).await.unwrap().is_none()); |
| 643 | assert!( |
| 644 | crate::db::solution::list_for(&db, q.get_id(), None, 0) |
| 645 | .await |
| 646 | .unwrap() |
| 647 | .0 |
| 648 | .is_empty() |
| 649 | ); |
| 650 | |
| 651 | |
| 652 | assert!(delete(&db, q.get_id()).await.unwrap().is_none()); |
| 653 | } |
| 654 | |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 673 | async fn a_solution_offered_inside_a_delete_never_outlives_its_question() { |
| 674 | let (db, _leases) = database::init_test_db().await; |
| 675 | |
| 676 | async fn offer( |
| 677 | db: &Database, |
| 678 | id: &PoolQuestionId, |
| 679 | helper: &UserId, |
| 680 | ) -> Result<Solution, AppError> { |
| 681 | crate::db::solution::insert( |
| 682 | db, |
| 683 | Solution::new( |
| 684 | id, |
| 685 | helper, |
| 686 | SolutionBody::try_new("Kismi integrasyon uygula.").unwrap(), |
| 687 | ), |
| 688 | ) |
| 689 | .await |
| 690 | } |
| 691 | |
| 692 | async fn solutions(db: &Database, id: &PoolQuestionId) -> usize { |
| 693 | crate::db::solution::list_for(db, id, None, 0) |
| 694 | .await |
| 695 | .unwrap() |
| 696 | .0 |
| 697 | .len() |
| 698 | } |
| 699 | |
| 700 | |
| 701 | { |
| 702 | let asker = a_user(&db).await; |
| 703 | let helper = a_user(&db).await; |
| 704 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 705 | let id = *q.get_id(); |
| 706 | let dropped = delete(&db, &id).await; |
| 707 | assert!( |
| 708 | !matches!(dropped, Err(AppError::Db(_))), |
| 709 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 710 | ); |
| 711 | assert!( |
| 712 | read(&db, &id).await.unwrap().is_none(), |
| 713 | "delete-first: the question is still there after delete: {dropped:?}" |
| 714 | ); |
| 715 | let child = offer(&db, &id, &helper).await; |
| 716 | assert!( |
| 717 | !matches!(child, Err(AppError::Db(_))), |
| 718 | "delete-first: an offer must be answered, not 500: {child:?}" |
| 719 | ); |
| 720 | assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); |
| 721 | } |
| 722 | |
| 723 | |
| 724 | { |
| 725 | let asker = a_user(&db).await; |
| 726 | let helper = a_user(&db).await; |
| 727 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 728 | let id = *q.get_id(); |
| 729 | let child = offer(&db, &id, &helper).await; |
| 730 | assert!( |
| 731 | child.is_ok(), |
| 732 | "write-first: the offer must land before the delete: {child:?}" |
| 733 | ); |
| 734 | let dropped = delete(&db, &id).await; |
| 735 | assert!( |
| 736 | !matches!(dropped, Err(AppError::Db(_))), |
| 737 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 738 | ); |
| 739 | assert!( |
| 740 | read(&db, &id).await.unwrap().is_none(), |
| 741 | "write-first: the question is still there" |
| 742 | ); |
| 743 | assert_eq!(solutions(&db, &id).await, 0, "a solution outlived its question"); |
| 744 | } |
| 745 | |
| 746 | |
| 747 | let mut swept = 0; |
| 748 | for round in 0..4 { |
| 749 | let asker = a_user(&db).await; |
| 750 | let helper = a_user(&db).await; |
| 751 | let q = insert(&db, question(&asker)).await.unwrap(); |
| 752 | let id = *q.get_id(); |
| 753 | |
| 754 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 755 | let drop_it = { |
| 756 | let (db, id, gate) = (db.clone(), id, gate.clone()); |
| 757 | tokio::spawn(async move { |
| 758 | gate.wait().await; |
| 759 | delete(&db, &id).await |
| 760 | }) |
| 761 | }; |
| 762 | let child = { |
| 763 | let (db, id, helper, gate) = (db.clone(), id, helper, gate); |
| 764 | tokio::spawn(async move { |
| 765 | gate.wait().await; |
| 766 | offer(&db, &id, &helper).await |
| 767 | }) |
| 768 | }; |
| 769 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 770 | assert!( |
| 771 | !matches!(child, Err(AppError::Db(_))), |
| 772 | "round {round}: a raced offer must be answered, not 500: {child:?}" |
| 773 | ); |
| 774 | assert!( |
| 775 | !matches!(drop_it, Err(AppError::Db(_))), |
| 776 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 777 | ); |
| 778 | |
| 779 | if read(&db, &id).await.unwrap().is_none() { |
| 780 | swept += 1; |
| 781 | assert_eq!( |
| 782 | solutions(&db, &id).await, |
| 783 | 0, |
| 784 | "round {round}: a solution outlived its question" |
| 785 | ); |
| 786 | } else if drop_it.is_ok() { |
| 787 | panic!( |
| 788 | "round {round}: the delete reported success but the question is still there" |
| 789 | ); |
| 790 | } |
| 791 | } |
| 792 | eprintln!( |
| 793 | "pool_question::delete raced by an offer: {swept}/4 concurrent rounds deleted the question" |
| 794 | ); |
| 795 | } |
| 796 | } |