| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use sqlx::PgConnection; |
| 6 | |
| 7 | use crate::database::{Database, foreign_key_violation, tx_with_retry}; |
| 8 | use crate::db::page::{PagedList, Param}; |
| 9 | use crate::domain::class_course::ClassCourseId; |
| 10 | use crate::domain::course::CourseId; |
| 11 | use crate::domain::exam::{ |
| 12 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamId, ExamKind, ExamMode, |
| 13 | ExamSchedule, ExamTitle, redraft_error, |
| 14 | }; |
| 15 | use crate::domain::term::TermId; |
| 16 | use crate::domain::timestamp::Timestamp; |
| 17 | use crate::domain::user::UserId; |
| 18 | use crate::error::AppError; |
| 19 | |
| 20 | #[expect( |
| 21 | clippy::too_many_arguments, |
| 22 | reason = "mirrors the sibling entities' create(field, field, ..) shape" |
| 23 | )] |
| 24 | pub async fn create( |
| 25 | db: &Database, |
| 26 | creator: &UserId, |
| 27 | class_course: &ClassCourseId, |
| 28 | term: &TermId, |
| 29 | title: ExamTitle, |
| 30 | description: ExamDescription, |
| 31 | kind: ExamKind, |
| 32 | schedule: ExamSchedule, |
| 33 | max_attempts: ExamAttemptLimit, |
| 34 | allow_rejoin: bool, |
| 35 | allow_review: bool, |
| 36 | draft: bool, |
| 37 | ) -> Result<Exam, AppError> { |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | let id = ExamId::generate(); |
| 55 | let creator = *creator; |
| 56 | let class_course = class_course.clone(); |
| 57 | |
| 58 | |
| 59 | let term = *term; |
| 60 | |
| 61 | |
| 62 | |
| 63 | let title_text = title.as_str().to_string(); |
| 64 | let description_text = description.as_str().to_string(); |
| 65 | let kind_text = kind.as_str().to_string(); |
| 66 | let mode_text = schedule.mode.as_ref().map(|mode| mode.as_str().to_string()); |
| 67 | let starts_at = schedule.starts_at.map(|at| at.as_millis()); |
| 68 | let ends_at = schedule.ends_at.map(|at| at.as_millis()); |
| 69 | let duration_ms = schedule.duration_ms.map(|duration| duration.as_millis()); |
| 70 | let max_attempts = max_attempts.as_i64(); |
| 71 | let created = tx_with_retry(db, false, async move |tx| { |
| 72 | insert_in( |
| 73 | tx, |
| 74 | id.clone(), |
| 75 | creator, |
| 76 | class_course.clone(), |
| 77 | term, |
| 78 | title_text.clone(), |
| 79 | description_text.clone(), |
| 80 | kind_text.clone(), |
| 81 | mode_text.clone(), |
| 82 | starts_at, |
| 83 | ends_at, |
| 84 | duration_ms, |
| 85 | max_attempts, |
| 86 | allow_rejoin, |
| 87 | allow_review, |
| 88 | draft, |
| 89 | ) |
| 90 | .await |
| 91 | }) |
| 92 | .await?; |
| 93 | Ok(created) |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | #[expect( |
| 113 | clippy::too_many_arguments, |
| 114 | reason = "the create's own field list, spelled once for the named future" |
| 115 | )] |
| 116 | pub(crate) async fn insert_in( |
| 117 | tx: &mut PgConnection, |
| 118 | id: ExamId, |
| 119 | creator: UserId, |
| 120 | class_course: ClassCourseId, |
| 121 | term: TermId, |
| 122 | title: String, |
| 123 | description: String, |
| 124 | kind: String, |
| 125 | mode: Option<String>, |
| 126 | starts_at: Option<i64>, |
| 127 | ends_at: Option<i64>, |
| 128 | duration_ms: Option<i64>, |
| 129 | max_attempts: i64, |
| 130 | allow_rejoin: bool, |
| 131 | allow_review: bool, |
| 132 | draft: bool, |
| 133 | ) -> Result<Exam, AppError> { |
| 134 | let written = sqlx::query_as!( |
| 135 | Exam, |
| 136 | r#"WITH room AS ( |
| 137 | UPDATE term SET exam_count = exam_count + 1 |
| 138 | WHERE id = $3 |
| 139 | RETURNING 1) |
| 140 | INSERT INTO exam (id, creator, class_course, term, title, description, kind, mode, |
| 141 | starts_at, ends_at, duration_ms, max_attempts, |
| 142 | allow_rejoin, allow_review, draft) |
| 143 | SELECT $1, $2, $4, $3, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15 |
| 144 | WHERE EXISTS (SELECT 1 FROM room) |
| 145 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 146 | class_course AS "class_course: ClassCourseId", |
| 147 | term AS "term: TermId", title AS "title: ExamTitle", |
| 148 | description AS "description: ExamDescription", |
| 149 | kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 150 | starts_at AS "starts_at: Timestamp", |
| 151 | ends_at AS "ends_at: Timestamp", |
| 152 | duration_ms AS "duration_ms: ExamDuration", |
| 153 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 154 | allow_rejoin, allow_review, draft"#, |
| 155 | id.uuid(), |
| 156 | creator.uuid(), |
| 157 | term.uuid(), |
| 158 | class_course.uuid(), |
| 159 | title.as_str(), |
| 160 | description.as_str(), |
| 161 | kind.as_str(), |
| 162 | mode.as_deref(), |
| 163 | starts_at, |
| 164 | ends_at, |
| 165 | duration_ms, |
| 166 | max_attempts, |
| 167 | allow_rejoin, |
| 168 | allow_review, |
| 169 | draft, |
| 170 | ) |
| 171 | .fetch_optional(&mut *tx) |
| 172 | .await; |
| 173 | let exam = match written { |
| 174 | Ok(Some(exam)) => exam, |
| 175 | |
| 176 | Ok(None) => return Err(crate::domain::term::gone_error()), |
| 177 | Err(err) if foreign_key_violation(&err) => return Err(AppError::NotFound), |
| 178 | Err(err) => return Err(err.into()), |
| 179 | }; |
| 180 | sqlx::query!( |
| 181 | r#"INSERT INTO exam_audience (exam, class_course) VALUES ($1, $2)"#, |
| 182 | exam.id.uuid(), |
| 183 | exam.class_course.uuid(), |
| 184 | ) |
| 185 | .execute(&mut *tx) |
| 186 | .await?; |
| 187 | Ok(exam) |
| 188 | } |
| 189 | |
| 190 | pub async fn read(db: &Database, id: &ExamId) -> Result<Option<Exam>, AppError> { |
| 191 | Ok(sqlx::query_as!( |
| 192 | Exam, |
| 193 | r#"SELECT id AS "id: ExamId", creator AS "creator: UserId", |
| 194 | class_course AS "class_course: ClassCourseId", term AS "term: TermId", |
| 195 | title AS "title: ExamTitle", description AS "description: ExamDescription", |
| 196 | kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 197 | starts_at AS "starts_at: Timestamp", |
| 198 | ends_at AS "ends_at: Timestamp", |
| 199 | duration_ms AS "duration_ms: ExamDuration", |
| 200 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 201 | allow_rejoin, allow_review, draft |
| 202 | FROM exam WHERE id = $1"#, |
| 203 | id.uuid(), |
| 204 | ) |
| 205 | .fetch_optional(db) |
| 206 | .await?) |
| 207 | } |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | #[derive(Default)] |
| 219 | pub struct WindowedListParams { |
| 220 | pub starts_after: Option<i64>, |
| 221 | pub ends_after: Option<i64>, |
| 222 | pub starts_before: Option<i64>, |
| 223 | pub ends_before: Option<i64>, |
| 224 | |
| 225 | pub limit: Option<i64>, |
| 226 | pub offset: i64, |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | pub async fn list_windowed( |
| 240 | db: &Database, |
| 241 | visible: Option<&[ClassCourseId]>, |
| 242 | managed: Option<&[ClassCourseId]>, |
| 243 | params: WindowedListParams, |
| 244 | ) -> Result<(Vec<Exam>, i64), AppError> { |
| 245 | let WindowedListParams { |
| 246 | starts_after, |
| 247 | ends_after, |
| 248 | starts_before, |
| 249 | ends_before, |
| 250 | limit, |
| 251 | offset, |
| 252 | } = params; |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | let base = usize::from(visible.is_some()) * 2; |
| 258 | let mut conds: Vec<String> = Vec::new(); |
| 259 | let mut bounds: Vec<i64> = Vec::new(); |
| 260 | let mut bound = |column: &str, op: &str, value: Option<i64>| { |
| 261 | if let Some(value) = value { |
| 262 | conds.push(format!("{column} {op} ${}", base + bounds.len() + 1)); |
| 263 | bounds.push(value); |
| 264 | } |
| 265 | }; |
| 266 | bound("starts_at", ">", starts_after); |
| 267 | bound("starts_at", "<", starts_before); |
| 268 | bound("COALESCE(ends_at, starts_at)", ">", ends_after); |
| 269 | bound("COALESCE(ends_at, starts_at)", "<", ends_before); |
| 270 | let window = if conds.is_empty() { |
| 271 | String::new() |
| 272 | } else { |
| 273 | format!(" AND {}", conds.join(" AND ")) |
| 274 | }; |
| 275 | let (from_where, mut binds): (String, Vec<Param>) = match visible { |
| 276 | None => ( |
| 277 | if conds.is_empty() { |
| 278 | "exam".to_owned() |
| 279 | } else { |
| 280 | format!("exam WHERE {}", conds.join(" AND ")) |
| 281 | }, |
| 282 | Vec::new(), |
| 283 | ), |
| 284 | Some(visible) => { |
| 285 | let managed = managed.expect("visible and managed travel together"); |
| 286 | ( |
| 287 | format!( |
| 288 | "(SELECT DISTINCT ON (e.id) e.* \ |
| 289 | FROM exam e \ |
| 290 | JOIN exam_audience a ON a.exam = e.id \ |
| 291 | WHERE a.class_course = ANY($1::uuid[]) \ |
| 292 | AND (NOT e.draft OR e.class_course = ANY($2::uuid[])){window} \ |
| 293 | ORDER BY e.id)" |
| 294 | ), |
| 295 | vec![ |
| 296 | Param::Texts(visible.iter().map(ClassCourseId::key).collect()), |
| 297 | Param::Texts(managed.iter().map(ClassCourseId::key).collect()), |
| 298 | ], |
| 299 | ) |
| 300 | } |
| 301 | }; |
| 302 | let order = if conds.is_empty() { |
| 303 | "ORDER BY id DESC" |
| 304 | } else { |
| 305 | "ORDER BY COALESCE(starts_at, ends_at) ASC, id ASC" |
| 306 | }; |
| 307 | let mut list = PagedList::new(from_where, order); |
| 308 | for bind in binds.drain(..) { |
| 309 | list = list.bind(bind); |
| 310 | } |
| 311 | for value in bounds { |
| 312 | list = list.bind(value); |
| 313 | } |
| 314 | list.run::<Exam>(limit, offset, db).await |
| 315 | } |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | pub async fn list_for_class_course( |
| 324 | db: &Database, |
| 325 | class_course: &ClassCourseId, |
| 326 | ) -> Result<Vec<Exam>, AppError> { |
| 327 | Ok(sqlx::query_as!( |
| 328 | Exam, |
| 329 | r#"SELECT DISTINCT ON (e.id) |
| 330 | e.id AS "id: ExamId", e.creator AS "creator: UserId", |
| 331 | e.class_course AS "class_course: ClassCourseId", |
| 332 | e.term AS "term: TermId", e.title AS "title: ExamTitle", |
| 333 | e.description AS "description: ExamDescription", |
| 334 | e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", |
| 335 | e.starts_at AS "starts_at: Timestamp", |
| 336 | e.ends_at AS "ends_at: Timestamp", |
| 337 | e.duration_ms AS "duration_ms: ExamDuration", |
| 338 | e.max_attempts AS "max_attempts: ExamAttemptLimit", |
| 339 | e.allow_rejoin, e.allow_review, e.draft |
| 340 | FROM exam e |
| 341 | JOIN exam_audience a ON a.exam = e.id |
| 342 | WHERE a.class_course = $1 |
| 343 | ORDER BY e.id DESC"#, |
| 344 | class_course.uuid(), |
| 345 | ) |
| 346 | .fetch_all(db) |
| 347 | .await?) |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | pub async fn list_for_class_course_courses( |
| 359 | db: &Database, |
| 360 | instances: &[ClassCourseId], |
| 361 | ) -> Result<Vec<Exam>, AppError> { |
| 362 | if instances.is_empty() { |
| 363 | return Ok(Vec::new()); |
| 364 | } |
| 365 | let instances = instances |
| 366 | .iter() |
| 367 | .map(ClassCourseId::uuid) |
| 368 | .collect::<Vec<_>>(); |
| 369 | Ok(sqlx::query_as!( |
| 370 | Exam, |
| 371 | r#"SELECT DISTINCT ON (e.id) |
| 372 | e.id AS "id: ExamId", e.creator AS "creator: UserId", |
| 373 | e.class_course AS "class_course: ClassCourseId", |
| 374 | e.term AS "term: TermId", e.title AS "title: ExamTitle", |
| 375 | e.description AS "description: ExamDescription", |
| 376 | e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", |
| 377 | e.starts_at AS "starts_at: Timestamp", |
| 378 | e.ends_at AS "ends_at: Timestamp", |
| 379 | e.duration_ms AS "duration_ms: ExamDuration", |
| 380 | e.max_attempts AS "max_attempts: ExamAttemptLimit", |
| 381 | e.allow_rejoin, e.allow_review, e.draft |
| 382 | FROM exam e |
| 383 | JOIN exam_audience a ON a.exam = e.id |
| 384 | WHERE a.class_course = ANY($1) |
| 385 | ORDER BY e.id DESC"#, |
| 386 | &instances, |
| 387 | ) |
| 388 | .fetch_all(db) |
| 389 | .await?) |
| 390 | } |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | pub async fn list_for_courses(db: &Database, courses: &[CourseId]) -> Result<Vec<Exam>, AppError> { |
| 396 | if courses.is_empty() { |
| 397 | return Ok(Vec::new()); |
| 398 | } |
| 399 | let courses = courses.iter().map(CourseId::uuid).collect::<Vec<_>>(); |
| 400 | Ok(sqlx::query_as!( |
| 401 | Exam, |
| 402 | r#"SELECT DISTINCT ON (e.id) |
| 403 | e.id AS "id: ExamId", e.creator AS "creator: UserId", |
| 404 | e.class_course AS "class_course: ClassCourseId", |
| 405 | e.term AS "term: TermId", e.title AS "title: ExamTitle", |
| 406 | e.description AS "description: ExamDescription", |
| 407 | e.kind AS "kind: ExamKind", e.mode AS "mode: ExamMode", |
| 408 | e.starts_at AS "starts_at: Timestamp", |
| 409 | e.ends_at AS "ends_at: Timestamp", |
| 410 | e.duration_ms AS "duration_ms: ExamDuration", |
| 411 | e.max_attempts AS "max_attempts: ExamAttemptLimit", |
| 412 | e.allow_rejoin, e.allow_review, e.draft |
| 413 | FROM exam e |
| 414 | JOIN exam_audience a ON a.exam = e.id |
| 415 | JOIN class_course cc ON cc.id = a.class_course |
| 416 | WHERE cc.course = ANY($1) |
| 417 | ORDER BY e.id DESC"#, |
| 418 | &courses, |
| 419 | ) |
| 420 | .fetch_all(db) |
| 421 | .await?) |
| 422 | } |
| 423 | |
| 424 | |
| 425 | |
| 426 | |
| 427 | |
| 428 | pub async fn result_count(db: &Database, id: &ExamId) -> Result<i64, AppError> { |
| 429 | let row = sqlx::query!( |
| 430 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, |
| 431 | id.uuid(), |
| 432 | ) |
| 433 | .fetch_one(db) |
| 434 | .await?; |
| 435 | Ok(row.result_count) |
| 436 | } |
| 437 | |
| 438 | |
| 439 | |
| 440 | #[expect( |
| 441 | clippy::too_many_arguments, |
| 442 | reason = "mirrors the sibling entities' update(field, field, ..) shape" |
| 443 | )] |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | |
| 466 | pub async fn update_if_unchanged( |
| 467 | db: &Database, |
| 468 | mut expected: Exam, |
| 469 | title: ExamTitle, |
| 470 | description: ExamDescription, |
| 471 | kind: ExamKind, |
| 472 | schedule: ExamSchedule, |
| 473 | max_attempts: ExamAttemptLimit, |
| 474 | allow_rejoin: bool, |
| 475 | allow_review: bool, |
| 476 | draft: bool, |
| 477 | ) -> Result<Option<Exam>, AppError> { |
| 478 | let redraft = draft && !expected.draft; |
| 479 | let was = ( |
| 480 | expected.title.clone(), |
| 481 | expected.description.clone(), |
| 482 | expected.kind.clone(), |
| 483 | expected.mode.clone(), |
| 484 | expected.starts_at, |
| 485 | expected.ends_at, |
| 486 | expected.duration_ms, |
| 487 | expected.max_attempts, |
| 488 | expected.allow_rejoin, |
| 489 | expected.allow_review, |
| 490 | expected.draft, |
| 491 | ); |
| 492 | expected.title = title; |
| 493 | expected.description = description; |
| 494 | expected.kind = kind; |
| 495 | expected.mode = schedule.mode; |
| 496 | expected.starts_at = schedule.starts_at; |
| 497 | expected.ends_at = schedule.ends_at; |
| 498 | expected.duration_ms = schedule.duration_ms; |
| 499 | expected.max_attempts = max_attempts; |
| 500 | expected.allow_rejoin = allow_rejoin; |
| 501 | expected.allow_review = allow_review; |
| 502 | expected.draft = draft; |
| 503 | let saved = tx_with_retry(db, false, async move |conn| { |
| 504 | if redraft { |
| 505 | |
| 506 | |
| 507 | |
| 508 | let gates = sqlx::query!( |
| 509 | r#"SELECT EXISTS(SELECT 1 FROM exam_attempt WHERE exam = $1) AS sat, |
| 510 | EXISTS(SELECT 1 FROM exam_result WHERE exam = $1) AS graded"#, |
| 511 | expected.id.uuid(), |
| 512 | ) |
| 513 | .fetch_one(&mut *conn) |
| 514 | .await?; |
| 515 | if gates.sat.unwrap_or(false) || gates.graded.unwrap_or(false) { |
| 516 | return Err(redraft_error()); |
| 517 | } |
| 518 | } |
| 519 | let was_results = sqlx::query!( |
| 520 | r#"SELECT result_count AS "result_count: i64" FROM exam WHERE id = $1"#, |
| 521 | expected.id.uuid(), |
| 522 | ) |
| 523 | .fetch_optional(&mut *conn) |
| 524 | .await? |
| 525 | .map(|row| row.result_count) |
| 526 | .unwrap_or(0); |
| 527 | let written = sqlx::query_as!( |
| 528 | Exam, |
| 529 | r#"UPDATE exam SET title = $2, description = $3, kind = $4, mode = $5, |
| 530 | starts_at = $6, ends_at = $7, duration_ms = $8, |
| 531 | max_attempts = $9, allow_rejoin = $10, allow_review = $11, |
| 532 | draft = $12 |
| 533 | WHERE id = $1 |
| 534 | AND title = $13 AND description = $14 AND kind = $15 |
| 535 | AND mode IS NOT DISTINCT FROM $16 |
| 536 | AND starts_at IS NOT DISTINCT FROM $17 |
| 537 | AND ends_at IS NOT DISTINCT FROM $18 |
| 538 | AND duration_ms IS NOT DISTINCT FROM $19 |
| 539 | AND max_attempts = $20 AND allow_rejoin = $21 AND allow_review = $22 |
| 540 | AND draft = $23 |
| 541 | AND result_count = $24 |
| 542 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 543 | class_course AS "class_course: ClassCourseId", |
| 544 | term AS "term: TermId", title AS "title: ExamTitle", |
| 545 | description AS "description: ExamDescription", |
| 546 | kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 547 | starts_at AS "starts_at: Timestamp", |
| 548 | ends_at AS "ends_at: Timestamp", |
| 549 | duration_ms AS "duration_ms: ExamDuration", |
| 550 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 551 | allow_rejoin, allow_review, draft"#, |
| 552 | expected.id.uuid(), |
| 553 | expected.title.as_str(), |
| 554 | expected.description.as_str(), |
| 555 | expected.kind.as_str(), |
| 556 | expected.mode.as_ref().map(ExamMode::as_str), |
| 557 | expected.starts_at.map(|at| at.as_millis()), |
| 558 | expected.ends_at.map(|at| at.as_millis()), |
| 559 | expected.duration_ms.map(|duration| duration.as_millis()), |
| 560 | expected.max_attempts.as_i64(), |
| 561 | expected.allow_rejoin, |
| 562 | expected.allow_review, |
| 563 | expected.draft, |
| 564 | was.0.as_str(), |
| 565 | was.1.as_str(), |
| 566 | was.2.as_str(), |
| 567 | was.3.as_ref().map(ExamMode::as_str), |
| 568 | was.4.map(|at| at.as_millis()), |
| 569 | was.5.map(|at| at.as_millis()), |
| 570 | was.6.map(|duration| duration.as_millis()), |
| 571 | was.7.as_i64(), |
| 572 | was.8, |
| 573 | was.9, |
| 574 | was.10, |
| 575 | was_results, |
| 576 | ) |
| 577 | .fetch_optional(&mut *conn) |
| 578 | .await?; |
| 579 | Ok(written) |
| 580 | }) |
| 581 | .await?; |
| 582 | Ok(saved) |
| 583 | } |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | #[derive(Debug)] |
| 589 | pub struct Deleted { |
| 590 | pub exam: Exam, |
| 591 | pub question_image_files: Vec<String>, |
| 592 | pub answer_image_files: Vec<String>, |
| 593 | } |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | |
| 623 | pub async fn delete(db: &Database, target: Exam) -> Result<Deleted, AppError> { |
| 624 | tx_with_retry( |
| 625 | db, |
| 626 | true, |
| 627 | async move |conn| { |
| 628 | |
| 629 | |
| 630 | |
| 631 | |
| 632 | let locked = sqlx::query!( |
| 633 | r#"SELECT term AS "term: TermId" FROM exam WHERE id = $1 FOR UPDATE"#, |
| 634 | target.id.uuid(), |
| 635 | ) |
| 636 | .fetch_optional(&mut *conn) |
| 637 | .await?; |
| 638 | let Some(locked) = locked else { |
| 639 | return Err(AppError::NotFound); |
| 640 | }; |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | let image_files = sqlx::query!( |
| 646 | r#"SELECT file FROM question_image WHERE exam = $1"#, |
| 647 | target.id.uuid(), |
| 648 | ) |
| 649 | .fetch_all(&mut *conn) |
| 650 | .await? |
| 651 | .into_iter() |
| 652 | .map(|row| row.file) |
| 653 | .collect(); |
| 654 | let answer_image_files = sqlx::query!( |
| 655 | r#"SELECT file FROM answer_image WHERE exam = $1"#, |
| 656 | target.id.uuid(), |
| 657 | ) |
| 658 | .fetch_all(&mut *conn) |
| 659 | .await? |
| 660 | .into_iter() |
| 661 | .map(|row| row.file) |
| 662 | .collect(); |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | sqlx::query!( |
| 668 | r#"WITH kinds AS ( |
| 669 | SELECT e.kind AS kind, count(*) AS n |
| 670 | FROM exam_result r JOIN exam e ON e.id = r.exam |
| 671 | WHERE r.exam = $1 |
| 672 | GROUP BY e.kind) |
| 673 | UPDATE kind_ref k SET count = GREATEST(k.count - c.n, 0) |
| 674 | FROM kinds c WHERE k.name = c.kind"#, |
| 675 | target.id.uuid(), |
| 676 | ) |
| 677 | .execute(&mut *conn) |
| 678 | .await?; |
| 679 | sqlx::query!(r#"DELETE FROM exam_result WHERE exam = $1"#, target.id.uuid()) |
| 680 | .execute(&mut *conn) |
| 681 | .await?; |
| 682 | sqlx::query!(r#"DELETE FROM exam_attempt WHERE exam = $1"#, target.id.uuid()) |
| 683 | .execute(&mut *conn) |
| 684 | .await?; |
| 685 | sqlx::query!(r#"DELETE FROM exam_answer WHERE exam = $1"#, target.id.uuid()) |
| 686 | .execute(&mut *conn) |
| 687 | .await?; |
| 688 | sqlx::query!(r#"DELETE FROM answer_image WHERE exam = $1"#, target.id.uuid()) |
| 689 | .execute(&mut *conn) |
| 690 | .await?; |
| 691 | sqlx::query!(r#"DELETE FROM question_image WHERE exam = $1"#, target.id.uuid()) |
| 692 | .execute(&mut *conn) |
| 693 | .await?; |
| 694 | |
| 695 | |
| 696 | |
| 697 | sqlx::query!( |
| 698 | r#"WITH subs AS ( |
| 699 | SELECT subject, count(*) AS n |
| 700 | FROM exam_question WHERE exam = $1 |
| 701 | GROUP BY subject) |
| 702 | UPDATE subject s SET exam_question_count = GREATEST(s.exam_question_count - c.n, 0) |
| 703 | FROM subs c WHERE s.id = c.subject"#, |
| 704 | target.id.uuid(), |
| 705 | ) |
| 706 | .execute(&mut *conn) |
| 707 | .await?; |
| 708 | sqlx::query!(r#"DELETE FROM exam_question WHERE exam = $1"#, target.id.uuid()) |
| 709 | .execute(&mut *conn) |
| 710 | .await?; |
| 711 | sqlx::query!( |
| 712 | r#"UPDATE bank_question SET source_exam = NULL WHERE source_exam = $1"#, |
| 713 | target.id.uuid(), |
| 714 | ) |
| 715 | .execute(&mut *conn) |
| 716 | .await?; |
| 717 | |
| 718 | |
| 719 | |
| 720 | sqlx::query!( |
| 721 | r#"DELETE FROM exam_audience WHERE exam = $1"#, |
| 722 | target.id.uuid(), |
| 723 | ) |
| 724 | .execute(&mut *conn) |
| 725 | .await?; |
| 726 | let deleted = sqlx::query_as!( |
| 727 | Exam, |
| 728 | r#"DELETE FROM exam WHERE id = $1 |
| 729 | RETURNING id AS "id: ExamId", creator AS "creator: UserId", |
| 730 | class_course AS "class_course: ClassCourseId", |
| 731 | term AS "term: TermId", title AS "title: ExamTitle", |
| 732 | description AS "description: ExamDescription", |
| 733 | kind AS "kind: ExamKind", mode AS "mode: ExamMode", |
| 734 | starts_at AS "starts_at: Timestamp", |
| 735 | ends_at AS "ends_at: Timestamp", |
| 736 | duration_ms AS "duration_ms: ExamDuration", |
| 737 | max_attempts AS "max_attempts: ExamAttemptLimit", |
| 738 | allow_rejoin, allow_review, draft"#, |
| 739 | target.id.uuid(), |
| 740 | ) |
| 741 | .fetch_optional(&mut *conn) |
| 742 | .await?; |
| 743 | let Some(exam) = deleted else { |
| 744 | return Err(AppError::NotFound); |
| 745 | }; |
| 746 | |
| 747 | |
| 748 | sqlx::query!( |
| 749 | r#"UPDATE term SET exam_count = GREATEST(exam_count - 1, 0) |
| 750 | WHERE id = $1"#, |
| 751 | locked.term.uuid(), |
| 752 | ) |
| 753 | .execute(&mut *conn) |
| 754 | .await?; |
| 755 | Ok(Deleted { |
| 756 | exam, |
| 757 | question_image_files: image_files, |
| 758 | answer_image_files, |
| 759 | }) |
| 760 | }, |
| 761 | ) |
| 762 | .await |
| 763 | } |
| 764 | |
| 765 | #[cfg(test)] |
| 766 | use crate::domain::settings::ExamKindDef; |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | #[cfg(test)] |
| 774 | pub(crate) async fn published_exam(db: &Database) -> Exam { |
| 775 | let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults() |
| 776 | .get_exam_kinds() |
| 777 | .to_vec(); |
| 778 | |
| 779 | let creator = UserId::generate(); |
| 780 | sqlx::query( |
| 781 | "INSERT INTO app_user (id, username, created_at, role) \ |
| 782 | VALUES ($1, $2, 0, 'teacher')", |
| 783 | ) |
| 784 | .bind(creator.uuid()) |
| 785 | .bind(format!("exam-fixture-{}", &creator.key()[30..])) |
| 786 | .execute(db) |
| 787 | .await |
| 788 | .unwrap(); |
| 789 | |
| 790 | |
| 791 | |
| 792 | |
| 793 | let (instance, _course) = crate::db::course::a_test_instance(db).await; |
| 794 | let term = crate::db::term::a_test_term(db).await; |
| 795 | create( |
| 796 | db, |
| 797 | &creator, |
| 798 | &instance, |
| 799 | &term, |
| 800 | ExamTitle::try_new("midterm").unwrap(), |
| 801 | ExamDescription::try_new("").unwrap(), |
| 802 | ExamKind::try_new("yazili", &allowed).unwrap(), |
| 803 | ExamSchedule::try_new(None, None, None, None).unwrap(), |
| 804 | ExamAttemptLimit::try_new(1).unwrap(), |
| 805 | true, |
| 806 | false, |
| 807 | false, |
| 808 | ) |
| 809 | .await |
| 810 | .unwrap() |
| 811 | } |
| 812 | |
| 813 | #[cfg(test)] |
| 814 | mod tests { |
| 815 | use super::*; |
| 816 | |
| 817 | use super::published_exam as published; |
| 818 | |
| 819 | use crate::domain::exam::{ExamDuration, ExamMode}; |
| 820 | use crate::domain::settings::ExamKindDef; |
| 821 | use crate::domain::timestamp::Timestamp; |
| 822 | use crate::error::ValidationError; |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | |
| 837 | |
| 838 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 839 | async fn an_exam_never_outlives_its_course() { |
| 840 | fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { |
| 841 | tokio::spawn(async move { |
| 842 | let kinds = crate::domain::settings::Settings::defaults() |
| 843 | .get_exam_kinds() |
| 844 | .to_vec(); |
| 845 | let creator = UserId::generate(); |
| 846 | sqlx::query( |
| 847 | "INSERT INTO app_user (id, username, created_at, role) \ |
| 848 | VALUES ($1, $2, 0, 'teacher')", |
| 849 | ) |
| 850 | .bind(creator.uuid()) |
| 851 | .bind(format!("orphan-race-{}", &creator.key()[30..])) |
| 852 | .execute(&db) |
| 853 | .await |
| 854 | .unwrap(); |
| 855 | |
| 856 | |
| 857 | |
| 858 | |
| 859 | let term = crate::db::term::a_test_term(&db).await; |
| 860 | let class = crate::db::class_group::create( |
| 861 | &db, |
| 862 | &creator, |
| 863 | crate::domain::class_group::ClassName::try_new("9-A").unwrap(), |
| 864 | crate::domain::grade::GradeLevel::new(9).unwrap(), |
| 865 | None, |
| 866 | None, |
| 867 | ) |
| 868 | .await? |
| 869 | .get_id() |
| 870 | .clone(); |
| 871 | let instance = crate::service::class_course::attach(&db, &class, &course, &creator) |
| 872 | .await? |
| 873 | .get_id() |
| 874 | .clone(); |
| 875 | create( |
| 876 | &db, |
| 877 | &creator, |
| 878 | &instance, |
| 879 | &term, |
| 880 | ExamTitle::try_new("quiz").unwrap(), |
| 881 | ExamDescription::try_new("").unwrap(), |
| 882 | ExamKind::try_new("yazili", &kinds).unwrap(), |
| 883 | ExamSchedule::try_new(None, None, None, None).unwrap(), |
| 884 | ExamAttemptLimit::try_new(1).unwrap(), |
| 885 | true, |
| 886 | false, |
| 887 | false, |
| 888 | ) |
| 889 | .await |
| 890 | .map(|_| ()) |
| 891 | }) |
| 892 | } |
| 893 | crate::db::course::assert_no_child_outlives_a_course_delete( |
| 894 | "exam", |
| 895 | "SELECT count(*) FROM exam e JOIN class_course cc ON cc.id = e.class_course |
| 896 | WHERE cc.course = $1", |
| 897 | make, |
| 898 | ) |
| 899 | .await; |
| 900 | } |
| 901 | |
| 902 | |
| 903 | |
| 904 | |
| 905 | async fn a_person(db: &Database, label: &str, role: &str) -> UserId { |
| 906 | let user = UserId::generate(); |
| 907 | sqlx::query( |
| 908 | "INSERT INTO app_user (id, username, created_at, role) \ |
| 909 | VALUES ($1, $2, 0, $3)", |
| 910 | ) |
| 911 | .bind(user.uuid()) |
| 912 | .bind(format!("{label}-{}", &user.key()[30..])) |
| 913 | .bind(role) |
| 914 | .execute(db) |
| 915 | .await |
| 916 | .unwrap(); |
| 917 | user |
| 918 | } |
| 919 | |
| 920 | fn edit(exam: &Exam) -> (ExamTitle, ExamDescription, ExamKind, ExamSchedule) { |
| 921 | ( |
| 922 | exam.get_title().clone(), |
| 923 | exam.get_description().clone(), |
| 924 | exam.get_kind().clone(), |
| 925 | ExamSchedule::try_new(None, None, None, None).unwrap(), |
| 926 | ) |
| 927 | } |
| 928 | |
| 929 | |
| 930 | |
| 931 | |
| 932 | |
| 933 | #[tokio::test] |
| 934 | async fn a_merge_built_on_a_stale_snapshot_is_refused() { |
| 935 | let (db, _leases) = crate::database::init_test_db().await; |
| 936 | let stale = published(&db).await; |
| 937 | let (_, description, kind, schedule) = edit(&stale); |
| 938 | let landed = update_if_unchanged( |
| 939 | &db, |
| 940 | stale.clone(), |
| 941 | ExamTitle::try_new("theirs").unwrap(), |
| 942 | description, |
| 943 | kind, |
| 944 | schedule, |
| 945 | ExamAttemptLimit::try_new(1).unwrap(), |
| 946 | true, |
| 947 | false, |
| 948 | false, |
| 949 | ) |
| 950 | .await |
| 951 | .unwrap(); |
| 952 | assert!(landed.is_some(), "the first write is on a fresh snapshot"); |
| 953 | |
| 954 | let (_, description, kind, schedule) = edit(&stale); |
| 955 | let refused = update_if_unchanged( |
| 956 | &db, |
| 957 | stale, |
| 958 | ExamTitle::try_new("mine").unwrap(), |
| 959 | description, |
| 960 | kind, |
| 961 | schedule, |
| 962 | ExamAttemptLimit::try_new(1).unwrap(), |
| 963 | true, |
| 964 | false, |
| 965 | false, |
| 966 | ) |
| 967 | .await |
| 968 | .unwrap(); |
| 969 | assert!(refused.is_none(), "a stale merge must not be written"); |
| 970 | let stored = read(&db, landed.unwrap().get_id()).await.unwrap().unwrap(); |
| 971 | assert_eq!(stored.get_title().as_str(), "theirs"); |
| 972 | } |
| 973 | |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | #[tokio::test] |
| 979 | async fn re_drafting_is_refused_by_the_write_itself_once_a_mark_exists() { |
| 980 | use crate::db::exam_result; |
| 981 | use crate::domain::exam_result::Mark; |
| 982 | let (db, _leases) = crate::database::init_test_db().await; |
| 983 | let exam = published(&db).await; |
| 984 | let student = a_person(&db, "student", "student").await; |
| 985 | let grader = a_person(&db, "teacher", "teacher").await; |
| 986 | exam_result::grade( |
| 987 | &db, |
| 988 | exam.get_id(), |
| 989 | &student, |
| 990 | 1, |
| 991 | Mark::try_new(80).unwrap(), |
| 992 | &grader, |
| 993 | exam.get_kind().as_str(), |
| 994 | ) |
| 995 | .await |
| 996 | .unwrap(); |
| 997 | |
| 998 | let (title, description, kind, schedule) = edit(&exam); |
| 999 | let refused = update_if_unchanged( |
| 1000 | &db, |
| 1001 | exam.clone(), |
| 1002 | title, |
| 1003 | description, |
| 1004 | kind, |
| 1005 | schedule, |
| 1006 | ExamAttemptLimit::try_new(1).unwrap(), |
| 1007 | true, |
| 1008 | false, |
| 1009 | true, |
| 1010 | ) |
| 1011 | .await |
| 1012 | .expect_err("a graded exam cannot be re-drafted"); |
| 1013 | assert!(refused.to_string().contains("back into a draft")); |
| 1014 | let stored = read(&db, exam.get_id()).await.unwrap().unwrap(); |
| 1015 | assert!(!stored.is_draft(), "nothing may have been written"); |
| 1016 | } |
| 1017 | |
| 1018 | #[tokio::test] |
| 1019 | async fn title_is_required() { |
| 1020 | assert!(ExamTitle::try_new("midterm").is_ok()); |
| 1021 | assert!(ExamTitle::try_new("").is_err()); |
| 1022 | assert!(ExamTitle::try_new(" ").is_err()); |
| 1023 | } |
| 1024 | |
| 1025 | #[tokio::test] |
| 1026 | async fn description_is_optional() { |
| 1027 | assert!(ExamDescription::try_new("").is_ok()); |
| 1028 | } |
| 1029 | |
| 1030 | #[tokio::test] |
| 1031 | async fn kind_must_be_in_the_allowed_list() { |
| 1032 | let allowed: Vec<ExamKindDef> = crate::domain::settings::Settings::defaults() |
| 1033 | .get_exam_kinds() |
| 1034 | .to_vec(); |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | for kind in ["yazili", "sozlu", "uygulama"] { |
| 1039 | assert_eq!(ExamKind::try_new(kind, &allowed).unwrap().as_str(), kind); |
| 1040 | } |
| 1041 | for stale in ["quiz", "midterm", "exam"] { |
| 1042 | assert!( |
| 1043 | ExamKind::try_new(stale, &allowed).is_err(), |
| 1044 | "{stale} is not in the school's list" |
| 1045 | ); |
| 1046 | } |
| 1047 | assert!(ExamKind::try_new("", &allowed).is_err()); |
| 1048 | |
| 1049 | let custom = vec![ExamKindDef::try_new("lab", 2).unwrap()]; |
| 1050 | assert!(ExamKind::try_new("lab", &custom).is_ok()); |
| 1051 | assert!(ExamKind::try_new("midterm", &custom).is_err()); |
| 1052 | |
| 1053 | |
| 1054 | assert!(ExamKind::try_new("Lab", &custom).is_err()); |
| 1055 | } |
| 1056 | |
| 1057 | #[tokio::test] |
| 1058 | async fn mode_must_be_known() { |
| 1059 | for mode in ["sync", "async", "open"] { |
| 1060 | assert_eq!(ExamMode::try_new(mode).unwrap().as_str(), mode); |
| 1061 | } |
| 1062 | assert!(ExamMode::try_new("live").is_err()); |
| 1063 | } |
| 1064 | |
| 1065 | #[tokio::test] |
| 1066 | async fn attempt_limit_counts_or_never_runs_out() { |
| 1067 | let single = ExamAttemptLimit::single(); |
| 1068 | assert_eq!(single.as_i64(), 1); |
| 1069 | assert!(!single.is_unlimited()); |
| 1070 | assert!(single.allows_another(0)); |
| 1071 | assert!(!single.allows_another(1)); |
| 1072 | |
| 1073 | let three = ExamAttemptLimit::try_new(3).unwrap(); |
| 1074 | assert!(three.allows_another(2)); |
| 1075 | assert!(!three.allows_another(3)); |
| 1076 | assert!(!three.allows_another(4)); |
| 1077 | |
| 1078 | let unlimited = ExamAttemptLimit::try_new(0).unwrap(); |
| 1079 | assert!(unlimited.is_unlimited()); |
| 1080 | assert!(unlimited.allows_another(0)); |
| 1081 | assert!(unlimited.allows_another(10_000)); |
| 1082 | |
| 1083 | assert!(ExamAttemptLimit::try_new(-1).is_err()); |
| 1084 | assert!(ExamAttemptLimit::try_new(101).is_err()); |
| 1085 | } |
| 1086 | |
| 1087 | #[tokio::test] |
| 1088 | async fn schedule_invariants_hold() { |
| 1089 | let mode = |m| Some(ExamMode::try_new(m).unwrap()); |
| 1090 | let at = |ms| Some(Timestamp::from_millis(ms)); |
| 1091 | let dur = Some(ExamDuration::try_new(90 * 60 * 1000).unwrap()); |
| 1092 | |
| 1093 | |
| 1094 | assert!(ExamSchedule::try_new(None, None, None, None).is_ok()); |
| 1095 | assert!(ExamSchedule::try_new(None, at(1), None, None).is_err()); |
| 1096 | assert!(ExamSchedule::try_new(None, None, at(2), None).is_err()); |
| 1097 | assert!(ExamSchedule::try_new(None, None, None, dur).is_err()); |
| 1098 | |
| 1099 | |
| 1100 | assert!(ExamSchedule::try_new(mode("sync"), at(1), at(2), None).is_ok()); |
| 1101 | assert!(ExamSchedule::try_new(mode("sync"), None, at(2), None).is_err()); |
| 1102 | assert!(ExamSchedule::try_new(mode("sync"), at(1), None, None).is_err()); |
| 1103 | |
| 1104 | |
| 1105 | assert!(matches!( |
| 1106 | ExamSchedule::try_new(mode("sync"), at(1), at(2), dur), |
| 1107 | Err(ValidationError::Invalid { |
| 1108 | reason: "only async and open exams take a duration", |
| 1109 | .. |
| 1110 | }) |
| 1111 | )); |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | |
| 1116 | assert!(ExamSchedule::try_new(mode("async"), at(1), at(1 + 90 * 60 * 1000), dur).is_ok()); |
| 1117 | assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), dur).is_err()); |
| 1118 | assert!(ExamSchedule::try_new(mode("async"), at(1), at(2), None).is_err()); |
| 1119 | |
| 1120 | |
| 1121 | assert!(ExamSchedule::try_new(mode("open"), None, None, None).is_ok()); |
| 1122 | assert!(ExamSchedule::try_new(mode("open"), None, None, dur).is_ok()); |
| 1123 | assert!(ExamSchedule::try_new(mode("open"), at(1), None, None).is_err()); |
| 1124 | assert!(ExamSchedule::try_new(mode("open"), None, at(2), None).is_err()); |
| 1125 | assert!(ExamSchedule::try_new(mode("open"), at(1), at(2), dur).is_err()); |
| 1126 | |
| 1127 | |
| 1128 | assert!(ExamSchedule::try_new(mode("sync"), at(2), at(2), None).is_err()); |
| 1129 | assert!(ExamSchedule::try_new(mode("async"), at(3), at(2), dur).is_err()); |
| 1130 | } |
| 1131 | |
| 1132 | |
| 1133 | |
| 1134 | |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 1153 | |
| 1154 | |
| 1155 | |
| 1156 | |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | |
| 1161 | |
| 1162 | |
| 1163 | |
| 1164 | |
| 1165 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1166 | async fn a_delete_racing_a_mark_never_answers_500() { |
| 1167 | use crate::db::exam_result; |
| 1168 | use crate::domain::exam_result::Mark; |
| 1169 | let (db, _leases) = crate::database::init_test_db().await; |
| 1170 | let teacher = a_person(&db, "teacher", "teacher").await; |
| 1171 | let (mut delete_500, mut grade_500) = (0, 0); |
| 1172 | let (mut delete_first, mut grade_first, mut swept) = (0, 0, 0); |
| 1173 | let (mut last_delete, mut last_grade) = (String::new(), String::new()); |
| 1174 | for round in 0..20 { |
| 1175 | let exam = published(&db).await; |
| 1176 | let kind = exam.get_kind().as_str().to_string(); |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | |
| 1181 | |
| 1182 | let drop_it = { |
| 1183 | let (exam, db) = (exam.clone(), db.clone()); |
| 1184 | |
| 1185 | |
| 1186 | |
| 1187 | |
| 1188 | let beat = std::time::Duration::from_millis(round * 2); |
| 1189 | tokio::spawn(async move { |
| 1190 | tokio::time::sleep(beat).await; |
| 1191 | delete(&db, exam).await |
| 1192 | }) |
| 1193 | }; |
| 1194 | |
| 1195 | |
| 1196 | let mut students = Vec::with_capacity(6); |
| 1197 | for _ in 0..6 { |
| 1198 | students.push(a_person(&db, "student", "student").await); |
| 1199 | } |
| 1200 | let marks: Vec<_> = (0..6) |
| 1201 | .map(|seat| { |
| 1202 | let (id, db, kind) = (exam.get_id().clone(), db.clone(), kind.clone()); |
| 1203 | let (student, teacher) = (students[seat], teacher); |
| 1204 | tokio::spawn(async move { |
| 1205 | exam_result::grade( |
| 1206 | &db, |
| 1207 | &id, |
| 1208 | &student, |
| 1209 | 1, |
| 1210 | Mark::try_new(50).unwrap(), |
| 1211 | &teacher, |
| 1212 | &kind, |
| 1213 | ) |
| 1214 | .await |
| 1215 | }) |
| 1216 | }) |
| 1217 | .collect(); |
| 1218 | let drop_it = drop_it.await.unwrap(); |
| 1219 | if matches!(drop_it, Err(AppError::Db(_))) { |
| 1220 | delete_500 += 1; |
| 1221 | last_delete = format!("{:?}", drop_it.as_ref().err()); |
| 1222 | } |
| 1223 | let mut refused = 0; |
| 1224 | for mark in marks { |
| 1225 | let mark = mark.await.unwrap(); |
| 1226 | match mark { |
| 1227 | |
| 1228 | |
| 1229 | Err(AppError::NotFound) => refused += 1, |
| 1230 | Err(AppError::Db(_)) => { |
| 1231 | grade_500 += 1; |
| 1232 | last_grade = format!("{mark:?}"); |
| 1233 | } |
| 1234 | _ => {} |
| 1235 | } |
| 1236 | } |
| 1237 | |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | if refused > 0 { |
| 1242 | delete_first += 1; |
| 1243 | } |
| 1244 | if refused < 6 { |
| 1245 | grade_first += 1; |
| 1246 | } |
| 1247 | if exam_result::list_for_exam(&db, exam.get_id()) |
| 1248 | .await |
| 1249 | .unwrap() |
| 1250 | .is_empty() |
| 1251 | { |
| 1252 | swept += 1; |
| 1253 | } |
| 1254 | } |
| 1255 | eprintln!( |
| 1256 | "Exam::delete raced: {delete_500}/20 delete 500s, {grade_500} grade 500s, \ |
| 1257 | {delete_first} rounds with a grade refused / {grade_first} with one through, \ |
| 1258 | {swept} swept clean" |
| 1259 | ); |
| 1260 | assert!( |
| 1261 | delete_first > 0 && grade_first > 0, |
| 1262 | "the sweep never crossed the window ({delete_first} rounds with a grade \ |
| 1263 | refused / {grade_first} with one through)" |
| 1264 | ); |
| 1265 | |
| 1266 | |
| 1267 | assert_eq!( |
| 1268 | swept, |
| 1269 | 20, |
| 1270 | "a mark outlived its exam in {} rounds", |
| 1271 | 20 - swept |
| 1272 | ); |
| 1273 | assert_eq!( |
| 1274 | delete_500, 0, |
| 1275 | "a raced delete must not 500: {delete_500}/20 rounds, last {last_delete}" |
| 1276 | ); |
| 1277 | assert_eq!( |
| 1278 | grade_500, 0, |
| 1279 | "a raced grade must retry, not 500: {grade_500}/20 rounds, last {last_grade}" |
| 1280 | ); |
| 1281 | } |
| 1282 | |
| 1283 | |
| 1284 | |
| 1285 | async fn question_on(exam: &Exam, db: &Database) -> crate::domain::exam_question::ExamQuestion { |
| 1286 | use crate::domain::exam_question::{ |
| 1287 | ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 1288 | }; |
| 1289 | let spec = QuestionSpec::try_new( |
| 1290 | QuestionKind::try_new("choice").unwrap(), |
| 1291 | Some(vec![ |
| 1292 | ChoiceInput { |
| 1293 | id: Some("a".into()), |
| 1294 | text: "5".into(), |
| 1295 | }, |
| 1296 | ChoiceInput { |
| 1297 | id: Some("b".into()), |
| 1298 | text: "6".into(), |
| 1299 | }, |
| 1300 | ]), |
| 1301 | Some("b".into()), |
| 1302 | &[], |
| 1303 | ) |
| 1304 | .unwrap(); |
| 1305 | let subject = crate::db::subject::create( |
| 1306 | db, |
| 1307 | &crate::db::course::a_test_course(db).await, |
| 1308 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 1309 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 1310 | ) |
| 1311 | .await |
| 1312 | .unwrap(); |
| 1313 | crate::db::exam_question::create( |
| 1314 | db, |
| 1315 | exam.get_id(), |
| 1316 | *subject.get_id(), |
| 1317 | QuestionText::try_new("3 + 3?").unwrap(), |
| 1318 | QuestionPoints::try_new(5).unwrap(), |
| 1319 | spec, |
| 1320 | ) |
| 1321 | .await |
| 1322 | .unwrap() |
| 1323 | } |
| 1324 | |
| 1325 | |
| 1326 | |
| 1327 | |
| 1328 | |
| 1329 | |
| 1330 | |
| 1331 | |
| 1332 | |
| 1333 | |
| 1334 | |
| 1335 | |
| 1336 | |
| 1337 | |
| 1338 | |
| 1339 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1340 | async fn an_answer_written_inside_a_delete_never_outlives_the_exam() { |
| 1341 | use crate::db::exam_answer; |
| 1342 | let (db, _leases) = crate::database::init_test_db().await; |
| 1343 | |
| 1344 | let student = a_person(&db, "student", "student").await; |
| 1345 | |
| 1346 | |
| 1347 | { |
| 1348 | let exam = published(&db).await; |
| 1349 | let question = question_on(&exam, &db).await; |
| 1350 | let id = exam.get_id().clone(); |
| 1351 | let pick = question.get_choices().unwrap()[1] |
| 1352 | .get_id() |
| 1353 | .as_str() |
| 1354 | .to_string(); |
| 1355 | let dropped = delete(&db, exam).await; |
| 1356 | assert!( |
| 1357 | !matches!(dropped, Err(AppError::Db(_))), |
| 1358 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 1359 | ); |
| 1360 | assert!( |
| 1361 | read(&db, &id).await.unwrap().is_none(), |
| 1362 | "delete-first: the exam is still there after delete: {dropped:?}" |
| 1363 | ); |
| 1364 | let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; |
| 1365 | assert!( |
| 1366 | !matches!(child, Err(AppError::Db(_))), |
| 1367 | "delete-first: a save must be answered, not 500: {child:?}" |
| 1368 | ); |
| 1369 | assert_eq!( |
| 1370 | exam_answer::list_for_exam(&db, &id).await.unwrap().len(), |
| 1371 | 0, |
| 1372 | "an answer outlived its exam" |
| 1373 | ); |
| 1374 | } |
| 1375 | |
| 1376 | |
| 1377 | { |
| 1378 | let exam = published(&db).await; |
| 1379 | let question = question_on(&exam, &db).await; |
| 1380 | let id = exam.get_id().clone(); |
| 1381 | let pick = question.get_choices().unwrap()[1] |
| 1382 | .get_id() |
| 1383 | .as_str() |
| 1384 | .to_string(); |
| 1385 | let child = exam_answer::save(&db, &question, &student, 1, Some(pick), None).await; |
| 1386 | assert!( |
| 1387 | child.is_ok(), |
| 1388 | "write-first: the save must land before the delete: {child:?}" |
| 1389 | ); |
| 1390 | let dropped = delete(&db, exam).await; |
| 1391 | assert!( |
| 1392 | !matches!(dropped, Err(AppError::Db(_))), |
| 1393 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 1394 | ); |
| 1395 | assert!( |
| 1396 | read(&db, &id).await.unwrap().is_none(), |
| 1397 | "write-first: the exam is still there" |
| 1398 | ); |
| 1399 | assert_eq!( |
| 1400 | exam_answer::list_for_exam(&db, &id).await.unwrap().len(), |
| 1401 | 0, |
| 1402 | "an answer outlived its exam" |
| 1403 | ); |
| 1404 | } |
| 1405 | |
| 1406 | |
| 1407 | let mut swept = 0; |
| 1408 | for round in 0..4 { |
| 1409 | let exam = published(&db).await; |
| 1410 | let question = question_on(&exam, &db).await; |
| 1411 | let id = exam.get_id().clone(); |
| 1412 | let pick = question.get_choices().unwrap()[1] |
| 1413 | .get_id() |
| 1414 | .as_str() |
| 1415 | .to_string(); |
| 1416 | |
| 1417 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1418 | let drop_it = { |
| 1419 | let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1420 | tokio::spawn(async move { |
| 1421 | gate.wait().await; |
| 1422 | delete(&db, exam).await |
| 1423 | }) |
| 1424 | }; |
| 1425 | let child = { |
| 1426 | let (db, question, student, pick, gate) = |
| 1427 | (db.clone(), question, student, pick, gate); |
| 1428 | tokio::spawn(async move { |
| 1429 | gate.wait().await; |
| 1430 | exam_answer::save(&db, &question, &student, 1, Some(pick), None).await |
| 1431 | }) |
| 1432 | }; |
| 1433 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1434 | assert!( |
| 1435 | !matches!(child, Err(AppError::Db(_))), |
| 1436 | "round {round}: a raced save must be answered, not 500: {child:?}" |
| 1437 | ); |
| 1438 | assert!( |
| 1439 | !matches!(drop_it, Err(AppError::Db(_))), |
| 1440 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 1441 | ); |
| 1442 | |
| 1443 | if read(&db, &id).await.unwrap().is_none() { |
| 1444 | swept += 1; |
| 1445 | assert_eq!( |
| 1446 | exam_answer::list_for_exam(&db, &id).await.unwrap().len(), |
| 1447 | 0, |
| 1448 | "round {round}: an answer outlived its exam" |
| 1449 | ); |
| 1450 | } else if drop_it.is_ok() { |
| 1451 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1452 | } |
| 1453 | } |
| 1454 | eprintln!("Exam::delete raced by an answer save: {swept}/4 concurrent rounds deleted the exam"); |
| 1455 | } |
| 1456 | |
| 1457 | |
| 1458 | |
| 1459 | |
| 1460 | |
| 1461 | |
| 1462 | |
| 1463 | |
| 1464 | |
| 1465 | |
| 1466 | |
| 1467 | |
| 1468 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1469 | async fn a_question_written_inside_a_delete_never_outlives_the_exam() { |
| 1470 | use crate::domain::exam_question::{ |
| 1471 | ChoiceInput, QuestionKind, QuestionPoints, QuestionSpec, QuestionText, |
| 1472 | }; |
| 1473 | let (db, _leases) = crate::database::init_test_db().await; |
| 1474 | |
| 1475 | fn spec() -> QuestionSpec { |
| 1476 | QuestionSpec::try_new( |
| 1477 | QuestionKind::try_new("choice").unwrap(), |
| 1478 | Some(vec![ |
| 1479 | ChoiceInput { |
| 1480 | id: Some("a".into()), |
| 1481 | text: "5".into(), |
| 1482 | }, |
| 1483 | ChoiceInput { |
| 1484 | id: Some("b".into()), |
| 1485 | text: "6".into(), |
| 1486 | }, |
| 1487 | ]), |
| 1488 | Some("b".into()), |
| 1489 | &[], |
| 1490 | ) |
| 1491 | .unwrap() |
| 1492 | } |
| 1493 | |
| 1494 | async fn ask( |
| 1495 | db: &Database, |
| 1496 | exam: &ExamId, |
| 1497 | on: crate::domain::subject::SubjectId, |
| 1498 | ) -> Result<crate::domain::exam_question::ExamQuestion, AppError> { |
| 1499 | crate::db::exam_question::create( |
| 1500 | db, |
| 1501 | exam, |
| 1502 | on, |
| 1503 | QuestionText::try_new("3 + 3?").unwrap(), |
| 1504 | QuestionPoints::try_new(5).unwrap(), |
| 1505 | spec(), |
| 1506 | ) |
| 1507 | .await |
| 1508 | } |
| 1509 | |
| 1510 | async fn subject_stuck(db: &Database, subject: &crate::domain::subject::Subject) -> bool { |
| 1511 | crate::db::subject::delete( |
| 1512 | db, |
| 1513 | crate::db::subject::read(db, subject.get_id()) |
| 1514 | .await |
| 1515 | .unwrap() |
| 1516 | .unwrap(), |
| 1517 | ) |
| 1518 | .await |
| 1519 | .is_err() |
| 1520 | } |
| 1521 | |
| 1522 | async fn a_subject(db: &Database) -> crate::domain::subject::Subject { |
| 1523 | crate::db::subject::create( |
| 1524 | db, |
| 1525 | &crate::db::course::a_test_course(db).await, |
| 1526 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 1527 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 1528 | ) |
| 1529 | .await |
| 1530 | .unwrap() |
| 1531 | } |
| 1532 | |
| 1533 | |
| 1534 | { |
| 1535 | let exam = published(&db).await; |
| 1536 | let id = exam.get_id().clone(); |
| 1537 | let subject = a_subject(&db).await; |
| 1538 | let dropped = delete(&db, exam).await; |
| 1539 | assert!( |
| 1540 | !matches!(dropped, Err(AppError::Db(_))), |
| 1541 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 1542 | ); |
| 1543 | assert!( |
| 1544 | read(&db, &id).await.unwrap().is_none(), |
| 1545 | "delete-first: the exam is still there after delete: {dropped:?}" |
| 1546 | ); |
| 1547 | let child = ask(&db, &id, *subject.get_id()).await; |
| 1548 | assert!( |
| 1549 | !matches!(child, Err(AppError::Db(_))), |
| 1550 | "delete-first: a question write must be answered, not 500: {child:?}" |
| 1551 | ); |
| 1552 | assert_eq!( |
| 1553 | crate::db::exam_question::list_for_exam(&db, &id, None, 0) |
| 1554 | .await |
| 1555 | .unwrap() |
| 1556 | .0 |
| 1557 | .len(), |
| 1558 | 0, |
| 1559 | "a question outlived its exam" |
| 1560 | ); |
| 1561 | assert!( |
| 1562 | !subject_stuck(&db, &subject).await, |
| 1563 | "an orphan question left its subject undeletable" |
| 1564 | ); |
| 1565 | } |
| 1566 | |
| 1567 | |
| 1568 | |
| 1569 | { |
| 1570 | let exam = published(&db).await; |
| 1571 | let id = exam.get_id().clone(); |
| 1572 | let subject = a_subject(&db).await; |
| 1573 | let child = ask(&db, &id, *subject.get_id()).await; |
| 1574 | assert!( |
| 1575 | child.is_ok(), |
| 1576 | "write-first: the question must land before the delete: {child:?}" |
| 1577 | ); |
| 1578 | let dropped = delete(&db, exam).await; |
| 1579 | assert!( |
| 1580 | !matches!(dropped, Err(AppError::Db(_))), |
| 1581 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 1582 | ); |
| 1583 | assert!( |
| 1584 | read(&db, &id).await.unwrap().is_none(), |
| 1585 | "write-first: the exam is still there" |
| 1586 | ); |
| 1587 | assert_eq!( |
| 1588 | crate::db::exam_question::list_for_exam(&db, &id, None, 0) |
| 1589 | .await |
| 1590 | .unwrap() |
| 1591 | .0 |
| 1592 | .len(), |
| 1593 | 0, |
| 1594 | "a question outlived its exam" |
| 1595 | ); |
| 1596 | assert!( |
| 1597 | !subject_stuck(&db, &subject).await, |
| 1598 | "an orphan question left its subject undeletable" |
| 1599 | ); |
| 1600 | } |
| 1601 | |
| 1602 | |
| 1603 | let mut swept = 0; |
| 1604 | for round in 0..4 { |
| 1605 | let exam = published(&db).await; |
| 1606 | let id = exam.get_id().clone(); |
| 1607 | let subject = a_subject(&db).await; |
| 1608 | |
| 1609 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1610 | let drop_it = { |
| 1611 | let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1612 | tokio::spawn(async move { |
| 1613 | gate.wait().await; |
| 1614 | delete(&db, exam).await |
| 1615 | }) |
| 1616 | }; |
| 1617 | let child = { |
| 1618 | let (db, exam_id, on, gate) = (db.clone(), id.clone(), *subject.get_id(), gate); |
| 1619 | tokio::spawn(async move { |
| 1620 | gate.wait().await; |
| 1621 | ask(&db, &exam_id, on).await |
| 1622 | }) |
| 1623 | }; |
| 1624 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1625 | assert!( |
| 1626 | !matches!(child, Err(AppError::Db(_))), |
| 1627 | "round {round}: a raced question write must be answered, not 500: {child:?}" |
| 1628 | ); |
| 1629 | assert!( |
| 1630 | !matches!(drop_it, Err(AppError::Db(_))), |
| 1631 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 1632 | ); |
| 1633 | |
| 1634 | if read(&db, &id).await.unwrap().is_none() { |
| 1635 | swept += 1; |
| 1636 | assert_eq!( |
| 1637 | crate::db::exam_question::list_for_exam(&db, &id, None, 0) |
| 1638 | .await |
| 1639 | .unwrap() |
| 1640 | .0 |
| 1641 | .len(), |
| 1642 | 0, |
| 1643 | "round {round}: a question outlived its exam" |
| 1644 | ); |
| 1645 | assert!( |
| 1646 | !subject_stuck(&db, &subject).await, |
| 1647 | "round {round}: an orphan question left its subject undeletable" |
| 1648 | ); |
| 1649 | } else if drop_it.is_ok() { |
| 1650 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1651 | } |
| 1652 | } |
| 1653 | eprintln!( |
| 1654 | "Exam::delete raced by a question write: {swept}/4 concurrent rounds deleted the exam" |
| 1655 | ); |
| 1656 | } |
| 1657 | |
| 1658 | |
| 1659 | |
| 1660 | |
| 1661 | |
| 1662 | |
| 1663 | |
| 1664 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1665 | async fn a_drawing_written_inside_a_delete_never_outlives_the_exam() { |
| 1666 | use crate::domain::answer_image::AnswerImage; |
| 1667 | use crate::domain::note_file::FileContentType; |
| 1668 | let (db, _leases) = crate::database::init_test_db().await; |
| 1669 | let student = a_person(&db, "student", "student").await; |
| 1670 | |
| 1671 | async fn draw( |
| 1672 | db: &Database, |
| 1673 | exam: &ExamId, |
| 1674 | question: &crate::domain::exam_question::ExamQuestionId, |
| 1675 | student: &UserId, |
| 1676 | ) -> Result<(AnswerImage, Option<String>), AppError> { |
| 1677 | let image = AnswerImage::new( |
| 1678 | exam, |
| 1679 | question, |
| 1680 | student, |
| 1681 | 1, |
| 1682 | FileContentType::try_new("image/png").unwrap(), |
| 1683 | 3, |
| 1684 | ); |
| 1685 | crate::db::answer_image::upsert(db, image).await |
| 1686 | } |
| 1687 | |
| 1688 | |
| 1689 | { |
| 1690 | let exam = published(&db).await; |
| 1691 | let question = question_on(&exam, &db).await; |
| 1692 | let id = exam.get_id().clone(); |
| 1693 | let on = question.get_id().clone(); |
| 1694 | let dropped = delete(&db, exam).await; |
| 1695 | assert!( |
| 1696 | !matches!(dropped, Err(AppError::Db(_))), |
| 1697 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 1698 | ); |
| 1699 | assert!( |
| 1700 | read(&db, &id).await.unwrap().is_none(), |
| 1701 | "delete-first: the exam is still there after delete: {dropped:?}" |
| 1702 | ); |
| 1703 | let child = draw(&db, &id, &on, &student).await; |
| 1704 | assert!( |
| 1705 | !matches!(child, Err(AppError::Db(_))), |
| 1706 | "delete-first: a drawing write must be answered, not 500: {child:?}" |
| 1707 | ); |
| 1708 | assert_eq!( |
| 1709 | crate::db::answer_image::list_for_exam(&db, &id) |
| 1710 | .await |
| 1711 | .unwrap() |
| 1712 | .len(), |
| 1713 | 0, |
| 1714 | "a drawing outlived its exam" |
| 1715 | ); |
| 1716 | } |
| 1717 | |
| 1718 | |
| 1719 | { |
| 1720 | let exam = published(&db).await; |
| 1721 | let question = question_on(&exam, &db).await; |
| 1722 | let id = exam.get_id().clone(); |
| 1723 | let on = question.get_id().clone(); |
| 1724 | let child = draw(&db, &id, &on, &student).await; |
| 1725 | assert!( |
| 1726 | child.is_ok(), |
| 1727 | "write-first: the drawing must land before the delete: {child:?}" |
| 1728 | ); |
| 1729 | let dropped = delete(&db, exam).await; |
| 1730 | assert!( |
| 1731 | !matches!(dropped, Err(AppError::Db(_))), |
| 1732 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 1733 | ); |
| 1734 | assert!( |
| 1735 | read(&db, &id).await.unwrap().is_none(), |
| 1736 | "write-first: the exam is still there" |
| 1737 | ); |
| 1738 | assert_eq!( |
| 1739 | crate::db::answer_image::list_for_exam(&db, &id) |
| 1740 | .await |
| 1741 | .unwrap() |
| 1742 | .len(), |
| 1743 | 0, |
| 1744 | "a drawing outlived its exam" |
| 1745 | ); |
| 1746 | } |
| 1747 | |
| 1748 | |
| 1749 | let mut swept = 0; |
| 1750 | for round in 0..4 { |
| 1751 | let exam = published(&db).await; |
| 1752 | let question = question_on(&exam, &db).await; |
| 1753 | let id = exam.get_id().clone(); |
| 1754 | |
| 1755 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1756 | let drop_it = { |
| 1757 | let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1758 | tokio::spawn(async move { |
| 1759 | gate.wait().await; |
| 1760 | delete(&db, exam).await |
| 1761 | }) |
| 1762 | }; |
| 1763 | let child = { |
| 1764 | let (db, exam_id, on, student, gate) = ( |
| 1765 | db.clone(), |
| 1766 | id.clone(), |
| 1767 | question.get_id().clone(), |
| 1768 | student, |
| 1769 | gate, |
| 1770 | ); |
| 1771 | tokio::spawn(async move { |
| 1772 | gate.wait().await; |
| 1773 | draw(&db, &exam_id, &on, &student).await |
| 1774 | }) |
| 1775 | }; |
| 1776 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1777 | assert!( |
| 1778 | !matches!(child, Err(AppError::Db(_))), |
| 1779 | "round {round}: a raced drawing write must be answered, not 500: {child:?}" |
| 1780 | ); |
| 1781 | assert!( |
| 1782 | !matches!(drop_it, Err(AppError::Db(_))), |
| 1783 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 1784 | ); |
| 1785 | |
| 1786 | if read(&db, &id).await.unwrap().is_none() { |
| 1787 | swept += 1; |
| 1788 | assert_eq!( |
| 1789 | crate::db::answer_image::list_for_exam(&db, &id) |
| 1790 | .await |
| 1791 | .unwrap() |
| 1792 | .len(), |
| 1793 | 0, |
| 1794 | "round {round}: a drawing outlived its exam" |
| 1795 | ); |
| 1796 | } else if drop_it.is_ok() { |
| 1797 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1798 | } |
| 1799 | } |
| 1800 | eprintln!( |
| 1801 | "Exam::delete raced by a drawing write: {swept}/4 concurrent rounds deleted the exam" |
| 1802 | ); |
| 1803 | } |
| 1804 | |
| 1805 | |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | |
| 1810 | |
| 1811 | |
| 1812 | |
| 1813 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1814 | async fn a_picture_written_inside_a_delete_never_outlives_the_exam() { |
| 1815 | use crate::domain::note_file::FileContentType; |
| 1816 | use crate::domain::question_image::QuestionImage; |
| 1817 | let (db, _leases) = crate::database::init_test_db().await; |
| 1818 | |
| 1819 | async fn shoot( |
| 1820 | db: &Database, |
| 1821 | exam: &ExamId, |
| 1822 | question: &crate::domain::exam_question::ExamQuestionId, |
| 1823 | ) -> Result<(QuestionImage, Option<String>), AppError> { |
| 1824 | let image = QuestionImage::new( |
| 1825 | exam, |
| 1826 | question, |
| 1827 | None, |
| 1828 | FileContentType::try_new("image/png").unwrap(), |
| 1829 | 3, |
| 1830 | ); |
| 1831 | crate::db::question_image::upsert(db, image).await |
| 1832 | } |
| 1833 | |
| 1834 | |
| 1835 | { |
| 1836 | let exam = published(&db).await; |
| 1837 | let question = question_on(&exam, &db).await; |
| 1838 | let id = exam.get_id().clone(); |
| 1839 | let on = question.get_id().clone(); |
| 1840 | let dropped = delete(&db, exam).await; |
| 1841 | assert!( |
| 1842 | !matches!(dropped, Err(AppError::Db(_))), |
| 1843 | "delete-first: a delete must be answered, not 500: {dropped:?}" |
| 1844 | ); |
| 1845 | assert!( |
| 1846 | read(&db, &id).await.unwrap().is_none(), |
| 1847 | "delete-first: the exam is still there after delete: {dropped:?}" |
| 1848 | ); |
| 1849 | let child = shoot(&db, &id, &on).await; |
| 1850 | assert!( |
| 1851 | !matches!(child, Err(AppError::Db(_))), |
| 1852 | "delete-first: a picture write must be answered, not 500: {child:?}" |
| 1853 | ); |
| 1854 | assert_eq!( |
| 1855 | crate::db::question_image::list_for_exam(&db, &id) |
| 1856 | .await |
| 1857 | .unwrap() |
| 1858 | .len(), |
| 1859 | 0, |
| 1860 | "a picture outlived its exam" |
| 1861 | ); |
| 1862 | } |
| 1863 | |
| 1864 | |
| 1865 | { |
| 1866 | let exam = published(&db).await; |
| 1867 | let question = question_on(&exam, &db).await; |
| 1868 | let id = exam.get_id().clone(); |
| 1869 | let on = question.get_id().clone(); |
| 1870 | let child = shoot(&db, &id, &on).await; |
| 1871 | assert!( |
| 1872 | child.is_ok(), |
| 1873 | "write-first: the picture must land before the delete: {child:?}" |
| 1874 | ); |
| 1875 | let dropped = delete(&db, exam).await; |
| 1876 | assert!( |
| 1877 | !matches!(dropped, Err(AppError::Db(_))), |
| 1878 | "write-first: a delete must be answered, not 500: {dropped:?}" |
| 1879 | ); |
| 1880 | assert!( |
| 1881 | read(&db, &id).await.unwrap().is_none(), |
| 1882 | "write-first: the exam is still there" |
| 1883 | ); |
| 1884 | assert_eq!( |
| 1885 | crate::db::question_image::list_for_exam(&db, &id) |
| 1886 | .await |
| 1887 | .unwrap() |
| 1888 | .len(), |
| 1889 | 0, |
| 1890 | "a picture outlived its exam" |
| 1891 | ); |
| 1892 | } |
| 1893 | |
| 1894 | |
| 1895 | let mut swept = 0; |
| 1896 | for round in 0..4 { |
| 1897 | let exam = published(&db).await; |
| 1898 | let question = question_on(&exam, &db).await; |
| 1899 | let id = exam.get_id().clone(); |
| 1900 | |
| 1901 | let gate = std::sync::Arc::new(tokio::sync::Barrier::new(2)); |
| 1902 | let drop_it = { |
| 1903 | let (db, exam, gate) = (db.clone(), exam, gate.clone()); |
| 1904 | tokio::spawn(async move { |
| 1905 | gate.wait().await; |
| 1906 | delete(&db, exam).await |
| 1907 | }) |
| 1908 | }; |
| 1909 | let child = { |
| 1910 | let (db, exam_id, on, gate) = |
| 1911 | (db.clone(), id.clone(), question.get_id().clone(), gate); |
| 1912 | tokio::spawn(async move { |
| 1913 | gate.wait().await; |
| 1914 | shoot(&db, &exam_id, &on).await |
| 1915 | }) |
| 1916 | }; |
| 1917 | let (drop_it, child) = (drop_it.await.unwrap(), child.await.unwrap()); |
| 1918 | assert!( |
| 1919 | !matches!(child, Err(AppError::Db(_))), |
| 1920 | "round {round}: a raced picture write must be answered, not 500: {child:?}" |
| 1921 | ); |
| 1922 | assert!( |
| 1923 | !matches!(drop_it, Err(AppError::Db(_))), |
| 1924 | "round {round}: a raced delete must be answered, not 500: {drop_it:?}" |
| 1925 | ); |
| 1926 | |
| 1927 | if read(&db, &id).await.unwrap().is_none() { |
| 1928 | swept += 1; |
| 1929 | assert_eq!( |
| 1930 | crate::db::question_image::list_for_exam(&db, &id) |
| 1931 | .await |
| 1932 | .unwrap() |
| 1933 | .len(), |
| 1934 | 0, |
| 1935 | "round {round}: a picture outlived its exam" |
| 1936 | ); |
| 1937 | } else if drop_it.is_ok() { |
| 1938 | panic!("round {round}: the delete reported success but the exam is still there"); |
| 1939 | } |
| 1940 | } |
| 1941 | eprintln!( |
| 1942 | "Exam::delete raced by a picture write: {swept}/4 concurrent rounds deleted the exam" |
| 1943 | ); |
| 1944 | } |
| 1945 | } |