Split homework domains into domain/db/service layers
Browse files at this commite37f2b667d63969bb72d9739b32ae246e2a54fd8Parent: 387eb31- chore
- split homework domains into domain/db/service layers
19 changed files +2961 -2516
- src/db/homework.rs +539 -0
- src/db/homework_file.rs +419 -0
- src/db/homework_result.rs +433 -0
- src/db/homework_submission.rs +720 -0
- src/db/mod.rs +4 -0
- src/domain/homework.rs +16 -498
- src/domain/homework_file.rs +12 -423
- src/domain/homework_result.rs +16 -458
- src/domain/homework_submission.rs +17 -746
- src/migration_sql.rs +1 -1
- src/service/course.rs +4 -4
- src/service/homework.rs +274 -0
- src/service/homework_file.rs +92 -0
- src/service/homework_result.rs +132 -0
- src/service/homework_submission.rs +140 -0
- src/service/mod.rs +4 -0
- src/web/courses.rs +19 -8
- src/web/homework.rs +110 -371
- tests/regress_homework_orphans.rs +9 -7
src/db/homework.rsadded+539 -0
| @@ -0,0 +1,539 @@ | |||
| 1 | +//! The `homework` table: row reads and listings, the count-and-create that | ||
| 2 | +//! pins a homework to a live subject row, the reference-counting PATCH, and | ||
| 3 | +//! the cascading delete. The PATCH's orphan guard and the audience gate live | ||
| 4 | +//! in [`crate::service::homework`]. | ||
| 5 | + | ||
| 6 | +use surrealdb::types::RecordId; | ||
| 7 | + | ||
| 8 | +use crate::constant::SUBJECT_HOMEWORK_COUNT_FIELD; | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::db::cap; | ||
| 11 | +use crate::db::field_update::FieldUpdate; | ||
| 12 | +use crate::domain::course::CourseId; | ||
| 13 | +use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; | ||
| 14 | +use crate::domain::subject::SubjectId; | ||
| 15 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | +use crate::domain::user::UserId; | ||
| 17 | +use crate::error::{AppError, ValidationError}; | ||
| 18 | + | ||
| 19 | +/// The answer a link to a subject that is not there gets, on create and on | ||
| 20 | +/// re-tag alike — both claims are conditional writes on the subject row, so a | ||
| 21 | +/// subject a delete already removed matches nothing and the caller says exactly | ||
| 22 | +/// what the web layer's pre-flight lookup would have. | ||
| 23 | +fn subject_gone() -> AppError { | ||
| 24 | + AppError::Validation(ValidationError::Invalid { | ||
| 25 | + field: "subject_id", | ||
| 26 | + reason: "subject does not exist", | ||
| 27 | + }) | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +#[expect( | ||
| 31 | + clippy::too_many_arguments, | ||
| 32 | + reason = "mirrors the sibling entities' create(field, field, ..) shape" | ||
| 33 | +)] | ||
| 34 | +pub async fn create( | ||
| 35 | + db: &Database, | ||
| 36 | + course: &CourseId, | ||
| 37 | + subject: &SubjectId, | ||
| 38 | + title: HomeworkTitle, | ||
| 39 | + description: Option<HomeworkDescription>, | ||
| 40 | + due_at: Timestamp, | ||
| 41 | + assigned: Option<Vec<UserId>>, | ||
| 42 | + created_by: &UserId, | ||
| 43 | +) -> Result<Homework, AppError> { | ||
| 44 | + // The subject's reference is taken in the very transaction that writes | ||
| 45 | + // the row — the exam question's twin | ||
| 46 | + // ([`crate::db::exam_question`]): the subject delete | ||
| 47 | + // is refused while this counter is non-zero, so the create and the | ||
| 48 | + // delete contend on the subject record rather than on a cross-table | ||
| 49 | + // count neither of them sees the other move, and a crash can no longer | ||
| 50 | + // strand a claim that would make the subject undeletable forever. A | ||
| 51 | + // refused claim means the subject is already gone, which is the 400 the | ||
| 52 | + // web layer's pre-flight check answers with. | ||
| 53 | + let counted = subject.record(); | ||
| 54 | + let homework = Homework { | ||
| 55 | + id: HomeworkId::generate(), | ||
| 56 | + course: course.clone(), | ||
| 57 | + subject: subject.clone(), | ||
| 58 | + title, | ||
| 59 | + description, | ||
| 60 | + due_at, | ||
| 61 | + assigned, | ||
| 62 | + created_by: created_by.clone(), | ||
| 63 | + created_at: Timestamp::now(), | ||
| 64 | + }; | ||
| 65 | + let id = homework.id.record(); | ||
| 66 | + match cap::claim_and_create( | ||
| 67 | + &counted, | ||
| 68 | + SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 69 | + cap::UNLIMITED, | ||
| 70 | + &id, | ||
| 71 | + &homework, | ||
| 72 | + db, | ||
| 73 | + ) | ||
| 74 | + .await? | ||
| 75 | + { | ||
| 76 | + cap::Claimed::Made(created) => Ok(created), | ||
| 77 | + cap::Claimed::Full => Err(subject_gone()), | ||
| 78 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), | ||
| 79 | + } | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> { | ||
| 83 | + Ok(db.select(id.record()).await?) | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// The course's homework, newest first (ULID ids sort by creation). The web | ||
| 87 | +/// layer retains only the rows a given student `student_sees`. | ||
| 88 | +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> { | ||
| 89 | + let mut result = db | ||
| 90 | + .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") | ||
| 91 | + .bind(("course", course.record())) | ||
| 92 | + .await? | ||
| 93 | + .check()?; | ||
| 94 | + Ok(result.take::<Vec<Homework>>(0)?) | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +/// Every homework in the system, newest first — the manager+ view of the | ||
| 98 | +/// cross-course "my homework" list. | ||
| 99 | +pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> { | ||
| 100 | + let mut result = db | ||
| 101 | + .query("SELECT * FROM homework ORDER BY id DESC") | ||
| 102 | + .await? | ||
| 103 | + .check()?; | ||
| 104 | + Ok(result.take::<Vec<Homework>>(0)?) | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// Every homework of every course in `courses`, newest first (one query) — | ||
| 108 | +/// the cross-course list over a caller's visible courses. The web layer | ||
| 109 | +/// still trims each course's rows to what the caller may see (a student to | ||
| 110 | +/// the ones they `student_sees`). | ||
| 111 | +pub async fn list_for_courses( | ||
| 112 | + db: &Database, | ||
| 113 | + courses: &[CourseId], | ||
| 114 | +) -> Result<Vec<Homework>, AppError> { | ||
| 115 | + if courses.is_empty() { | ||
| 116 | + return Ok(Vec::new()); | ||
| 117 | + } | ||
| 118 | + let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect(); | ||
| 119 | + let mut result = db | ||
| 120 | + .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") | ||
| 121 | + .bind(("courses", records)) | ||
| 122 | + .await? | ||
| 123 | + .check()?; | ||
| 124 | + Ok(result.take::<Vec<Homework>>(0)?) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The homework of `course` that `user` is meant to see — whole-course ones | ||
| 128 | +/// plus any subset that names them — newest first. Backs a student's (or an | ||
| 129 | +/// observer's) per-course homework report; mirrors | ||
| 130 | +/// [`Homework::student_sees`](crate::domain::homework::Homework::student_sees) | ||
| 131 | +/// in SurQL so the filter runs in the database. | ||
| 132 | +pub async fn list_for_user_in_course( | ||
| 133 | + db: &Database, | ||
| 134 | + course: &CourseId, | ||
| 135 | + user: &UserId, | ||
| 136 | +) -> Result<Vec<Homework>, AppError> { | ||
| 137 | + let mut result = db | ||
| 138 | + .query( | ||
| 139 | + "SELECT * FROM homework | ||
| 140 | + WHERE course = $course | ||
| 141 | + AND (assigned = NONE OR assigned = [] OR $usr IN assigned) | ||
| 142 | + ORDER BY id DESC", | ||
| 143 | + ) | ||
| 144 | + .bind(("course", course.record())) | ||
| 145 | + .bind(("usr", user.record())) | ||
| 146 | + .await? | ||
| 147 | + .check()?; | ||
| 148 | + Ok(result.take::<Vec<Homework>>(0)?) | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. | ||
| 152 | +/// Request-scoped: every parameter is `Option`, `None` meaning the PATCH | ||
| 153 | +/// did not carry that field, so it is not written at all. Handing the | ||
| 154 | +/// snapshot's value back instead would revert a concurrent edit of that | ||
| 155 | +/// field — scoping the `SET` alone does not prevent that, the *values* must | ||
| 156 | +/// come from the request. `course`, `created_by`, and `created_at` are | ||
| 157 | +/// `READONLY` and never appear in the write. | ||
| 158 | +/// | ||
| 159 | +/// `description` and `assigned` are nullable columns, so they take a | ||
| 160 | +/// `NONE` (clear the description / widen back to the whole course). The web | ||
| 161 | +/// layer has already re-checked a new `due_at` against now, a new `subject` | ||
| 162 | +/// against the course, and refused a narrowing that would orphan work. | ||
| 163 | +pub async fn update( | ||
| 164 | + db: &Database, | ||
| 165 | + homework: Homework, | ||
| 166 | + subject: Option<SubjectId>, | ||
| 167 | + title: Option<HomeworkTitle>, | ||
| 168 | + description: Option<Option<HomeworkDescription>>, | ||
| 169 | + due_at: Option<Timestamp>, | ||
| 170 | + assigned: Option<Option<Vec<UserId>>>, | ||
| 171 | +) -> Result<Homework, AppError> { | ||
| 172 | + let assigned = assigned | ||
| 173 | + .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>())); | ||
| 174 | + // A re-tag moves a reference: the new subject's claim and the old one's | ||
| 175 | + // release ride the same transaction as the link write, so no crash can | ||
| 176 | + // leave a count without its link (the subject would be undeletable | ||
| 177 | + // forever) or a link without its count. `subject` is required, so the | ||
| 178 | + // snapshot's value is always the CAS expectation — two PATCHes moving | ||
| 179 | + // the same homework off the same subject would otherwise both claim | ||
| 180 | + // their target, and the loser is refused with a 409 instead. The | ||
| 181 | + // `.refcount` call is unconditional: the CAS is armed by the request | ||
| 182 | + // *carrying* `subject_id`, not by a counter moving, so a PATCH that | ||
| 183 | + // re-states the tag its snapshot showed — shifting no counter at all — | ||
| 184 | + // is still refused when a rival moved the tag in between. A PATCH that | ||
| 185 | + // carried no `subject_id` arms nothing and writes what it always did. | ||
| 186 | + let (claim, release) = subject | ||
| 187 | + .as_ref() | ||
| 188 | + .filter(|next| **next != homework.subject) | ||
| 189 | + .map(|next| (next.record(), homework.subject.record())) | ||
| 190 | + .unzip(); | ||
| 191 | + FieldUpdate::new(homework.id.record()) | ||
| 192 | + .set("subject", subject.map(|subject| subject.record())) | ||
| 193 | + .set("title", title) | ||
| 194 | + .set("description", description) | ||
| 195 | + .set("due_at", due_at) | ||
| 196 | + .set("assigned", assigned) | ||
| 197 | + .refcount( | ||
| 198 | + SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 199 | + "subject", | ||
| 200 | + Some(homework.subject.record()), | ||
| 201 | + claim, | ||
| 202 | + release, | ||
| 203 | + subject_gone(), | ||
| 204 | + ) | ||
| 205 | + .run::<Homework>(db) | ||
| 206 | + .await | ||
| 207 | +} | ||
| 208 | + | ||
| 209 | +/// Delete the homework and cascade its submissions, their files, and its | ||
| 210 | +/// results — one transaction, so a crash can't orphan a submission under a | ||
| 211 | +/// vanished homework. The submission file *blobs* are the web layer's to | ||
| 212 | +/// unlink: it collects their names via | ||
| 213 | +/// [`crate::db::homework_file::file_keys_for_homework`] | ||
| 214 | +/// before calling this, and removes them after the rows are gone. | ||
| 215 | +pub async fn delete(db: &Database, homework: Homework) -> Result<Homework, AppError> { | ||
| 216 | + let mut result = db | ||
| 217 | + .query( | ||
| 218 | + format!( | ||
| 219 | + "BEGIN TRANSACTION; | ||
| 220 | + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); | ||
| 221 | + DELETE homework_submission WHERE homework = $hw; | ||
| 222 | + DELETE homework_result WHERE homework = $hw; | ||
| 223 | + LET $gone = (DELETE $hw RETURN BEFORE); | ||
| 224 | + FOR $sub IN ($gone.subject ?? []) {{ | ||
| 225 | + UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = | ||
| 226 | + math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) | ||
| 227 | + }}; | ||
| 228 | + RETURN $gone; | ||
| 229 | + COMMIT TRANSACTION;" | ||
| 230 | + ), | ||
| 231 | + ) | ||
| 232 | + .bind(("hw", homework.id.record())) | ||
| 233 | + .await? | ||
| 234 | + .check()?; | ||
| 235 | + // The subject's reference is given back in this same transaction, off | ||
| 236 | + // what the delete actually removed. Read through the trailing `RETURN`, | ||
| 237 | + // not a hand-counted slot — see [`crate::db::exam::delete`]. | ||
| 238 | + let slot = result.num_statements().saturating_sub(2); | ||
| 239 | + let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next(); | ||
| 240 | + deleted.ok_or(AppError::NotFound) | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +#[cfg(test)] | ||
| 244 | +mod tests { | ||
| 245 | + use super::*; | ||
| 246 | + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 247 | + | ||
| 248 | + async fn a_subject(name: &str, db: &Database) -> Subject { | ||
| 249 | + Subject::create( | ||
| 250 | + &crate::db::course::a_test_course(db).await, | ||
| 251 | + SubjectName::try_new(name).unwrap(), | ||
| 252 | + SubjectDescription::try_new("").unwrap(), | ||
| 253 | + db, | ||
| 254 | + ) | ||
| 255 | + .await | ||
| 256 | + .unwrap() | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { | ||
| 260 | + create( | ||
| 261 | + db, | ||
| 262 | + &CourseId::from_key("course"), | ||
| 263 | + subject, | ||
| 264 | + HomeworkTitle::try_new("essay").unwrap(), | ||
| 265 | + None, | ||
| 266 | + Timestamp::from_millis(1), | ||
| 267 | + None, | ||
| 268 | + &UserId::from_key("teacher"), | ||
| 269 | + ) | ||
| 270 | + .await | ||
| 271 | + .unwrap() | ||
| 272 | + } | ||
| 273 | + | ||
| 274 | + /// The stored `homework_count` on one subject, absent counting as zero. | ||
| 275 | + async fn count_on(subject: &SubjectId, db: &Database) -> i64 { | ||
| 276 | + let mut result = db | ||
| 277 | + .query(format!( | ||
| 278 | + "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" | ||
| 279 | + )) | ||
| 280 | + .bind(("sub", subject.record())) | ||
| 281 | + .await | ||
| 282 | + .unwrap() | ||
| 283 | + .check() | ||
| 284 | + .unwrap(); | ||
| 285 | + result | ||
| 286 | + .take::<Vec<i64>>(0) | ||
| 287 | + .unwrap() | ||
| 288 | + .first() | ||
| 289 | + .copied() | ||
| 290 | + .unwrap_or(0) | ||
| 291 | + } | ||
| 292 | + | ||
| 293 | + /// How many rows `sql` selects ids for. | ||
| 294 | + async fn rows(sql: &str, db: &Database) -> usize { | ||
| 295 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 296 | + result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 297 | + } | ||
| 298 | + | ||
| 299 | + /// The invariant on the create path: the claim and the row it accounts for | ||
| 300 | + /// commit together or not at all. A refused create leaves *neither* — no | ||
| 301 | + /// homework row, and no count stranded on a subject (the subject's delete | ||
| 302 | + /// guard reads that count, so a stray one makes it undeletable forever). | ||
| 303 | + #[tokio::test] | ||
| 304 | + async fn a_refused_create_writes_neither_row_nor_count() { | ||
| 305 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 306 | + let subject = a_subject("algebra", &db).await; | ||
| 307 | + let id = subject.get_id().clone(); | ||
| 308 | + subject.delete(&db).await.unwrap(); | ||
| 309 | + | ||
| 310 | + let error = create( | ||
| 311 | + &db, | ||
| 312 | + &CourseId::from_key("course"), | ||
| 313 | + &id, | ||
| 314 | + HomeworkTitle::try_new("essay").unwrap(), | ||
| 315 | + None, | ||
| 316 | + Timestamp::from_millis(1), | ||
| 317 | + None, | ||
| 318 | + &UserId::from_key("teacher"), | ||
| 319 | + ) | ||
| 320 | + .await | ||
| 321 | + .expect_err("a subject that is gone must not be taggable"); | ||
| 322 | + assert!(error.to_string().contains("subject does not exist")); | ||
| 323 | + assert_eq!( | ||
| 324 | + rows("SELECT VALUE id FROM homework", &db).await, | ||
| 325 | + 0, | ||
| 326 | + "a refused create may write no row" | ||
| 327 | + ); | ||
| 328 | + assert_eq!( | ||
| 329 | + rows("SELECT VALUE id FROM subject", &db).await, | ||
| 330 | + 0, | ||
| 331 | + "…and least of all a count on a subject it just brought back" | ||
| 332 | + ); | ||
| 333 | + } | ||
| 334 | + | ||
| 335 | + /// The invariant on the PATCH path: a re-tag carries the new subject's | ||
| 336 | + /// claim and the old one's release with the link itself. | ||
| 337 | + #[tokio::test] | ||
| 338 | + async fn a_subject_move_moves_the_count() { | ||
| 339 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 340 | + let from = a_subject("algebra", &db).await; | ||
| 341 | + let to = a_subject("geometry", &db).await; | ||
| 342 | + let homework = homework_on(from.get_id(), &db).await; | ||
| 343 | + assert_eq!(count_on(from.get_id(), &db).await, 1); | ||
| 344 | + | ||
| 345 | + let moved = update( | ||
| 346 | + &db, | ||
| 347 | + homework, | ||
| 348 | + Some(to.get_id().clone()), | ||
| 349 | + None, | ||
| 350 | + None, | ||
| 351 | + None, | ||
| 352 | + None, | ||
| 353 | + ) | ||
| 354 | + .await | ||
| 355 | + .unwrap(); | ||
| 356 | + assert_eq!(moved.get_subject(), to.get_id()); | ||
| 357 | + assert_eq!( | ||
| 358 | + count_on(from.get_id(), &db).await, | ||
| 359 | + 0, | ||
| 360 | + "the old subject is free" | ||
| 361 | + ); | ||
| 362 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | ||
| 363 | + assert!(from.delete(&db).await.is_ok(), "no reference left"); | ||
| 364 | + assert!( | ||
| 365 | + to.delete(&db).await.is_err(), | ||
| 366 | + "the reference moved here refuses the delete" | ||
| 367 | + ); | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// The claim throws inside the same transaction as the link write, so a | ||
| 371 | + /// move onto a subject that is gone rolls the release back with it: the row | ||
| 372 | + /// keeps its tag and both counters read as if nothing ran. | ||
| 373 | + #[tokio::test] | ||
| 374 | + async fn a_move_to_a_dead_subject_leaves_everything_untouched() { | ||
| 375 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 376 | + let from = a_subject("algebra", &db).await; | ||
| 377 | + let dead = a_subject("geometry", &db).await; | ||
| 378 | + let gone = dead.get_id().clone(); | ||
| 379 | + dead.delete(&db).await.unwrap(); | ||
| 380 | + let homework = homework_on(from.get_id(), &db).await; | ||
| 381 | + | ||
| 382 | + let error = update( | ||
| 383 | + &db, | ||
| 384 | + homework.clone(), | ||
| 385 | + Some(gone.clone()), | ||
| 386 | + None, | ||
| 387 | + None, | ||
| 388 | + None, | ||
| 389 | + None, | ||
| 390 | + ) | ||
| 391 | + .await | ||
| 392 | + .expect_err("a subject that is gone must not be taggable"); | ||
| 393 | + assert!(error.to_string().contains("subject does not exist")); | ||
| 394 | + let stored = read(&db, homework.get_id()).await.unwrap().unwrap(); | ||
| 395 | + assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); | ||
| 396 | + assert_eq!( | ||
| 397 | + count_on(from.get_id(), &db).await, | ||
| 398 | + 1, | ||
| 399 | + "the release rolled back with the claim" | ||
| 400 | + ); | ||
| 401 | + assert_eq!( | ||
| 402 | + rows("SELECT VALUE id FROM subject", &db).await, | ||
| 403 | + 1, | ||
| 404 | + "the dead subject was not brought back by a count" | ||
| 405 | + ); | ||
| 406 | + assert_eq!(count_on(&gone, &db).await, 0); | ||
| 407 | + } | ||
| 408 | + | ||
| 409 | + /// The double-claim guard. Both movers compute their claim and release from | ||
| 410 | + /// the row as *they* read it, so two PATCHes re-tagging the same homework | ||
| 411 | + /// off the same subject both release it and both claim their target — two | ||
| 412 | + /// counts for one link, and the loser's target is undeletable forever. The | ||
| 413 | + /// second call here runs on the struct read before the first one landed, | ||
| 414 | + /// which is that race with the interleaving pinned: it must be refused | ||
| 415 | + /// outright, and the counts must read as if it never ran. | ||
| 416 | + #[tokio::test] | ||
| 417 | + async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 418 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 419 | + let from = a_subject("algebra", &db).await; | ||
| 420 | + let to = a_subject("geometry", &db).await; | ||
| 421 | + let other = a_subject("calculus", &db).await; | ||
| 422 | + let homework = homework_on(from.get_id(), &db).await; | ||
| 423 | + let stale = homework.clone(); | ||
| 424 | + update( | ||
| 425 | + &db, | ||
| 426 | + homework, | ||
| 427 | + Some(to.get_id().clone()), | ||
| 428 | + None, | ||
| 429 | + None, | ||
| 430 | + None, | ||
| 431 | + None, | ||
| 432 | + ) | ||
| 433 | + .await | ||
| 434 | + .unwrap(); | ||
| 435 | + | ||
| 436 | + let error = update( | ||
| 437 | + &db, | ||
| 438 | + stale.clone(), | ||
| 439 | + Some(other.get_id().clone()), | ||
| 440 | + None, | ||
| 441 | + None, | ||
| 442 | + None, | ||
| 443 | + None, | ||
| 444 | + ) | ||
| 445 | + .await | ||
| 446 | + .expect_err("a mover that read a tag it no longer holds must be refused"); | ||
| 447 | + assert!( | ||
| 448 | + matches!(error, AppError::Conflict(_)), | ||
| 449 | + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 450 | + ); | ||
| 451 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 452 | + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); | ||
| 453 | + assert_eq!( | ||
| 454 | + count_on(from.get_id(), &db).await, | ||
| 455 | + 0, | ||
| 456 | + "released once, not twice" | ||
| 457 | + ); | ||
| 458 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); | ||
| 459 | + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); | ||
| 460 | + } | ||
| 461 | + | ||
| 462 | + /// The same race with the counters taken out of it. A PATCH that re-states | ||
| 463 | + /// the subject its snapshot showed shifts *nothing* — no claim and no | ||
| 464 | + /// release — so if the guard were armed off the counter move it would not be | ||
| 465 | + /// armed here at all, and the write would land: the winner's tag silently | ||
| 466 | + /// dragged back, its claim stranded on a subject nothing points at | ||
| 467 | + /// (undeletable forever) and the reverted-to subject tagged at a count of | ||
| 468 | + /// zero (deletable while tagged). The guard is armed by the request | ||
| 469 | + /// *carrying* the column instead, which is why this is refused. | ||
| 470 | + #[tokio::test] | ||
| 471 | + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 472 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 473 | + let from = a_subject("algebra", &db).await; | ||
| 474 | + let to = a_subject("geometry", &db).await; | ||
| 475 | + let homework = homework_on(from.get_id(), &db).await; | ||
| 476 | + let stale = homework.clone(); | ||
| 477 | + update( | ||
| 478 | + &db, | ||
| 479 | + homework, | ||
| 480 | + Some(to.get_id().clone()), | ||
| 481 | + None, | ||
| 482 | + None, | ||
| 483 | + None, | ||
| 484 | + None, | ||
| 485 | + ) | ||
| 486 | + .await | ||
| 487 | + .unwrap(); | ||
| 488 | + | ||
| 489 | + let error = update( | ||
| 490 | + &db, | ||
| 491 | + stale.clone(), | ||
| 492 | + Some(from.get_id().clone()), | ||
| 493 | + None, | ||
| 494 | + None, | ||
| 495 | + None, | ||
| 496 | + None, | ||
| 497 | + ) | ||
| 498 | + .await | ||
| 499 | + .expect_err("re-stating a tag someone else moved must be refused"); | ||
| 500 | + assert!( | ||
| 501 | + matches!(error, AppError::Conflict(_)), | ||
| 502 | + "a lost CAS is a conflict, not a silent 200: {error:?}" | ||
| 503 | + ); | ||
| 504 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 505 | + assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); | ||
| 506 | + assert_eq!( | ||
| 507 | + count_on(from.get_id(), &db).await, | ||
| 508 | + 0, | ||
| 509 | + "the reverted-to subject must not end up tagged at zero" | ||
| 510 | + ); | ||
| 511 | + assert_eq!( | ||
| 512 | + count_on(to.get_id(), &db).await, | ||
| 513 | + 1, | ||
| 514 | + "…nor the winner's subject counted with nothing pointing at it" | ||
| 515 | + ); | ||
| 516 | + | ||
| 517 | + // A *genuine* no-op re-state — nobody moved underneath it — still lands, | ||
| 518 | + // and still moves no counter: the CAS passes trivially. | ||
| 519 | + let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 520 | + let same = update( | ||
| 521 | + &db, | ||
| 522 | + fresh, | ||
| 523 | + Some(to.get_id().clone()), | ||
| 524 | + None, | ||
| 525 | + None, | ||
| 526 | + None, | ||
| 527 | + None, | ||
| 528 | + ) | ||
| 529 | + .await | ||
| 530 | + .expect("re-stating the tag actually held is not a race"); | ||
| 531 | + assert_eq!(same.get_subject(), to.get_id()); | ||
| 532 | + assert_eq!( | ||
| 533 | + count_on(from.get_id(), &db).await, | ||
| 534 | + 0, | ||
| 535 | + "still no counter move" | ||
| 536 | + ); | ||
| 537 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); | ||
| 538 | + } | ||
| 539 | +} | ||
src/db/homework_file.rsadded+419 -0
| @@ -0,0 +1,419 @@ | |||
| 1 | +//! The `homework_file` table: the attachment rows behind a submission's | ||
| 2 | +//! files — the seat-claiming insert, the scoped reads, the GC key | ||
| 3 | +//! collectors, and the gate-guarded delete. The rows' assembly (`new`) and | ||
| 4 | +//! their validated fields live in [`crate::domain::homework_file`]; the | ||
| 5 | +//! upload workflow around them in [`crate::service::homework_file`]. | ||
| 6 | + | ||
| 7 | +use surrealdb::types::SurrealValue; | ||
| 8 | + | ||
| 9 | +use crate::constant::{ | ||
| 10 | + MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, SUBMISSION_OPEN_GUARD, | ||
| 11 | +}; | ||
| 12 | +use crate::database::{Database, transaction_with_retry}; | ||
| 13 | +use crate::db::cap; | ||
| 14 | +use crate::domain::course::CourseId; | ||
| 15 | +use crate::domain::homework::HomeworkId; | ||
| 16 | +use crate::domain::homework_file::HomeworkFile; | ||
| 17 | +use crate::domain::timestamp::Timestamp; | ||
| 18 | +use crate::error::AppError; | ||
| 19 | + | ||
| 20 | +/// What [`delete`]'s transaction reports: whether the submission | ||
| 21 | +/// was still open (`open` = 1, the gate bit) and the row it then removed. Two | ||
| 22 | +/// answers in one object because an empty `gone` alone cannot say whether the | ||
| 23 | +/// delete was refused or the file had simply vanished. | ||
| 24 | +#[derive(Debug, SurrealValue)] | ||
| 25 | +struct DeleteOutcome { | ||
| 26 | + open: i64, | ||
| 27 | + gone: Vec<HomeworkFile>, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// Persist the row assembled by | ||
| 31 | +/// [`HomeworkFile::new`](crate::domain::homework_file::HomeworkFile::new), | ||
| 32 | +/// refusing once its submission already holds | ||
| 33 | +/// [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) | ||
| 34 | +/// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own | ||
| 35 | +/// wording). Both are decided by one [`cap::claim_when_and_create`] on the | ||
| 36 | +/// submission row — the seat and the file row commit together, so a crash | ||
| 37 | +/// between them can no longer leave a slot claimed by a file that does not | ||
| 38 | +/// exist, and a losing upload never has to be un-counted. Which of the two | ||
| 39 | +/// conditions refused it is read back afterwards, off the losing path only, | ||
| 40 | +/// and only to pick the message: `Claimed::Full` says "full *or* graded *or* | ||
| 41 | +/// the submission is gone". | ||
| 42 | +pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | ||
| 43 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 44 | + match cap::claim_when_and_create( | ||
| 45 | + &file.submission.record(), | ||
| 46 | + SUBMISSION_FILE_COUNT_FIELD, | ||
| 47 | + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, | ||
| 48 | + SUBMISSION_OPEN_GUARD, | ||
| 49 | + &file.id.record(), | ||
| 50 | + &file, | ||
| 51 | + db, | ||
| 52 | + ) | ||
| 53 | + .await? | ||
| 54 | + { | ||
| 55 | + cap::Claimed::Made(created) => Ok(Some(created)), | ||
| 56 | + cap::Claimed::Full => { | ||
| 57 | + if super::homework_submission::is_graded(db, &file.submission).await? { | ||
| 58 | + return Ok(None); | ||
| 59 | + } | ||
| 60 | + Err(AppError::Conflict( | ||
| 61 | + "the submission already holds the maximum of 10 files — delete one first", | ||
| 62 | + )) | ||
| 63 | + } | ||
| 64 | + // The id is a fresh ULID minted by `new`, so a row already holding it | ||
| 65 | + // is a collision, not a re-upload. | ||
| 66 | + cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +/// Read a file's row only if it belongs to `submission` — callers have | ||
| 71 | +/// already checked the submission belongs to the requesting user. | ||
| 72 | +pub async fn read_for( | ||
| 73 | + db: &Database, | ||
| 74 | + id: &crate::domain::homework_file::HomeworkFileId, | ||
| 75 | + submission: &crate::domain::homework_submission::HomeworkSubmissionId, | ||
| 76 | +) -> Result<Option<HomeworkFile>, AppError> { | ||
| 77 | + let file: Option<HomeworkFile> = db.select(id.record()).await?; | ||
| 78 | + Ok(file.filter(|file| &file.submission == submission)) | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +/// Read a file by id only if it hangs off a submission to `homework` — the | ||
| 82 | +/// grader's download scoping. The teacher download path carries the homework | ||
| 83 | +/// id but not the owning student (unlike `read_for`, which needs the | ||
| 84 | +/// submission), so this both finds the file and confirms it belongs under | ||
| 85 | +/// `homework`: a teacher can't pass a homework they manage to read a file | ||
| 86 | +/// from a different (perhaps unmanaged) one. | ||
| 87 | +pub async fn read_in_homework( | ||
| 88 | + db: &Database, | ||
| 89 | + id: &crate::domain::homework_file::HomeworkFileId, | ||
| 90 | + homework: &HomeworkId, | ||
| 91 | +) -> Result<Option<HomeworkFile>, AppError> { | ||
| 92 | + let mut result = db | ||
| 93 | + .query( | ||
| 94 | + "SELECT * FROM homework_file WHERE id = $id AND submission IN \ | ||
| 95 | + (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | ||
| 96 | + ) | ||
| 97 | + .bind(("id", id.record())) | ||
| 98 | + .bind(("hw", homework.record())) | ||
| 99 | + .await? | ||
| 100 | + .check()?; | ||
| 101 | + Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next()) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// All of `submission`'s files, newest first. | ||
| 105 | +pub async fn list_for_submission( | ||
| 106 | + db: &Database, | ||
| 107 | + submission: &crate::domain::homework_submission::HomeworkSubmissionId, | ||
| 108 | +) -> Result<Vec<HomeworkFile>, AppError> { | ||
| 109 | + let mut result = db | ||
| 110 | + .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") | ||
| 111 | + .bind(("sub", submission.record())) | ||
| 112 | + .await? | ||
| 113 | + .check()?; | ||
| 114 | + Ok(result.take::<Vec<HomeworkFile>>(0)?) | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// How many files `submission` holds — the cap check reads this under the | ||
| 118 | +/// lock. Counting via the rows (not a `count()` query) keeps it identical | ||
| 119 | +/// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. | ||
| 120 | +pub async fn count_for_submission( | ||
| 121 | + db: &Database, | ||
| 122 | + submission: &crate::domain::homework_submission::HomeworkSubmissionId, | ||
| 123 | +) -> Result<usize, AppError> { | ||
| 124 | + Ok(list_for_submission(db, submission).await?.len()) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +/// The blob names behind every file of every submission to `homework` — | ||
| 128 | +/// collected *before* the homework-delete cascade wipes the rows, so the | ||
| 129 | +/// web layer can unlink them once the rows are gone. | ||
| 130 | +pub async fn file_keys_for_homework( | ||
| 131 | + db: &Database, | ||
| 132 | + homework: &HomeworkId, | ||
| 133 | +) -> Result<Vec<String>, AppError> { | ||
| 134 | + let mut result = db | ||
| 135 | + .query( | ||
| 136 | + "SELECT VALUE file FROM homework_file \ | ||
| 137 | + WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | ||
| 138 | + ) | ||
| 139 | + .bind(("hw", homework.record())) | ||
| 140 | + .await? | ||
| 141 | + .check()?; | ||
| 142 | + Ok(result.take::<Vec<String>>(0)?) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// The blob names behind every homework file of `course` — collected | ||
| 146 | +/// *before* the course-delete cascade wipes the rows. | ||
| 147 | +pub async fn file_keys_for_course( | ||
| 148 | + db: &Database, | ||
| 149 | + course: &CourseId, | ||
| 150 | +) -> Result<Vec<String>, AppError> { | ||
| 151 | + let mut result = db | ||
| 152 | + .query( | ||
| 153 | + "SELECT VALUE file FROM homework_file WHERE submission IN ( \ | ||
| 154 | + SELECT VALUE id FROM homework_submission \ | ||
| 155 | + WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ | ||
| 156 | + )", | ||
| 157 | + ) | ||
| 158 | + .bind(("course", course.record())) | ||
| 159 | + .await? | ||
| 160 | + .check()?; | ||
| 161 | + Ok(result.take::<Vec<String>>(0)?) | ||
| 162 | +} | ||
| 163 | + | ||
| 164 | +/// Delete the row and give its slot back in the same transaction. The | ||
| 165 | +/// submission survives, so its counter has to be corrected; the cascades | ||
| 166 | +/// that delete the submission itself take the counter with it. | ||
| 167 | +/// | ||
| 168 | +/// The gate is the first statement: a conditional write on the *submission* | ||
| 169 | +/// row — the "last touched" re-stamp a file delete owes the late flag | ||
| 170 | +/// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the | ||
| 171 | +/// transaction runs unless it bit, so a grade landing concurrently either | ||
| 172 | +/// stamps first (this delete is refused, `Ok(None)`) or stamps after (the | ||
| 173 | +/// file was already gone when it graded). `Err(NotFound)` still means the | ||
| 174 | +/// file row itself had vanished. | ||
| 175 | +/// | ||
| 176 | +/// Sound to re-send while the store answers "conflict, retry", and it has | ||
| 177 | +/// to be: the gate writes the *submission* row, the very record an upload's | ||
| 178 | +/// [`insert`] claims its seat on, and both handlers hold only | ||
| 179 | +/// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of | ||
| 180 | +/// one submission contend by design, and a lost round used to come back as | ||
| 181 | +/// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` | ||
| 182 | +/// are in the batch, and neither can legitimately answer "already exists", | ||
| 183 | +/// which is what makes the whole of it re-sendable. | ||
| 184 | +pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | ||
| 185 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 186 | + db, | ||
| 187 | + &format!( | ||
| 188 | + "BEGIN TRANSACTION; | ||
| 189 | + LET $open = (UPDATE $sub SET updated_at = $now \ | ||
| 190 | + WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); | ||
| 191 | + LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; | ||
| 192 | + UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 193 | + RETURN {{ open: array::len($open), gone: $gone }}; | ||
| 194 | + COMMIT TRANSACTION;" | ||
| 195 | + ), | ||
| 196 | + &[ | ||
| 197 | + ("id".into(), file.id.record().into_value()), | ||
| 198 | + ("sub".into(), file.submission.record().into_value()), | ||
| 199 | + ("now".into(), Timestamp::now().into_value()), | ||
| 200 | + ], | ||
| 201 | + &[], | ||
| 202 | + ) | ||
| 203 | + .await?; | ||
| 204 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 205 | + return Err(error.into()); | ||
| 206 | + } | ||
| 207 | + // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; | ||
| 208 | + // the RETURN is slot 4. | ||
| 209 | + let outcome: Option<DeleteOutcome> = result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next(); | ||
| 210 | + let outcome = | ||
| 211 | + outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; | ||
| 212 | + if outcome.open == 0 { | ||
| 213 | + return Ok(None); | ||
| 214 | + } | ||
| 215 | + outcome | ||
| 216 | + .gone | ||
| 217 | + .into_iter() | ||
| 218 | + .next() | ||
| 219 | + .map(Some) | ||
| 220 | + .ok_or(AppError::NotFound) | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +#[cfg(test)] | ||
| 224 | +mod tests { | ||
| 225 | + use super::*; | ||
| 226 | + use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 227 | + use crate::domain::note_file::{FileContentType, FileName}; | ||
| 228 | + use crate::domain::user::UserId; | ||
| 229 | + | ||
| 230 | + /// A real homework row (with the subject it references): `upsert` reads the | ||
| 231 | + /// deadline off the entity now, so a bare id no longer does. | ||
| 232 | + async fn a_homework(db: &Database) -> crate::domain::homework::Homework { | ||
| 233 | + use crate::db::homework as hw; | ||
| 234 | + use crate::domain::homework::HomeworkTitle; | ||
| 235 | + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 236 | + | ||
| 237 | + let course = crate::db::course::a_test_course(db).await; | ||
| 238 | + let subject = Subject::create( | ||
| 239 | + &course, | ||
| 240 | + SubjectName::try_new("topic").unwrap(), | ||
| 241 | + SubjectDescription::try_new("").unwrap(), | ||
| 242 | + db, | ||
| 243 | + ) | ||
| 244 | + .await | ||
| 245 | + .unwrap(); | ||
| 246 | + hw::create( | ||
| 247 | + db, | ||
| 248 | + &course, | ||
| 249 | + subject.get_id(), | ||
| 250 | + HomeworkTitle::try_new("essay").unwrap(), | ||
| 251 | + None, | ||
| 252 | + crate::domain::timestamp::Timestamp::from_millis(1), | ||
| 253 | + None, | ||
| 254 | + &UserId::from_key("teacher"), | ||
| 255 | + ) | ||
| 256 | + .await | ||
| 257 | + .unwrap() | ||
| 258 | + } | ||
| 259 | + | ||
| 260 | + fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { | ||
| 261 | + HomeworkFile::new( | ||
| 262 | + submission, | ||
| 263 | + FileName::try_new("answer.pdf").unwrap(), | ||
| 264 | + FileContentType::try_new("application/pdf").unwrap(), | ||
| 265 | + 3, | ||
| 266 | + ) | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + /// The counter as *stored* — the only witness that the seat and the row | ||
| 270 | + /// moved together, since every other read counts the rows themselves. | ||
| 271 | + async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { | ||
| 272 | + db.query("SELECT VALUE file_count FROM $sub") | ||
| 273 | + .bind(("sub", submission.record())) | ||
| 274 | + .await | ||
| 275 | + .unwrap() | ||
| 276 | + .take::<Vec<i64>>(0) | ||
| 277 | + .unwrap() | ||
| 278 | + .into_iter() | ||
| 279 | + .next() | ||
| 280 | + .unwrap_or(0) | ||
| 281 | + } | ||
| 282 | + #[tokio::test] | ||
| 283 | + async fn rows_scope_to_their_submission_gc_and_cap() { | ||
| 284 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 285 | + let hw = a_homework(&db).await; | ||
| 286 | + let homework = hw.get_id().clone(); | ||
| 287 | + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 288 | + // A real submission row, so the GC join through it resolves. | ||
| 289 | + let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) | ||
| 290 | + .await | ||
| 291 | + .unwrap() | ||
| 292 | + .unwrap(); | ||
| 293 | + let sub_a = submission.get_id().clone(); | ||
| 294 | + let sub_b = HomeworkSubmissionId::composite( | ||
| 295 | + &homework, | ||
| 296 | + &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), | ||
| 297 | + ); | ||
| 298 | + | ||
| 299 | + let stored = insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); | ||
| 300 | + // Readable under its own submission, invisible under another. | ||
| 301 | + assert!( | ||
| 302 | + read_for(&db, stored.get_id(), &sub_a) | ||
| 303 | + .await | ||
| 304 | + .unwrap() | ||
| 305 | + .is_some() | ||
| 306 | + ); | ||
| 307 | + assert!( | ||
| 308 | + read_for(&db, stored.get_id(), &sub_b) | ||
| 309 | + .await | ||
| 310 | + .unwrap() | ||
| 311 | + .is_none() | ||
| 312 | + ); | ||
| 313 | + assert_eq!(count_for_submission(&db, &sub_a).await.unwrap(), 1); | ||
| 314 | + assert_eq!( | ||
| 315 | + stored_count(&sub_a, &db).await, | ||
| 316 | + 1, | ||
| 317 | + "the seat rode with the row" | ||
| 318 | + ); | ||
| 319 | + | ||
| 320 | + // The grader's download scoping: found under its own homework, invisible | ||
| 321 | + // under another — so a teacher can't read it by naming a homework they | ||
| 322 | + // happen to manage. | ||
| 323 | + assert!( | ||
| 324 | + read_in_homework(&db, stored.get_id(), &homework) | ||
| 325 | + .await | ||
| 326 | + .unwrap() | ||
| 327 | + .is_some() | ||
| 328 | + ); | ||
| 329 | + assert!( | ||
| 330 | + read_in_homework( | ||
| 331 | + &db, | ||
| 332 | + stored.get_id(), | ||
| 333 | + &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), | ||
| 334 | + ) | ||
| 335 | + .await | ||
| 336 | + .unwrap() | ||
| 337 | + .is_none() | ||
| 338 | + ); | ||
| 339 | + | ||
| 340 | + // The blob name is collectable for GC before a cascade wipes the rows. | ||
| 341 | + let keys = file_keys_for_homework(&db, &homework).await.unwrap(); | ||
| 342 | + assert_eq!(keys, vec![stored.get_file().to_string()]); | ||
| 343 | + | ||
| 344 | + // Fill to the cap, then the 11th is refused. | ||
| 345 | + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { | ||
| 346 | + insert(&db, a_file(&sub_a)).await.unwrap().unwrap(); | ||
| 347 | + } | ||
| 348 | + assert!(matches!( | ||
| 349 | + insert(&db, a_file(&sub_a)).await, | ||
| 350 | + Err(AppError::Conflict(_)) | ||
| 351 | + )); | ||
| 352 | + // The refusal wrote nothing at all: neither a row nor a seat. | ||
| 353 | + assert_eq!( | ||
| 354 | + count_for_submission(&db, &sub_a).await.unwrap() as i64, | ||
| 355 | + stored_count(&sub_a, &db).await, | ||
| 356 | + ); | ||
| 357 | + assert_eq!( | ||
| 358 | + stored_count(&sub_a, &db).await, | ||
| 359 | + MAX_HOMEWORK_FILES_PER_SUBMISSION as i64 | ||
| 360 | + ); | ||
| 361 | + } | ||
| 362 | + | ||
| 363 | + /// A graded submission takes no more files and gives none up — decided by | ||
| 364 | + /// the same conditional write that claims the file slot, so no | ||
| 365 | + /// `homework_result` read stands between the check and the write. | ||
| 366 | + /// | ||
| 367 | + /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from [`insert`]'s | ||
| 368 | + /// [`cap::claim_when_and_create`] and the add below lands; drop it from | ||
| 369 | + /// [`delete`]'s gate and the delete below succeeds. | ||
| 370 | + #[tokio::test] | ||
| 371 | + async fn a_grade_freezes_the_files_too() { | ||
| 372 | + use crate::db::homework_result; | ||
| 373 | + use crate::domain::homework_result::HomeworkStatus; | ||
| 374 | + | ||
| 375 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 376 | + let hw = a_homework(&db).await; | ||
| 377 | + let homework = hw.get_id().clone(); | ||
| 378 | + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 379 | + let submission = crate::db::homework_submission::upsert(&db, &hw, &user, None) | ||
| 380 | + .await | ||
| 381 | + .unwrap() | ||
| 382 | + .unwrap(); | ||
| 383 | + let sub = submission.get_id().clone(); | ||
| 384 | + let stored = insert(&db, a_file(&sub)).await.unwrap().unwrap(); | ||
| 385 | + | ||
| 386 | + homework_result::grade( | ||
| 387 | + &db, | ||
| 388 | + &homework, | ||
| 389 | + &user, | ||
| 390 | + HomeworkStatus::try_new("done").unwrap(), | ||
| 391 | + None, | ||
| 392 | + &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | ||
| 393 | + ) | ||
| 394 | + .await | ||
| 395 | + .unwrap(); | ||
| 396 | + | ||
| 397 | + // Neither adding nor removing an attachment: `None` is the freeze, and | ||
| 398 | + // the cap's own `Err(Conflict)` stays distinct from it. | ||
| 399 | + assert!(insert(&db, a_file(&sub)).await.unwrap().is_none()); | ||
| 400 | + assert!(delete(&db, stored.clone()).await.unwrap().is_none()); | ||
| 401 | + assert_eq!( | ||
| 402 | + count_for_submission(&db, &sub).await.unwrap(), | ||
| 403 | + 1, | ||
| 404 | + "the graded submission keeps exactly the files it was graded on" | ||
| 405 | + ); | ||
| 406 | + // Refused by the *guard*, not the cap (nine seats free) — and still no | ||
| 407 | + // seat moved, so the counter matches the rows. | ||
| 408 | + assert_eq!(stored_count(&sub, &db).await, 1); | ||
| 409 | + // The refused add took no slot either, so un-grading gives back a | ||
| 410 | + // submission with room, not one that silently lost nine. | ||
| 411 | + homework_result::remove(&db, &homework, &user) | ||
| 412 | + .await | ||
| 413 | + .unwrap(); | ||
| 414 | + for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { | ||
| 415 | + insert(&db, a_file(&sub)).await.unwrap().unwrap(); | ||
| 416 | + } | ||
| 417 | + assert!(delete(&db, stored).await.unwrap().is_some()); | ||
| 418 | + } | ||
| 419 | +} | ||
src/db/homework_result.rsadded+433 -0
| @@ -0,0 +1,433 @@ | |||
| 1 | +//! The `homework_result` table: one grade per (homework, user) — the | ||
| 2 | +//! freeze-stamping UPSERT, the reads the roster and report join on, and the | ||
| 3 | +//! un-grade that gives the grader's counter back. Grading's policy gates | ||
| 4 | +//! (who may grade whom) live in [`crate::service::homework_result`]; the | ||
| 5 | +//! validated status and mark types in | ||
| 6 | +//! [`crate::domain::homework_result`]. | ||
| 7 | + | ||
| 8 | +use crate::constant::{MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD}; | ||
| 9 | +use crate::database::{Database, transaction_with_retry}; | ||
| 10 | +use crate::domain::course::CourseId; | ||
| 11 | +use crate::domain::exam_result::Mark; | ||
| 12 | +use crate::domain::homework::HomeworkId; | ||
| 13 | +use crate::domain::homework_result::{HomeworkResult, HomeworkResultId, HomeworkStatus}; | ||
| 14 | +use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 15 | +use crate::domain::timestamp::Timestamp; | ||
| 16 | +use crate::domain::user::UserId; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | +use surrealdb::types::SurrealValue; | ||
| 19 | + | ||
| 20 | +/// Record (or overwrite) the grade for (homework, user). One row per pair, | ||
| 21 | +/// keyed by the deterministic composite id, so this is a single atomic | ||
| 22 | +/// UPSERT — concurrent grades for the same pair converge on one row instead | ||
| 23 | +/// of racing a unique index into a 500. Grading before the due date, or | ||
| 24 | +/// before any submission exists, is allowed (the caller's policy call). | ||
| 25 | +/// | ||
| 26 | +/// In the same transaction the grade *stamps* the student's submission | ||
| 27 | +/// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: | ||
| 28 | +/// every student-side write to that row then fails its own | ||
| 29 | +/// `graded_by_result = NONE` condition, with no cross-table read for a | ||
| 30 | +/// concurrent write to slip past. A submission that does not exist yet is | ||
| 31 | +/// left alone — grading absent work must not conjure a hand-in (the report reads | ||
| 32 | +/// `submitted`/`missing`/`late` straight off that row). | ||
| 33 | +/// | ||
| 34 | +/// That one case is where this function stops defending itself: a student's | ||
| 35 | +/// *first* hand-in committing between this grade and nothing-to-stamp would | ||
| 36 | +/// land unstamped, leaving a grade beside an editable submission. Nothing | ||
| 37 | +/// here forbids it — what forbids it is the caller. Grading holds | ||
| 38 | +/// `HOMEWORK_LOCK` (see [`crate::service::homework`]) for writing across this | ||
| 39 | +/// whole transaction while every student-side write holds it for reading across | ||
| 40 | +/// its own, and the two leases are mutually exclusive in the one process | ||
| 41 | +/// this backend runs as, so the interleaving never gets a window. | ||
| 42 | +// | ||
| 43 | +// corner-cut: that makes the freeze depend on lock discipline at the call | ||
| 44 | +// sites, not on this row. Moving a student write's lease to *after* its | ||
| 45 | +// database write — or sharding HOMEWORK_LOCK per homework — reopens the | ||
| 46 | +// window with nothing to catch it. Closing it in the db layer needs a | ||
| 47 | +// record both sides own (a per-(homework, user) row the grade can always | ||
| 48 | +// stamp); a tombstone submission is not it, since every read path would | ||
| 49 | +// have to learn to ignore it and one missed filter fabricates a hand-in. | ||
| 50 | +pub async fn grade( | ||
| 51 | + db: &Database, | ||
| 52 | + homework: &HomeworkId, | ||
| 53 | + user: &UserId, | ||
| 54 | + status: HomeworkStatus, | ||
| 55 | + mark: Option<Mark>, | ||
| 56 | + graded_by: &UserId, | ||
| 57 | +) -> Result<HomeworkResult, AppError> { | ||
| 58 | + let id = HomeworkResultId::composite(homework, user); | ||
| 59 | + let submission = HomeworkSubmissionId::composite(homework, user); | ||
| 60 | + let result = HomeworkResult { | ||
| 61 | + id: id.clone(), | ||
| 62 | + homework: homework.clone(), | ||
| 63 | + user: user.clone(), | ||
| 64 | + status, | ||
| 65 | + mark, | ||
| 66 | + graded_by: graded_by.clone(), | ||
| 67 | + created_at: Timestamp::now(), | ||
| 68 | + }; | ||
| 69 | + // Whether the pair was already graded is read one statement ahead of | ||
| 70 | + // the write, inside the same transaction — it is what keeps a regrade | ||
| 71 | + // from crediting the grader a second time. No mark counter here: a | ||
| 72 | + // homework mark is optional and most grades are status-only, so | ||
| 73 | + // `high_mark` is an exam-only family. | ||
| 74 | + // | ||
| 75 | + // The first three statements are the parent gate, the twin of | ||
| 76 | + // [`crate::db::homework_submission::upsert`]'s | ||
| 77 | + // and written the same way on purpose: the id is deterministic, so a | ||
| 78 | + // grade landing inside a homework (or course) delete's window does not | ||
| 79 | + // fail — it *re-creates* a result row under a homework that is gone, | ||
| 80 | + // readable ever after at `GET /homework/{id}/result` (no existence check | ||
| 81 | + // there) with a `marks_given_total` no ungrade can reach, because every | ||
| 82 | + // route to the grade goes through the homework. Reading the homework | ||
| 83 | + // first — which the web layer does, under the lease — cannot close that: | ||
| 84 | + // the store conflict-checks write sets, not read sets. So the gate | ||
| 85 | + // *moves* a value on the homework row (`due_at` up by one and straight | ||
| 86 | + // back to the captured value, leaving the row byte-identical) and the | ||
| 87 | + // cascade's delete of that same row is what refuses it. `homework` owns | ||
| 88 | + // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it | ||
| 89 | + // already has; do not invent a second spelling. | ||
| 90 | + // | ||
| 91 | + // Not [`crate::db::cap::touch_and_create`], which is the same shape | ||
| 92 | + // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), | ||
| 93 | + // and the freeze stamp and the grader's counter have to ride the same | ||
| 94 | + // transaction, which that helper has no room for. | ||
| 95 | + // | ||
| 96 | + // Sound to re-send, which is what the gate needed first — a `THROW` | ||
| 97 | + // inside a plain `db.query` would have turned every lost round into a | ||
| 98 | + // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already | ||
| 99 | + // exists", and the `UPSERT`'s id is bijective with the (homework, user) | ||
| 100 | + // pair the table keys, on a table whose only index is non-unique | ||
| 101 | + // (`homework_result_homework`), so its index entry can only ever point | ||
| 102 | + // at the row the id already names: it resolves onto that row instead of | ||
| 103 | + // colliding with it. A lost round wrote nothing. | ||
| 104 | + let (mut saved, mut errors) = transaction_with_retry( | ||
| 105 | + db, | ||
| 106 | + &format!( | ||
| 107 | + "BEGIN TRANSACTION; | ||
| 108 | + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | ||
| 109 | + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | ||
| 110 | + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | ||
| 111 | + UPDATE $hw SET due_at = $was_due; | ||
| 112 | + LET $before = (SELECT VALUE id FROM ONLY $id); | ||
| 113 | + LET $after = (UPSERT $id CONTENT $row RETURN AFTER); | ||
| 114 | + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ | ||
| 115 | + WHERE {SUBMISSION_OPEN_GUARD}; | ||
| 116 | + IF $before = NONE {{ | ||
| 117 | + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | ||
| 118 | + ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 | ||
| 119 | + }}; | ||
| 120 | + RETURN $after; | ||
| 121 | + COMMIT TRANSACTION;" | ||
| 122 | + ), | ||
| 123 | + &[ | ||
| 124 | + ("hw".into(), homework.record().into_value()), | ||
| 125 | + ("id".into(), id.record().into_value()), | ||
| 126 | + ("sub".into(), submission.record().into_value()), | ||
| 127 | + ("grader".into(), graded_by.record().into_value()), | ||
| 128 | + ("row".into(), result.into_value()), | ||
| 129 | + ], | ||
| 130 | + &["no_homework"], | ||
| 131 | + ) | ||
| 132 | + .await?; | ||
| 133 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 134 | + // executed" — only the THROW's own slot names the reason. | ||
| 135 | + if errors | ||
| 136 | + .values() | ||
| 137 | + .any(|error| error.to_string().contains("no_homework")) | ||
| 138 | + { | ||
| 139 | + return Err(AppError::NotFound); | ||
| 140 | + } | ||
| 141 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 142 | + return Err(error.into()); | ||
| 143 | + } | ||
| 144 | + // The trailing `RETURN` is always the last statement before `COMMIT`, | ||
| 145 | + // so its slot follows the statement count instead of a hand-kept | ||
| 146 | + // number — which the gate above would otherwise have shifted, silently | ||
| 147 | + // handing back something else. | ||
| 148 | + let slot = saved.num_statements().saturating_sub(2); | ||
| 149 | + saved | ||
| 150 | + .take::<Vec<HomeworkResult>>(slot)? | ||
| 151 | + .into_iter() | ||
| 152 | + .next() | ||
| 153 | + .ok_or_else(|| AppError::Internal("failed to record homework result".into())) | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// `user`'s grade for `homework`, if graded. | ||
| 157 | +pub async fn read_for( | ||
| 158 | + db: &Database, | ||
| 159 | + homework: &HomeworkId, | ||
| 160 | + user: &UserId, | ||
| 161 | +) -> Result<Option<HomeworkResult>, AppError> { | ||
| 162 | + Ok(db | ||
| 163 | + .select(HomeworkResultId::composite(homework, user).record()) | ||
| 164 | + .await?) | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +/// Every grade for `homework` — the roster joins these onto the submissions. | ||
| 168 | +pub async fn list_for_homework( | ||
| 169 | + db: &Database, | ||
| 170 | + homework: &HomeworkId, | ||
| 171 | +) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 172 | + let mut result = db | ||
| 173 | + .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") | ||
| 174 | + .bind(("hw", homework.record())) | ||
| 175 | + .await? | ||
| 176 | + .check()?; | ||
| 177 | + Ok(result.take::<Vec<HomeworkResult>>(0)?) | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +/// `user`'s homework grades across one course — the raw rows behind the | ||
| 181 | +/// per-course block of a homework report. Mirrors | ||
| 182 | +/// `ExamResult::list_for_user_in_course`. | ||
| 183 | +pub async fn list_for_user_in_course( | ||
| 184 | + db: &Database, | ||
| 185 | + course: &CourseId, | ||
| 186 | + user: &UserId, | ||
| 187 | +) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 188 | + let mut result = db | ||
| 189 | + .query( | ||
| 190 | + "SELECT * FROM homework_result WHERE user = $usr | ||
| 191 | + AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) | ||
| 192 | + ORDER BY id DESC", | ||
| 193 | + ) | ||
| 194 | + .bind(("usr", user.record())) | ||
| 195 | + .bind(("course", course.record())) | ||
| 196 | + .await? | ||
| 197 | + .check()?; | ||
| 198 | + Ok(result.take::<Vec<HomeworkResult>>(0)?) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// Un-grade (homework, user), returning the removed row (`None` if there | ||
| 202 | +/// was none). Removing the grade unfreezes the student's submission, so the | ||
| 203 | +/// stamp [`grade`] left on it is cleared in the same | ||
| 204 | +/// transaction — scoped to *this* grade's id, so it can never wipe a stamp a | ||
| 205 | +/// concurrent re-grade has just written. | ||
| 206 | +/// | ||
| 207 | +/// The grader's `marks_given_total` comes back with it, in that same | ||
| 208 | +/// transaction and only when a row was really deleted. [`grade`] | ||
| 209 | +/// credits on the branch that finds no row, and a deleted row *is* no row: | ||
| 210 | +/// left standing, ungrade-then-regrade credited a second time off one | ||
| 211 | +/// stored grade, and looped it minted a badge with no exam, no mark and no | ||
| 212 | +/// submission behind it — permanently, since an award is never revoked. | ||
| 213 | +/// Given back to the *removed row's own* grader, not the caller: a manager | ||
| 214 | +/// may un-grade what a teacher graded, and the credit is the teacher's. | ||
| 215 | +/// | ||
| 216 | +/// Sound to re-send while the store answers "conflict, retry" — this is the | ||
| 217 | +/// upgrade `grade` still wants, taken here because the counter above is what | ||
| 218 | +/// makes it necessary: the grader's row is written by exam grading too, so | ||
| 219 | +/// the delete now contends with another domain, and only `DELETE`/`UPDATE` | ||
| 220 | +/// are in the batch, none of which can legitimately answer "already exists". | ||
| 221 | +pub async fn remove( | ||
| 222 | + db: &Database, | ||
| 223 | + homework: &HomeworkId, | ||
| 224 | + user: &UserId, | ||
| 225 | +) -> Result<Option<HomeworkResult>, AppError> { | ||
| 226 | + let id = HomeworkResultId::composite(homework, user); | ||
| 227 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 228 | + db, | ||
| 229 | + &format!( | ||
| 230 | + "BEGIN TRANSACTION; | ||
| 231 | + LET $gone = (DELETE $id RETURN BEFORE); | ||
| 232 | + UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ | ||
| 233 | + WHERE {SUBMISSION_GRADED_FIELD} = $id; | ||
| 234 | + IF array::len($gone) > 0 {{ | ||
| 235 | + LET $grader = $gone[0].graded_by; | ||
| 236 | + UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | ||
| 237 | + math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) | ||
| 238 | + }}; | ||
| 239 | + RETURN $gone; | ||
| 240 | + COMMIT TRANSACTION;" | ||
| 241 | + ), | ||
| 242 | + &[ | ||
| 243 | + ("id".into(), id.record().into_value()), | ||
| 244 | + ( | ||
| 245 | + "sub".into(), | ||
| 246 | + HomeworkSubmissionId::composite(homework, user) | ||
| 247 | + .record() | ||
| 248 | + .into_value(), | ||
| 249 | + ), | ||
| 250 | + ], | ||
| 251 | + &[], | ||
| 252 | + ) | ||
| 253 | + .await?; | ||
| 254 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 255 | + return Err(error.into()); | ||
| 256 | + } | ||
| 257 | + // The trailing `RETURN` is always the last statement before `COMMIT`, so | ||
| 258 | + // its slot follows the statement count — the hand-kept "slot 1" this | ||
| 259 | + // replaces was one added statement away from handing back the unstamp. | ||
| 260 | + let slot = result.num_statements().saturating_sub(2); | ||
| 261 | + Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next()) | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +#[cfg(test)] | ||
| 265 | +mod tests { | ||
| 266 | + use super::*; | ||
| 267 | + | ||
| 268 | + /// A real homework row (with the course and subject it needs): the grade now | ||
| 269 | + /// carries a parent gate, so a minted id nothing wrote is a `404` here, the | ||
| 270 | + /// same way it already is for a submission. | ||
| 271 | + async fn a_homework(db: &Database) -> HomeworkId { | ||
| 272 | + use crate::db::homework; | ||
| 273 | + use crate::domain::homework::HomeworkTitle; | ||
| 274 | + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 275 | + | ||
| 276 | + let course = crate::db::course::a_test_course(db).await; | ||
| 277 | + let subject = Subject::create( | ||
| 278 | + &course, | ||
| 279 | + SubjectName::try_new("topic").unwrap(), | ||
| 280 | + SubjectDescription::try_new("").unwrap(), | ||
| 281 | + db, | ||
| 282 | + ) | ||
| 283 | + .await | ||
| 284 | + .unwrap(); | ||
| 285 | + homework::create( | ||
| 286 | + db, | ||
| 287 | + &course, | ||
| 288 | + subject.get_id(), | ||
| 289 | + HomeworkTitle::try_new("essay").unwrap(), | ||
| 290 | + None, | ||
| 291 | + Timestamp::from_millis(1), | ||
| 292 | + None, | ||
| 293 | + &UserId::from_key("teacher"), | ||
| 294 | + ) | ||
| 295 | + .await | ||
| 296 | + .unwrap() | ||
| 297 | + .get_id() | ||
| 298 | + .clone() | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + #[tokio::test] | ||
| 302 | + async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { | ||
| 303 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 304 | + let homework = a_homework(&db).await; | ||
| 305 | + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 306 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 307 | + | ||
| 308 | + let first = grade( | ||
| 309 | + &db, | ||
| 310 | + &homework, | ||
| 311 | + &user, | ||
| 312 | + HomeworkStatus::try_new("incomplete").unwrap(), | ||
| 313 | + None, | ||
| 314 | + &teacher, | ||
| 315 | + ) | ||
| 316 | + .await | ||
| 317 | + .unwrap(); | ||
| 318 | + // A regrade lands on the same row (composite id), overwriting the grade. | ||
| 319 | + let second = grade( | ||
| 320 | + &db, | ||
| 321 | + &homework, | ||
| 322 | + &user, | ||
| 323 | + HomeworkStatus::try_new("done").unwrap(), | ||
| 324 | + Some(Mark::try_new(80).unwrap()), | ||
| 325 | + &teacher, | ||
| 326 | + ) | ||
| 327 | + .await | ||
| 328 | + .unwrap(); | ||
| 329 | + assert_eq!(first.get_id(), second.get_id()); | ||
| 330 | + assert_eq!(second.get_status().as_str(), "done"); | ||
| 331 | + assert_eq!(second.get_mark().unwrap().as_i64(), 80); | ||
| 332 | + assert_eq!(list_for_homework(&db, &homework).await.unwrap().len(), 1); | ||
| 333 | + | ||
| 334 | + assert!(read_for(&db, &homework, &user).await.unwrap().is_some()); | ||
| 335 | + assert!(remove(&db, &homework, &user).await.unwrap().is_some()); | ||
| 336 | + assert!(read_for(&db, &homework, &user).await.unwrap().is_none()); | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + /// The grader is credited once per graded pair: a regrade lands on the same | ||
| 340 | + /// row, so it is not a mark given twice. The student's counters are not | ||
| 341 | + /// touched at all — a homework grade is not a homework submission. | ||
| 342 | + #[tokio::test] | ||
| 343 | + async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { | ||
| 344 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 345 | + let homework = a_homework(&db).await; | ||
| 346 | + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 347 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 348 | + // `UPDATE` writes nothing to a user row that does not exist. | ||
| 349 | + db.query("CREATE $usr SET username = 't', password_hash = 'x'") | ||
| 350 | + .bind(("usr", teacher.record())) | ||
| 351 | + .await | ||
| 352 | + .unwrap() | ||
| 353 | + .check() | ||
| 354 | + .unwrap(); | ||
| 355 | + | ||
| 356 | + for status in ["incomplete", "done"] { | ||
| 357 | + grade( | ||
| 358 | + &db, | ||
| 359 | + &homework, | ||
| 360 | + &user, | ||
| 361 | + HomeworkStatus::try_new(status).unwrap(), | ||
| 362 | + None, | ||
| 363 | + &teacher, | ||
| 364 | + ) | ||
| 365 | + .await | ||
| 366 | + .unwrap(); | ||
| 367 | + } | ||
| 368 | + assert_eq!( | ||
| 369 | + marks_given(&teacher, &db).await, | ||
| 370 | + 1, | ||
| 371 | + "one graded pair, one mark given" | ||
| 372 | + ); | ||
| 373 | + } | ||
| 374 | + | ||
| 375 | + /// Un-grading gives the credit back, so grade → ungrade → regrade nets to | ||
| 376 | + /// one however often it is run. Crediting the grade without refunding the | ||
| 377 | + /// delete was the cheapest counter farm in the codebase — two requests per | ||
| 378 | + /// mark given, with no exam, no mark and no submission behind them. | ||
| 379 | + #[tokio::test] | ||
| 380 | + async fn ungrading_gives_the_grader_credit_back() { | ||
| 381 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 382 | + let homework = a_homework(&db).await; | ||
| 383 | + let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 384 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 385 | + db.query("CREATE $usr SET username = 't', password_hash = 'x'") | ||
| 386 | + .bind(("usr", teacher.record())) | ||
| 387 | + .await | ||
| 388 | + .unwrap() | ||
| 389 | + .check() | ||
| 390 | + .unwrap(); | ||
| 391 | + | ||
| 392 | + for _ in 0..3 { | ||
| 393 | + grade( | ||
| 394 | + &db, | ||
| 395 | + &homework, | ||
| 396 | + &user, | ||
| 397 | + HomeworkStatus::try_new("missing").unwrap(), | ||
| 398 | + None, | ||
| 399 | + &teacher, | ||
| 400 | + ) | ||
| 401 | + .await | ||
| 402 | + .unwrap(); | ||
| 403 | + assert_eq!(marks_given(&teacher, &db).await, 1); | ||
| 404 | + assert!( | ||
| 405 | + remove(&db, &homework, &user).await.unwrap().is_some(), | ||
| 406 | + "the grade was there" | ||
| 407 | + ); | ||
| 408 | + assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one"); | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + // Nothing to remove is nothing to give back — the floor holds. | ||
| 412 | + assert!(remove(&db, &homework, &user).await.unwrap().is_none()); | ||
| 413 | + assert_eq!(marks_given(&teacher, &db).await, 0); | ||
| 414 | + } | ||
| 415 | + /// The grader's badge counter, re-read out of the store. | ||
| 416 | + async fn marks_given(user: &UserId, db: &Database) -> i64 { | ||
| 417 | + let mut result = db | ||
| 418 | + .query(format!( | ||
| 419 | + "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" | ||
| 420 | + )) | ||
| 421 | + .bind(("usr", user.record())) | ||
| 422 | + .await | ||
| 423 | + .unwrap() | ||
| 424 | + .check() | ||
| 425 | + .unwrap(); | ||
| 426 | + result | ||
| 427 | + .take::<Vec<i64>>(0) | ||
| 428 | + .unwrap() | ||
| 429 | + .into_iter() | ||
| 430 | + .next() | ||
| 431 | + .unwrap_or(0) | ||
| 432 | + } | ||
| 433 | +} | ||
src/db/homework_submission.rsadded+720 -0
| @@ -0,0 +1,720 @@ | |||
| 1 | +//! The `homework_submission` table: one row per (homework, user) — the | ||
| 2 | +//! freeze-guarded UPSERT with its badge counters, the touch, the reads the | ||
| 3 | +//! roster and report join on, and the counter-returning delete. The | ||
| 4 | +//! submit/withdraw workflows live in | ||
| 5 | +//! [`crate::service::homework_submission`]; the validated text type in | ||
| 6 | +//! [`crate::domain::homework_submission`]. | ||
| 7 | + | ||
| 8 | +use crate::constant::{ | ||
| 9 | + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, | ||
| 10 | + SUBMISSION_OPEN_GUARD, | ||
| 11 | +}; | ||
| 12 | +use crate::database::{Database, transaction_with_retry}; | ||
| 13 | +use crate::domain::homework::Homework; | ||
| 14 | +use crate::domain::homework_submission::{ | ||
| 15 | + HomeworkSubmission, HomeworkSubmissionId, SubmissionText, | ||
| 16 | +}; | ||
| 17 | +use crate::domain::timestamp::Timestamp; | ||
| 18 | +use crate::domain::user::UserId; | ||
| 19 | +use crate::error::AppError; | ||
| 20 | +use surrealdb::types::SurrealValue; | ||
| 21 | + | ||
| 22 | +/// Create or re-stamp `user`'s submission to `homework`, unless a grade has | ||
| 23 | +/// frozen it — `None` means frozen, and the caller answers 409. `updated_at` | ||
| 24 | +/// moves to now every time; `submitted_at` (readonly, the first-submit stamp) | ||
| 25 | +/// is kept on an existing row and set only on a fresh one. | ||
| 26 | +/// | ||
| 27 | +/// Hand-written rather than `.content()` on purpose: `.content()` re-sends | ||
| 28 | +/// the whole row, so it would carry a `submitted_at`, and any value differing | ||
| 29 | +/// from the stored one trips the readonly guard. The | ||
| 30 | +/// `submitted_at = submitted_at ?? $now` expression preserves it inside the | ||
| 31 | +/// one UPSERT statement — race-free without a lock, where a read-then-content | ||
| 32 | +/// could let two concurrent first-submits pick different stamps and 500. | ||
| 33 | +/// | ||
| 34 | +/// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded | ||
| 35 | +/// yet" a condition of this very write instead of a read a concurrent grade | ||
| 36 | +/// can land behind. An absent row satisfies it (the stamp is `NONE` there | ||
| 37 | +/// too), so a first submit still creates. | ||
| 38 | +/// | ||
| 39 | +/// The badge counters on the student's user row move in this very | ||
| 40 | +/// transaction, and the order is load-bearing: the increment sits *after* | ||
| 41 | +/// the UPSERT and is conditional on it having matched a row, because a | ||
| 42 | +/// frozen row makes that `WHERE` match nothing **silently** (unlike | ||
| 43 | +/// [`crate::db::homework_result::grade`], which `THROW`s) — put | ||
| 44 | +/// first, it would count a submission the freeze refused. `$before = NONE` | ||
| 45 | +/// keeps it to a genuine first create, so an edit moves neither counter, | ||
| 46 | +/// which is what makes the live count mean the same thing the one-time | ||
| 47 | +/// backfill seeded (one per row; on time judged against `due_at`, equal | ||
| 48 | +/// counting as on time). | ||
| 49 | +/// | ||
| 50 | +/// `counted_on_time` is stamped on the row from the *same* `$on_time` | ||
| 51 | +/// expression the increment adds, in the same statement block: the deadline | ||
| 52 | +/// is mutable, so a withdrawal that re-judged it against the live `due_at` | ||
| 53 | +/// gave back something other than what was taken. Writing the verdict beside | ||
| 54 | +/// the counter is what keeps the two from ever disagreeing — read back by | ||
| 55 | +/// [`delete`], never re-derived. | ||
| 56 | +/// | ||
| 57 | +/// That deadline is `$was_due`, the one the gate below already read *inside | ||
| 58 | +/// this transaction* — never the caller's [`Homework`] snapshot, which was | ||
| 59 | +/// read before the lease and is exactly one `PATCH due_at` old in the | ||
| 60 | +/// "teacher extends the deadline at 23:59 while the class submits" moment. | ||
| 61 | +/// Judging on the snapshot stored a verdict the web layer's own `late` flag | ||
| 62 | +/// (`updated_at > due_at`, re-derived live on every read) then contradicted | ||
| 63 | +/// forever, in both directions. An in-process lock cannot fix this — it | ||
| 64 | +/// orders two handlers, not two store transactions — so the comparison has | ||
| 65 | +/// to live where the write does. The whole entity is still taken (both | ||
| 66 | +/// callers hold the row, and the id comes off it); its `due_at` must not be. | ||
| 67 | +/// | ||
| 68 | +/// The first three statements are the parent gate, and they are why this | ||
| 69 | +/// write cannot outlive its homework: the id is deterministic, so nothing | ||
| 70 | +/// else here would fail against a homework a cascade already removed — it | ||
| 71 | +/// would simply re-create the row, badge counters and all, unreachable ever | ||
| 72 | +/// after (every route to a submission goes through its homework). A *read* | ||
| 73 | +/// of the homework does not close that, on either side of the call: the | ||
| 74 | +/// store does no read-set conflict detection, so a delete committing | ||
| 75 | +/// alongside is invisible to it. The gate therefore *moves* a value on the | ||
| 76 | +/// homework row — `due_at` up by one and straight back to the captured | ||
| 77 | +/// value, so the row is byte-identical afterwards — because only a write | ||
| 78 | +/// collides, and `SET x = x` is elided and never reaches the write set. It | ||
| 79 | +/// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. | ||
| 80 | +/// `Err(NotFound)` means the homework is gone, which is the 404 the web | ||
| 81 | +/// layer's own lookup would have answered. | ||
| 82 | +pub async fn upsert( | ||
| 83 | + db: &Database, | ||
| 84 | + homework: &Homework, | ||
| 85 | + user: &UserId, | ||
| 86 | + text: Option<SubmissionText>, | ||
| 87 | +) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 88 | + let id = HomeworkSubmissionId::composite(homework.get_id(), user); | ||
| 89 | + let now = Timestamp::now(); | ||
| 90 | + let text = text.map(|text| text.as_str().to_string()); | ||
| 91 | + // Sound to re-send: the UPSERT is on a deterministic id on a table with | ||
| 92 | + // no unique index, so it can never legitimately answer "already exists", | ||
| 93 | + // and the counter UPDATEs never can either. | ||
| 94 | + let (mut saved, mut errors) = transaction_with_retry( | ||
| 95 | + db, | ||
| 96 | + &format!( | ||
| 97 | + "BEGIN TRANSACTION; | ||
| 98 | + LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | ||
| 99 | + LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | ||
| 100 | + IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | ||
| 101 | + UPDATE $hw SET due_at = $was_due; | ||
| 102 | + LET $before = (SELECT VALUE id FROM ONLY $id); | ||
| 103 | + LET $on_time = $now <= $was_due; | ||
| 104 | + LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, | ||
| 105 | + updated_at = $now, submitted_at = submitted_at ?? $now | ||
| 106 | + WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); | ||
| 107 | + IF $before = NONE AND array::len($after) > 0 {{ | ||
| 108 | + UPDATE $id SET counted_on_time = $on_time; | ||
| 109 | + UPDATE $usr SET | ||
| 110 | + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, | ||
| 111 | + {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) | ||
| 112 | + + IF $on_time {{ 1 }} ELSE {{ 0 }} | ||
| 113 | + }}; | ||
| 114 | + RETURN $after; | ||
| 115 | + COMMIT TRANSACTION;" | ||
| 116 | + ), | ||
| 117 | + &[ | ||
| 118 | + ("id".into(), id.record().into_value()), | ||
| 119 | + ("hw".into(), homework.get_id().record().into_value()), | ||
| 120 | + ("usr".into(), user.record().into_value()), | ||
| 121 | + ("text".into(), text.into_value()), | ||
| 122 | + ("now".into(), now.into_value()), | ||
| 123 | + ], | ||
| 124 | + &["no_homework"], | ||
| 125 | + ) | ||
| 126 | + .await?; | ||
| 127 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 128 | + // executed" — only the THROW's own slot names the reason. | ||
| 129 | + if errors | ||
| 130 | + .values() | ||
| 131 | + .any(|error| error.to_string().contains("no_homework")) | ||
| 132 | + { | ||
| 133 | + return Err(AppError::NotFound); | ||
| 134 | + } | ||
| 135 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 136 | + return Err(error.into()); | ||
| 137 | + } | ||
| 138 | + // The trailing `RETURN` is always the last statement before `COMMIT`, so | ||
| 139 | + // its slot follows the statement count rather than a hand-kept number. | ||
| 140 | + // It returns the whole array, never `$after[0]`: a refused write makes | ||
| 141 | + // that `NONE`, which fails to deserialize ("expected object, got none") | ||
| 142 | + // instead of reading as the "frozen" the caller answers 409 to. | ||
| 143 | + let slot = saved.num_statements().saturating_sub(2); | ||
| 144 | + Ok(saved | ||
| 145 | + .take::<Vec<HomeworkSubmission>>(slot)? | ||
| 146 | + .into_iter() | ||
| 147 | + .next()) | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +/// Re-stamp a submission's `updated_at` to now, leaving its text and files | ||
| 151 | +/// alone. A file add or delete modifies the submission as a whole, so its | ||
| 152 | +/// "last touched" clock — which drives the computed late flag — must move | ||
| 153 | +/// even though the text row is unchanged. Free-standing because the file | ||
| 154 | +/// paths hold the composite id, not always the row. A targeted single-field | ||
| 155 | +/// UPDATE, so the `READONLY` `submitted_at` is never re-sent (a `.content()` | ||
| 156 | +/// would trip its guard). Returns the re-stamped row, or a 404 if it has | ||
| 157 | +/// since vanished. | ||
| 158 | +pub async fn touch( | ||
| 159 | + db: &Database, | ||
| 160 | + id: &HomeworkSubmissionId, | ||
| 161 | +) -> Result<HomeworkSubmission, AppError> { | ||
| 162 | + let now = Timestamp::now(); | ||
| 163 | + let mut result = db | ||
| 164 | + .query("UPDATE $id SET updated_at = $now RETURN AFTER") | ||
| 165 | + .bind(("id", id.record())) | ||
| 166 | + .bind(("now", now)) | ||
| 167 | + .await? | ||
| 168 | + .check()?; | ||
| 169 | + result | ||
| 170 | + .take::<Vec<HomeworkSubmission>>(0)? | ||
| 171 | + .into_iter() | ||
| 172 | + .next() | ||
| 173 | + .ok_or(AppError::NotFound) | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/// Whether a grade has frozen this submission. Only ever read to tell two | ||
| 177 | +/// refusals apart *after* a conditional write has already refused one — the | ||
| 178 | +/// stamp on the row, never this read, is what decides. | ||
| 179 | +pub async fn is_graded(db: &Database, id: &HomeworkSubmissionId) -> Result<bool, AppError> { | ||
| 180 | + let mut result = db | ||
| 181 | + .query(format!( | ||
| 182 | + "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" | ||
| 183 | + )) | ||
| 184 | + .bind(("id", id.record())) | ||
| 185 | + .await? | ||
| 186 | + .check()?; | ||
| 187 | + Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty()) | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// `user`'s submission to `homework`, if they have one. | ||
| 191 | +pub async fn read_for( | ||
| 192 | + db: &Database, | ||
| 193 | + homework: &crate::domain::homework::HomeworkId, | ||
| 194 | + user: &UserId, | ||
| 195 | +) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 196 | + Ok(db | ||
| 197 | + .select(HomeworkSubmissionId::composite(homework, user).record()) | ||
| 198 | + .await?) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +/// Every submission to `homework`, in student (composite-id) order — the | ||
| 202 | +/// roster's raw rows. | ||
| 203 | +pub async fn list_for_homework( | ||
| 204 | + db: &Database, | ||
| 205 | + homework: &crate::domain::homework::HomeworkId, | ||
| 206 | +) -> Result<Vec<HomeworkSubmission>, AppError> { | ||
| 207 | + let mut result = db | ||
| 208 | + .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") | ||
| 209 | + .bind(("hw", homework.record())) | ||
| 210 | + .await? | ||
| 211 | + .check()?; | ||
| 212 | + Ok(result.take::<Vec<HomeworkSubmission>>(0)?) | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Delete this submission and its files in one transaction — so a crash | ||
| 216 | +/// can't leave a file pointing at a vanished submission. The file *blobs* | ||
| 217 | +/// are the web layer's to unlink: it lists them | ||
| 218 | +/// ([`crate::db::homework_file::list_for_submission`]) | ||
| 219 | +/// before calling this. `None` means a grade froze the row (the caller | ||
| 220 | +/// answers 409): the submission's own delete carries | ||
| 221 | +/// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having | ||
| 222 | +/// bitten, so a refused delete leaves the children standing too. | ||
| 223 | +/// | ||
| 224 | +/// The one place either badge counter comes back down, and deliberately the | ||
| 225 | +/// only one: this route is student-callable on their own row, so without it | ||
| 226 | +/// a student farms "handed in 50 homeworks" by submit/delete/submit on a | ||
| 227 | +/// single homework. A teacher's homework delete and the course cascade | ||
| 228 | +/// leave the counters alone — history a teacher erased is still history the | ||
| 229 | +/// student lived. | ||
| 230 | +/// | ||
| 231 | +/// The on-time half is given back by the verdict [`upsert`] | ||
| 232 | +/// *stored* on the row, never by re-judging the deadline: `due_at` is | ||
| 233 | +/// mutable, so re-deriving read whatever the teacher had moved it to since | ||
| 234 | +/// and gave back something other than what was taken — extend it after a | ||
| 235 | +/// late hand-in and this debited a credit that was never given; pull it back | ||
| 236 | +/// after a punctual one and it debited nothing, leaving `on_time` above | ||
| 237 | +/// `submitted`. A row from before the column exists carries no verdict, and | ||
| 238 | +/// cannot be given one for a credit that already happened, so it falls back | ||
| 239 | +/// to the old cut (`submitted_at`, the readonly stamp the increment judged, | ||
| 240 | +/// against the live deadline); a dangling `homework` link leaves `$due` | ||
| 241 | +/// `NONE` there, which compares false and so counts as late, matching the | ||
| 242 | +/// backfill. Floored at zero: a row that predates the columns has none. | ||
| 243 | +/// | ||
| 244 | +/// Badges already earned are never taken away — [`crate::domain::badge`] is | ||
| 245 | +/// add-only, which is where that permanence lives. | ||
| 246 | +pub async fn delete( | ||
| 247 | + db: &Database, | ||
| 248 | + submission: HomeworkSubmission, | ||
| 249 | +) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 250 | + // Sound to re-send: DELETE and UPDATE can never answer "already exists". | ||
| 251 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 252 | + db, | ||
| 253 | + &format!( | ||
| 254 | + "BEGIN TRANSACTION; | ||
| 255 | + LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); | ||
| 256 | + LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); | ||
| 257 | + IF array::len($gone) > 0 {{ | ||
| 258 | + DELETE homework_file WHERE submission = $sub; | ||
| 259 | + LET $on_time = IF ($gone[0].counted_on_time | ||
| 260 | + ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; | ||
| 261 | + UPDATE $usr SET | ||
| 262 | + {HOMEWORK_SUBMITTED_TOTAL_FIELD} = | ||
| 263 | + math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), | ||
| 264 | + {HOMEWORK_ON_TIME_TOTAL_FIELD} = | ||
| 265 | + math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) | ||
| 266 | + }}; | ||
| 267 | + RETURN $gone; | ||
| 268 | + COMMIT TRANSACTION;" | ||
| 269 | + ), | ||
| 270 | + &[ | ||
| 271 | + ("sub".into(), submission.id.record().into_value()), | ||
| 272 | + ("usr".into(), submission.user.record().into_value()), | ||
| 273 | + ], | ||
| 274 | + &[], | ||
| 275 | + ) | ||
| 276 | + .await?; | ||
| 277 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 278 | + return Err(error.into()); | ||
| 279 | + } | ||
| 280 | + // The trailing `RETURN` is always the last statement before `COMMIT`. | ||
| 281 | + let slot = result.num_statements().saturating_sub(2); | ||
| 282 | + Ok(result | ||
| 283 | + .take::<Vec<HomeworkSubmission>>(slot)? | ||
| 284 | + .into_iter() | ||
| 285 | + .next()) | ||
| 286 | +} | ||
| 287 | + | ||
| 288 | +#[cfg(test)] | ||
| 289 | +mod tests { | ||
| 290 | + use super::*; | ||
| 291 | + use crate::constant::{ | ||
| 292 | + HOMEWORK_ON_TIME_TOTAL_FIELD as ON_TIME, HOMEWORK_SUBMITTED_TOTAL_FIELD as SUBMITTED, | ||
| 293 | + }; | ||
| 294 | + use crate::db::homework as homework_db; | ||
| 295 | + use crate::domain::homework::HomeworkTitle; | ||
| 296 | + use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 297 | + | ||
| 298 | + /// A real homework row (and the subject it must reference) due at `due_at` — | ||
| 299 | + /// `upsert` now reads the deadline off the entity, so the tests need one. | ||
| 300 | + async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { | ||
| 301 | + let course = crate::db::course::a_test_course(db).await; | ||
| 302 | + let subject = Subject::create( | ||
| 303 | + &course, | ||
| 304 | + SubjectName::try_new("topic").unwrap(), | ||
| 305 | + SubjectDescription::try_new("").unwrap(), | ||
| 306 | + db, | ||
| 307 | + ) | ||
| 308 | + .await | ||
| 309 | + .unwrap(); | ||
| 310 | + homework_db::create( | ||
| 311 | + db, | ||
| 312 | + &course, | ||
| 313 | + subject.get_id(), | ||
| 314 | + HomeworkTitle::try_new("essay").unwrap(), | ||
| 315 | + None, | ||
| 316 | + due_at, | ||
| 317 | + None, | ||
| 318 | + &UserId::from_key("teacher"), | ||
| 319 | + ) | ||
| 320 | + .await | ||
| 321 | + .unwrap() | ||
| 322 | + } | ||
| 323 | + | ||
| 324 | + /// A deadline no test run can reach, so a submission is unambiguously on | ||
| 325 | + /// time; `Timestamp::from_millis(1)` is its late twin. | ||
| 326 | + fn far_future() -> Timestamp { | ||
| 327 | + Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000) | ||
| 328 | + } | ||
| 329 | + | ||
| 330 | + /// A real user row: the counters live on it, and an `UPDATE` has nothing to | ||
| 331 | + /// write to without one. | ||
| 332 | + async fn a_student(username: &str, db: &Database) -> UserId { | ||
| 333 | + let hash = crate::domain::user::Password::try_new("secret1") | ||
| 334 | + .unwrap() | ||
| 335 | + .hash_async() | ||
| 336 | + .await | ||
| 337 | + .unwrap(); | ||
| 338 | + crate::db::user::create( | ||
| 339 | + db, | ||
| 340 | + crate::domain::user::Username::try_new(username).unwrap(), | ||
| 341 | + hash, | ||
| 342 | + ) | ||
| 343 | + .await | ||
| 344 | + .unwrap() | ||
| 345 | + .get_id() | ||
| 346 | + .clone() | ||
| 347 | + } | ||
| 348 | + | ||
| 349 | + /// Move the stored deadline the way a teacher's PATCH does, leaving the | ||
| 350 | + /// caller's `homework` snapshot untouched — the stale-snapshot shape the | ||
| 351 | + /// handler produces when a `PATCH due_at` commits between its gate read and | ||
| 352 | + /// its write. | ||
| 353 | + async fn deadline_moves_to(homework: &Homework, due_at: Timestamp, db: &Database) { | ||
| 354 | + let stored = homework_db::read(db, homework.get_id()) | ||
| 355 | + .await | ||
| 356 | + .unwrap() | ||
| 357 | + .expect("the homework exists"); | ||
| 358 | + homework_db::update(db, stored, None, None, None, Some(due_at), None) | ||
| 359 | + .await | ||
| 360 | + .unwrap(); | ||
| 361 | + } | ||
| 362 | + | ||
| 363 | + /// The verdict `upsert` stored on the row — what `delete` debits off. | ||
| 364 | + /// `None` is a row from before the column existed. | ||
| 365 | + async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> { | ||
| 366 | + let mut result = db | ||
| 367 | + .query("SELECT VALUE counted_on_time FROM $sub") | ||
| 368 | + .bind(("sub", id.record())) | ||
| 369 | + .await | ||
| 370 | + .unwrap() | ||
| 371 | + .check() | ||
| 372 | + .unwrap(); | ||
| 373 | + result | ||
| 374 | + .take::<Vec<Option<bool>>>(0) | ||
| 375 | + .unwrap() | ||
| 376 | + .into_iter() | ||
| 377 | + .flatten() | ||
| 378 | + .next() | ||
| 379 | + } | ||
| 380 | + | ||
| 381 | + /// The web layer's computed flag, exactly as `SubmissionResponse::new` | ||
| 382 | + /// derives it (`src/web/homework.rs`): `updated_at` against the *live* | ||
| 383 | + /// deadline, re-read here because that is what a later GET reads. | ||
| 384 | + async fn late_flag(submission: &HomeworkSubmission, db: &Database) -> bool { | ||
| 385 | + let live = homework_db::read(db, submission.get_homework()) | ||
| 386 | + .await | ||
| 387 | + .unwrap() | ||
| 388 | + .expect("the homework exists"); | ||
| 389 | + submission.get_updated_at() > live.get_due_at() | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + /// The two badge counters on a user row, absent counting as zero. | ||
| 393 | + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { | ||
| 394 | + let mut result = db | ||
| 395 | + .query(format!( | ||
| 396 | + "SELECT VALUE [({SUBMITTED} ?? 0), ({ON_TIME} ?? 0)] FROM $usr" | ||
| 397 | + )) | ||
| 398 | + .bind(("usr", user.record())) | ||
| 399 | + .await | ||
| 400 | + .unwrap() | ||
| 401 | + .check() | ||
| 402 | + .unwrap(); | ||
| 403 | + let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | ||
| 404 | + let row = rows.first().cloned().unwrap_or_default(); | ||
| 405 | + ( | ||
| 406 | + row.first().copied().unwrap_or(0), | ||
| 407 | + row.get(1).copied().unwrap_or(0), | ||
| 408 | + ) | ||
| 409 | + } | ||
| 410 | + | ||
| 411 | + #[tokio::test] | ||
| 412 | + async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { | ||
| 413 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 414 | + let homework = a_homework(far_future(), &db).await; | ||
| 415 | + let user = a_student("ogrenci", &db).await; | ||
| 416 | + | ||
| 417 | + let first = upsert( | ||
| 418 | + &db, | ||
| 419 | + &homework, | ||
| 420 | + &user, | ||
| 421 | + Some(SubmissionText::try_new("draft").unwrap()), | ||
| 422 | + ) | ||
| 423 | + .await | ||
| 424 | + .unwrap() | ||
| 425 | + .unwrap(); | ||
| 426 | + // A re-submit lands on the same row: submitted_at (the first hand-in) | ||
| 427 | + // pinned, updated_at moves forward, and the text can be cleared. | ||
| 428 | + let second = upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | ||
| 429 | + // ... and it is one submission, not two: the edit moves no counter. | ||
| 430 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 431 | + assert_eq!(first.get_id(), second.get_id()); | ||
| 432 | + assert_eq!(first.get_submitted_at(), second.get_submitted_at()); | ||
| 433 | + assert!(second.get_updated_at() >= first.get_updated_at()); | ||
| 434 | + assert!(second.get_text().is_none()); | ||
| 435 | + // One row per (homework, user), whatever the re-submit count. | ||
| 436 | + assert_eq!( | ||
| 437 | + list_for_homework(&db, homework.get_id()) | ||
| 438 | + .await | ||
| 439 | + .unwrap() | ||
| 440 | + .len(), | ||
| 441 | + 1 | ||
| 442 | + ); | ||
| 443 | + } | ||
| 444 | + | ||
| 445 | + /// The freeze, as stored state rather than as a race: the grade stamps the | ||
| 446 | + /// submission row, and from then on the submission's own writes fail their | ||
| 447 | + /// condition — no read of `homework_result` involved, which is what makes it | ||
| 448 | + /// hold when the grade lands mid-request. Un-grading clears the stamp | ||
| 449 | + /// and the row is writable again. | ||
| 450 | + /// | ||
| 451 | + /// Bite check: drop `WHERE graded_by_result = NONE` from | ||
| 452 | + /// [`upsert`] and the "version B" upsert below comes | ||
| 453 | + /// back `Some` — the exact swap this guards against. | ||
| 454 | + #[tokio::test] | ||
| 455 | + async fn a_grade_freezes_the_submission_row_itself() { | ||
| 456 | + use crate::db::homework_result; | ||
| 457 | + use crate::domain::homework_result::HomeworkStatus; | ||
| 458 | + | ||
| 459 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 460 | + let homework = a_homework(far_future(), &db).await; | ||
| 461 | + let user = a_student("ogrenci", &db).await; | ||
| 462 | + let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 463 | + let graded = |value| { | ||
| 464 | + let text = SubmissionText::try_new(value).unwrap(); | ||
| 465 | + upsert(&db, &homework, &user, Some(text)) | ||
| 466 | + }; | ||
| 467 | + | ||
| 468 | + let version_a = graded("version A").await.unwrap().unwrap(); | ||
| 469 | + assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); | ||
| 470 | + | ||
| 471 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 472 | + | ||
| 473 | + homework_result::grade( | ||
| 474 | + &db, | ||
| 475 | + homework.get_id(), | ||
| 476 | + &user, | ||
| 477 | + HomeworkStatus::try_new("done").unwrap(), | ||
| 478 | + None, | ||
| 479 | + &teacher, | ||
| 480 | + ) | ||
| 481 | + .await | ||
| 482 | + .unwrap(); | ||
| 483 | + assert!(is_graded(&db, version_a.get_id()).await.unwrap()); | ||
| 484 | + | ||
| 485 | + // The swap the teacher would never see: refused, and the stored text is | ||
| 486 | + // still the version that was graded. | ||
| 487 | + assert!(graded("version B").await.unwrap().is_none()); | ||
| 488 | + assert_eq!( | ||
| 489 | + read_for(&db, homework.get_id(), &user) | ||
| 490 | + .await | ||
| 491 | + .unwrap() | ||
| 492 | + .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), | ||
| 493 | + Some("version A".to_string()) | ||
| 494 | + ); | ||
| 495 | + // The refusal is silent — the UPSERT simply matches nothing — so the | ||
| 496 | + // counters are the only thing that can catch an increment placed in | ||
| 497 | + // front of it: a submission the freeze refused must count for nothing. | ||
| 498 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 499 | + // ... and so is withdrawing it wholesale. | ||
| 500 | + let frozen = read_for(&db, homework.get_id(), &user) | ||
| 501 | + .await | ||
| 502 | + .unwrap() | ||
| 503 | + .unwrap(); | ||
| 504 | + assert!(delete(&db, frozen).await.unwrap().is_none()); | ||
| 505 | + assert!( | ||
| 506 | + read_for(&db, homework.get_id(), &user) | ||
| 507 | + .await | ||
| 508 | + .unwrap() | ||
| 509 | + .is_some() | ||
| 510 | + ); | ||
| 511 | + // A refused delete decrements nothing either. | ||
| 512 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 513 | + | ||
| 514 | + // Un-grading unfreezes it, stamp and all. | ||
| 515 | + homework_result::remove(&db, homework.get_id(), &user) | ||
| 516 | + .await | ||
| 517 | + .unwrap(); | ||
| 518 | + assert!(!is_graded(&db, version_a.get_id()).await.unwrap()); | ||
| 519 | + let reopened = graded("version B").await.unwrap().unwrap(); | ||
| 520 | + assert_eq!( | ||
| 521 | + reopened.get_text().map(SubmissionText::as_str), | ||
| 522 | + Some("version B") | ||
| 523 | + ); | ||
| 524 | + // Still an edit to the row that was already counted, un-freeze or not. | ||
| 525 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 526 | + // The two-stamp lateness rule is untouched by any of it: the first | ||
| 527 | + // hand-in is still the first hand-in. | ||
| 528 | + assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); | ||
| 529 | + assert!(reopened.get_updated_at() >= version_a.get_updated_at()); | ||
| 530 | + } | ||
| 531 | + | ||
| 532 | + #[tokio::test] | ||
| 533 | + async fn touch_moves_updated_at_but_not_submitted_at_or_text() { | ||
| 534 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 535 | + let homework = a_homework(far_future(), &db).await; | ||
| 536 | + let user = a_student("ogrenci", &db).await; | ||
| 537 | + | ||
| 538 | + let original = upsert( | ||
| 539 | + &db, | ||
| 540 | + &homework, | ||
| 541 | + &user, | ||
| 542 | + Some(SubmissionText::try_new("photo answer").unwrap()), | ||
| 543 | + ) | ||
| 544 | + .await | ||
| 545 | + .unwrap() | ||
| 546 | + .unwrap(); | ||
| 547 | + // A file add/delete touches the submission: updated_at moves (never | ||
| 548 | + // backwards), while the first-submit stamp and the text stay put. | ||
| 549 | + let touched = touch(&db, original.get_id()).await.unwrap(); | ||
| 550 | + assert_eq!(touched.get_submitted_at(), original.get_submitted_at()); | ||
| 551 | + assert!(touched.get_updated_at() >= original.get_updated_at()); | ||
| 552 | + assert_eq!( | ||
| 553 | + touched.get_text().map(SubmissionText::as_str), | ||
| 554 | + Some("photo answer") | ||
| 555 | + ); | ||
| 556 | + } | ||
| 557 | + | ||
| 558 | + /// The farm, closed: `delete_submission` is the student's own route, so a | ||
| 559 | + /// counter that only ever went up would let one homework be handed in fifty | ||
| 560 | + /// times. Submit → withdraw → submit is worth exactly one submission. | ||
| 561 | + /// | ||
| 562 | + /// Bite check: drop the `UPDATE $usr` from [`delete`] | ||
| 563 | + /// and the last assertion reads `(2, 2)` — the farm. | ||
| 564 | + #[tokio::test] | ||
| 565 | + async fn submit_delete_submit_is_worth_one_submission() { | ||
| 566 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 567 | + let homework = a_homework(far_future(), &db).await; | ||
| 568 | + let user = a_student("ogrenci", &db).await; | ||
| 569 | + | ||
| 570 | + upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | ||
| 571 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 572 | + | ||
| 573 | + let mine = read_for(&db, homework.get_id(), &user) | ||
| 574 | + .await | ||
| 575 | + .unwrap() | ||
| 576 | + .unwrap(); | ||
| 577 | + delete(&db, mine).await.unwrap().unwrap(); | ||
| 578 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 579 | + // Floored: a second withdrawal (or a row from before the columns | ||
| 580 | + // existed) can never push either counter negative. | ||
| 581 | + assert!( | ||
| 582 | + read_for(&db, homework.get_id(), &user) | ||
| 583 | + .await | ||
| 584 | + .unwrap() | ||
| 585 | + .is_none() | ||
| 586 | + ); | ||
| 587 | + | ||
| 588 | + upsert(&db, &homework, &user, None).await.unwrap().unwrap(); | ||
| 589 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 590 | + } | ||
| 591 | + | ||
| 592 | + /// Lateness is judged against the homework's own deadline at hand-in, the | ||
| 593 | + /// same cut the one-time backfill used, and only the on-time counter sees | ||
| 594 | + /// it: a late hand-in is still a hand-in. Its withdrawal gives back only | ||
| 595 | + /// what it took. | ||
| 596 | + #[tokio::test] | ||
| 597 | + async fn a_late_submission_counts_as_submitted_but_not_on_time() { | ||
| 598 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 599 | + let punctual = a_homework(far_future(), &db).await; | ||
| 600 | + let overdue = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 601 | + let user = a_student("ogrenci", &db).await; | ||
| 602 | + | ||
| 603 | + upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); | ||
| 604 | + upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); | ||
| 605 | + assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 606 | + | ||
| 607 | + // Withdrawing the *late* one takes back only the submission, never the | ||
| 608 | + // on-time credit the punctual one earned — the zero floor would hide a | ||
| 609 | + // wrong subtraction here if the on-time count were sitting at zero. | ||
| 610 | + let late = read_for(&db, overdue.get_id(), &user) | ||
| 611 | + .await | ||
| 612 | + .unwrap() | ||
| 613 | + .unwrap(); | ||
| 614 | + delete(&db, late).await.unwrap().unwrap(); | ||
| 615 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 616 | + | ||
| 617 | + // ... and withdrawing the punctual one gives back exactly that credit. | ||
| 618 | + let kept = read_for(&db, punctual.get_id(), &user) | ||
| 619 | + .await | ||
| 620 | + .unwrap() | ||
| 621 | + .unwrap(); | ||
| 622 | + delete(&db, kept).await.unwrap().unwrap(); | ||
| 623 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 624 | + } | ||
| 625 | + | ||
| 626 | + /// A row from before `counted_on_time` existed carries no verdict — it was | ||
| 627 | + /// credited by a comparison that left no trace, and cannot be given one | ||
| 628 | + /// retroactively. Withdrawing it falls back to that same comparison, so the | ||
| 629 | + /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did. | ||
| 630 | + /// | ||
| 631 | + /// Bite check: an absent verdict read as `false` rather than falling through | ||
| 632 | + /// (`??` binding the wrong side of the `<=`) leaves the last assertion at | ||
| 633 | + /// `(0, 1)` — on time above submitted, the shape the stored verdict exists | ||
| 634 | + /// to prevent. | ||
| 635 | + #[tokio::test] | ||
| 636 | + async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { | ||
| 637 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 638 | + let punctual = a_homework(far_future(), &db).await; | ||
| 639 | + let overdue = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 640 | + let user = a_student("ogrenci", &db).await; | ||
| 641 | + | ||
| 642 | + upsert(&db, &punctual, &user, None).await.unwrap().unwrap(); | ||
| 643 | + upsert(&db, &overdue, &user, None).await.unwrap().unwrap(); | ||
| 644 | + assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 645 | + // Aged into legacy rows: the counters keep the credit, the rows lose the | ||
| 646 | + // verdict — the exact state of every submission on an existing volume. | ||
| 647 | + db.query("UPDATE homework_submission UNSET counted_on_time") | ||
| 648 | + .await | ||
| 649 | + .unwrap() | ||
| 650 | + .check() | ||
| 651 | + .unwrap(); | ||
| 652 | + | ||
| 653 | + let late = read_for(&db, overdue.get_id(), &user) | ||
| 654 | + .await | ||
| 655 | + .unwrap() | ||
| 656 | + .unwrap(); | ||
| 657 | + delete(&db, late).await.unwrap().unwrap(); | ||
| 658 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 659 | + | ||
| 660 | + let kept = read_for(&db, punctual.get_id(), &user) | ||
| 661 | + .await | ||
| 662 | + .unwrap() | ||
| 663 | + .unwrap(); | ||
| 664 | + delete(&db, kept).await.unwrap().unwrap(); | ||
| 665 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 666 | + } | ||
| 667 | + | ||
| 668 | + /// The stale snapshot, both directions: the teacher's `PATCH due_at` commits | ||
| 669 | + /// between the handler's gate read and its write, so the caller's entity | ||
| 670 | + /// carries a deadline the store no longer has. The verdict must follow the | ||
| 671 | + /// *stored* deadline the write itself reads, because the API's `late` flag | ||
| 672 | + /// is re-derived from that same stored value on every later read — a verdict | ||
| 673 | + /// judged on the snapshot disagrees with it permanently, and `delete` then | ||
| 674 | + /// gives back the wrong credit. | ||
| 675 | + /// | ||
| 676 | + /// Bite check: judge `$on_time` against the caller's `$due` instead of | ||
| 677 | + /// `$was_due` and both halves fail — extended reads `(1, 0)` with a stored | ||
| 678 | + /// `false` against a live `late = false`, pulled reads `(1, 1)` with a | ||
| 679 | + /// stored `true` against a live `late = true`. | ||
| 680 | + #[tokio::test] | ||
| 681 | + async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { | ||
| 682 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 683 | + let user = a_student("ogrenci", &db).await; | ||
| 684 | + | ||
| 685 | + // Extended at 23:59: the snapshot says the deadline has passed, the | ||
| 686 | + // store says it has not. A hand-in now is on time. | ||
| 687 | + let extended = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 688 | + deadline_moves_to(&extended, far_future(), &db).await; | ||
| 689 | + let landed = upsert(&db, &extended, &user, None).await.unwrap().unwrap(); | ||
| 690 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 691 | + assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); | ||
| 692 | + assert!(!late_flag(&landed, &db).await); | ||
| 693 | + | ||
| 694 | + // Pulled earlier: the snapshot says there is time left, the store says | ||
| 695 | + // the deadline is gone. The same hand-in is late. | ||
| 696 | + let pulled = a_homework(far_future(), &db).await; | ||
| 697 | + deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; | ||
| 698 | + let missed = upsert(&db, &pulled, &user, None).await.unwrap().unwrap(); | ||
| 699 | + assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 700 | + assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); | ||
| 701 | + assert!(late_flag(&missed, &db).await); | ||
| 702 | + | ||
| 703 | + // The invariant behind both: the stored verdict is the negation of the | ||
| 704 | + // flag the web layer computes for the same submission, never its twin. | ||
| 705 | + for submission in [&landed, &missed] { | ||
| 706 | + assert_eq!( | ||
| 707 | + stored_verdict(submission.get_id(), &db).await, | ||
| 708 | + Some(!late_flag(submission, &db).await), | ||
| 709 | + "stored verdict and the API's late flag must never disagree" | ||
| 710 | + ); | ||
| 711 | + } | ||
| 712 | + | ||
| 713 | + // ... and the withdrawal, which debits off the stamp, gives back exactly | ||
| 714 | + // what each one took. | ||
| 715 | + delete(&db, missed).await.unwrap().unwrap(); | ||
| 716 | + assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 717 | + delete(&db, landed).await.unwrap().unwrap(); | ||
| 718 | + assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 719 | + } | ||
| 720 | +} | ||
src/db/mod.rsmodified+4 -0
| @@ -11,6 +11,10 @@ pub mod exam; | |||
| 11 | pub mod exam_attempt; | 11 | pub mod exam_attempt; |
| 12 | pub mod exam_question; | 12 | pub mod exam_question; |
| 13 | pub mod field_update; | 13 | pub mod field_update; |
| 14 | +pub mod homework; | ||
| 15 | +pub mod homework_file; | ||
| 16 | +pub mod homework_result; | ||
| 17 | +pub mod homework_submission; | ||
| 14 | pub mod meal_booking; | 18 | pub mod meal_booking; |
| 15 | pub mod note; | 19 | pub mod note; |
| 16 | pub mod page; | 20 | pub mod page; |
src/domain/homework.rsmodified+16 -498
| @@ -1,8 +1,10 @@ | |||
| 1 | //! A homework assignment: a teacher hands it out per course, optionally | 1 | //! A homework assignment: a teacher hands it out per course, optionally |
| 2 | //! narrowed to a subset of the enrolled students, and every homework is tagged | 2 | //! narrowed to a subset of the enrolled students, and every homework is tagged |
| 3 | -//! with one of its course's subjects. Students submit against it | 3 | +//! with one of its course's subjects. |
| 4 | -//! ([`crate::domain::homework_submission`]) and a teacher grades a status plus | 4 | +//! Students submit against it ([`crate::domain::homework_submission`]) and a |
| 5 | -//! an optional mark ([`crate::domain::homework_result`]). | 5 | +//! teacher grades a status plus an optional mark |
| 6 | +//! ([`crate::domain::homework_result`]). Persistence lives in | ||
| 7 | +//! [`crate::db::homework`], workflows in [`crate::service::homework`]. | ||
| 6 | //! | 8 | //! |
| 7 | //! `course`, `created_by`, and `created_at` are fixed at creation (the schema | 9 | //! `course`, `created_by`, and `created_at` are fixed at creation (the schema |
| 8 | //! marks them `READONLY`): moving a homework between courses would strand the | 10 | //! marks them `READONLY`): moving a homework between courses would strand the |
| @@ -12,32 +14,15 @@ | |||
| 12 | 14 | ||
| 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 15 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 14 | 16 | ||
| 15 | -use crate::constant::{ | 17 | +use crate::constant::{HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN}; |
| 16 | - HOMEWORK_TABLE, MAX_HOMEWORK_DESCRIPTION_LEN, MAX_HOMEWORK_TITLE_LEN, | ||
| 17 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 18 | -}; | ||
| 19 | -use crate::database::Database; | ||
| 20 | -use crate::db::cap; | ||
| 21 | -use crate::db::field_update::FieldUpdate; | ||
| 22 | use crate::domain::course::CourseId; | 18 | use crate::domain::course::CourseId; |
| 23 | use crate::domain::monotonic_id::next_ulid; | 19 | use crate::domain::monotonic_id::next_ulid; |
| 24 | use crate::domain::subject::SubjectId; | 20 | use crate::domain::subject::SubjectId; |
| 25 | use crate::domain::timestamp::Timestamp; | 21 | use crate::domain::timestamp::Timestamp; |
| 26 | use crate::domain::user::UserId; | 22 | use crate::domain::user::UserId; |
| 27 | -use crate::error::{AppError, ValidationError}; | 23 | +use crate::error::ValidationError; |
| 28 | use crate::validate::{validate_optional, validate_required}; | 24 | use crate::validate::{validate_optional, validate_required}; |
| 29 | 25 | ||
| 30 | -/// The answer a link to a subject that is not there gets, on create and on | ||
| 31 | -/// re-tag alike — both claims are conditional writes on the subject row, so a | ||
| 32 | -/// subject a delete already removed matches nothing and the caller says exactly | ||
| 33 | -/// what the web layer's pre-flight lookup would have. | ||
| 34 | -fn subject_gone() -> AppError { | ||
| 35 | - AppError::Validation(ValidationError::Invalid { | ||
| 36 | - field: "subject_id", | ||
| 37 | - reason: "subject does not exist", | ||
| 38 | - }) | ||
| 39 | -} | ||
| 40 | - | ||
| 41 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 26 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 42 | pub struct HomeworkId(RecordId); | 27 | pub struct HomeworkId(RecordId); |
| 43 | 28 | ||
| @@ -100,15 +85,15 @@ impl HomeworkDescription { | |||
| 100 | /// snapshot of the students named at assign (or last PATCH) time. | 85 | /// snapshot of the students named at assign (or last PATCH) time. |
| 101 | #[derive(Debug, Clone, SurrealValue)] | 86 | #[derive(Debug, Clone, SurrealValue)] |
| 102 | pub struct Homework { | 87 | pub struct Homework { |
| 103 | - id: HomeworkId, | 88 | + pub(crate) id: HomeworkId, |
| 104 | - course: CourseId, | 89 | + pub(crate) course: CourseId, |
| 105 | - subject: SubjectId, | 90 | + pub(crate) subject: SubjectId, |
| 106 | - title: HomeworkTitle, | 91 | + pub(crate) title: HomeworkTitle, |
| 107 | - description: Option<HomeworkDescription>, | 92 | + pub(crate) description: Option<HomeworkDescription>, |
| 108 | - due_at: Timestamp, | 93 | + pub(crate) due_at: Timestamp, |
| 109 | - assigned: Option<Vec<UserId>>, | 94 | + pub(crate) assigned: Option<Vec<UserId>>, |
| 110 | - created_by: UserId, | 95 | + pub(crate) created_by: UserId, |
| 111 | - created_at: Timestamp, | 96 | + pub(crate) created_at: Timestamp, |
| 112 | } | 97 | } |
| 113 | 98 | ||
| 114 | impl Homework { | 99 | impl Homework { |
| @@ -159,222 +144,6 @@ impl Homework { | |||
| 159 | Some(assigned) => assigned.is_empty() || assigned.contains(user), | 144 | Some(assigned) => assigned.is_empty() || assigned.contains(user), |
| 160 | } | 145 | } |
| 161 | } | 146 | } |
| 162 | - | ||
| 163 | - #[expect( | ||
| 164 | - clippy::too_many_arguments, | ||
| 165 | - reason = "mirrors the sibling entities' create(field, field, ..) shape" | ||
| 166 | - )] | ||
| 167 | - pub async fn create( | ||
| 168 | - course: &CourseId, | ||
| 169 | - subject: &SubjectId, | ||
| 170 | - title: HomeworkTitle, | ||
| 171 | - description: Option<HomeworkDescription>, | ||
| 172 | - due_at: Timestamp, | ||
| 173 | - assigned: Option<Vec<UserId>>, | ||
| 174 | - created_by: &UserId, | ||
| 175 | - db: &Database, | ||
| 176 | - ) -> Result<Homework, AppError> { | ||
| 177 | - // The subject's reference is taken in the very transaction that writes | ||
| 178 | - // the row — the exam question's twin | ||
| 179 | - // ([`crate::domain::exam_question::ExamQuestion`]): the subject delete | ||
| 180 | - // is refused while this counter is non-zero, so the create and the | ||
| 181 | - // delete contend on the subject record rather than on a cross-table | ||
| 182 | - // count neither of them sees the other move, and a crash can no longer | ||
| 183 | - // strand a claim that would make the subject undeletable forever. A | ||
| 184 | - // refused claim means the subject is already gone, which is the 400 the | ||
| 185 | - // web layer's pre-flight check answers with. | ||
| 186 | - let counted = subject.record(); | ||
| 187 | - let homework = Homework { | ||
| 188 | - id: HomeworkId::generate(), | ||
| 189 | - course: course.clone(), | ||
| 190 | - subject: subject.clone(), | ||
| 191 | - title, | ||
| 192 | - description, | ||
| 193 | - due_at, | ||
| 194 | - assigned, | ||
| 195 | - created_by: created_by.clone(), | ||
| 196 | - created_at: Timestamp::now(), | ||
| 197 | - }; | ||
| 198 | - let id = homework.id.record(); | ||
| 199 | - match cap::claim_and_create( | ||
| 200 | - &counted, | ||
| 201 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 202 | - cap::UNLIMITED, | ||
| 203 | - &id, | ||
| 204 | - &homework, | ||
| 205 | - db, | ||
| 206 | - ) | ||
| 207 | - .await? | ||
| 208 | - { | ||
| 209 | - cap::Claimed::Made(created) => Ok(created), | ||
| 210 | - cap::Claimed::Full => Err(subject_gone()), | ||
| 211 | - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create homework".into())), | ||
| 212 | - } | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - pub async fn read(id: &HomeworkId, db: &Database) -> Result<Option<Homework>, AppError> { | ||
| 216 | - Ok(db.select(id.record()).await?) | ||
| 217 | - } | ||
| 218 | - | ||
| 219 | - /// The course's homework, newest first (ULID ids sort by creation). The web | ||
| 220 | - /// layer retains only the rows a given student `student_sees`. | ||
| 221 | - pub async fn list_for_course( | ||
| 222 | - course: &CourseId, | ||
| 223 | - db: &Database, | ||
| 224 | - ) -> Result<Vec<Homework>, AppError> { | ||
| 225 | - let mut result = db | ||
| 226 | - .query("SELECT * FROM homework WHERE course = $course ORDER BY id DESC") | ||
| 227 | - .bind(("course", course.record())) | ||
| 228 | - .await? | ||
| 229 | - .check()?; | ||
| 230 | - Ok(result.take::<Vec<Homework>>(0)?) | ||
| 231 | - } | ||
| 232 | - | ||
| 233 | - /// Every homework in the system, newest first — the manager+ view of the | ||
| 234 | - /// cross-course "my homework" list. | ||
| 235 | - pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> { | ||
| 236 | - let mut result = db | ||
| 237 | - .query("SELECT * FROM homework ORDER BY id DESC") | ||
| 238 | - .await? | ||
| 239 | - .check()?; | ||
| 240 | - Ok(result.take::<Vec<Homework>>(0)?) | ||
| 241 | - } | ||
| 242 | - | ||
| 243 | - /// Every homework of every course in `courses`, newest first (one query) — | ||
| 244 | - /// the cross-course list over a caller's visible courses. The web layer | ||
| 245 | - /// still trims each course's rows to what the caller may see (a student to | ||
| 246 | - /// the ones they `student_sees`). | ||
| 247 | - pub async fn list_for_courses( | ||
| 248 | - courses: &[CourseId], | ||
| 249 | - db: &Database, | ||
| 250 | - ) -> Result<Vec<Homework>, AppError> { | ||
| 251 | - if courses.is_empty() { | ||
| 252 | - return Ok(Vec::new()); | ||
| 253 | - } | ||
| 254 | - let records: Vec<RecordId> = courses.iter().map(CourseId::record).collect(); | ||
| 255 | - let mut result = db | ||
| 256 | - .query("SELECT * FROM homework WHERE course IN $courses ORDER BY id DESC") | ||
| 257 | - .bind(("courses", records)) | ||
| 258 | - .await? | ||
| 259 | - .check()?; | ||
| 260 | - Ok(result.take::<Vec<Homework>>(0)?) | ||
| 261 | - } | ||
| 262 | - | ||
| 263 | - /// The homework of `course` that `user` is meant to see — whole-course ones | ||
| 264 | - /// plus any subset that names them — newest first. Backs a student's (or an | ||
| 265 | - /// observer's) per-course homework report; mirrors [`Homework::student_sees`] | ||
| 266 | - /// in SurQL so the filter runs in the database. | ||
| 267 | - pub async fn list_for_user_in_course( | ||
| 268 | - course: &CourseId, | ||
| 269 | - user: &UserId, | ||
| 270 | - db: &Database, | ||
| 271 | - ) -> Result<Vec<Homework>, AppError> { | ||
| 272 | - let mut result = db | ||
| 273 | - .query( | ||
| 274 | - "SELECT * FROM homework | ||
| 275 | - WHERE course = $course | ||
| 276 | - AND (assigned = NONE OR assigned = [] OR $usr IN assigned) | ||
| 277 | - ORDER BY id DESC", | ||
| 278 | - ) | ||
| 279 | - .bind(("course", course.record())) | ||
| 280 | - .bind(("usr", user.record())) | ||
| 281 | - .await? | ||
| 282 | - .check()?; | ||
| 283 | - Ok(result.take::<Vec<Homework>>(0)?) | ||
| 284 | - } | ||
| 285 | - | ||
| 286 | - /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. | ||
| 287 | - /// Request-scoped: every parameter is `Option`, `None` meaning the PATCH | ||
| 288 | - /// did not carry that field, so it is not written at all. Handing the | ||
| 289 | - /// snapshot's value back instead would revert a concurrent edit of that | ||
| 290 | - /// field — scoping the `SET` alone does not prevent that, the *values* must | ||
| 291 | - /// come from the request. `course`, `created_by`, and `created_at` are | ||
| 292 | - /// `READONLY` and never appear in the write. | ||
| 293 | - /// | ||
| 294 | - /// `description` and `assigned` are nullable columns, so they take a | ||
| 295 | - /// *double* option: outer `None` = absent (keep), `Some(None)` = write | ||
| 296 | - /// `NONE` (clear the description / widen back to the whole course). The web | ||
| 297 | - /// layer has already re-checked a new `due_at` against now, a new `subject` | ||
| 298 | - /// against the course, and refused a narrowing that would orphan work. | ||
| 299 | - pub async fn update( | ||
| 300 | - self, | ||
| 301 | - subject: Option<SubjectId>, | ||
| 302 | - title: Option<HomeworkTitle>, | ||
| 303 | - description: Option<Option<HomeworkDescription>>, | ||
| 304 | - due_at: Option<Timestamp>, | ||
| 305 | - assigned: Option<Option<Vec<UserId>>>, | ||
| 306 | - db: &Database, | ||
| 307 | - ) -> Result<Homework, AppError> { | ||
| 308 | - let assigned = assigned | ||
| 309 | - .map(|subset| subset.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>())); | ||
| 310 | - // A re-tag moves a reference: the new subject's claim and the old one's | ||
| 311 | - // release ride the same transaction as the link write, so no crash can | ||
| 312 | - // leave a count without its link (the subject would be undeletable | ||
| 313 | - // forever) or a link without its count. `subject` is required, so the | ||
| 314 | - // snapshot's value is always the CAS expectation — two PATCHes moving | ||
| 315 | - // the same homework off the same subject would otherwise both claim | ||
| 316 | - // their target, and the loser is refused with a 409 instead. The | ||
| 317 | - // `.refcount` call is unconditional: the CAS is armed by the request | ||
| 318 | - // *carrying* `subject_id`, not by a counter moving, so a PATCH that | ||
| 319 | - // re-states the tag its snapshot showed — shifting no counter at all — | ||
| 320 | - // is still refused when a rival moved the tag in between. A PATCH that | ||
| 321 | - // carried no `subject_id` arms nothing and writes what it always did. | ||
| 322 | - let (claim, release) = subject | ||
| 323 | - .as_ref() | ||
| 324 | - .filter(|next| **next != self.subject) | ||
| 325 | - .map(|next| (next.record(), self.subject.record())) | ||
| 326 | - .unzip(); | ||
| 327 | - FieldUpdate::new(self.id.record()) | ||
| 328 | - .set("subject", subject.map(|subject| subject.record())) | ||
| 329 | - .set("title", title) | ||
| 330 | - .set("description", description) | ||
| 331 | - .set("due_at", due_at) | ||
| 332 | - .set("assigned", assigned) | ||
| 333 | - .refcount( | ||
| 334 | - SUBJECT_HOMEWORK_COUNT_FIELD, | ||
| 335 | - "subject", | ||
| 336 | - Some(self.subject.record()), | ||
| 337 | - claim, | ||
| 338 | - release, | ||
| 339 | - subject_gone(), | ||
| 340 | - ) | ||
| 341 | - .run::<Homework>(db) | ||
| 342 | - .await | ||
| 343 | - } | ||
| 344 | - | ||
| 345 | - /// Delete the homework and cascade its submissions, their files, and its | ||
| 346 | - /// results — one transaction, so a crash can't orphan a submission under a | ||
| 347 | - /// vanished homework. The submission file *blobs* are the web layer's to | ||
| 348 | - /// unlink: it collects their names via | ||
| 349 | - /// [`crate::domain::homework_file::HomeworkFile::file_keys_for_homework`] | ||
| 350 | - /// before calling this, and removes them after the rows are gone. | ||
| 351 | - pub async fn delete(self, db: &Database) -> Result<Homework, AppError> { | ||
| 352 | - let mut result = db | ||
| 353 | - .query( | ||
| 354 | - format!( | ||
| 355 | - "BEGIN TRANSACTION; | ||
| 356 | - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw); | ||
| 357 | - DELETE homework_submission WHERE homework = $hw; | ||
| 358 | - DELETE homework_result WHERE homework = $hw; | ||
| 359 | - LET $gone = (DELETE $hw RETURN BEFORE); | ||
| 360 | - FOR $sub IN ($gone.subject ?? []) {{ | ||
| 361 | - UPDATE $sub SET {SUBJECT_HOMEWORK_COUNT_FIELD} = | ||
| 362 | - math::max([({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) - 1, 0]) | ||
| 363 | - }}; | ||
| 364 | - RETURN $gone; | ||
| 365 | - COMMIT TRANSACTION;" | ||
| 366 | - ), | ||
| 367 | - ) | ||
| 368 | - .bind(("hw", self.id.record())) | ||
| 369 | - .await? | ||
| 370 | - .check()?; | ||
| 371 | - // The subject's reference is given back in this same transaction, off | ||
| 372 | - // what the delete actually removed. Read through the trailing `RETURN`, | ||
| 373 | - // not a hand-counted slot — see [`crate::db::exam::delete`]. | ||
| 374 | - let slot = result.num_statements().saturating_sub(2); | ||
| 375 | - let deleted: Option<Homework> = result.take::<Vec<Homework>>(slot)?.into_iter().next(); | ||
| 376 | - deleted.ok_or(AppError::NotFound) | ||
| 377 | - } | ||
| 378 | } | 147 | } |
| 379 | 148 | ||
| 380 | #[cfg(test)] | 149 | #[cfg(test)] |
| @@ -417,255 +186,4 @@ mod tests { | |||
| 417 | assert!(with(Some(vec![a.clone()])).student_sees(&a)); | 186 | assert!(with(Some(vec![a.clone()])).student_sees(&a)); |
| 418 | assert!(!with(Some(vec![a.clone()])).student_sees(&b)); | 187 | assert!(!with(Some(vec![a.clone()])).student_sees(&b)); |
| 419 | } | 188 | } |
| 420 | - | ||
| 421 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 422 | - | ||
| 423 | - async fn a_subject(name: &str, db: &Database) -> Subject { | ||
| 424 | - Subject::create( | ||
| 425 | - &crate::db::course::a_test_course(db).await, | ||
| 426 | - SubjectName::try_new(name).unwrap(), | ||
| 427 | - SubjectDescription::try_new("").unwrap(), | ||
| 428 | - db, | ||
| 429 | - ) | ||
| 430 | - .await | ||
| 431 | - .unwrap() | ||
| 432 | - } | ||
| 433 | - | ||
| 434 | - async fn homework_on(subject: &SubjectId, db: &Database) -> Homework { | ||
| 435 | - Homework::create( | ||
| 436 | - &CourseId::from_key("course"), | ||
| 437 | - subject, | ||
| 438 | - HomeworkTitle::try_new("essay").unwrap(), | ||
| 439 | - None, | ||
| 440 | - Timestamp::from_millis(1), | ||
| 441 | - None, | ||
| 442 | - &UserId::from_key("teacher"), | ||
| 443 | - db, | ||
| 444 | - ) | ||
| 445 | - .await | ||
| 446 | - .unwrap() | ||
| 447 | - } | ||
| 448 | - | ||
| 449 | - /// The stored `homework_count` on one subject, absent counting as zero. | ||
| 450 | - async fn count_on(subject: &SubjectId, db: &Database) -> i64 { | ||
| 451 | - let mut result = db | ||
| 452 | - .query(format!( | ||
| 453 | - "SELECT VALUE ({SUBJECT_HOMEWORK_COUNT_FIELD} ?? 0) FROM $sub" | ||
| 454 | - )) | ||
| 455 | - .bind(("sub", subject.record())) | ||
| 456 | - .await | ||
| 457 | - .unwrap() | ||
| 458 | - .check() | ||
| 459 | - .unwrap(); | ||
| 460 | - result | ||
| 461 | - .take::<Vec<i64>>(0) | ||
| 462 | - .unwrap() | ||
| 463 | - .first() | ||
| 464 | - .copied() | ||
| 465 | - .unwrap_or(0) | ||
| 466 | - } | ||
| 467 | - | ||
| 468 | - /// How many rows `sql` selects ids for. | ||
| 469 | - async fn rows(sql: &str, db: &Database) -> usize { | ||
| 470 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 471 | - result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 472 | - } | ||
| 473 | - | ||
| 474 | - /// The invariant on the create path: the claim and the row it accounts for | ||
| 475 | - /// commit together or not at all. A refused create leaves *neither* — no | ||
| 476 | - /// homework row, and no count stranded on a subject (the subject's delete | ||
| 477 | - /// guard reads that count, so a stray one makes it undeletable forever). | ||
| 478 | - #[tokio::test] | ||
| 479 | - async fn a_refused_create_writes_neither_row_nor_count() { | ||
| 480 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 481 | - let subject = a_subject("algebra", &db).await; | ||
| 482 | - let id = subject.get_id().clone(); | ||
| 483 | - subject.delete(&db).await.unwrap(); | ||
| 484 | - | ||
| 485 | - let error = Homework::create( | ||
| 486 | - &CourseId::from_key("course"), | ||
| 487 | - &id, | ||
| 488 | - HomeworkTitle::try_new("essay").unwrap(), | ||
| 489 | - None, | ||
| 490 | - Timestamp::from_millis(1), | ||
| 491 | - None, | ||
| 492 | - &UserId::from_key("teacher"), | ||
| 493 | - &db, | ||
| 494 | - ) | ||
| 495 | - .await | ||
| 496 | - .expect_err("a subject that is gone must not be taggable"); | ||
| 497 | - assert!(error.to_string().contains("subject does not exist")); | ||
| 498 | - assert_eq!( | ||
| 499 | - rows("SELECT VALUE id FROM homework", &db).await, | ||
| 500 | - 0, | ||
| 501 | - "a refused create may write no row" | ||
| 502 | - ); | ||
| 503 | - assert_eq!( | ||
| 504 | - rows("SELECT VALUE id FROM subject", &db).await, | ||
| 505 | - 0, | ||
| 506 | - "…and least of all a count on a subject it just brought back" | ||
| 507 | - ); | ||
| 508 | - } | ||
| 509 | - | ||
| 510 | - /// The invariant on the PATCH path: a re-tag carries the new subject's | ||
| 511 | - /// claim and the old one's release with the link itself. | ||
| 512 | - #[tokio::test] | ||
| 513 | - async fn a_subject_move_moves_the_count() { | ||
| 514 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 515 | - let from = a_subject("algebra", &db).await; | ||
| 516 | - let to = a_subject("geometry", &db).await; | ||
| 517 | - let homework = homework_on(from.get_id(), &db).await; | ||
| 518 | - assert_eq!(count_on(from.get_id(), &db).await, 1); | ||
| 519 | - | ||
| 520 | - let moved = homework | ||
| 521 | - .update(Some(to.get_id().clone()), None, None, None, None, &db) | ||
| 522 | - .await | ||
| 523 | - .unwrap(); | ||
| 524 | - assert_eq!(moved.get_subject(), to.get_id()); | ||
| 525 | - assert_eq!( | ||
| 526 | - count_on(from.get_id(), &db).await, | ||
| 527 | - 0, | ||
| 528 | - "the old subject is free" | ||
| 529 | - ); | ||
| 530 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | ||
| 531 | - assert!(from.delete(&db).await.is_ok(), "no reference left"); | ||
| 532 | - assert!( | ||
| 533 | - to.delete(&db).await.is_err(), | ||
| 534 | - "the reference moved here refuses the delete" | ||
| 535 | - ); | ||
| 536 | - } | ||
| 537 | - | ||
| 538 | - /// The claim throws inside the same transaction as the link write, so a | ||
| 539 | - /// move onto a subject that is gone rolls the release back with it: the row | ||
| 540 | - /// keeps its tag and both counters read as if nothing ran. | ||
| 541 | - #[tokio::test] | ||
| 542 | - async fn a_move_to_a_dead_subject_leaves_everything_untouched() { | ||
| 543 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 544 | - let from = a_subject("algebra", &db).await; | ||
| 545 | - let dead = a_subject("geometry", &db).await; | ||
| 546 | - let gone = dead.get_id().clone(); | ||
| 547 | - dead.delete(&db).await.unwrap(); | ||
| 548 | - let homework = homework_on(from.get_id(), &db).await; | ||
| 549 | - | ||
| 550 | - let error = homework | ||
| 551 | - .clone() | ||
| 552 | - .update(Some(gone.clone()), None, None, None, None, &db) | ||
| 553 | - .await | ||
| 554 | - .expect_err("a subject that is gone must not be taggable"); | ||
| 555 | - assert!(error.to_string().contains("subject does not exist")); | ||
| 556 | - let stored = Homework::read(homework.get_id(), &db) | ||
| 557 | - .await | ||
| 558 | - .unwrap() | ||
| 559 | - .unwrap(); | ||
| 560 | - assert_eq!(stored.get_subject(), from.get_id(), "the tag never moved"); | ||
| 561 | - assert_eq!( | ||
| 562 | - count_on(from.get_id(), &db).await, | ||
| 563 | - 1, | ||
| 564 | - "the release rolled back with the claim" | ||
| 565 | - ); | ||
| 566 | - assert_eq!( | ||
| 567 | - rows("SELECT VALUE id FROM subject", &db).await, | ||
| 568 | - 1, | ||
| 569 | - "the dead subject was not brought back by a count" | ||
| 570 | - ); | ||
| 571 | - assert_eq!(count_on(&gone, &db).await, 0); | ||
| 572 | - } | ||
| 573 | - | ||
| 574 | - /// The double-claim guard. Both movers compute their claim and release from | ||
| 575 | - /// the row as *they* read it, so two PATCHes re-tagging the same homework | ||
| 576 | - /// off the same subject both release it and both claim their target — two | ||
| 577 | - /// counts for one link, and the loser's target is undeletable forever. The | ||
| 578 | - /// second call here runs on the struct read before the first one landed, | ||
| 579 | - /// which is that race with the interleaving pinned: it must be refused | ||
| 580 | - /// outright, and the counts must read as if it never ran. | ||
| 581 | - #[tokio::test] | ||
| 582 | - async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 583 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 584 | - let from = a_subject("algebra", &db).await; | ||
| 585 | - let to = a_subject("geometry", &db).await; | ||
| 586 | - let other = a_subject("calculus", &db).await; | ||
| 587 | - let homework = homework_on(from.get_id(), &db).await; | ||
| 588 | - let stale = homework.clone(); | ||
| 589 | - homework | ||
| 590 | - .update(Some(to.get_id().clone()), None, None, None, None, &db) | ||
| 591 | - .await | ||
| 592 | - .unwrap(); | ||
| 593 | - | ||
| 594 | - let error = stale | ||
| 595 | - .clone() | ||
| 596 | - .update(Some(other.get_id().clone()), None, None, None, None, &db) | ||
| 597 | - .await | ||
| 598 | - .expect_err("a mover that read a tag it no longer holds must be refused"); | ||
| 599 | - assert!( | ||
| 600 | - matches!(error, AppError::Conflict(_)), | ||
| 601 | - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 602 | - ); | ||
| 603 | - let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 604 | - assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); | ||
| 605 | - assert_eq!( | ||
| 606 | - count_on(from.get_id(), &db).await, | ||
| 607 | - 0, | ||
| 608 | - "released once, not twice" | ||
| 609 | - ); | ||
| 610 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); | ||
| 611 | - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); | ||
| 612 | - } | ||
| 613 | - | ||
| 614 | - /// The same race with the counters taken out of it. A PATCH that re-states | ||
| 615 | - /// the subject its snapshot showed shifts *nothing* — no claim and no | ||
| 616 | - /// release — so if the guard were armed off the counter move it would not be | ||
| 617 | - /// armed here at all, and the write would land: the winner's tag silently | ||
| 618 | - /// dragged back, its claim stranded on a subject nothing points at | ||
| 619 | - /// (undeletable forever) and the reverted-to subject tagged at a count of | ||
| 620 | - /// zero (deletable while tagged). The guard is armed by the request | ||
| 621 | - /// *carrying* the column instead, which is why this is refused. | ||
| 622 | - #[tokio::test] | ||
| 623 | - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 624 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 625 | - let from = a_subject("algebra", &db).await; | ||
| 626 | - let to = a_subject("geometry", &db).await; | ||
| 627 | - let homework = homework_on(from.get_id(), &db).await; | ||
| 628 | - let stale = homework.clone(); | ||
| 629 | - homework | ||
| 630 | - .update(Some(to.get_id().clone()), None, None, None, None, &db) | ||
| 631 | - .await | ||
| 632 | - .unwrap(); | ||
| 633 | - | ||
| 634 | - let error = stale | ||
| 635 | - .clone() | ||
| 636 | - .update(Some(from.get_id().clone()), None, None, None, None, &db) | ||
| 637 | - .await | ||
| 638 | - .expect_err("re-stating a tag someone else moved must be refused"); | ||
| 639 | - assert!( | ||
| 640 | - matches!(error, AppError::Conflict(_)), | ||
| 641 | - "a lost CAS is a conflict, not a silent 200: {error:?}" | ||
| 642 | - ); | ||
| 643 | - let stored = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 644 | - assert_eq!(stored.get_subject(), to.get_id(), "the winner's tag"); | ||
| 645 | - assert_eq!( | ||
| 646 | - count_on(from.get_id(), &db).await, | ||
| 647 | - 0, | ||
| 648 | - "the reverted-to subject must not end up tagged at zero" | ||
| 649 | - ); | ||
| 650 | - assert_eq!( | ||
| 651 | - count_on(to.get_id(), &db).await, | ||
| 652 | - 1, | ||
| 653 | - "…nor the winner's subject counted with nothing pointing at it" | ||
| 654 | - ); | ||
| 655 | - | ||
| 656 | - // A *genuine* no-op re-state — nobody moved underneath it — still lands, | ||
| 657 | - // and still moves no counter: the CAS passes trivially. | ||
| 658 | - let fresh = Homework::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 659 | - let same = fresh | ||
| 660 | - .update(Some(to.get_id().clone()), None, None, None, None, &db) | ||
| 661 | - .await | ||
| 662 | - .expect("re-stating the tag actually held is not a race"); | ||
| 663 | - assert_eq!(same.get_subject(), to.get_id()); | ||
| 664 | - assert_eq!( | ||
| 665 | - count_on(from.get_id(), &db).await, | ||
| 666 | - 0, | ||
| 667 | - "still no counter move" | ||
| 668 | - ); | ||
| 669 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still"); | ||
| 670 | - } | ||
| 671 | } | 189 | } |
src/domain/homework_file.rsmodified+12 -423
| @@ -6,24 +6,18 @@ | |||
| 6 | //! disk path. Files are immutable: created and deleted, never updated, so the | 6 | //! disk path. Files are immutable: created and deleted, never updated, so the |
| 7 | //! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. | 7 | //! `READONLY` `submission`/`file`/`created_at` columns are only ever set once. |
| 8 | //! The web layer owns the blob I/O and its ordering (blob before row on | 8 | //! The web layer owns the blob I/O and its ordering (blob before row on |
| 9 | -//! upload, row before blob on delete); this module owns the rows. | 9 | +//! upload, row before blob on delete); the rows are written and read by |
| 10 | +//! [`crate::db::homework_file`], the upload/attach workflow by | ||
| 11 | +//! [`crate::service::homework_file`]. | ||
| 10 | 12 | ||
| 11 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 13 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 12 | use ulid::Ulid; | 14 | use ulid::Ulid; |
| 13 | 15 | ||
| 14 | -use crate::constant::{ | 16 | +use crate::constant::HOMEWORK_FILE_TABLE; |
| 15 | - HOMEWORK_FILE_TABLE, MAX_HOMEWORK_FILES_PER_SUBMISSION, SUBMISSION_FILE_COUNT_FIELD, | 17 | +use crate::domain::homework_submission::HomeworkSubmissionId; |
| 16 | - SUBMISSION_OPEN_GUARD, | ||
| 17 | -}; | ||
| 18 | -use crate::database::{Database, transaction_with_retry}; | ||
| 19 | -use crate::db::cap; | ||
| 20 | -use crate::domain::course::CourseId; | ||
| 21 | -use crate::domain::homework::HomeworkId; | ||
| 22 | -use crate::domain::homework_submission::{HomeworkSubmission, HomeworkSubmissionId}; | ||
| 23 | use crate::domain::monotonic_id::next_ulid; | 18 | use crate::domain::monotonic_id::next_ulid; |
| 24 | use crate::domain::note_file::{FileContentType, FileName}; | 19 | use crate::domain::note_file::{FileContentType, FileName}; |
| 25 | use crate::domain::timestamp::Timestamp; | 20 | use crate::domain::timestamp::Timestamp; |
| 26 | -use crate::error::AppError; | ||
| 27 | 21 | ||
| 28 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 22 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 29 | pub struct HomeworkFileId(RecordId); | 23 | pub struct HomeworkFileId(RecordId); |
| @@ -56,23 +50,13 @@ impl HomeworkFileId { | |||
| 56 | /// upload), independent of the row id and reused as the GC key on cascade. | 50 | /// upload), independent of the row id and reused as the GC key on cascade. |
| 57 | #[derive(Debug, Clone, SurrealValue)] | 51 | #[derive(Debug, Clone, SurrealValue)] |
| 58 | pub struct HomeworkFile { | 52 | pub struct HomeworkFile { |
| 59 | - id: HomeworkFileId, | 53 | + pub(crate) id: HomeworkFileId, |
| 60 | - submission: HomeworkSubmissionId, | 54 | + pub(crate) submission: HomeworkSubmissionId, |
| 61 | - name: FileName, | 55 | + pub(crate) name: FileName, |
| 62 | - content_type: FileContentType, | 56 | + pub(crate) content_type: FileContentType, |
| 63 | - size: i64, | 57 | + pub(crate) size: i64, |
| 64 | - file: String, | 58 | + pub(crate) file: String, |
| 65 | - created_at: Timestamp, | 59 | + pub(crate) created_at: Timestamp, |
| 66 | -} | ||
| 67 | - | ||
| 68 | -/// What [`HomeworkFile::delete`]'s transaction reports: whether the submission | ||
| 69 | -/// was still open (`open` = 1, the gate bit) and the row it then removed. Two | ||
| 70 | -/// answers in one object because an empty `gone` alone cannot say whether the | ||
| 71 | -/// delete was refused or the file had simply vanished. | ||
| 72 | -#[derive(Debug, SurrealValue)] | ||
| 73 | -struct DeleteOutcome { | ||
| 74 | - open: i64, | ||
| 75 | - gone: Vec<HomeworkFile>, | ||
| 76 | } | 60 | } |
| 77 | 61 | ||
| 78 | impl HomeworkFile { | 62 | impl HomeworkFile { |
| @@ -124,399 +108,4 @@ impl HomeworkFile { | |||
| 124 | pub fn get_created_at(&self) -> Timestamp { | 108 | pub fn get_created_at(&self) -> Timestamp { |
| 125 | self.created_at | 109 | self.created_at |
| 126 | } | 110 | } |
| 127 | - | ||
| 128 | - /// Persist the row assembled by [`Self::new`], refusing once its submission | ||
| 129 | - /// already holds [`MAX_HOMEWORK_FILES_PER_SUBMISSION`] (an `Err(Conflict)`) | ||
| 130 | - /// or once a grade has frozen it (`Ok(None)`, so the web layer keeps its own | ||
| 131 | - /// wording). Both are decided by one [`cap::claim_when_and_create`] on the | ||
| 132 | - /// submission row — the seat and the file row commit together, so a crash | ||
| 133 | - /// between them can no longer leave a slot claimed by a file that does not | ||
| 134 | - /// exist, and a losing upload never has to be un-counted. Which of the two | ||
| 135 | - /// conditions refused it is read back afterwards, off the losing path only, | ||
| 136 | - /// and only to pick the message: `Claimed::Full` says "full *or* graded *or* | ||
| 137 | - /// the submission is gone". | ||
| 138 | - pub async fn insert(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> { | ||
| 139 | - // whole-row-save-ok: create of a fresh ULID row built in place by `new` — there is no prior row to clobber | ||
| 140 | - match cap::claim_when_and_create( | ||
| 141 | - &self.submission.record(), | ||
| 142 | - SUBMISSION_FILE_COUNT_FIELD, | ||
| 143 | - MAX_HOMEWORK_FILES_PER_SUBMISSION as i64, | ||
| 144 | - SUBMISSION_OPEN_GUARD, | ||
| 145 | - &self.id.record(), | ||
| 146 | - &self, | ||
| 147 | - db, | ||
| 148 | - ) | ||
| 149 | - .await? | ||
| 150 | - { | ||
| 151 | - cap::Claimed::Made(created) => Ok(Some(created)), | ||
| 152 | - cap::Claimed::Full => { | ||
| 153 | - if HomeworkSubmission::is_graded(&self.submission, db).await? { | ||
| 154 | - return Ok(None); | ||
| 155 | - } | ||
| 156 | - Err(AppError::Conflict( | ||
| 157 | - "the submission already holds the maximum of 10 files — delete one first", | ||
| 158 | - )) | ||
| 159 | - } | ||
| 160 | - // The id is a fresh ULID minted by `new`, so a row already holding it | ||
| 161 | - // is a collision, not a re-upload. | ||
| 162 | - cap::Claimed::Duplicate => Err(AppError::Internal("homework file id collided".into())), | ||
| 163 | - } | ||
| 164 | - } | ||
| 165 | - | ||
| 166 | - /// Read a file's row only if it belongs to `submission` — callers have | ||
| 167 | - /// already checked the submission belongs to the requesting user. | ||
| 168 | - pub async fn read_for( | ||
| 169 | - id: &HomeworkFileId, | ||
| 170 | - submission: &HomeworkSubmissionId, | ||
| 171 | - db: &Database, | ||
| 172 | - ) -> Result<Option<HomeworkFile>, AppError> { | ||
| 173 | - let file: Option<HomeworkFile> = db.select(id.record()).await?; | ||
| 174 | - Ok(file.filter(|file| &file.submission == submission)) | ||
| 175 | - } | ||
| 176 | - | ||
| 177 | - /// Read a file by id only if it hangs off a submission to `homework` — the | ||
| 178 | - /// grader's download scoping. The teacher download path carries the homework | ||
| 179 | - /// id but not the owning student (unlike `read_for`, which needs the | ||
| 180 | - /// submission), so this both finds the file and confirms it belongs under | ||
| 181 | - /// `homework`: a teacher can't pass a homework they manage to read a file | ||
| 182 | - /// from a different (perhaps unmanaged) one. | ||
| 183 | - pub async fn read_in_homework( | ||
| 184 | - id: &HomeworkFileId, | ||
| 185 | - homework: &HomeworkId, | ||
| 186 | - db: &Database, | ||
| 187 | - ) -> Result<Option<HomeworkFile>, AppError> { | ||
| 188 | - let mut result = db | ||
| 189 | - .query( | ||
| 190 | - "SELECT * FROM homework_file WHERE id = $id AND submission IN \ | ||
| 191 | - (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | ||
| 192 | - ) | ||
| 193 | - .bind(("id", id.record())) | ||
| 194 | - .bind(("hw", homework.record())) | ||
| 195 | - .await? | ||
| 196 | - .check()?; | ||
| 197 | - Ok(result.take::<Vec<HomeworkFile>>(0)?.into_iter().next()) | ||
| 198 | - } | ||
| 199 | - | ||
| 200 | - /// All of `submission`'s files, newest first. | ||
| 201 | - pub async fn list_for_submission( | ||
| 202 | - submission: &HomeworkSubmissionId, | ||
| 203 | - db: &Database, | ||
| 204 | - ) -> Result<Vec<HomeworkFile>, AppError> { | ||
| 205 | - let mut result = db | ||
| 206 | - .query("SELECT * FROM homework_file WHERE submission = $sub ORDER BY id DESC") | ||
| 207 | - .bind(("sub", submission.record())) | ||
| 208 | - .await? | ||
| 209 | - .check()?; | ||
| 210 | - Ok(result.take::<Vec<HomeworkFile>>(0)?) | ||
| 211 | - } | ||
| 212 | - | ||
| 213 | - /// How many files `submission` holds — the cap check reads this under the | ||
| 214 | - /// lock. Counting via the rows (not a `count()` query) keeps it identical | ||
| 215 | - /// to `NoteFile`'s proven cap check; at a ceiling of 10 the cost is nil. | ||
| 216 | - pub async fn count_for_submission( | ||
| 217 | - submission: &HomeworkSubmissionId, | ||
| 218 | - db: &Database, | ||
| 219 | - ) -> Result<usize, AppError> { | ||
| 220 | - Ok(Self::list_for_submission(submission, db).await?.len()) | ||
| 221 | - } | ||
| 222 | - | ||
| 223 | - /// The blob names behind every file of every submission to `homework` — | ||
| 224 | - /// collected *before* the homework-delete cascade wipes the rows, so the | ||
| 225 | - /// web layer can unlink them once the rows are gone. | ||
| 226 | - pub async fn file_keys_for_homework( | ||
| 227 | - homework: &HomeworkId, | ||
| 228 | - db: &Database, | ||
| 229 | - ) -> Result<Vec<String>, AppError> { | ||
| 230 | - let mut result = db | ||
| 231 | - .query( | ||
| 232 | - "SELECT VALUE file FROM homework_file \ | ||
| 233 | - WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework = $hw)", | ||
| 234 | - ) | ||
| 235 | - .bind(("hw", homework.record())) | ||
| 236 | - .await? | ||
| 237 | - .check()?; | ||
| 238 | - Ok(result.take::<Vec<String>>(0)?) | ||
| 239 | - } | ||
| 240 | - | ||
| 241 | - /// The blob names behind every homework file of `course` — collected | ||
| 242 | - /// *before* the course-delete cascade wipes the rows. | ||
| 243 | - pub async fn file_keys_for_course( | ||
| 244 | - course: &CourseId, | ||
| 245 | - db: &Database, | ||
| 246 | - ) -> Result<Vec<String>, AppError> { | ||
| 247 | - let mut result = db | ||
| 248 | - .query( | ||
| 249 | - "SELECT VALUE file FROM homework_file WHERE submission IN ( \ | ||
| 250 | - SELECT VALUE id FROM homework_submission \ | ||
| 251 | - WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course) \ | ||
| 252 | - )", | ||
| 253 | - ) | ||
| 254 | - .bind(("course", course.record())) | ||
| 255 | - .await? | ||
| 256 | - .check()?; | ||
| 257 | - Ok(result.take::<Vec<String>>(0)?) | ||
| 258 | - } | ||
| 259 | - | ||
| 260 | - /// Delete the row and give its slot back in the same transaction. The | ||
| 261 | - /// submission survives, so its counter has to be corrected; the cascades | ||
| 262 | - /// that delete the submission itself take the counter with it. | ||
| 263 | - /// | ||
| 264 | - /// The gate is the first statement: a conditional write on the *submission* | ||
| 265 | - /// row — the "last touched" re-stamp a file delete owes the late flag | ||
| 266 | - /// anyway — carrying [`SUBMISSION_OPEN_GUARD`]. Nothing else in the | ||
| 267 | - /// transaction runs unless it bit, so a grade landing concurrently either | ||
| 268 | - /// stamps first (this delete is refused, `Ok(None)`) or stamps after (the | ||
| 269 | - /// file was already gone when it graded). `Err(NotFound)` still means the | ||
| 270 | - /// file row itself had vanished. | ||
| 271 | - /// | ||
| 272 | - /// Sound to re-send while the store answers "conflict, retry", and it has | ||
| 273 | - /// to be: the gate writes the *submission* row, the very record an upload's | ||
| 274 | - /// [`HomeworkFile::insert`] claims its seat on, and both handlers hold only | ||
| 275 | - /// `HOMEWORK_LOCK.read()` — so a concurrent add and delete of two files of | ||
| 276 | - /// one submission contend by design, and a lost round used to come back as | ||
| 277 | - /// a 500 on a request that had written nothing. Only `UPDATE` and `DELETE` | ||
| 278 | - /// are in the batch, and neither can legitimately answer "already exists", | ||
| 279 | - /// which is what makes the whole of it re-sendable. | ||
| 280 | - pub async fn delete(self, db: &Database) -> Result<Option<HomeworkFile>, AppError> { | ||
| 281 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 282 | - db, | ||
| 283 | - &format!( | ||
| 284 | - "BEGIN TRANSACTION; | ||
| 285 | - LET $open = (UPDATE $sub SET updated_at = $now \ | ||
| 286 | - WHERE {SUBMISSION_OPEN_GUARD} RETURN VALUE id); | ||
| 287 | - LET $gone = IF array::len($open) > 0 {{ (DELETE $id RETURN BEFORE) }} ELSE {{ [] }}; | ||
| 288 | - UPDATE $sub SET file_count = math::max([(file_count ?? 0) - array::len($gone), 0]); | ||
| 289 | - RETURN {{ open: array::len($open), gone: $gone }}; | ||
| 290 | - COMMIT TRANSACTION;" | ||
| 291 | - ), | ||
| 292 | - &[ | ||
| 293 | - ("id".into(), self.id.record().into_value()), | ||
| 294 | - ("sub".into(), self.submission.record().into_value()), | ||
| 295 | - ("now".into(), Timestamp::now().into_value()), | ||
| 296 | - ], | ||
| 297 | - &[], | ||
| 298 | - ) | ||
| 299 | - .await?; | ||
| 300 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 301 | - return Err(error.into()); | ||
| 302 | - } | ||
| 303 | - // BEGIN is slot 0, the two LETs slots 1-2 and the counter fix slot 3; | ||
| 304 | - // the RETURN is slot 4. | ||
| 305 | - let outcome: Option<DeleteOutcome> = | ||
| 306 | - result.take::<Vec<DeleteOutcome>>(4)?.into_iter().next(); | ||
| 307 | - let outcome = | ||
| 308 | - outcome.ok_or_else(|| AppError::Internal("failed to delete homework file".into()))?; | ||
| 309 | - if outcome.open == 0 { | ||
| 310 | - return Ok(None); | ||
| 311 | - } | ||
| 312 | - outcome | ||
| 313 | - .gone | ||
| 314 | - .into_iter() | ||
| 315 | - .next() | ||
| 316 | - .map(Some) | ||
| 317 | - .ok_or(AppError::NotFound) | ||
| 318 | - } | ||
| 319 | -} | ||
| 320 | - | ||
| 321 | -#[cfg(test)] | ||
| 322 | -mod tests { | ||
| 323 | - use super::*; | ||
| 324 | - use crate::domain::homework_submission::HomeworkSubmission; | ||
| 325 | - use crate::domain::user::UserId; | ||
| 326 | - | ||
| 327 | - /// A real homework row (with the subject it references): `upsert` reads the | ||
| 328 | - /// deadline off the entity now, so a bare id no longer does. | ||
| 329 | - async fn a_homework(db: &Database) -> crate::domain::homework::Homework { | ||
| 330 | - use crate::domain::homework::{Homework, HomeworkTitle}; | ||
| 331 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 332 | - | ||
| 333 | - let course = crate::db::course::a_test_course(db).await; | ||
| 334 | - let subject = Subject::create( | ||
| 335 | - &course, | ||
| 336 | - SubjectName::try_new("topic").unwrap(), | ||
| 337 | - SubjectDescription::try_new("").unwrap(), | ||
| 338 | - db, | ||
| 339 | - ) | ||
| 340 | - .await | ||
| 341 | - .unwrap(); | ||
| 342 | - Homework::create( | ||
| 343 | - &course, | ||
| 344 | - subject.get_id(), | ||
| 345 | - HomeworkTitle::try_new("essay").unwrap(), | ||
| 346 | - None, | ||
| 347 | - crate::domain::timestamp::Timestamp::from_millis(1), | ||
| 348 | - None, | ||
| 349 | - &UserId::from_key("teacher"), | ||
| 350 | - db, | ||
| 351 | - ) | ||
| 352 | - .await | ||
| 353 | - .unwrap() | ||
| 354 | - } | ||
| 355 | - | ||
| 356 | - fn a_file(submission: &HomeworkSubmissionId) -> HomeworkFile { | ||
| 357 | - HomeworkFile::new( | ||
| 358 | - submission, | ||
| 359 | - FileName::try_new("answer.pdf").unwrap(), | ||
| 360 | - FileContentType::try_new("application/pdf").unwrap(), | ||
| 361 | - 3, | ||
| 362 | - ) | ||
| 363 | - } | ||
| 364 | - | ||
| 365 | - /// The counter as *stored* — the only witness that the seat and the row | ||
| 366 | - /// moved together, since every other read counts the rows themselves. | ||
| 367 | - async fn stored_count(submission: &HomeworkSubmissionId, db: &Database) -> i64 { | ||
| 368 | - db.query("SELECT VALUE file_count FROM $sub") | ||
| 369 | - .bind(("sub", submission.record())) | ||
| 370 | - .await | ||
| 371 | - .unwrap() | ||
| 372 | - .take::<Vec<i64>>(0) | ||
| 373 | - .unwrap() | ||
| 374 | - .into_iter() | ||
| 375 | - .next() | ||
| 376 | - .unwrap_or(0) | ||
| 377 | - } | ||
| 378 | - | ||
| 379 | - #[tokio::test] | ||
| 380 | - async fn rows_scope_to_their_submission_gc_and_cap() { | ||
| 381 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 382 | - let hw = a_homework(&db).await; | ||
| 383 | - let homework = hw.get_id().clone(); | ||
| 384 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 385 | - // A real submission row, so the GC join through it resolves. | ||
| 386 | - let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) | ||
| 387 | - .await | ||
| 388 | - .unwrap() | ||
| 389 | - .unwrap(); | ||
| 390 | - let sub_a = submission.get_id().clone(); | ||
| 391 | - let sub_b = HomeworkSubmissionId::composite( | ||
| 392 | - &homework, | ||
| 393 | - &UserId::from_key("01TESTUSERBBBBBBBBBBBBBBBB"), | ||
| 394 | - ); | ||
| 395 | - | ||
| 396 | - let stored = a_file(&sub_a).insert(&db).await.unwrap().unwrap(); | ||
| 397 | - // Readable under its own submission, invisible under another. | ||
| 398 | - assert!( | ||
| 399 | - HomeworkFile::read_for(stored.get_id(), &sub_a, &db) | ||
| 400 | - .await | ||
| 401 | - .unwrap() | ||
| 402 | - .is_some() | ||
| 403 | - ); | ||
| 404 | - assert!( | ||
| 405 | - HomeworkFile::read_for(stored.get_id(), &sub_b, &db) | ||
| 406 | - .await | ||
| 407 | - .unwrap() | ||
| 408 | - .is_none() | ||
| 409 | - ); | ||
| 410 | - assert_eq!( | ||
| 411 | - HomeworkFile::count_for_submission(&sub_a, &db) | ||
| 412 | - .await | ||
| 413 | - .unwrap(), | ||
| 414 | - 1 | ||
| 415 | - ); | ||
| 416 | - assert_eq!( | ||
| 417 | - stored_count(&sub_a, &db).await, | ||
| 418 | - 1, | ||
| 419 | - "the seat rode with the row" | ||
| 420 | - ); | ||
| 421 | - | ||
| 422 | - // The grader's download scoping: found under its own homework, invisible | ||
| 423 | - // under another — so a teacher can't read it by naming a homework they | ||
| 424 | - // happen to manage. | ||
| 425 | - assert!( | ||
| 426 | - HomeworkFile::read_in_homework(stored.get_id(), &homework, &db) | ||
| 427 | - .await | ||
| 428 | - .unwrap() | ||
| 429 | - .is_some() | ||
| 430 | - ); | ||
| 431 | - assert!( | ||
| 432 | - HomeworkFile::read_in_homework( | ||
| 433 | - stored.get_id(), | ||
| 434 | - &HomeworkId::from_key("01TESTHWBBBBBBBBBBBBBBBBBB"), | ||
| 435 | - &db, | ||
| 436 | - ) | ||
| 437 | - .await | ||
| 438 | - .unwrap() | ||
| 439 | - .is_none() | ||
| 440 | - ); | ||
| 441 | - | ||
| 442 | - // The blob name is collectable for GC before a cascade wipes the rows. | ||
| 443 | - let keys = HomeworkFile::file_keys_for_homework(&homework, &db) | ||
| 444 | - .await | ||
| 445 | - .unwrap(); | ||
| 446 | - assert_eq!(keys, vec![stored.get_file().to_string()]); | ||
| 447 | - | ||
| 448 | - // Fill to the cap, then the 11th is refused. | ||
| 449 | - for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { | ||
| 450 | - a_file(&sub_a).insert(&db).await.unwrap().unwrap(); | ||
| 451 | - } | ||
| 452 | - assert!(matches!( | ||
| 453 | - a_file(&sub_a).insert(&db).await, | ||
| 454 | - Err(AppError::Conflict(_)) | ||
| 455 | - )); | ||
| 456 | - // The refusal wrote nothing at all: neither a row nor a seat. | ||
| 457 | - assert_eq!( | ||
| 458 | - HomeworkFile::count_for_submission(&sub_a, &db) | ||
| 459 | - .await | ||
| 460 | - .unwrap() as i64, | ||
| 461 | - stored_count(&sub_a, &db).await, | ||
| 462 | - ); | ||
| 463 | - assert_eq!( | ||
| 464 | - stored_count(&sub_a, &db).await, | ||
| 465 | - MAX_HOMEWORK_FILES_PER_SUBMISSION as i64 | ||
| 466 | - ); | ||
| 467 | - } | ||
| 468 | - | ||
| 469 | - /// A graded submission takes no more files and gives none up — decided by | ||
| 470 | - /// the same conditional write that claims the file slot, so no | ||
| 471 | - /// `homework_result` read stands between the check and the write. | ||
| 472 | - /// | ||
| 473 | - /// Bite check: drop [`SUBMISSION_OPEN_GUARD`] from `insert`'s | ||
| 474 | - /// [`cap::claim_when_and_create`] and the add below lands; drop it from | ||
| 475 | - /// `delete`'s gate and the delete below succeeds. | ||
| 476 | - #[tokio::test] | ||
| 477 | - async fn a_grade_freezes_the_files_too() { | ||
| 478 | - use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; | ||
| 479 | - | ||
| 480 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 481 | - let hw = a_homework(&db).await; | ||
| 482 | - let homework = hw.get_id().clone(); | ||
| 483 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 484 | - let submission = HomeworkSubmission::upsert(&hw, &user, None, &db) | ||
| 485 | - .await | ||
| 486 | - .unwrap() | ||
| 487 | - .unwrap(); | ||
| 488 | - let sub = submission.get_id().clone(); | ||
| 489 | - let stored = a_file(&sub).insert(&db).await.unwrap().unwrap(); | ||
| 490 | - | ||
| 491 | - HomeworkResult::grade( | ||
| 492 | - &homework, | ||
| 493 | - &user, | ||
| 494 | - HomeworkStatus::try_new("done").unwrap(), | ||
| 495 | - None, | ||
| 496 | - &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | ||
| 497 | - &db, | ||
| 498 | - ) | ||
| 499 | - .await | ||
| 500 | - .unwrap(); | ||
| 501 | - | ||
| 502 | - // Neither adding nor removing an attachment: `None` is the freeze, and | ||
| 503 | - // the cap's own `Err(Conflict)` stays distinct from it. | ||
| 504 | - assert!(a_file(&sub).insert(&db).await.unwrap().is_none()); | ||
| 505 | - assert!(stored.clone().delete(&db).await.unwrap().is_none()); | ||
| 506 | - assert_eq!( | ||
| 507 | - HomeworkFile::count_for_submission(&sub, &db).await.unwrap(), | ||
| 508 | - 1, | ||
| 509 | - "the graded submission keeps exactly the files it was graded on" | ||
| 510 | - ); | ||
| 511 | - // Refused by the *guard*, not the cap (nine seats free) — and still no | ||
| 512 | - // seat moved, so the counter matches the rows. | ||
| 513 | - assert_eq!(stored_count(&sub, &db).await, 1); | ||
| 514 | - // The refused add took no slot either, so un-grading gives back a | ||
| 515 | - // submission with room, not one that silently lost nine. | ||
| 516 | - HomeworkResult::remove(&homework, &user, &db).await.unwrap(); | ||
| 517 | - for _ in 1..MAX_HOMEWORK_FILES_PER_SUBMISSION { | ||
| 518 | - a_file(&sub).insert(&db).await.unwrap().unwrap(); | ||
| 519 | - } | ||
| 520 | - assert!(stored.delete(&db).await.unwrap().is_some()); | ||
| 521 | - } | ||
| 522 | } | 111 | } |
src/domain/homework_result.rsmodified+16 -458
| @@ -5,25 +5,22 @@ | |||
| 5 | //! and there is exactly one grade per (homework, user) by construction. | 5 | //! and there is exactly one grade per (homework, user) by construction. |
| 6 | //! | 6 | //! |
| 7 | //! A stored result is what *freezes* a submission: while a grade exists the | 7 | //! A stored result is what *freezes* a submission: while a grade exists the |
| 8 | -//! student's submission and files are locked (the web layer answers 409), until | 8 | +//! student's submission and files are locked (the web layer answers 409), |
| 9 | -//! the teacher removes the grade to reopen them. The teacher-set `missing` | 9 | +//! until the teacher removes the grade to reopen them. The teacher-set |
| 10 | -//! status is a deliberate verdict, distinct from the roster's *computed* | 10 | +//! `missing` status is a deliberate verdict, distinct from the roster's |
| 11 | -//! "missing" (unsubmitted past due) — the latter is derived in the web layer, | 11 | +//! *computed* "missing" (unsubmitted past due) — the latter is derived in the |
| 12 | -//! never stored. | 12 | +//! web layer, never stored. The grade transaction lives in |
| 13 | +//! [`crate::db::homework_result`], the grading gates in | ||
| 14 | +//! [`crate::service::homework_result`]. | ||
| 13 | 15 | ||
| 14 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 16 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 15 | 17 | ||
| 16 | -use crate::constant::{ | 18 | +use crate::constant::HOMEWORK_RESULT_TABLE; |
| 17 | - HOMEWORK_RESULT_TABLE, MARKS_GIVEN_TOTAL_FIELD, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, | ||
| 18 | -}; | ||
| 19 | -use crate::database::{Database, transaction_with_retry}; | ||
| 20 | -use crate::domain::course::CourseId; | ||
| 21 | use crate::domain::exam_result::Mark; | 19 | use crate::domain::exam_result::Mark; |
| 22 | use crate::domain::homework::HomeworkId; | 20 | use crate::domain::homework::HomeworkId; |
| 23 | -use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 24 | use crate::domain::timestamp::Timestamp; | 21 | use crate::domain::timestamp::Timestamp; |
| 25 | use crate::domain::user::UserId; | 22 | use crate::domain::user::UserId; |
| 26 | -use crate::error::{AppError, ValidationError}; | 23 | +use crate::error::ValidationError; |
| 27 | use crate::validate::validate_homework_status; | 24 | use crate::validate::validate_homework_status; |
| 28 | 25 | ||
| 29 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 26 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -78,13 +75,13 @@ impl HomeworkStatus { | |||
| 78 | 75 | ||
| 79 | #[derive(Debug, Clone, SurrealValue)] | 76 | #[derive(Debug, Clone, SurrealValue)] |
| 80 | pub struct HomeworkResult { | 77 | pub struct HomeworkResult { |
| 81 | - id: HomeworkResultId, | 78 | + pub(crate) id: HomeworkResultId, |
| 82 | - homework: HomeworkId, | 79 | + pub(crate) homework: HomeworkId, |
| 83 | - user: UserId, | 80 | + pub(crate) user: UserId, |
| 84 | - status: HomeworkStatus, | 81 | + pub(crate) status: HomeworkStatus, |
| 85 | - mark: Option<Mark>, | 82 | + pub(crate) mark: Option<Mark>, |
| 86 | - graded_by: UserId, | 83 | + pub(crate) graded_by: UserId, |
| 87 | - created_at: Timestamp, | 84 | + pub(crate) created_at: Timestamp, |
| 88 | } | 85 | } |
| 89 | 86 | ||
| 90 | impl HomeworkResult { | 87 | impl HomeworkResult { |
| @@ -116,250 +113,6 @@ impl HomeworkResult { | |||
| 116 | pub fn get_created_at(&self) -> Timestamp { | 113 | pub fn get_created_at(&self) -> Timestamp { |
| 117 | self.created_at | 114 | self.created_at |
| 118 | } | 115 | } |
| 119 | - | ||
| 120 | - /// Record (or overwrite) the grade for (homework, user). One row per pair, | ||
| 121 | - /// keyed by the deterministic composite id, so this is a single atomic | ||
| 122 | - /// UPSERT — concurrent grades for the same pair converge on one row instead | ||
| 123 | - /// of racing a unique index into a 500. Grading before the due date, or | ||
| 124 | - /// before any submission exists, is allowed (the caller's policy call). | ||
| 125 | - /// | ||
| 126 | - /// In the same transaction the grade *stamps* the student's submission | ||
| 127 | - /// ([`crate::constant::SUBMISSION_GRADED_FIELD`]), which is what freezes it: | ||
| 128 | - /// every student-side write to that row then fails its own | ||
| 129 | - /// `graded_by_result = NONE` condition, with no cross-table read for a | ||
| 130 | - /// concurrent write to slip past. A submission that does not exist yet is | ||
| 131 | - /// left alone — grading absent work must not conjure a hand-in (the report reads | ||
| 132 | - /// `submitted`/`missing`/`late` straight off that row). | ||
| 133 | - /// | ||
| 134 | - /// That one case is where this function stops defending itself: a student's | ||
| 135 | - /// *first* hand-in committing between this grade and nothing-to-stamp would | ||
| 136 | - /// land unstamped, leaving a grade beside an editable submission. Nothing | ||
| 137 | - /// here forbids it — what forbids it is the caller. Grading holds | ||
| 138 | - /// `HOMEWORK_LOCK` (see `crate::web::homework`) for writing across this | ||
| 139 | - /// whole transaction while every student-side write holds it for reading across | ||
| 140 | - /// its own, and the two leases are mutually exclusive in the one process | ||
| 141 | - /// this backend runs as, so the interleaving never gets a window. | ||
| 142 | - // | ||
| 143 | - // corner-cut: that makes the freeze depend on lock discipline at the call | ||
| 144 | - // sites, not on this row. Moving a student write's lease to *after* its | ||
| 145 | - // database write — or sharding HOMEWORK_LOCK per homework — reopens the | ||
| 146 | - // window with nothing to catch it. Closing it in the domain layer needs a | ||
| 147 | - // record both sides own (a per-(homework, user) row the grade can always | ||
| 148 | - // stamp); a tombstone submission is not it, since every read path would | ||
| 149 | - // have to learn to ignore it and one missed filter fabricates a hand-in. | ||
| 150 | - pub async fn grade( | ||
| 151 | - homework: &HomeworkId, | ||
| 152 | - user: &UserId, | ||
| 153 | - status: HomeworkStatus, | ||
| 154 | - mark: Option<Mark>, | ||
| 155 | - graded_by: &UserId, | ||
| 156 | - db: &Database, | ||
| 157 | - ) -> Result<HomeworkResult, AppError> { | ||
| 158 | - let id = HomeworkResultId::composite(homework, user); | ||
| 159 | - let submission = HomeworkSubmissionId::composite(homework, user); | ||
| 160 | - let result = HomeworkResult { | ||
| 161 | - id: id.clone(), | ||
| 162 | - homework: homework.clone(), | ||
| 163 | - user: user.clone(), | ||
| 164 | - status, | ||
| 165 | - mark, | ||
| 166 | - graded_by: graded_by.clone(), | ||
| 167 | - created_at: Timestamp::now(), | ||
| 168 | - }; | ||
| 169 | - // Whether the pair was already graded is read one statement ahead of | ||
| 170 | - // the write, inside the same transaction — it is what keeps a regrade | ||
| 171 | - // from crediting the grader a second time. No mark counter here: a | ||
| 172 | - // homework mark is optional and most grades are status-only, so | ||
| 173 | - // `high_mark` is an exam-only family. | ||
| 174 | - // | ||
| 175 | - // The first three statements are the parent gate, the twin of | ||
| 176 | - // [`crate::domain::homework_submission::HomeworkSubmission::upsert`]'s | ||
| 177 | - // and written the same way on purpose: the id is deterministic, so a | ||
| 178 | - // grade landing inside a homework (or course) delete's window does not | ||
| 179 | - // fail — it *re-creates* a result row under a homework that is gone, | ||
| 180 | - // readable ever after at `GET /homework/{id}/result` (no existence check | ||
| 181 | - // there) with a `marks_given_total` no ungrade can reach, because every | ||
| 182 | - // route to the grade goes through the homework. Reading the homework | ||
| 183 | - // first — which the web layer does, under the lease — cannot close that: | ||
| 184 | - // the store conflict-checks write sets, not read sets. So the gate | ||
| 185 | - // *moves* a value on the homework row (`due_at` up by one and straight | ||
| 186 | - // back to the captured value, leaving the row byte-identical) and the | ||
| 187 | - // cascade's delete of that same row is what refuses it. `homework` owns | ||
| 188 | - // no counter column and is SCHEMAFULL, so `due_at` is the one `int` it | ||
| 189 | - // already has; do not invent a second spelling. | ||
| 190 | - // | ||
| 191 | - // Not [`crate::db::cap::touch_and_create`], which is the same shape | ||
| 192 | - // for a bare `CREATE`: a grade is an UPSERT (a regrade must overwrite), | ||
| 193 | - // and the freeze stamp and the grader's counter have to ride the same | ||
| 194 | - // transaction, which that helper has no room for. | ||
| 195 | - // | ||
| 196 | - // Sound to re-send, which is what the gate needed first — a `THROW` | ||
| 197 | - // inside a plain `db.query` would have turned every lost round into a | ||
| 198 | - // 500. `SELECT`, `UPDATE` and the `IF`/`THROW` can never answer "already | ||
| 199 | - // exists", and the `UPSERT`'s id is bijective with the (homework, user) | ||
| 200 | - // pair the table keys, on a table whose only index is non-unique | ||
| 201 | - // (`homework_result_homework`), so its index entry can only ever point | ||
| 202 | - // at the row the id already names: it resolves onto that row instead of | ||
| 203 | - // colliding with it. A lost round wrote nothing. | ||
| 204 | - let (mut saved, mut errors) = transaction_with_retry( | ||
| 205 | - db, | ||
| 206 | - &format!( | ||
| 207 | - "BEGIN TRANSACTION; | ||
| 208 | - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | ||
| 209 | - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | ||
| 210 | - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | ||
| 211 | - UPDATE $hw SET due_at = $was_due; | ||
| 212 | - LET $before = (SELECT VALUE id FROM ONLY $id); | ||
| 213 | - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); | ||
| 214 | - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = $id \ | ||
| 215 | - WHERE {SUBMISSION_OPEN_GUARD}; | ||
| 216 | - IF $before = NONE {{ | ||
| 217 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | ||
| 218 | - ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) + 1 | ||
| 219 | - }}; | ||
| 220 | - RETURN $after; | ||
| 221 | - COMMIT TRANSACTION;" | ||
| 222 | - ), | ||
| 223 | - &[ | ||
| 224 | - ("hw".into(), homework.record().into_value()), | ||
| 225 | - ("id".into(), id.record().into_value()), | ||
| 226 | - ("sub".into(), submission.record().into_value()), | ||
| 227 | - ("grader".into(), graded_by.record().into_value()), | ||
| 228 | - ("row".into(), result.into_value()), | ||
| 229 | - ], | ||
| 230 | - &["no_homework"], | ||
| 231 | - ) | ||
| 232 | - .await?; | ||
| 233 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 234 | - // executed" — only the THROW's own slot names the reason. | ||
| 235 | - if errors | ||
| 236 | - .values() | ||
| 237 | - .any(|error| error.to_string().contains("no_homework")) | ||
| 238 | - { | ||
| 239 | - return Err(AppError::NotFound); | ||
| 240 | - } | ||
| 241 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 242 | - return Err(error.into()); | ||
| 243 | - } | ||
| 244 | - // The trailing `RETURN` is always the last statement before `COMMIT`, | ||
| 245 | - // so its slot follows the statement count instead of a hand-kept | ||
| 246 | - // number — which the gate above would otherwise have shifted, silently | ||
| 247 | - // handing back something else. | ||
| 248 | - let slot = saved.num_statements().saturating_sub(2); | ||
| 249 | - saved | ||
| 250 | - .take::<Vec<HomeworkResult>>(slot)? | ||
| 251 | - .into_iter() | ||
| 252 | - .next() | ||
| 253 | - .ok_or_else(|| AppError::Internal("failed to record homework result".into())) | ||
| 254 | - } | ||
| 255 | - | ||
| 256 | - /// `user`'s grade for `homework`, if graded. | ||
| 257 | - pub async fn read_for( | ||
| 258 | - homework: &HomeworkId, | ||
| 259 | - user: &UserId, | ||
| 260 | - db: &Database, | ||
| 261 | - ) -> Result<Option<HomeworkResult>, AppError> { | ||
| 262 | - Ok(db | ||
| 263 | - .select(HomeworkResultId::composite(homework, user).record()) | ||
| 264 | - .await?) | ||
| 265 | - } | ||
| 266 | - | ||
| 267 | - /// Every grade for `homework` — the roster joins these onto the submissions. | ||
| 268 | - pub async fn list_for_homework( | ||
| 269 | - homework: &HomeworkId, | ||
| 270 | - db: &Database, | ||
| 271 | - ) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 272 | - let mut result = db | ||
| 273 | - .query("SELECT * FROM homework_result WHERE homework = $hw ORDER BY id DESC") | ||
| 274 | - .bind(("hw", homework.record())) | ||
| 275 | - .await? | ||
| 276 | - .check()?; | ||
| 277 | - Ok(result.take::<Vec<HomeworkResult>>(0)?) | ||
| 278 | - } | ||
| 279 | - | ||
| 280 | - /// `user`'s homework grades across one course — the raw rows behind the | ||
| 281 | - /// per-course block of a homework report. Mirrors | ||
| 282 | - /// `ExamResult::list_for_user_in_course`. | ||
| 283 | - pub async fn list_for_user_in_course( | ||
| 284 | - course: &CourseId, | ||
| 285 | - user: &UserId, | ||
| 286 | - db: &Database, | ||
| 287 | - ) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 288 | - let mut result = db | ||
| 289 | - .query( | ||
| 290 | - "SELECT * FROM homework_result WHERE user = $usr | ||
| 291 | - AND homework IN (SELECT VALUE id FROM homework WHERE course = $course) | ||
| 292 | - ORDER BY id DESC", | ||
| 293 | - ) | ||
| 294 | - .bind(("usr", user.record())) | ||
| 295 | - .bind(("course", course.record())) | ||
| 296 | - .await? | ||
| 297 | - .check()?; | ||
| 298 | - Ok(result.take::<Vec<HomeworkResult>>(0)?) | ||
| 299 | - } | ||
| 300 | - | ||
| 301 | - /// Un-grade (homework, user), returning the removed row (`None` if there | ||
| 302 | - /// was none). Removing the grade unfreezes the student's submission, so the | ||
| 303 | - /// stamp [`grade`](Self::grade) left on it is cleared in the same | ||
| 304 | - /// transaction — scoped to *this* grade's id, so it can never wipe a stamp a | ||
| 305 | - /// concurrent re-grade has just written. | ||
| 306 | - /// | ||
| 307 | - /// The grader's `marks_given_total` comes back with it, in that same | ||
| 308 | - /// transaction and only when a row was really deleted. [`grade`](Self::grade) | ||
| 309 | - /// credits on the branch that finds no row, and a deleted row *is* no row: | ||
| 310 | - /// left standing, ungrade-then-regrade credited a second time off one | ||
| 311 | - /// stored grade, and looped it minted a badge with no exam, no mark and no | ||
| 312 | - /// submission behind it — permanently, since an award is never revoked. | ||
| 313 | - /// Given back to the *removed row's own* grader, not the caller: a manager | ||
| 314 | - /// may un-grade what a teacher graded, and the credit is the teacher's. | ||
| 315 | - /// | ||
| 316 | - /// Sound to re-send while the store answers "conflict, retry" — this is the | ||
| 317 | - /// upgrade `grade` still wants, taken here because the counter above is what | ||
| 318 | - /// makes it necessary: the grader's row is written by exam grading too, so | ||
| 319 | - /// the delete now contends with another domain, and only `DELETE`/`UPDATE` | ||
| 320 | - /// are in the batch, none of which can legitimately answer "already exists". | ||
| 321 | - pub async fn remove( | ||
| 322 | - homework: &HomeworkId, | ||
| 323 | - user: &UserId, | ||
| 324 | - db: &Database, | ||
| 325 | - ) -> Result<Option<HomeworkResult>, AppError> { | ||
| 326 | - let id = HomeworkResultId::composite(homework, user); | ||
| 327 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 328 | - db, | ||
| 329 | - &format!( | ||
| 330 | - "BEGIN TRANSACTION; | ||
| 331 | - LET $gone = (DELETE $id RETURN BEFORE); | ||
| 332 | - UPDATE $sub SET {SUBMISSION_GRADED_FIELD} = NONE \ | ||
| 333 | - WHERE {SUBMISSION_GRADED_FIELD} = $id; | ||
| 334 | - IF array::len($gone) > 0 {{ | ||
| 335 | - LET $grader = $gone[0].graded_by; | ||
| 336 | - UPDATE $grader SET {MARKS_GIVEN_TOTAL_FIELD} = | ||
| 337 | - math::max([({MARKS_GIVEN_TOTAL_FIELD} ?? 0) - 1, 0]) | ||
| 338 | - }}; | ||
| 339 | - RETURN $gone; | ||
| 340 | - COMMIT TRANSACTION;" | ||
| 341 | - ), | ||
| 342 | - &[ | ||
| 343 | - ("id".into(), id.record().into_value()), | ||
| 344 | - ( | ||
| 345 | - "sub".into(), | ||
| 346 | - HomeworkSubmissionId::composite(homework, user) | ||
| 347 | - .record() | ||
| 348 | - .into_value(), | ||
| 349 | - ), | ||
| 350 | - ], | ||
| 351 | - &[], | ||
| 352 | - ) | ||
| 353 | - .await?; | ||
| 354 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 355 | - return Err(error.into()); | ||
| 356 | - } | ||
| 357 | - // The trailing `RETURN` is always the last statement before `COMMIT`, so | ||
| 358 | - // its slot follows the statement count — the hand-kept "slot 1" this | ||
| 359 | - // replaces was one added statement away from handing back the unstamp. | ||
| 360 | - let slot = result.num_statements().saturating_sub(2); | ||
| 361 | - Ok(result.take::<Vec<HomeworkResult>>(slot)?.into_iter().next()) | ||
| 362 | - } | ||
| 363 | } | 116 | } |
| 364 | 117 | ||
| 365 | #[cfg(test)] | 118 | #[cfg(test)] |
| @@ -368,38 +121,6 @@ mod tests { | |||
| 368 | use crate::constant::HOMEWORK_STATUSES; | 121 | use crate::constant::HOMEWORK_STATUSES; |
| 369 | use surrealdb::types::Value; | 122 | use surrealdb::types::Value; |
| 370 | 123 | ||
| 371 | - /// A real homework row (with the course and subject it needs): the grade now | ||
| 372 | - /// carries a parent gate, so a minted id nothing wrote is a `404` here, the | ||
| 373 | - /// same way it already is for a submission. | ||
| 374 | - async fn a_homework(db: &Database) -> HomeworkId { | ||
| 375 | - use crate::domain::homework::{Homework, HomeworkTitle}; | ||
| 376 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 377 | - | ||
| 378 | - let course = crate::db::course::a_test_course(db).await; | ||
| 379 | - let subject = Subject::create( | ||
| 380 | - &course, | ||
| 381 | - SubjectName::try_new("topic").unwrap(), | ||
| 382 | - SubjectDescription::try_new("").unwrap(), | ||
| 383 | - db, | ||
| 384 | - ) | ||
| 385 | - .await | ||
| 386 | - .unwrap(); | ||
| 387 | - Homework::create( | ||
| 388 | - &course, | ||
| 389 | - subject.get_id(), | ||
| 390 | - HomeworkTitle::try_new("essay").unwrap(), | ||
| 391 | - None, | ||
| 392 | - Timestamp::from_millis(1), | ||
| 393 | - None, | ||
| 394 | - &UserId::from_key("teacher"), | ||
| 395 | - db, | ||
| 396 | - ) | ||
| 397 | - .await | ||
| 398 | - .unwrap() | ||
| 399 | - .get_id() | ||
| 400 | - .clone() | ||
| 401 | - } | ||
| 402 | - | ||
| 403 | #[tokio::test] | 124 | #[tokio::test] |
| 404 | async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { | 125 | async fn status_is_held_to_the_const_and_stores_as_a_bare_string() { |
| 405 | // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL | 126 | // Enforcement lives in the newtype against HOMEWORK_STATUSES (the DDL |
| @@ -413,167 +134,4 @@ mod tests { | |||
| 413 | assert!(HomeworkStatus::try_new("late").is_err()); | 134 | assert!(HomeworkStatus::try_new("late").is_err()); |
| 414 | assert!(HomeworkStatus::try_new("").is_err()); | 135 | assert!(HomeworkStatus::try_new("").is_err()); |
| 415 | } | 136 | } |
| 416 | - | ||
| 417 | - #[tokio::test] | ||
| 418 | - async fn grade_upserts_one_row_per_pair_and_remove_unfreezes() { | ||
| 419 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 420 | - let homework = a_homework(&db).await; | ||
| 421 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 422 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 423 | - | ||
| 424 | - let first = HomeworkResult::grade( | ||
| 425 | - &homework, | ||
| 426 | - &user, | ||
| 427 | - HomeworkStatus::try_new("incomplete").unwrap(), | ||
| 428 | - None, | ||
| 429 | - &teacher, | ||
| 430 | - &db, | ||
| 431 | - ) | ||
| 432 | - .await | ||
| 433 | - .unwrap(); | ||
| 434 | - // A regrade lands on the same row (composite id), overwriting the grade. | ||
| 435 | - let second = HomeworkResult::grade( | ||
| 436 | - &homework, | ||
| 437 | - &user, | ||
| 438 | - HomeworkStatus::try_new("done").unwrap(), | ||
| 439 | - Some(Mark::try_new(80).unwrap()), | ||
| 440 | - &teacher, | ||
| 441 | - &db, | ||
| 442 | - ) | ||
| 443 | - .await | ||
| 444 | - .unwrap(); | ||
| 445 | - assert_eq!(first.get_id(), second.get_id()); | ||
| 446 | - assert_eq!(second.get_status().as_str(), "done"); | ||
| 447 | - assert_eq!(second.get_mark().unwrap().as_i64(), 80); | ||
| 448 | - assert_eq!( | ||
| 449 | - HomeworkResult::list_for_homework(&homework, &db) | ||
| 450 | - .await | ||
| 451 | - .unwrap() | ||
| 452 | - .len(), | ||
| 453 | - 1 | ||
| 454 | - ); | ||
| 455 | - | ||
| 456 | - assert!( | ||
| 457 | - HomeworkResult::read_for(&homework, &user, &db) | ||
| 458 | - .await | ||
| 459 | - .unwrap() | ||
| 460 | - .is_some() | ||
| 461 | - ); | ||
| 462 | - assert!( | ||
| 463 | - HomeworkResult::remove(&homework, &user, &db) | ||
| 464 | - .await | ||
| 465 | - .unwrap() | ||
| 466 | - .is_some() | ||
| 467 | - ); | ||
| 468 | - assert!( | ||
| 469 | - HomeworkResult::read_for(&homework, &user, &db) | ||
| 470 | - .await | ||
| 471 | - .unwrap() | ||
| 472 | - .is_none() | ||
| 473 | - ); | ||
| 474 | - } | ||
| 475 | - | ||
| 476 | - /// The grader is credited once per graded pair: a regrade lands on the same | ||
| 477 | - /// row, so it is not a mark given twice. The student's counters are not | ||
| 478 | - /// touched at all — a homework grade is not a homework submission. | ||
| 479 | - #[tokio::test] | ||
| 480 | - async fn a_first_grade_credits_the_grader_and_a_regrade_does_not() { | ||
| 481 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 482 | - let homework = a_homework(&db).await; | ||
| 483 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 484 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 485 | - // `UPDATE` writes nothing to a user row that does not exist. | ||
| 486 | - db.query("CREATE $usr SET username = 't', password_hash = 'x'") | ||
| 487 | - .bind(("usr", teacher.record())) | ||
| 488 | - .await | ||
| 489 | - .unwrap() | ||
| 490 | - .check() | ||
| 491 | - .unwrap(); | ||
| 492 | - | ||
| 493 | - for status in ["incomplete", "done"] { | ||
| 494 | - HomeworkResult::grade( | ||
| 495 | - &homework, | ||
| 496 | - &user, | ||
| 497 | - HomeworkStatus::try_new(status).unwrap(), | ||
| 498 | - None, | ||
| 499 | - &teacher, | ||
| 500 | - &db, | ||
| 501 | - ) | ||
| 502 | - .await | ||
| 503 | - .unwrap(); | ||
| 504 | - } | ||
| 505 | - assert_eq!( | ||
| 506 | - marks_given(&teacher, &db).await, | ||
| 507 | - 1, | ||
| 508 | - "one graded pair, one mark given" | ||
| 509 | - ); | ||
| 510 | - } | ||
| 511 | - | ||
| 512 | - /// Un-grading gives the credit back, so grade → ungrade → regrade nets to | ||
| 513 | - /// one however often it is run. Crediting the grade without refunding the | ||
| 514 | - /// delete was the cheapest counter farm in the codebase — two requests per | ||
| 515 | - /// mark given, with no exam, no mark and no submission behind them. | ||
| 516 | - #[tokio::test] | ||
| 517 | - async fn ungrading_gives_the_grader_credit_back() { | ||
| 518 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 519 | - let homework = a_homework(&db).await; | ||
| 520 | - let user = UserId::from_key("01TESTUSERAAAAAAAAAAAAAAAA"); | ||
| 521 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 522 | - db.query("CREATE $usr SET username = 't', password_hash = 'x'") | ||
| 523 | - .bind(("usr", teacher.record())) | ||
| 524 | - .await | ||
| 525 | - .unwrap() | ||
| 526 | - .check() | ||
| 527 | - .unwrap(); | ||
| 528 | - | ||
| 529 | - for _ in 0..3 { | ||
| 530 | - HomeworkResult::grade( | ||
| 531 | - &homework, | ||
| 532 | - &user, | ||
| 533 | - HomeworkStatus::try_new("missing").unwrap(), | ||
| 534 | - None, | ||
| 535 | - &teacher, | ||
| 536 | - &db, | ||
| 537 | - ) | ||
| 538 | - .await | ||
| 539 | - .unwrap(); | ||
| 540 | - assert_eq!(marks_given(&teacher, &db).await, 1); | ||
| 541 | - assert!( | ||
| 542 | - HomeworkResult::remove(&homework, &user, &db) | ||
| 543 | - .await | ||
| 544 | - .unwrap() | ||
| 545 | - .is_some(), | ||
| 546 | - "the grade was there" | ||
| 547 | - ); | ||
| 548 | - assert_eq!(marks_given(&teacher, &db).await, 0, "the loop kept one"); | ||
| 549 | - } | ||
| 550 | - | ||
| 551 | - // Nothing to remove is nothing to give back — the floor holds. | ||
| 552 | - assert!( | ||
| 553 | - HomeworkResult::remove(&homework, &user, &db) | ||
| 554 | - .await | ||
| 555 | - .unwrap() | ||
| 556 | - .is_none() | ||
| 557 | - ); | ||
| 558 | - assert_eq!(marks_given(&teacher, &db).await, 0); | ||
| 559 | - } | ||
| 560 | - | ||
| 561 | - /// The grader's badge counter, re-read out of the store. | ||
| 562 | - async fn marks_given(user: &UserId, db: &Database) -> i64 { | ||
| 563 | - let mut result = db | ||
| 564 | - .query(format!( | ||
| 565 | - "SELECT VALUE ({MARKS_GIVEN_TOTAL_FIELD} ?? 0) FROM $usr" | ||
| 566 | - )) | ||
| 567 | - .bind(("usr", user.record())) | ||
| 568 | - .await | ||
| 569 | - .unwrap() | ||
| 570 | - .check() | ||
| 571 | - .unwrap(); | ||
| 572 | - result | ||
| 573 | - .take::<Vec<i64>>(0) | ||
| 574 | - .unwrap() | ||
| 575 | - .into_iter() | ||
| 576 | - .next() | ||
| 577 | - .unwrap_or(0) | ||
| 578 | - } | ||
| 579 | } | 137 | } |
src/domain/homework_submission.rsmodified+17 -746
| @@ -5,24 +5,22 @@ | |||
| 5 | //! UPSERT. | 5 | //! UPSERT. |
| 6 | //! | 6 | //! |
| 7 | //! `submitted_at` — the first-submit stamp — is `READONLY` and survives every | 7 | //! `submitted_at` — the first-submit stamp — is `READONLY` and survives every |
| 8 | -//! re-submit; [`HomeworkSubmission::upsert`] preserves it inside one statement | 8 | +//! re-submit; [`crate::db::homework_submission::upsert`] preserves it inside one |
| 9 | -//! rather than through `.content()`, see there. `updated_at` moves to now on | 9 | +//! statement rather than through `.content()`, see there. `updated_at` moves to |
| 10 | -//! every (re-)submit (and, later, on a file add/delete) and drives the computed | 10 | +//! now on every (re-)submit (and, later, on a file add/delete) and drives the |
| 11 | -//! "late" flag (`updated_at > homework.due_at`, judged in the web layer, never | 11 | +//! computed "late" flag (`updated_at > homework.due_at`, judged in the web |
| 12 | -//! stored): `submitted_at` answers "was the first hand-in on time", `updated_at` | 12 | +//! layer, never stored): `submitted_at` answers "was the first hand-in on |
| 13 | -//! "was it touched after the deadline". | 13 | +//! time", `updated_at` "was it touched after the deadline". The row writes |
| 14 | +//! live in [`crate::db::homework_submission`], the submit/withdraw workflows | ||
| 15 | +//! in [`crate::service::homework_submission`]. | ||
| 14 | 16 | ||
| 15 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 17 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 16 | 18 | ||
| 17 | -use crate::constant::{ | 19 | +use crate::constant::{HOMEWORK_SUBMISSION_TABLE, MAX_HOMEWORK_TEXT_LEN}; |
| 18 | - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMISSION_TABLE, HOMEWORK_SUBMITTED_TOTAL_FIELD, | 20 | +use crate::domain::homework::HomeworkId; |
| 19 | - MAX_HOMEWORK_TEXT_LEN, SUBMISSION_GRADED_FIELD, SUBMISSION_OPEN_GUARD, | ||
| 20 | -}; | ||
| 21 | -use crate::database::{Database, transaction_with_retry}; | ||
| 22 | -use crate::domain::homework::{Homework, HomeworkId}; | ||
| 23 | use crate::domain::timestamp::Timestamp; | 21 | use crate::domain::timestamp::Timestamp; |
| 24 | use crate::domain::user::UserId; | 22 | use crate::domain::user::UserId; |
| 25 | -use crate::error::{AppError, ValidationError}; | 23 | +use crate::error::ValidationError; |
| 26 | use crate::validate::validate_optional; | 24 | use crate::validate::validate_optional; |
| 27 | 25 | ||
| 28 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 26 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -70,12 +68,12 @@ impl SubmissionText { | |||
| 70 | 68 | ||
| 71 | #[derive(Debug, Clone, SurrealValue)] | 69 | #[derive(Debug, Clone, SurrealValue)] |
| 72 | pub struct HomeworkSubmission { | 70 | pub struct HomeworkSubmission { |
| 73 | - id: HomeworkSubmissionId, | 71 | + pub(crate) id: HomeworkSubmissionId, |
| 74 | - homework: HomeworkId, | 72 | + pub(crate) homework: HomeworkId, |
| 75 | - user: UserId, | 73 | + pub(crate) user: UserId, |
| 76 | - text: Option<SubmissionText>, | 74 | + pub(crate) text: Option<SubmissionText>, |
| 77 | - submitted_at: Timestamp, | 75 | + pub(crate) submitted_at: Timestamp, |
| 78 | - updated_at: Timestamp, | 76 | + pub(crate) updated_at: Timestamp, |
| 79 | } | 77 | } |
| 80 | 78 | ||
| 81 | impl HomeworkSubmission { | 79 | impl HomeworkSubmission { |
| @@ -102,743 +100,16 @@ impl HomeworkSubmission { | |||
| 102 | pub fn get_updated_at(&self) -> Timestamp { | 100 | pub fn get_updated_at(&self) -> Timestamp { |
| 103 | self.updated_at | 101 | self.updated_at |
| 104 | } | 102 | } |
| 105 | - | ||
| 106 | - /// Create or re-stamp `user`'s submission to `homework`, unless a grade has | ||
| 107 | - /// frozen it — `None` means frozen, and the caller answers 409. `updated_at` | ||
| 108 | - /// moves to now every time; `submitted_at` (readonly, the first-submit stamp) | ||
| 109 | - /// is kept on an existing row and set only on a fresh one. | ||
| 110 | - /// | ||
| 111 | - /// Hand-written rather than `.content()` on purpose: `.content()` re-sends | ||
| 112 | - /// the whole row, so it would carry a `submitted_at`, and any value differing | ||
| 113 | - /// from the stored one trips the readonly guard. The | ||
| 114 | - /// `submitted_at = submitted_at ?? $now` expression preserves it inside the | ||
| 115 | - /// one UPSERT statement — race-free without a lock, where a read-then-content | ||
| 116 | - /// could let two concurrent first-submits pick different stamps and 500. | ||
| 117 | - /// | ||
| 118 | - /// The `WHERE` is the freeze: [`SUBMISSION_OPEN_GUARD`] makes "not graded | ||
| 119 | - /// yet" a condition of this very write instead of a read a concurrent grade | ||
| 120 | - /// can land behind. An absent row satisfies it (the stamp is `NONE` there | ||
| 121 | - /// too), so a first submit still creates. | ||
| 122 | - /// | ||
| 123 | - /// The badge counters on the student's user row move in this very | ||
| 124 | - /// transaction, and the order is load-bearing: the increment sits *after* | ||
| 125 | - /// the UPSERT and is conditional on it having matched a row, because a | ||
| 126 | - /// frozen row makes that `WHERE` match nothing **silently** (unlike | ||
| 127 | - /// [`crate::domain::exam_result::ExamResult::grade`], which `THROW`s) — put | ||
| 128 | - /// first, it would count a submission the freeze refused. `$before = NONE` | ||
| 129 | - /// keeps it to a genuine first create, so an edit moves neither counter, | ||
| 130 | - /// which is what makes the live count mean the same thing the one-time | ||
| 131 | - /// backfill seeded (one per row; on time judged against `due_at`, equal | ||
| 132 | - /// counting as on time). | ||
| 133 | - /// | ||
| 134 | - /// `counted_on_time` is stamped on the row from the *same* `$on_time` | ||
| 135 | - /// expression the increment adds, in the same statement block: the deadline | ||
| 136 | - /// is mutable, so a withdrawal that re-judged it against the live `due_at` | ||
| 137 | - /// gave back something other than what was taken. Writing the verdict beside | ||
| 138 | - /// the counter is what keeps the two from ever disagreeing — read back by | ||
| 139 | - /// [`HomeworkSubmission::delete`], never re-derived. | ||
| 140 | - /// | ||
| 141 | - /// That deadline is `$was_due`, the one the gate below already read *inside | ||
| 142 | - /// this transaction* — never the caller's [`Homework`] snapshot, which was | ||
| 143 | - /// read before the lease and is exactly one `PATCH due_at` old in the | ||
| 144 | - /// "teacher extends the deadline at 23:59 while the class submits" moment. | ||
| 145 | - /// Judging on the snapshot stored a verdict the web layer's own `late` flag | ||
| 146 | - /// (`updated_at > due_at`, re-derived live on every read) then contradicted | ||
| 147 | - /// forever, in both directions. An in-process lock cannot fix this — it | ||
| 148 | - /// orders two handlers, not two store transactions — so the comparison has | ||
| 149 | - /// to live where the write does. The whole entity is still taken (both | ||
| 150 | - /// callers hold the row, and the id comes off it); its `due_at` must not be. | ||
| 151 | - /// | ||
| 152 | - /// The first three statements are the parent gate, and they are why this | ||
| 153 | - /// write cannot outlive its homework: the id is deterministic, so nothing | ||
| 154 | - /// else here would fail against a homework a cascade already removed — it | ||
| 155 | - /// would simply re-create the row, badge counters and all, unreachable ever | ||
| 156 | - /// after (every route to a submission goes through its homework). A *read* | ||
| 157 | - /// of the homework does not close that, on either side of the call: the | ||
| 158 | - /// store does no read-set conflict detection, so a delete committing | ||
| 159 | - /// alongside is invisible to it. The gate therefore *moves* a value on the | ||
| 160 | - /// homework row — `due_at` up by one and straight back to the captured | ||
| 161 | - /// value, so the row is byte-identical afterwards — because only a write | ||
| 162 | - /// collides, and `SET x = x` is elided and never reaches the write set. It | ||
| 163 | - /// is [`crate::domain::exam_answer::ExamAnswer::save`]'s shape exactly. | ||
| 164 | - /// `Err(NotFound)` means the homework is gone, which is the 404 the web | ||
| 165 | - /// layer's own lookup would have answered. | ||
| 166 | - pub async fn upsert( | ||
| 167 | - homework: &Homework, | ||
| 168 | - user: &UserId, | ||
| 169 | - text: Option<SubmissionText>, | ||
| 170 | - db: &Database, | ||
| 171 | - ) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 172 | - let id = HomeworkSubmissionId::composite(homework.get_id(), user); | ||
| 173 | - let now = Timestamp::now(); | ||
| 174 | - let text = text.map(|text| text.as_str().to_string()); | ||
| 175 | - // Sound to re-send: the UPSERT is on a deterministic id on a table with | ||
| 176 | - // no unique index, so it can never legitimately answer "already exists", | ||
| 177 | - // and the counter UPDATEs never can either. | ||
| 178 | - let (mut saved, mut errors) = transaction_with_retry( | ||
| 179 | - db, | ||
| 180 | - &format!( | ||
| 181 | - "BEGIN TRANSACTION; | ||
| 182 | - LET $was_due = (SELECT VALUE due_at FROM ONLY $hw); | ||
| 183 | - LET $alive = (UPDATE $hw SET due_at = due_at + 1 RETURN VALUE id); | ||
| 184 | - IF array::len($alive) = 0 {{ THROW 'no_homework' }}; | ||
| 185 | - UPDATE $hw SET due_at = $was_due; | ||
| 186 | - LET $before = (SELECT VALUE id FROM ONLY $id); | ||
| 187 | - LET $on_time = $now <= $was_due; | ||
| 188 | - LET $after = (UPSERT $id SET homework = $hw, user = $usr, text = $text, | ||
| 189 | - updated_at = $now, submitted_at = submitted_at ?? $now | ||
| 190 | - WHERE {SUBMISSION_OPEN_GUARD} RETURN AFTER); | ||
| 191 | - IF $before = NONE AND array::len($after) > 0 {{ | ||
| 192 | - UPDATE $id SET counted_on_time = $on_time; | ||
| 193 | - UPDATE $usr SET | ||
| 194 | - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = ({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) + 1, | ||
| 195 | - {HOMEWORK_ON_TIME_TOTAL_FIELD} = ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) | ||
| 196 | - + IF $on_time {{ 1 }} ELSE {{ 0 }} | ||
| 197 | - }}; | ||
| 198 | - RETURN $after; | ||
| 199 | - COMMIT TRANSACTION;" | ||
| 200 | - ), | ||
| 201 | - &[ | ||
| 202 | - ("id".into(), id.record().into_value()), | ||
| 203 | - ("hw".into(), homework.get_id().record().into_value()), | ||
| 204 | - ("usr".into(), user.record().into_value()), | ||
| 205 | - ("text".into(), text.into_value()), | ||
| 206 | - ("now".into(), now.into_value()), | ||
| 207 | - ], | ||
| 208 | - &["no_homework"], | ||
| 209 | - ) | ||
| 210 | - .await?; | ||
| 211 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 212 | - // executed" — only the THROW's own slot names the reason. | ||
| 213 | - if errors | ||
| 214 | - .values() | ||
| 215 | - .any(|error| error.to_string().contains("no_homework")) | ||
| 216 | - { | ||
| 217 | - return Err(AppError::NotFound); | ||
| 218 | - } | ||
| 219 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 220 | - return Err(error.into()); | ||
| 221 | - } | ||
| 222 | - // The trailing `RETURN` is always the last statement before `COMMIT`, so | ||
| 223 | - // its slot follows the statement count rather than a hand-kept number. | ||
| 224 | - // It returns the whole array, never `$after[0]`: a refused write makes | ||
| 225 | - // that `NONE`, which fails to deserialize ("expected object, got none") | ||
| 226 | - // instead of reading as the "frozen" the caller answers 409 to. | ||
| 227 | - let slot = saved.num_statements().saturating_sub(2); | ||
| 228 | - Ok(saved | ||
| 229 | - .take::<Vec<HomeworkSubmission>>(slot)? | ||
| 230 | - .into_iter() | ||
| 231 | - .next()) | ||
| 232 | - } | ||
| 233 | - | ||
| 234 | - /// Re-stamp a submission's `updated_at` to now, leaving its text and files | ||
| 235 | - /// alone. A file add or delete modifies the submission as a whole, so its | ||
| 236 | - /// "last touched" clock — which drives the computed late flag — must move | ||
| 237 | - /// even though the text row is unchanged. Static because the file paths hold | ||
| 238 | - /// the composite id, not always the row. A targeted single-field UPDATE, so | ||
| 239 | - /// the `READONLY` `submitted_at` is never re-sent (a `.content()` would trip | ||
| 240 | - /// its guard). Returns the re-stamped row, or a 404 if it has since vanished. | ||
| 241 | - pub async fn touch( | ||
| 242 | - id: &HomeworkSubmissionId, | ||
| 243 | - db: &Database, | ||
| 244 | - ) -> Result<HomeworkSubmission, AppError> { | ||
| 245 | - let now = Timestamp::now(); | ||
| 246 | - let mut result = db | ||
| 247 | - .query("UPDATE $id SET updated_at = $now RETURN AFTER") | ||
| 248 | - .bind(("id", id.record())) | ||
| 249 | - .bind(("now", now)) | ||
| 250 | - .await? | ||
| 251 | - .check()?; | ||
| 252 | - result | ||
| 253 | - .take::<Vec<HomeworkSubmission>>(0)? | ||
| 254 | - .into_iter() | ||
| 255 | - .next() | ||
| 256 | - .ok_or(AppError::NotFound) | ||
| 257 | - } | ||
| 258 | - | ||
| 259 | - /// Whether a grade has frozen this submission. Only ever read to tell two | ||
| 260 | - /// refusals apart *after* a conditional write has already refused one — the | ||
| 261 | - /// stamp on the row, never this read, is what decides. | ||
| 262 | - pub async fn is_graded(id: &HomeworkSubmissionId, db: &Database) -> Result<bool, AppError> { | ||
| 263 | - let mut result = db | ||
| 264 | - .query(format!( | ||
| 265 | - "SELECT VALUE id FROM $id WHERE {SUBMISSION_GRADED_FIELD} != NONE" | ||
| 266 | - )) | ||
| 267 | - .bind(("id", id.record())) | ||
| 268 | - .await? | ||
| 269 | - .check()?; | ||
| 270 | - Ok(!result.take::<Vec<HomeworkSubmissionId>>(0)?.is_empty()) | ||
| 271 | - } | ||
| 272 | - | ||
| 273 | - /// `user`'s submission to `homework`, if they have one. | ||
| 274 | - pub async fn read_for( | ||
| 275 | - homework: &HomeworkId, | ||
| 276 | - user: &UserId, | ||
| 277 | - db: &Database, | ||
| 278 | - ) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 279 | - Ok(db | ||
| 280 | - .select(HomeworkSubmissionId::composite(homework, user).record()) | ||
| 281 | - .await?) | ||
| 282 | - } | ||
| 283 | - | ||
| 284 | - /// Every submission to `homework`, in student (composite-id) order — the | ||
| 285 | - /// roster's raw rows. | ||
| 286 | - pub async fn list_for_homework( | ||
| 287 | - homework: &HomeworkId, | ||
| 288 | - db: &Database, | ||
| 289 | - ) -> Result<Vec<HomeworkSubmission>, AppError> { | ||
| 290 | - let mut result = db | ||
| 291 | - .query("SELECT * FROM homework_submission WHERE homework = $hw ORDER BY id ASC") | ||
| 292 | - .bind(("hw", homework.record())) | ||
| 293 | - .await? | ||
| 294 | - .check()?; | ||
| 295 | - Ok(result.take::<Vec<HomeworkSubmission>>(0)?) | ||
| 296 | - } | ||
| 297 | - | ||
| 298 | - /// Delete this submission and its files in one transaction — so a crash | ||
| 299 | - /// can't leave a file pointing at a vanished submission. The file *blobs* | ||
| 300 | - /// are the web layer's to unlink: it lists them | ||
| 301 | - /// ([`crate::domain::homework_file::HomeworkFile::list_for_submission`]) | ||
| 302 | - /// before calling this. `None` means a grade froze the row (the caller | ||
| 303 | - /// answers 409): the submission's own delete carries | ||
| 304 | - /// [`SUBMISSION_OPEN_GUARD`], and the file wipe is conditional on it having | ||
| 305 | - /// bitten, so a refused delete leaves the children standing too. | ||
| 306 | - /// | ||
| 307 | - /// The one place either badge counter comes back down, and deliberately the | ||
| 308 | - /// only one: this route is student-callable on their own row, so without it | ||
| 309 | - /// a student farms "handed in 50 homeworks" by submit/delete/submit on a | ||
| 310 | - /// single homework. A teacher's homework delete and the course cascade | ||
| 311 | - /// leave the counters alone — history a teacher erased is still history the | ||
| 312 | - /// student lived. | ||
| 313 | - /// | ||
| 314 | - /// The on-time half is given back by the verdict [`HomeworkSubmission::upsert`] | ||
| 315 | - /// *stored* on the row, never by re-judging the deadline: `due_at` is | ||
| 316 | - /// mutable, so re-deriving read whatever the teacher had moved it to since | ||
| 317 | - /// and gave back something other than what was taken — extend it after a | ||
| 318 | - /// late hand-in and this debited a credit that was never given; pull it back | ||
| 319 | - /// after a punctual one and it debited nothing, leaving `on_time` above | ||
| 320 | - /// `submitted`. A row from before the column exists carries no verdict, and | ||
| 321 | - /// cannot be given one for a credit that already happened, so it falls back | ||
| 322 | - /// to the old cut (`submitted_at`, the readonly stamp the increment judged, | ||
| 323 | - /// against the live deadline); a dangling `homework` link leaves `$due` | ||
| 324 | - /// `NONE` there, which compares false and so counts as late, matching the | ||
| 325 | - /// backfill. Floored at zero: a row that predates the columns has none. | ||
| 326 | - /// | ||
| 327 | - /// Badges already earned are never taken away — [`crate::domain::badge`] is | ||
| 328 | - /// add-only, which is where that permanence lives. | ||
| 329 | - pub async fn delete(self, db: &Database) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 330 | - // Sound to re-send: DELETE and UPDATE can never answer "already exists". | ||
| 331 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 332 | - db, | ||
| 333 | - &format!( | ||
| 334 | - "BEGIN TRANSACTION; | ||
| 335 | - LET $due = (SELECT VALUE homework.due_at FROM ONLY $sub); | ||
| 336 | - LET $gone = (DELETE $sub WHERE {SUBMISSION_OPEN_GUARD} RETURN BEFORE); | ||
| 337 | - IF array::len($gone) > 0 {{ | ||
| 338 | - DELETE homework_file WHERE submission = $sub; | ||
| 339 | - LET $on_time = IF ($gone[0].counted_on_time | ||
| 340 | - ?? ($gone[0].submitted_at <= $due)) {{ 1 }} ELSE {{ 0 }}; | ||
| 341 | - UPDATE $usr SET | ||
| 342 | - {HOMEWORK_SUBMITTED_TOTAL_FIELD} = | ||
| 343 | - math::max([({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0) - 1, 0]), | ||
| 344 | - {HOMEWORK_ON_TIME_TOTAL_FIELD} = | ||
| 345 | - math::max([({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0) - $on_time, 0]) | ||
| 346 | - }}; | ||
| 347 | - RETURN $gone; | ||
| 348 | - COMMIT TRANSACTION;" | ||
| 349 | - ), | ||
| 350 | - &[ | ||
| 351 | - ("sub".into(), self.id.record().into_value()), | ||
| 352 | - ("usr".into(), self.user.record().into_value()), | ||
| 353 | - ], | ||
| 354 | - &[], | ||
| 355 | - ) | ||
| 356 | - .await?; | ||
| 357 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 358 | - return Err(error.into()); | ||
| 359 | - } | ||
| 360 | - // The trailing `RETURN` is always the last statement before `COMMIT`. | ||
| 361 | - let slot = result.num_statements().saturating_sub(2); | ||
| 362 | - Ok(result | ||
| 363 | - .take::<Vec<HomeworkSubmission>>(slot)? | ||
| 364 | - .into_iter() | ||
| 365 | - .next()) | ||
| 366 | - } | ||
| 367 | } | 103 | } |
| 368 | 104 | ||
| 369 | #[cfg(test)] | 105 | #[cfg(test)] |
| 370 | mod tests { | 106 | mod tests { |
| 371 | use super::*; | 107 | use super::*; |
| 372 | 108 | ||
| 373 | - use crate::domain::homework::HomeworkTitle; | ||
| 374 | - use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | ||
| 375 | - | ||
| 376 | - /// A real homework row (and the subject it must reference) due at `due_at` — | ||
| 377 | - /// `upsert` now reads the deadline off the entity, so the tests need one. | ||
| 378 | - async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { | ||
| 379 | - let course = crate::db::course::a_test_course(db).await; | ||
| 380 | - let subject = Subject::create( | ||
| 381 | - &course, | ||
| 382 | - SubjectName::try_new("topic").unwrap(), | ||
| 383 | - SubjectDescription::try_new("").unwrap(), | ||
| 384 | - db, | ||
| 385 | - ) | ||
| 386 | - .await | ||
| 387 | - .unwrap(); | ||
| 388 | - Homework::create( | ||
| 389 | - &course, | ||
| 390 | - subject.get_id(), | ||
| 391 | - HomeworkTitle::try_new("essay").unwrap(), | ||
| 392 | - None, | ||
| 393 | - due_at, | ||
| 394 | - None, | ||
| 395 | - &UserId::from_key("teacher"), | ||
| 396 | - db, | ||
| 397 | - ) | ||
| 398 | - .await | ||
| 399 | - .unwrap() | ||
| 400 | - } | ||
| 401 | - | ||
| 402 | - /// A deadline no test run can reach, so a submission is unambiguously on | ||
| 403 | - /// time; `Timestamp::from_millis(1)` is its late twin. | ||
| 404 | - fn far_future() -> Timestamp { | ||
| 405 | - Timestamp::from_millis(Timestamp::now().as_millis() + 3_600_000) | ||
| 406 | - } | ||
| 407 | - | ||
| 408 | - /// A real user row: the counters live on it, and an `UPDATE` has nothing to | ||
| 409 | - /// write to without one. | ||
| 410 | - async fn a_student(username: &str, db: &Database) -> UserId { | ||
| 411 | - let hash = crate::domain::user::Password::try_new("secret1") | ||
| 412 | - .unwrap() | ||
| 413 | - .hash_async() | ||
| 414 | - .await | ||
| 415 | - .unwrap(); | ||
| 416 | - crate::db::user::create( | ||
| 417 | - db, | ||
| 418 | - crate::domain::user::Username::try_new(username).unwrap(), | ||
| 419 | - hash, | ||
| 420 | - ) | ||
| 421 | - .await | ||
| 422 | - .unwrap() | ||
| 423 | - .get_id() | ||
| 424 | - .clone() | ||
| 425 | - } | ||
| 426 | - | ||
| 427 | - /// Move the stored deadline the way a teacher's PATCH does, leaving the | ||
| 428 | - /// caller's `homework` snapshot untouched — the stale-snapshot shape the | ||
| 429 | - /// handler produces when a `PATCH due_at` commits between its gate read and | ||
| 430 | - /// its write. | ||
| 431 | - async fn deadline_moves_to(homework: &Homework, due_at: Timestamp, db: &Database) { | ||
| 432 | - Homework::read(homework.get_id(), db) | ||
| 433 | - .await | ||
| 434 | - .unwrap() | ||
| 435 | - .expect("the homework exists") | ||
| 436 | - .update(None, None, None, Some(due_at), None, db) | ||
| 437 | - .await | ||
| 438 | - .unwrap(); | ||
| 439 | - } | ||
| 440 | - | ||
| 441 | - /// The verdict `upsert` stored on the row — what `delete` debits off. | ||
| 442 | - /// `None` is a row from before the column existed. | ||
| 443 | - async fn stored_verdict(id: &HomeworkSubmissionId, db: &Database) -> Option<bool> { | ||
| 444 | - let mut result = db | ||
| 445 | - .query("SELECT VALUE counted_on_time FROM $sub") | ||
| 446 | - .bind(("sub", id.record())) | ||
| 447 | - .await | ||
| 448 | - .unwrap() | ||
| 449 | - .check() | ||
| 450 | - .unwrap(); | ||
| 451 | - result | ||
| 452 | - .take::<Vec<Option<bool>>>(0) | ||
| 453 | - .unwrap() | ||
| 454 | - .into_iter() | ||
| 455 | - .flatten() | ||
| 456 | - .next() | ||
| 457 | - } | ||
| 458 | - | ||
| 459 | - /// The web layer's computed flag, exactly as `SubmissionResponse::new` | ||
| 460 | - /// derives it (`src/web/homework.rs`): `updated_at` against the *live* | ||
| 461 | - /// deadline, re-read here because that is what a later GET reads. | ||
| 462 | - async fn late_flag(submission: &HomeworkSubmission, db: &Database) -> bool { | ||
| 463 | - let live = Homework::read(submission.get_homework(), db) | ||
| 464 | - .await | ||
| 465 | - .unwrap() | ||
| 466 | - .expect("the homework exists"); | ||
| 467 | - submission.get_updated_at() > live.get_due_at() | ||
| 468 | - } | ||
| 469 | - | ||
| 470 | - /// The two badge counters on a user row, absent counting as zero. | ||
| 471 | - async fn counters(user: &UserId, db: &Database) -> (i64, i64) { | ||
| 472 | - let mut result = db | ||
| 473 | - .query(format!( | ||
| 474 | - "SELECT VALUE [({HOMEWORK_SUBMITTED_TOTAL_FIELD} ?? 0), | ||
| 475 | - ({HOMEWORK_ON_TIME_TOTAL_FIELD} ?? 0)] FROM $usr" | ||
| 476 | - )) | ||
| 477 | - .bind(("usr", user.record())) | ||
| 478 | - .await | ||
| 479 | - .unwrap() | ||
| 480 | - .check() | ||
| 481 | - .unwrap(); | ||
| 482 | - let rows = result.take::<Vec<Vec<i64>>>(0).unwrap(); | ||
| 483 | - let row = rows.first().cloned().unwrap_or_default(); | ||
| 484 | - ( | ||
| 485 | - row.first().copied().unwrap_or(0), | ||
| 486 | - row.get(1).copied().unwrap_or(0), | ||
| 487 | - ) | ||
| 488 | - } | ||
| 489 | - | ||
| 490 | #[tokio::test] | 109 | #[tokio::test] |
| 491 | async fn text_is_optional_but_bounded() { | 110 | async fn text_is_optional_but_bounded() { |
| 492 | assert!(SubmissionText::try_new("").is_ok()); | 111 | assert!(SubmissionText::try_new("").is_ok()); |
| 493 | assert!(SubmissionText::try_new(&"x".repeat(5_000)).is_ok()); | 112 | assert!(SubmissionText::try_new(&"x".repeat(5_000)).is_ok()); |
| 494 | assert!(SubmissionText::try_new(&"x".repeat(5_001)).is_err()); | 113 | assert!(SubmissionText::try_new(&"x".repeat(5_001)).is_err()); |
| 495 | } | 114 | } |
| 496 | - | ||
| 497 | - #[tokio::test] | ||
| 498 | - async fn resubmit_keeps_submitted_at_and_restamps_updated_at() { | ||
| 499 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 500 | - let homework = a_homework(far_future(), &db).await; | ||
| 501 | - let user = a_student("ogrenci", &db).await; | ||
| 502 | - | ||
| 503 | - let first = HomeworkSubmission::upsert( | ||
| 504 | - &homework, | ||
| 505 | - &user, | ||
| 506 | - Some(SubmissionText::try_new("draft").unwrap()), | ||
| 507 | - &db, | ||
| 508 | - ) | ||
| 509 | - .await | ||
| 510 | - .unwrap() | ||
| 511 | - .unwrap(); | ||
| 512 | - // A re-submit lands on the same row: submitted_at (the first hand-in) | ||
| 513 | - // pinned, updated_at moves forward, and the text can be cleared. | ||
| 514 | - let second = HomeworkSubmission::upsert(&homework, &user, None, &db) | ||
| 515 | - .await | ||
| 516 | - .unwrap() | ||
| 517 | - .unwrap(); | ||
| 518 | - // ... and it is one submission, not two: the edit moves no counter. | ||
| 519 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 520 | - assert_eq!(first.get_id(), second.get_id()); | ||
| 521 | - assert_eq!(first.get_submitted_at(), second.get_submitted_at()); | ||
| 522 | - assert!(second.get_updated_at() >= first.get_updated_at()); | ||
| 523 | - assert!(second.get_text().is_none()); | ||
| 524 | - // One row per (homework, user), whatever the re-submit count. | ||
| 525 | - assert_eq!( | ||
| 526 | - HomeworkSubmission::list_for_homework(homework.get_id(), &db) | ||
| 527 | - .await | ||
| 528 | - .unwrap() | ||
| 529 | - .len(), | ||
| 530 | - 1 | ||
| 531 | - ); | ||
| 532 | - } | ||
| 533 | - | ||
| 534 | - /// The freeze, as stored state rather than as a race: the grade stamps the | ||
| 535 | - /// submission row, and from then on the submission's own writes fail their | ||
| 536 | - /// condition — no read of `homework_result` involved, which is what makes it | ||
| 537 | - /// hold when the grade lands mid-request. Un-grading clears the stamp | ||
| 538 | - /// and the row is writable again. | ||
| 539 | - /// | ||
| 540 | - /// Bite check: drop `WHERE graded_by_result = NONE` from | ||
| 541 | - /// [`HomeworkSubmission::upsert`] and the "version B" upsert below comes | ||
| 542 | - /// back `Some` — the exact swap this guards against. | ||
| 543 | - #[tokio::test] | ||
| 544 | - async fn a_grade_freezes_the_submission_row_itself() { | ||
| 545 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 546 | - let homework = a_homework(far_future(), &db).await; | ||
| 547 | - let user = a_student("ogrenci", &db).await; | ||
| 548 | - let teacher = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | ||
| 549 | - let graded = |value| { | ||
| 550 | - let text = SubmissionText::try_new(value).unwrap(); | ||
| 551 | - HomeworkSubmission::upsert(&homework, &user, Some(text), &db) | ||
| 552 | - }; | ||
| 553 | - | ||
| 554 | - let version_a = graded("version A").await.unwrap().unwrap(); | ||
| 555 | - assert!( | ||
| 556 | - !HomeworkSubmission::is_graded(version_a.get_id(), &db) | ||
| 557 | - .await | ||
| 558 | - .unwrap() | ||
| 559 | - ); | ||
| 560 | - | ||
| 561 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 562 | - | ||
| 563 | - crate::domain::homework_result::HomeworkResult::grade( | ||
| 564 | - homework.get_id(), | ||
| 565 | - &user, | ||
| 566 | - crate::domain::homework_result::HomeworkStatus::try_new("done").unwrap(), | ||
| 567 | - None, | ||
| 568 | - &teacher, | ||
| 569 | - &db, | ||
| 570 | - ) | ||
| 571 | - .await | ||
| 572 | - .unwrap(); | ||
| 573 | - assert!( | ||
| 574 | - HomeworkSubmission::is_graded(version_a.get_id(), &db) | ||
| 575 | - .await | ||
| 576 | - .unwrap() | ||
| 577 | - ); | ||
| 578 | - | ||
| 579 | - // The swap the teacher would never see: refused, and the stored text is | ||
| 580 | - // still the version that was graded. | ||
| 581 | - assert!(graded("version B").await.unwrap().is_none()); | ||
| 582 | - assert_eq!( | ||
| 583 | - HomeworkSubmission::read_for(homework.get_id(), &user, &db) | ||
| 584 | - .await | ||
| 585 | - .unwrap() | ||
| 586 | - .and_then(|row| row.get_text().map(|text| text.as_str().to_string())), | ||
| 587 | - Some("version A".to_string()) | ||
| 588 | - ); | ||
| 589 | - // The refusal is silent — the UPSERT simply matches nothing — so the | ||
| 590 | - // counters are the only thing that can catch an increment placed in | ||
| 591 | - // front of it: a submission the freeze refused must count for nothing. | ||
| 592 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 593 | - // ... and so is withdrawing it wholesale. | ||
| 594 | - let frozen = HomeworkSubmission::read_for(homework.get_id(), &user, &db) | ||
| 595 | - .await | ||
| 596 | - .unwrap() | ||
| 597 | - .unwrap(); | ||
| 598 | - assert!(frozen.delete(&db).await.unwrap().is_none()); | ||
| 599 | - assert!( | ||
| 600 | - HomeworkSubmission::read_for(homework.get_id(), &user, &db) | ||
| 601 | - .await | ||
| 602 | - .unwrap() | ||
| 603 | - .is_some() | ||
| 604 | - ); | ||
| 605 | - // A refused delete decrements nothing either. | ||
| 606 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 607 | - | ||
| 608 | - // Un-grading unfreezes it, stamp and all. | ||
| 609 | - crate::domain::homework_result::HomeworkResult::remove(homework.get_id(), &user, &db) | ||
| 610 | - .await | ||
| 611 | - .unwrap(); | ||
| 612 | - assert!( | ||
| 613 | - !HomeworkSubmission::is_graded(version_a.get_id(), &db) | ||
| 614 | - .await | ||
| 615 | - .unwrap() | ||
| 616 | - ); | ||
| 617 | - let reopened = graded("version B").await.unwrap().unwrap(); | ||
| 618 | - assert_eq!( | ||
| 619 | - reopened.get_text().map(SubmissionText::as_str), | ||
| 620 | - Some("version B") | ||
| 621 | - ); | ||
| 622 | - // Still an edit to the row that was already counted, un-freeze or not. | ||
| 623 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 624 | - // The two-stamp lateness rule is untouched by any of it: the first | ||
| 625 | - // hand-in is still the first hand-in. | ||
| 626 | - assert_eq!(reopened.get_submitted_at(), version_a.get_submitted_at()); | ||
| 627 | - assert!(reopened.get_updated_at() >= version_a.get_updated_at()); | ||
| 628 | - } | ||
| 629 | - | ||
| 630 | - #[tokio::test] | ||
| 631 | - async fn touch_moves_updated_at_but_not_submitted_at_or_text() { | ||
| 632 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 633 | - let homework = a_homework(far_future(), &db).await; | ||
| 634 | - let user = a_student("ogrenci", &db).await; | ||
| 635 | - | ||
| 636 | - let original = HomeworkSubmission::upsert( | ||
| 637 | - &homework, | ||
| 638 | - &user, | ||
| 639 | - Some(SubmissionText::try_new("photo answer").unwrap()), | ||
| 640 | - &db, | ||
| 641 | - ) | ||
| 642 | - .await | ||
| 643 | - .unwrap() | ||
| 644 | - .unwrap(); | ||
| 645 | - // A file add/delete touches the submission: updated_at moves (never | ||
| 646 | - // backwards), while the first-submit stamp and the text stay put. | ||
| 647 | - let touched = HomeworkSubmission::touch(original.get_id(), &db) | ||
| 648 | - .await | ||
| 649 | - .unwrap(); | ||
| 650 | - assert_eq!(touched.get_submitted_at(), original.get_submitted_at()); | ||
| 651 | - assert!(touched.get_updated_at() >= original.get_updated_at()); | ||
| 652 | - assert_eq!( | ||
| 653 | - touched.get_text().map(SubmissionText::as_str), | ||
| 654 | - Some("photo answer") | ||
| 655 | - ); | ||
| 656 | - } | ||
| 657 | - | ||
| 658 | - /// The farm, closed: `delete_submission` is the student's own route, so a | ||
| 659 | - /// counter that only ever went up would let one homework be handed in fifty | ||
| 660 | - /// times. Submit → withdraw → submit is worth exactly one submission. | ||
| 661 | - /// | ||
| 662 | - /// Bite check: drop the `UPDATE $usr` from [`HomeworkSubmission::delete`] | ||
| 663 | - /// and the last assertion reads `(2, 2)` — the farm. | ||
| 664 | - #[tokio::test] | ||
| 665 | - async fn submit_delete_submit_is_worth_one_submission() { | ||
| 666 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 667 | - let homework = a_homework(far_future(), &db).await; | ||
| 668 | - let user = a_student("ogrenci", &db).await; | ||
| 669 | - | ||
| 670 | - HomeworkSubmission::upsert(&homework, &user, None, &db) | ||
| 671 | - .await | ||
| 672 | - .unwrap() | ||
| 673 | - .unwrap(); | ||
| 674 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 675 | - | ||
| 676 | - let mine = HomeworkSubmission::read_for(homework.get_id(), &user, &db) | ||
| 677 | - .await | ||
| 678 | - .unwrap() | ||
| 679 | - .unwrap(); | ||
| 680 | - mine.delete(&db).await.unwrap().unwrap(); | ||
| 681 | - assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 682 | - // Floored: a second withdrawal (or a row from before the columns | ||
| 683 | - // existed) can never push either counter negative. | ||
| 684 | - assert!( | ||
| 685 | - HomeworkSubmission::read_for(homework.get_id(), &user, &db) | ||
| 686 | - .await | ||
| 687 | - .unwrap() | ||
| 688 | - .is_none() | ||
| 689 | - ); | ||
| 690 | - | ||
| 691 | - HomeworkSubmission::upsert(&homework, &user, None, &db) | ||
| 692 | - .await | ||
| 693 | - .unwrap() | ||
| 694 | - .unwrap(); | ||
| 695 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 696 | - } | ||
| 697 | - | ||
| 698 | - /// Lateness is judged against the homework's own deadline at hand-in, the | ||
| 699 | - /// same cut the one-time backfill used, and only the on-time counter sees | ||
| 700 | - /// it: a late hand-in is still a hand-in. Its withdrawal gives back only | ||
| 701 | - /// what it took. | ||
| 702 | - #[tokio::test] | ||
| 703 | - async fn a_late_submission_counts_as_submitted_but_not_on_time() { | ||
| 704 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 705 | - let punctual = a_homework(far_future(), &db).await; | ||
| 706 | - let overdue = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 707 | - let user = a_student("ogrenci", &db).await; | ||
| 708 | - | ||
| 709 | - HomeworkSubmission::upsert(&punctual, &user, None, &db) | ||
| 710 | - .await | ||
| 711 | - .unwrap() | ||
| 712 | - .unwrap(); | ||
| 713 | - HomeworkSubmission::upsert(&overdue, &user, None, &db) | ||
| 714 | - .await | ||
| 715 | - .unwrap() | ||
| 716 | - .unwrap(); | ||
| 717 | - assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 718 | - | ||
| 719 | - // Withdrawing the *late* one takes back only the submission, never the | ||
| 720 | - // on-time credit the punctual one earned — the zero floor would hide a | ||
| 721 | - // wrong subtraction here if the on-time count were sitting at zero. | ||
| 722 | - let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) | ||
| 723 | - .await | ||
| 724 | - .unwrap() | ||
| 725 | - .unwrap(); | ||
| 726 | - late.delete(&db).await.unwrap().unwrap(); | ||
| 727 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 728 | - | ||
| 729 | - // ... and withdrawing the punctual one gives back exactly that credit. | ||
| 730 | - let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) | ||
| 731 | - .await | ||
| 732 | - .unwrap() | ||
| 733 | - .unwrap(); | ||
| 734 | - kept.delete(&db).await.unwrap().unwrap(); | ||
| 735 | - assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 736 | - } | ||
| 737 | - | ||
| 738 | - /// A row from before `counted_on_time` existed carries no verdict — it was | ||
| 739 | - /// credited by a comparison that left no trace, and cannot be given one | ||
| 740 | - /// retroactively. Withdrawing it falls back to that same comparison, so the | ||
| 741 | - /// pre-2026-08-04 rows on a live volume keep behaving exactly as they did. | ||
| 742 | - /// | ||
| 743 | - /// Bite check: an absent verdict read as `false` rather than falling through | ||
| 744 | - /// (`??` binding the wrong side of the `<=`) leaves the last assertion at | ||
| 745 | - /// `(0, 1)` — on time above submitted, the shape the stored verdict exists | ||
| 746 | - /// to prevent. | ||
| 747 | - #[tokio::test] | ||
| 748 | - async fn a_row_with_no_stored_verdict_falls_back_to_the_deadline() { | ||
| 749 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 750 | - let punctual = a_homework(far_future(), &db).await; | ||
| 751 | - let overdue = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 752 | - let user = a_student("ogrenci", &db).await; | ||
| 753 | - | ||
| 754 | - HomeworkSubmission::upsert(&punctual, &user, None, &db) | ||
| 755 | - .await | ||
| 756 | - .unwrap() | ||
| 757 | - .unwrap(); | ||
| 758 | - HomeworkSubmission::upsert(&overdue, &user, None, &db) | ||
| 759 | - .await | ||
| 760 | - .unwrap() | ||
| 761 | - .unwrap(); | ||
| 762 | - assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 763 | - // Aged into legacy rows: the counters keep the credit, the rows lose the | ||
| 764 | - // verdict — the exact state of every submission on an existing volume. | ||
| 765 | - db.query("UPDATE homework_submission UNSET counted_on_time") | ||
| 766 | - .await | ||
| 767 | - .unwrap() | ||
| 768 | - .check() | ||
| 769 | - .unwrap(); | ||
| 770 | - | ||
| 771 | - let late = HomeworkSubmission::read_for(overdue.get_id(), &user, &db) | ||
| 772 | - .await | ||
| 773 | - .unwrap() | ||
| 774 | - .unwrap(); | ||
| 775 | - late.delete(&db).await.unwrap().unwrap(); | ||
| 776 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 777 | - | ||
| 778 | - let kept = HomeworkSubmission::read_for(punctual.get_id(), &user, &db) | ||
| 779 | - .await | ||
| 780 | - .unwrap() | ||
| 781 | - .unwrap(); | ||
| 782 | - kept.delete(&db).await.unwrap().unwrap(); | ||
| 783 | - assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 784 | - } | ||
| 785 | - | ||
| 786 | - /// The stale snapshot, both directions: the teacher's `PATCH due_at` commits | ||
| 787 | - /// between the handler's gate read and its write, so the caller's entity | ||
| 788 | - /// carries a deadline the store no longer has. The verdict must follow the | ||
| 789 | - /// *stored* deadline the write itself reads, because the API's `late` flag | ||
| 790 | - /// is re-derived from that same stored value on every later read — a verdict | ||
| 791 | - /// judged on the snapshot disagrees with it permanently, and `delete` then | ||
| 792 | - /// gives back the wrong credit. | ||
| 793 | - /// | ||
| 794 | - /// Bite check: judge `$on_time` against the caller's `$due` instead of | ||
| 795 | - /// `$was_due` and both halves fail — extended reads `(1, 0)` with a stored | ||
| 796 | - /// `false` against a live `late = false`, pulled reads `(1, 1)` with a | ||
| 797 | - /// stored `true` against a live `late = true`. | ||
| 798 | - #[tokio::test] | ||
| 799 | - async fn a_deadline_moved_under_the_caller_is_judged_by_the_stored_value() { | ||
| 800 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 801 | - let user = a_student("ogrenci", &db).await; | ||
| 802 | - | ||
| 803 | - // Extended at 23:59: the snapshot says the deadline has passed, the | ||
| 804 | - // store says it has not. A hand-in now is on time. | ||
| 805 | - let extended = a_homework(Timestamp::from_millis(1), &db).await; | ||
| 806 | - deadline_moves_to(&extended, far_future(), &db).await; | ||
| 807 | - let landed = HomeworkSubmission::upsert(&extended, &user, None, &db) | ||
| 808 | - .await | ||
| 809 | - .unwrap() | ||
| 810 | - .unwrap(); | ||
| 811 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 812 | - assert_eq!(stored_verdict(landed.get_id(), &db).await, Some(true)); | ||
| 813 | - assert!(!late_flag(&landed, &db).await); | ||
| 814 | - | ||
| 815 | - // Pulled earlier: the snapshot says there is time left, the store says | ||
| 816 | - // the deadline is gone. The same hand-in is late. | ||
| 817 | - let pulled = a_homework(far_future(), &db).await; | ||
| 818 | - deadline_moves_to(&pulled, Timestamp::from_millis(1), &db).await; | ||
| 819 | - let missed = HomeworkSubmission::upsert(&pulled, &user, None, &db) | ||
| 820 | - .await | ||
| 821 | - .unwrap() | ||
| 822 | - .unwrap(); | ||
| 823 | - assert_eq!(counters(&user, &db).await, (2, 1)); | ||
| 824 | - assert_eq!(stored_verdict(missed.get_id(), &db).await, Some(false)); | ||
| 825 | - assert!(late_flag(&missed, &db).await); | ||
| 826 | - | ||
| 827 | - // The invariant behind both: the stored verdict is the negation of the | ||
| 828 | - // flag the web layer computes for the same submission, never its twin. | ||
| 829 | - for submission in [&landed, &missed] { | ||
| 830 | - assert_eq!( | ||
| 831 | - stored_verdict(submission.get_id(), &db).await, | ||
| 832 | - Some(!late_flag(submission, &db).await), | ||
| 833 | - "stored verdict and the API's late flag must never disagree" | ||
| 834 | - ); | ||
| 835 | - } | ||
| 836 | - | ||
| 837 | - // ... and the withdrawal, which debits off the stamp, gives back exactly | ||
| 838 | - // what each one took. | ||
| 839 | - missed.delete(&db).await.unwrap().unwrap(); | ||
| 840 | - assert_eq!(counters(&user, &db).await, (1, 1)); | ||
| 841 | - landed.delete(&db).await.unwrap().unwrap(); | ||
| 842 | - assert_eq!(counters(&user, &db).await, (0, 0)); | ||
| 843 | - } | ||
| 844 | } | 115 | } |
src/migration_sql.rsmodified+1 -1
| @@ -703,7 +703,7 @@ pub const MIGRATION: &str = " | |||
| 703 | -- above submitted. `option<>` because every row predating 2026-08-04 has no | 703 | -- above submitted. `option<>` because every row predating 2026-08-04 has no |
| 704 | -- stored verdict and cannot be given one for a credit that already happened: | 704 | -- stored verdict and cannot be given one for a credit that already happened: |
| 705 | -- those fall back to the old comparison (see | 705 | -- those fall back to the old comparison (see |
| 706 | - -- [`crate::domain::homework_submission::HomeworkSubmission::delete`]). | 706 | + -- [`crate::db::homework_submission::delete`]). |
| 707 | DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option<bool>; | 707 | DEFINE FIELD IF NOT EXISTS counted_on_time ON homework_submission TYPE option<bool>; |
| 708 | -- The grade that froze this submission, absent while it is still open. The | 708 | -- The grade that froze this submission, absent while it is still open. The |
| 709 | -- freeze used to be a cross-table read (does a homework_result exist?) | 709 | -- freeze used to be a cross-table read (does a homework_result exist?) |
src/service/course.rsmodified+4 -4
| @@ -9,7 +9,6 @@ use crate::db::course; | |||
| 9 | use crate::domain::answer_image::AnswerImage; | 9 | use crate::domain::answer_image::AnswerImage; |
| 10 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | 10 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 11 | use crate::domain::course_note_file::CourseNoteFile; | 11 | use crate::domain::course_note_file::CourseNoteFile; |
| 12 | -use crate::domain::homework_file::HomeworkFile; | ||
| 13 | use crate::domain::question_image::QuestionImage; | 12 | use crate::domain::question_image::QuestionImage; |
| 14 | use crate::domain::role::Role; | 13 | use crate::domain::role::Role; |
| 15 | use crate::domain::term::{self, TermId}; | 14 | use crate::domain::term::{self, TermId}; |
| @@ -150,7 +149,7 @@ pub struct DeleteOutcome { | |||
| 150 | /// And the homework half of the same cascade, for | 149 | /// And the homework half of the same cascade, for |
| 151 | /// [`crate::web::homework::delete_homework`]'s reason: it sweeps the | 150 | /// [`crate::web::homework::delete_homework`]'s reason: it sweeps the |
| 152 | /// course's homework with its submissions, files and results, and grading | 151 | /// course's homework with its submissions, files and results, and grading |
| 153 | -/// ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a | 152 | +/// ([`crate::db::homework_result::grade`]) writes a |
| 154 | /// result row against a homework it only *read*, which a delete committing | 153 | /// result row against a homework it only *read*, which a delete committing |
| 155 | /// alongside is invisible to. Without this lease the grade lands behind the | 154 | /// alongside is invisible to. Without this lease the grade lands behind the |
| 156 | /// sweep: an orphan `homework_result` under a vanished homework, plus a | 155 | /// sweep: an orphan `homework_result` under a vanished homework, plus a |
| @@ -164,10 +163,11 @@ pub struct DeleteOutcome { | |||
| 164 | pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> { | 163 | pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> { |
| 165 | require_open(db, course).await?; | 164 | require_open(db, course).await?; |
| 166 | let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; | 165 | let _guard = crate::service::exam_attempt::EXAM_LOCK.write().await; |
| 167 | - let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; | 166 | + let _homework_guard = crate::service::homework::HOMEWORK_LOCK.write().await; |
| 168 | let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; | 167 | let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; |
| 169 | let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; | 168 | let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; |
| 170 | - let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), db).await?; | 169 | + let homework_files = |
| 170 | + crate::db::homework_file::file_keys_for_course(db, course.get_id()).await?; | ||
| 171 | let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; | 171 | let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; |
| 172 | let deleted = course::delete(db, course.clone()).await?; | 172 | let deleted = course::delete(db, course.clone()).await?; |
| 173 | Ok(DeleteOutcome { | 173 | Ok(DeleteOutcome { |
src/service/homework.rsadded+274 -0
| @@ -0,0 +1,274 @@ | |||
| 1 | +//! Homework workflows: the PATCH re-scope with its orphan guard, the | ||
| 2 | +//! cascading delete, and the shared student-side wall | ||
| 3 | +//! ([`gate_own_submission`]) every submission path walks. Row reads and | ||
| 4 | +//! listings pass through to [`crate::db::homework`]; the submission, file, | ||
| 5 | +//! and grade workflows live in the sibling `service::homework_*` modules, | ||
| 6 | +//! whose every locked path leases [`HOMEWORK_LOCK`]. | ||
| 7 | + | ||
| 8 | +use crate::database::Database; | ||
| 9 | +use crate::db::homework; | ||
| 10 | +use crate::db::homework_file; | ||
| 11 | +use crate::db::homework_result; | ||
| 12 | +use crate::db::homework_submission; | ||
| 13 | +use crate::domain::badge; | ||
| 14 | +use crate::domain::course::CourseId; | ||
| 15 | +use crate::domain::homework::{Homework, HomeworkDescription, HomeworkId, HomeworkTitle}; | ||
| 16 | +use crate::domain::homework_result::HomeworkResult; | ||
| 17 | +use crate::domain::homework_submission::HomeworkSubmission; | ||
| 18 | +use crate::domain::role::Role; | ||
| 19 | +use crate::domain::subject::SubjectId; | ||
| 20 | +use crate::domain::timestamp::Timestamp; | ||
| 21 | +use crate::domain::user::{User, UserId}; | ||
| 22 | +use crate::error::AppError; | ||
| 23 | + | ||
| 24 | +/// Serializes the homework subsystem's cross-record check-then-writes, which | ||
| 25 | +/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as | ||
| 26 | +/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the | ||
| 27 | +/// database write it guards, so within this one process it does order a full | ||
| 28 | +/// round trip — but the freeze no longer *rests* on that: a graded submission | ||
| 29 | +/// used to stay unedited only because the "no grade yet" read and the write it | ||
| 30 | +/// licensed sat under one lease. That rule now lives in the database too — | ||
| 31 | +/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the | ||
| 32 | +/// submission row and every student-side write carries `graded_by_result = | ||
| 33 | +/// NONE` as its own condition. The one case the stamp cannot cover — grading | ||
| 34 | +/// work with no submission row yet — falls back to the lease pair, so a write | ||
| 35 | +/// lease must never stop spanning its own database call (see | ||
| 36 | +/// [`crate::db::homework_result::grade`]). | ||
| 37 | +/// | ||
| 38 | +/// What still leases it, honestly: | ||
| 39 | +/// - Write: the homework PATCH's orphan guard ([`update`]), the | ||
| 40 | +/// homework-delete cascade ([`delete`]), and grade/ungrade — whose | ||
| 41 | +/// freeze rule (the stamp landing on a submission that may be written in the | ||
| 42 | +/// same instant) is the one thing here still resting on the two leases being | ||
| 43 | +/// mutually exclusive. The *existence* half has left: a grade now moves a | ||
| 44 | +/// value on the homework row inside its own transaction | ||
| 45 | +/// ([`crate::db::homework_result::grade`]), so a | ||
| 46 | +/// concurrent delete refuses it rather than being read around. | ||
| 47 | +/// - Read: the student's submission/file writes, which no longer gate the | ||
| 48 | +/// freeze but still must not land under a PATCH re-scoping the audience out | ||
| 49 | +/// from under them. | ||
| 50 | +/// | ||
| 51 | +/// The subject rule has left: creating a homework and re-tagging one move the | ||
| 52 | +/// subject's reference counter, and the subject delete is refused while that | ||
| 53 | +/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so | ||
| 54 | +/// neither the create (in `web::courses`) nor the outside writer the subject | ||
| 55 | +/// delete used to take is on this list any more. | ||
| 56 | +/// | ||
| 57 | +/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in | ||
| 58 | +/// [`crate::db::cap`], never the reverse. | ||
| 59 | +// corner-cut: global RwLock, shard per-homework if write latency ever matters. | ||
| 60 | +pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); | ||
| 61 | + | ||
| 62 | +#[expect( | ||
| 63 | + clippy::too_many_arguments, | ||
| 64 | + reason = "mirrors the sibling entities' create(field, field, ..) shape" | ||
| 65 | +)] | ||
| 66 | +pub async fn create( | ||
| 67 | + db: &Database, | ||
| 68 | + course: &CourseId, | ||
| 69 | + subject: &SubjectId, | ||
| 70 | + title: HomeworkTitle, | ||
| 71 | + description: Option<HomeworkDescription>, | ||
| 72 | + due_at: Timestamp, | ||
| 73 | + assigned: Option<Vec<UserId>>, | ||
| 74 | + created_by: &UserId, | ||
| 75 | +) -> Result<Homework, AppError> { | ||
| 76 | + homework::create( | ||
| 77 | + db, | ||
| 78 | + course, | ||
| 79 | + subject, | ||
| 80 | + title, | ||
| 81 | + description, | ||
| 82 | + due_at, | ||
| 83 | + assigned, | ||
| 84 | + created_by, | ||
| 85 | + ) | ||
| 86 | + .await | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// The homework row, for callers that only inspect it — the web layer's gates | ||
| 90 | +/// read through here. | ||
| 91 | +pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> { | ||
| 92 | + homework::read(db, id).await | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> { | ||
| 96 | + homework::list_all(db).await | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Homework>, AppError> { | ||
| 100 | + homework::list_for_course(db, course).await | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// Every homework of every course in `courses` (one query) — the catalog as | ||
| 104 | +/// one user sees it. | ||
| 105 | +pub async fn list_for_courses( | ||
| 106 | + db: &Database, | ||
| 107 | + courses: &[CourseId], | ||
| 108 | +) -> Result<Vec<Homework>, AppError> { | ||
| 109 | + homework::list_for_courses(db, courses).await | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// The homework of `course` that `user` is meant to see — the per-course | ||
| 113 | +/// block of a homework report. | ||
| 114 | +pub async fn list_for_user_in_course( | ||
| 115 | + db: &Database, | ||
| 116 | + course: &CourseId, | ||
| 117 | + user: &UserId, | ||
| 118 | +) -> Result<Vec<Homework>, AppError> { | ||
| 119 | + homework::list_for_user_in_course(db, course, user).await | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/// Re-scope (or re-tag, re-title, re-describe, re-schedule) the homework. | ||
| 123 | +/// | ||
| 124 | +/// Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the | ||
| 125 | +/// live submissions and results, and the row write depends on what it saw — | ||
| 126 | +/// without the lease a submission (a reader) could land between the check | ||
| 127 | +/// and the write, orphaned by the narrowing that just missed it. The subject | ||
| 128 | +/// re-tag no longer needs it — it moves the two subjects' reference counters | ||
| 129 | +/// inside [`homework::update`]. | ||
| 130 | +/// | ||
| 131 | +/// The orphan guard runs on exactly the requests that re-scope the audience. | ||
| 132 | +/// An absent `assigned` writes nothing, so the stored subset is untouched and | ||
| 133 | +/// no narrowing can happen behind the guard's back — which the old "carry the | ||
| 134 | +/// snapshot back" branch could do, re-narrowing over a concurrent widening. | ||
| 135 | +pub async fn update( | ||
| 136 | + db: &Database, | ||
| 137 | + homework: Homework, | ||
| 138 | + subject: Option<SubjectId>, | ||
| 139 | + title: Option<HomeworkTitle>, | ||
| 140 | + description: Option<Option<HomeworkDescription>>, | ||
| 141 | + due_at: Option<Timestamp>, | ||
| 142 | + assigned: Option<Option<Vec<UserId>>>, | ||
| 143 | +) -> Result<Homework, AppError> { | ||
| 144 | + let _guard = HOMEWORK_LOCK.write().await; | ||
| 145 | + if let Some(resolved) = assigned.as_ref() { | ||
| 146 | + ensure_no_orphans(&homework, resolved.as_deref(), db).await?; | ||
| 147 | + } | ||
| 148 | + homework::update(db, homework, subject, title, description, due_at, assigned).await | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student | ||
| 152 | +/// who already submitted or was graded falls outside it — their work would be | ||
| 153 | +/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in | ||
| 154 | +/// which case no one can be orphaned). The blocking students are named in the | ||
| 155 | +/// message so the teacher knows whose work to clear (or whom to keep assigned) | ||
| 156 | +/// first. | ||
| 157 | +async fn ensure_no_orphans( | ||
| 158 | + homework: &Homework, | ||
| 159 | + new_assigned: Option<&[UserId]>, | ||
| 160 | + db: &Database, | ||
| 161 | +) -> Result<(), AppError> { | ||
| 162 | + // Whole-course covers everyone — no narrowing, no orphans. | ||
| 163 | + let Some(subset) = new_assigned else { | ||
| 164 | + return Ok(()); | ||
| 165 | + }; | ||
| 166 | + let submissions = homework_submission::list_for_homework(db, homework.get_id()).await?; | ||
| 167 | + let results = homework_result::list_for_homework(db, homework.get_id()).await?; | ||
| 168 | + let mut blocked: Vec<String> = Vec::new(); | ||
| 169 | + for user in submissions | ||
| 170 | + .iter() | ||
| 171 | + .map(HomeworkSubmission::get_user) | ||
| 172 | + .chain(results.iter().map(HomeworkResult::get_user)) | ||
| 173 | + { | ||
| 174 | + let key = user.key().to_string(); | ||
| 175 | + if !subset.contains(user) && !blocked.contains(&key) { | ||
| 176 | + blocked.push(key); | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + if blocked.is_empty() { | ||
| 180 | + Ok(()) | ||
| 181 | + } else { | ||
| 182 | + Err(AppError::ConflictOwned(format!( | ||
| 183 | + "narrowing the assigned list would orphan existing work by {} student(s): {}", | ||
| 184 | + blocked.len(), | ||
| 185 | + blocked.join(", ") | ||
| 186 | + ))) | ||
| 187 | + } | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +/// Delete the homework: collect the submission-file blob keys, then run the | ||
| 191 | +/// cascading delete under [`HOMEWORK_LOCK`]'s write lease | ||
| 192 | +/// so no submission can land under the homework mid-delete; the blob names are | ||
| 193 | +/// collected before the rows are wiped (the cascade is one transaction, children | ||
| 194 | +/// first) and removed after, so a crash in between strands at worst an | ||
| 195 | +/// unreachable file. | ||
| 196 | +pub async fn delete(db: &Database, homework: Homework) -> Result<Vec<String>, AppError> { | ||
| 197 | + let _guard = HOMEWORK_LOCK.write().await; | ||
| 198 | + let blob_keys = homework_file::file_keys_for_homework(db, homework.get_id()).await?; | ||
| 199 | + homework::delete(db, homework).await?; | ||
| 200 | + Ok(blob_keys) | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +/// A 403 unless `user` is enrolled in `course` — the homework twin of the exam | ||
| 204 | +/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped). | ||
| 205 | +/// Submitting is course content, so leaving the course closes it; re-checked on | ||
| 206 | +/// every submission and file write, so an unenrollment mid-task bites the next. | ||
| 207 | +async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 208 | + if crate::service::enrollment::read_for_user(db, course, user) | ||
| 209 | + .await? | ||
| 210 | + .is_none() | ||
| 211 | + { | ||
| 212 | + return Err(AppError::Forbidden( | ||
| 213 | + "you are not enrolled in this homework's course", | ||
| 214 | + )); | ||
| 215 | + } | ||
| 216 | + Ok(()) | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// Read a homework and clear `user` to act on their own submission to it — the | ||
| 220 | +/// shared wall of the submission, file, and (student side of the) download | ||
| 221 | +/// paths. Three gates, in order: | ||
| 222 | +/// | ||
| 223 | +/// 1. Exact `Student` on the *live* role. Teachers assign homework, they never | ||
| 224 | +/// hand it in; the `RequireStudent` extractor's ≥Student would wave a | ||
| 225 | +/// promoted teacher through, so this checks the role `CurrentUser` read for | ||
| 226 | +/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`]. | ||
| 227 | +/// 2. Current enrollment in the course. | ||
| 228 | +/// 3. The audience check: a student a subset homework does not name gets a 404, | ||
| 229 | +/// never a 403, so a subset assignment never leaks to those left out (the | ||
| 230 | +/// no-leak idiom an unseen exam draft uses). | ||
| 231 | +pub async fn gate_own_submission( | ||
| 232 | + id: &str, | ||
| 233 | + user: &User, | ||
| 234 | + db: &Database, | ||
| 235 | +) -> Result<Homework, AppError> { | ||
| 236 | + let homework = homework::read(db, &HomeworkId::from_key(id)) | ||
| 237 | + .await? | ||
| 238 | + .ok_or(AppError::NotFound)?; | ||
| 239 | + if user.get_role() != Role::Student { | ||
| 240 | + return Err(AppError::Forbidden( | ||
| 241 | + "only students have homework submissions", | ||
| 242 | + )); | ||
| 243 | + } | ||
| 244 | + ensure_enrolled(homework.get_course(), user.get_id(), db).await?; | ||
| 245 | + if !homework.student_sees(user.get_id()) { | ||
| 246 | + return Err(AppError::NotFound); | ||
| 247 | + } | ||
| 248 | + Ok(homework) | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +/// The term wall of the student side: an archived term makes past years | ||
| 252 | +/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate | ||
| 253 | +/// also fronts the download read, and an archived year is still browsable. So | ||
| 254 | +/// every student *write* calls this right after the gate, which keeps the | ||
| 255 | +/// order that matters: a student the homework never named is refused by the | ||
| 256 | +/// audience check with a 404 and never learns the homework exists. A course | ||
| 257 | +/// that vanished under us is the gates' own business, not this one's. | ||
| 258 | +pub async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { | ||
| 259 | + if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { | ||
| 260 | + crate::service::course::require_open(db, &course).await?; | ||
| 261 | + } | ||
| 262 | + Ok(()) | ||
| 263 | +} | ||
| 264 | + | ||
| 265 | +/// Bring one user's badge awards up to date after a write moved their counters | ||
| 266 | +/// — the student's after a submission, the grader's after a grade. Never fails | ||
| 267 | +/// the request it follows: a badge is a decoration on top | ||
| 268 | +/// of the work, and losing one to a transient database error is not worth | ||
| 269 | +/// refusing a hand-in over — the next counter move re-runs this and heals it. | ||
| 270 | +pub(crate) async fn award_badges(user: &UserId, db: &Database) { | ||
| 271 | + if let Err(err) = badge::sync(user, db).await { | ||
| 272 | + tracing::warn!("failed to sync badges for {}: {err}", user.key()); | ||
| 273 | + } | ||
| 274 | +} | ||
src/service/homework_file.rsadded+92 -0
| @@ -0,0 +1,92 @@ | |||
| 1 | +//! Homework file workflows: the attachment of one file to the caller's | ||
| 2 | +//! submission (the graded gate plus the auto-created seat it hangs off) and | ||
| 3 | +//! the pass-through reads the download paths scope through. The blob bytes | ||
| 4 | +//! and their ordering (blob before row on upload, row before blob on delete) | ||
| 5 | +//! stay the web layer's — it owns `files_path` — but every lease holder is | ||
| 6 | +//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s reader side. | ||
| 7 | +//! The row writes live in [`crate::db::homework_file`]. | ||
| 8 | + | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::db::homework_file; | ||
| 11 | +use crate::db::homework_submission; | ||
| 12 | +use crate::domain::homework::Homework; | ||
| 13 | +use crate::domain::homework_file::{HomeworkFile, HomeworkFileId}; | ||
| 14 | +use crate::domain::homework_submission::HomeworkSubmission; | ||
| 15 | +use crate::domain::homework_submission::HomeworkSubmissionId; | ||
| 16 | +use crate::domain::user::User; | ||
| 17 | +use crate::error::AppError; | ||
| 18 | + | ||
| 19 | +/// The submission the file will hang off, created if absent — a photo-only | ||
| 20 | +/// homework never types text, so an upload auto-creates an empty submission | ||
| 21 | +/// to carry the file (an existing one's text is preserved). A photo-only | ||
| 22 | +/// hand-in is a hand-in: it creates the row, so it moves the counters, so it | ||
| 23 | +/// earns badges exactly as a text submit does. Refused (409) when a grade | ||
| 24 | +/// has frozen the homework. | ||
| 25 | +pub async fn ensure_can_attach( | ||
| 26 | + db: &Database, | ||
| 27 | + user: &User, | ||
| 28 | + homework: &Homework, | ||
| 29 | +) -> Result<HomeworkSubmission, AppError> { | ||
| 30 | + const GRADED: AppError = AppError::Conflict( | ||
| 31 | + "this homework has been graded — ask the teacher to remove the grade before adding files", | ||
| 32 | + ); | ||
| 33 | + // The common-case gate; the freeze itself rides on the writes below. | ||
| 34 | + if crate::db::homework_result::read_for(db, homework.get_id(), user.get_id()) | ||
| 35 | + .await? | ||
| 36 | + .is_some() | ||
| 37 | + { | ||
| 38 | + return Err(GRADED); | ||
| 39 | + } | ||
| 40 | + match homework_submission::read_for(db, homework.get_id(), user.get_id()).await? { | ||
| 41 | + Some(existing) => Ok(existing), | ||
| 42 | + None => { | ||
| 43 | + let created = homework_submission::upsert(db, homework, user.get_id(), None) | ||
| 44 | + .await? | ||
| 45 | + .ok_or(GRADED)?; | ||
| 46 | + crate::service::homework::award_badges(user.get_id(), db).await; | ||
| 47 | + Ok(created) | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +/// Persist the assembled row — the seat claim and the freeze in one | ||
| 53 | +/// conditional write (see [`homework_file::insert`]). `Ok(None)` is the | ||
| 54 | +/// freeze; the web layer keeps its own wording and unlinks the blob it wrote. | ||
| 55 | +pub async fn insert(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | ||
| 56 | + homework_file::insert(db, file).await | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// Delete one file row and give its seat back in the same transaction. | ||
| 60 | +/// `Ok(None)` is the freeze biting (the caller answers 409); `Err(NotFound)` | ||
| 61 | +/// means the row had already vanished. | ||
| 62 | +pub async fn delete(db: &Database, file: HomeworkFile) -> Result<Option<HomeworkFile>, AppError> { | ||
| 63 | + homework_file::delete(db, file).await | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Read a file's row only if it belongs to `submission` — the student's | ||
| 67 | +/// download path, behind the submission gate. | ||
| 68 | +pub async fn read_for( | ||
| 69 | + db: &Database, | ||
| 70 | + id: &HomeworkFileId, | ||
| 71 | + submission: &HomeworkSubmissionId, | ||
| 72 | +) -> Result<Option<HomeworkFile>, AppError> { | ||
| 73 | + homework_file::read_for(db, id, submission).await | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +/// Read a file by id only if it hangs off a submission to `homework` — the | ||
| 77 | +/// grader's download scoping. | ||
| 78 | +pub async fn read_in_homework( | ||
| 79 | + db: &Database, | ||
| 80 | + id: &HomeworkFileId, | ||
| 81 | + homework: &crate::domain::homework::HomeworkId, | ||
| 82 | +) -> Result<Option<HomeworkFile>, AppError> { | ||
| 83 | + homework_file::read_in_homework(db, id, homework).await | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +/// All of `submission`'s files, newest first. | ||
| 87 | +pub async fn list_for_submission( | ||
| 88 | + db: &Database, | ||
| 89 | + submission: &HomeworkSubmissionId, | ||
| 90 | +) -> Result<Vec<HomeworkFile>, AppError> { | ||
| 91 | + homework_file::list_for_submission(db, submission).await | ||
| 92 | +} | ||
src/service/homework_result.rsadded+132 -0
| @@ -0,0 +1,132 @@ | |||
| 1 | +//! Homework grading workflows: the policy gates around the atomic grade — | ||
| 2 | +//! nobody grades themselves, the target must be a live enrolled student in | ||
| 3 | +//! the homework's audience — and the un-grade. The freeze-stamping | ||
| 4 | +//! transaction lives in [`crate::db::homework_result`]; grading holds | ||
| 5 | +//! [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK)'s writer lease | ||
| 6 | +//! across its gates and the write, the reader side of every student write's | ||
| 7 | +//! lease pair. | ||
| 8 | + | ||
| 9 | +use crate::database::Database; | ||
| 10 | +use crate::db::homework; | ||
| 11 | +use crate::db::homework_result; | ||
| 12 | +use crate::domain::course::CourseId; | ||
| 13 | +use crate::domain::exam_result::Mark; | ||
| 14 | +use crate::domain::homework::HomeworkId; | ||
| 15 | +use crate::domain::homework_result::{HomeworkResult, HomeworkStatus}; | ||
| 16 | +use crate::domain::role::Role; | ||
| 17 | +use crate::domain::user::{User, UserId}; | ||
| 18 | +use crate::error::{AppError, ValidationError}; | ||
| 19 | + | ||
| 20 | +/// Record (or overwrite) `target`'s grade for the homework. The web layer | ||
| 21 | +/// has already read the homework, checked course-management rights, walled | ||
| 22 | +/// the archived term, and validated the status and mark; everything here is | ||
| 23 | +/// re-run or decided under the writer lease: | ||
| 24 | +/// | ||
| 25 | +/// - the homework is re-read (a homework delete is a fellow writer — its | ||
| 26 | +/// lease excludes this one, so a grade cannot resurrect a result row under | ||
| 27 | +/// a vanished homework; the vanished row answers 404); | ||
| 28 | +/// - grading never targets oneself — no grader, whatever their role, may | ||
| 29 | +/// write their own grade; | ||
| 30 | +/// - the target user must exist, and only students carry homework grades — | ||
| 31 | +/// the live role, so a stale enrollment left behind by a promotion can't | ||
| 32 | +/// reopen grading for staff; | ||
| 33 | +/// - the target must be enrolled in the homework's course, and in the | ||
| 34 | +/// homework's audience — a subset assignment is also the grading roster. | ||
| 35 | +pub async fn grade( | ||
| 36 | + db: &Database, | ||
| 37 | + id: &HomeworkId, | ||
| 38 | + teacher: &User, | ||
| 39 | + status: HomeworkStatus, | ||
| 40 | + mark: Option<Mark>, | ||
| 41 | + target: &UserId, | ||
| 42 | +) -> Result<HomeworkResult, AppError> { | ||
| 43 | + let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; | ||
| 44 | + let homework = homework::read(db, id).await?.ok_or(AppError::NotFound)?; | ||
| 45 | + | ||
| 46 | + // Grading never targets oneself. | ||
| 47 | + if target == teacher.get_id() { | ||
| 48 | + return Err(AppError::Forbidden("grading yourself is not allowed")); | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + // Target user must exist. | ||
| 52 | + let Some(target_user) = crate::service::user::read(db, target).await? else { | ||
| 53 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 54 | + field: "user", | ||
| 55 | + reason: "target user does not exist", | ||
| 56 | + })); | ||
| 57 | + }; | ||
| 58 | + | ||
| 59 | + // Only students carry homework grades. | ||
| 60 | + if target_user.get_role() != Role::Student { | ||
| 61 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 62 | + field: "user", | ||
| 63 | + reason: "only students can be graded", | ||
| 64 | + })); | ||
| 65 | + } | ||
| 66 | + | ||
| 67 | + // ... enrolled in the homework's course ... | ||
| 68 | + if crate::service::enrollment::read_for_user(db, homework.get_course(), target) | ||
| 69 | + .await? | ||
| 70 | + .is_none() | ||
| 71 | + { | ||
| 72 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 73 | + field: "user", | ||
| 74 | + reason: "target user is not enrolled in this course", | ||
| 75 | + })); | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + // ... and in the homework's audience — a subset assignment is also the | ||
| 79 | + // grading roster, so a grade can't land on a student the homework never | ||
| 80 | + // named. | ||
| 81 | + if !homework.student_sees(target) { | ||
| 82 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 83 | + field: "user", | ||
| 84 | + reason: "target user is not in this homework's audience", | ||
| 85 | + })); | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + let result = homework_result::grade(db, id, target, status, mark, teacher.get_id()).await?; | ||
| 89 | + // The grade credited the *grader*'s `marks_given`, not the student's — a | ||
| 90 | + // homework grade moves no counter of the student's at all. | ||
| 91 | + crate::service::homework::award_badges(teacher.get_id(), db).await; | ||
| 92 | + Ok(result) | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +/// Remove a student's grade from a homework — un-grading, which unfreezes | ||
| 96 | +/// the student's submission and files for further edits. `None` means there | ||
| 97 | +/// was no grade (the web layer answers 404). | ||
| 98 | +pub async fn ungrade( | ||
| 99 | + db: &Database, | ||
| 100 | + id: &HomeworkId, | ||
| 101 | + target: &UserId, | ||
| 102 | +) -> Result<Option<HomeworkResult>, AppError> { | ||
| 103 | + let _guard = crate::service::homework::HOMEWORK_LOCK.write().await; | ||
| 104 | + homework_result::remove(db, id, target).await | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +/// `user`'s grade for `homework`, if graded — the web layer's read paths go | ||
| 108 | +/// through here. | ||
| 109 | +pub async fn read_for( | ||
| 110 | + db: &Database, | ||
| 111 | + homework_id: &HomeworkId, | ||
| 112 | + user: &UserId, | ||
| 113 | +) -> Result<Option<HomeworkResult>, AppError> { | ||
| 114 | + homework_result::read_for(db, homework_id, user).await | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +/// Every grade for `homework` — the roster joins these onto the submissions. | ||
| 118 | +pub async fn list_for_homework( | ||
| 119 | + db: &Database, | ||
| 120 | + homework_id: &HomeworkId, | ||
| 121 | +) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 122 | + homework_result::list_for_homework(db, homework_id).await | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +/// `user`'s homework grades across one course. | ||
| 126 | +pub async fn list_for_user_in_course( | ||
| 127 | + db: &Database, | ||
| 128 | + course: &CourseId, | ||
| 129 | + user: &UserId, | ||
| 130 | +) -> Result<Vec<HomeworkResult>, AppError> { | ||
| 131 | + homework_result::list_for_user_in_course(db, course, user).await | ||
| 132 | +} | ||
src/service/homework_submission.rsadded+140 -0
| @@ -0,0 +1,140 @@ | |||
| 1 | +//! Homework submission workflows: the student's submit (the lease-to-write | ||
| 2 | +//! window that keeps a PATCH's audience re-scope from stranding a hand-in) | ||
| 3 | +//! and the withdrawal that gives the badge counters back. The row writes | ||
| 4 | +//! live in [`crate::db::homework_submission`]; every locked path here | ||
| 5 | +//! leases [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK). | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::homework_file; | ||
| 9 | +use crate::db::homework_result; | ||
| 10 | +use crate::db::homework_submission; | ||
| 11 | +use crate::domain::homework::Homework; | ||
| 12 | +use crate::domain::homework_file::HomeworkFile; | ||
| 13 | +use crate::domain::homework_submission::{HomeworkSubmission, SubmissionText}; | ||
| 14 | +use crate::domain::user::User; | ||
| 15 | +use crate::error::AppError; | ||
| 16 | + | ||
| 17 | +/// What [`submit`] landed: whether the (homework, user) row existed before | ||
| 18 | +/// (the web layer's 200-vs-201), the homework it answered, and the row. | ||
| 19 | +pub struct Submitted { | ||
| 20 | + pub existed: bool, | ||
| 21 | + pub homework: Homework, | ||
| 22 | + pub submission: HomeworkSubmission, | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/// Submit (or re-submit) the caller's own work for a homework. The graded | ||
| 26 | +/// gate and the audience interlock are the reader lease's — taken *before* | ||
| 27 | +/// the gate read: read first and the audience this gate approved is one | ||
| 28 | +/// committed PATCH old, so the narrowing that just passed the orphan guard | ||
| 29 | +/// (no submission yet) is followed by the very submission it would have | ||
| 30 | +/// refused. Holding the lease across gate *and* write is what makes the | ||
| 31 | +/// PATCH wait and then see the row. | ||
| 32 | +/// | ||
| 33 | +/// `None` from [`homework_submission::upsert`] is a grade landing mid-request | ||
| 34 | +/// (the stamp on the row refusing the write); the graded read above answers | ||
| 35 | +/// the common case, and both return the same 409. | ||
| 36 | +pub async fn submit( | ||
| 37 | + db: &Database, | ||
| 38 | + user: &User, | ||
| 39 | + id: &str, | ||
| 40 | + text: Option<SubmissionText>, | ||
| 41 | +) -> Result<Submitted, AppError> { | ||
| 42 | + let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; | ||
| 43 | + let homework = crate::service::homework::gate_own_submission(id, user, db).await?; | ||
| 44 | + crate::service::homework::require_open_term(&homework, db).await?; | ||
| 45 | + // The graded gate, twice over. This read answers the common case — graded | ||
| 46 | + // minutes ago, and the student who never submitted has no row to carry the | ||
| 47 | + // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what | ||
| 48 | + // holds when the grade lands *while* this request runs. | ||
| 49 | + const GRADED: AppError = AppError::Conflict( | ||
| 50 | + "this homework has been graded — ask the teacher to remove the grade before editing your submission", | ||
| 51 | + ); | ||
| 52 | + if homework_result::read_for(db, homework.get_id(), user.get_id()) | ||
| 53 | + .await? | ||
| 54 | + .is_some() | ||
| 55 | + { | ||
| 56 | + return Err(GRADED); | ||
| 57 | + } | ||
| 58 | + // 201-vs-200: a prior read is exact, where comparing the returned stamps | ||
| 59 | + // would misreport a same-millisecond re-submit as a create. | ||
| 60 | + let existed = homework_submission::read_for(db, homework.get_id(), user.get_id()) | ||
| 61 | + .await? | ||
| 62 | + .is_some(); | ||
| 63 | + let Some(submission) = homework_submission::upsert(db, &homework, user.get_id(), text).await? | ||
| 64 | + else { | ||
| 65 | + return Err(GRADED); | ||
| 66 | + }; | ||
| 67 | + // Only a first hand-in moved a counter, so only a first hand-in can have | ||
| 68 | + // earned anything — an edit re-runs nothing. | ||
| 69 | + if !existed { | ||
| 70 | + crate::service::homework::award_badges(user.get_id(), db).await; | ||
| 71 | + } | ||
| 72 | + Ok(Submitted { | ||
| 73 | + existed, | ||
| 74 | + homework, | ||
| 75 | + submission, | ||
| 76 | + }) | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +/// Withdraw the caller's own submission — its text, its file rows, and their | ||
| 80 | +/// blobs. Returns the file rows (the blobs are the web layer's to unlink: | ||
| 81 | +/// collected before the wipe, unlinked after). Refused (409) once the work | ||
| 82 | +/// is graded — the first read answers the common case, and the delete's own | ||
| 83 | +/// freeze condition (the stamp on the row) holds when a grade lands since | ||
| 84 | +/// the read above, refusing the write rather than wiping graded work. | ||
| 85 | +pub async fn delete(db: &Database, user: &User, id: &str) -> Result<Vec<HomeworkFile>, AppError> { | ||
| 86 | + let homework = crate::service::homework::gate_own_submission(id, user, db).await?; | ||
| 87 | + crate::service::homework::require_open_term(&homework, db).await?; | ||
| 88 | + let _guard = crate::service::homework::HOMEWORK_LOCK.read().await; | ||
| 89 | + const GRADED: AppError = AppError::Conflict( | ||
| 90 | + "this homework has been graded — ask the teacher to remove the grade before deleting your submission", | ||
| 91 | + ); | ||
| 92 | + if homework_result::read_for(db, homework.get_id(), user.get_id()) | ||
| 93 | + .await? | ||
| 94 | + .is_some() | ||
| 95 | + { | ||
| 96 | + return Err(GRADED); | ||
| 97 | + } | ||
| 98 | + let submission = homework_submission::read_for(db, homework.get_id(), user.get_id()) | ||
| 99 | + .await? | ||
| 100 | + .ok_or(AppError::NotFound)?; | ||
| 101 | + // Collect blob names before the cascade (the delete wipes the file | ||
| 102 | + // rows in the same transaction), then unlink after the rows are gone. | ||
| 103 | + let files = homework_file::list_for_submission(db, submission.get_id()).await?; | ||
| 104 | + if homework_submission::delete(db, submission).await?.is_none() { | ||
| 105 | + return Err(GRADED); | ||
| 106 | + } | ||
| 107 | + // The counters just came down; a badge already earned stays earned (`sync` | ||
| 108 | + // only ever adds), so this is here to keep the award rows in step with the | ||
| 109 | + // *next* submission rather than to take anything back. | ||
| 110 | + crate::service::homework::award_badges(user.get_id(), db).await; | ||
| 111 | + Ok(files) | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// `user`'s submission to `homework`, if they have one — the web layer's | ||
| 115 | +/// read paths go through here. | ||
| 116 | +pub async fn read_for( | ||
| 117 | + db: &Database, | ||
| 118 | + homework: &crate::domain::homework::HomeworkId, | ||
| 119 | + user: &crate::domain::user::UserId, | ||
| 120 | +) -> Result<Option<HomeworkSubmission>, AppError> { | ||
| 121 | + homework_submission::read_for(db, homework, user).await | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +/// Re-stamp a submission's `updated_at` to now — a file add/delete moves the | ||
| 125 | +/// submission's "last touched" clock (the late flag) without touching the | ||
| 126 | +/// text. | ||
| 127 | +pub async fn touch( | ||
| 128 | + db: &Database, | ||
| 129 | + id: &crate::domain::homework_submission::HomeworkSubmissionId, | ||
| 130 | +) -> Result<HomeworkSubmission, AppError> { | ||
| 131 | + homework_submission::touch(db, id).await | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +/// Every submission to `homework` — the roster's raw rows. | ||
| 135 | +pub async fn list_for_homework( | ||
| 136 | + db: &Database, | ||
| 137 | + homework: &crate::domain::homework::HomeworkId, | ||
| 138 | +) -> Result<Vec<HomeworkSubmission>, AppError> { | ||
| 139 | + homework_submission::list_for_homework(db, homework).await | ||
| 140 | +} | ||
src/service/mod.rsmodified+4 -0
| @@ -10,6 +10,10 @@ pub mod enrollment; | |||
| 10 | pub mod exam; | 10 | pub mod exam; |
| 11 | pub mod exam_attempt; | 11 | pub mod exam_attempt; |
| 12 | pub mod exam_question; | 12 | pub mod exam_question; |
| 13 | +pub mod homework; | ||
| 14 | +pub mod homework_file; | ||
| 15 | +pub mod homework_result; | ||
| 16 | +pub mod homework_submission; | ||
| 13 | pub mod meal_booking; | 17 | pub mod meal_booking; |
| 14 | pub mod note; | 18 | pub mod note; |
| 15 | pub mod payment_ledger; | 19 | pub mod payment_ledger; |
src/web/courses.rsmodified+19 -8
| @@ -16,7 +16,7 @@ use crate::domain::enrollment::Enrollment; | |||
| 16 | use crate::domain::exam::{ | 16 | use crate::domain::exam::{ |
| 17 | ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, | 17 | ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, ExamTitle, |
| 18 | }; | 18 | }; |
| 19 | -use crate::domain::homework::{Homework, HomeworkTitle}; | 19 | +use crate::domain::homework::HomeworkTitle; |
| 20 | use crate::domain::role::Role; | 20 | use crate::domain::role::Role; |
| 21 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | 21 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; |
| 22 | use crate::domain::timestamp::Timestamp; | 22 | use crate::domain::timestamp::Timestamp; |
| @@ -1084,7 +1084,8 @@ async fn create_homework_in_course( | |||
| 1084 | // is non-zero — so the check below is only a pre-flight for the message. | 1084 | // is non-zero — so the check below is only a pre-flight for the message. |
| 1085 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; | 1085 | let subject = subject_in_course(&req.subject_id, course.get_id(), &st.db).await?; |
| 1086 | let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; | 1086 | let assigned = resolve_assigned(req.assigned, course.get_id(), &st.db).await?; |
| 1087 | - let homework = Homework::create( | 1087 | + let homework = service::homework::create( |
| 1088 | + &st.db, | ||
| 1088 | course.get_id(), | 1089 | course.get_id(), |
| 1089 | &subject, | 1090 | &subject, |
| 1090 | title, | 1091 | title, |
| @@ -1092,7 +1093,6 @@ async fn create_homework_in_course( | |||
| 1092 | due_at, | 1093 | due_at, |
| 1093 | assigned, | 1094 | assigned, |
| 1094 | user.get_id(), | 1095 | user.get_id(), |
| 1095 | - &st.db, | ||
| 1096 | ) | 1096 | ) |
| 1097 | .await?; | 1097 | .await?; |
| 1098 | Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework)))) | 1098 | Ok((StatusCode::CREATED, Json(HomeworkResponse::new(&homework)))) |
| @@ -1134,7 +1134,7 @@ async fn list_course_homework( | |||
| 1134 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", | 1134 | "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course", |
| 1135 | )); | 1135 | )); |
| 1136 | } | 1136 | } |
| 1137 | - let mut homework = Homework::list_for_course(course.get_id(), &st.db).await?; | 1137 | + let mut homework = service::homework::list_for_course(&st.db, course.get_id()).await?; |
| 1138 | // A student sees only the homework they are assigned; managers see all. | 1138 | // A student sees only the homework they are assigned; managers see all. |
| 1139 | let manages = can_manage_course(&course, &user); | 1139 | let manages = can_manage_course(&course, &user); |
| 1140 | if !manages { | 1140 | if !manages { |
| @@ -1297,7 +1297,10 @@ mod tests { | |||
| 1297 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) | 1297 | let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) |
| 1298 | .await | 1298 | .await |
| 1299 | .unwrap(); | 1299 | .unwrap(); |
| 1300 | - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 | 1300 | + crate::service::user::set_role(db, user.get_id(), role) |
| 1301 | + .await | ||
| 1302 | + .unwrap() | ||
| 1303 | + .0 | ||
| 1301 | } | 1304 | } |
| 1302 | 1305 | ||
| 1303 | /// A course `creator` made, with nobody assigned. | 1306 | /// A course `creator` made, with nobody assigned. |
| @@ -1326,7 +1329,10 @@ mod tests { | |||
| 1326 | assert!(owns_course(&course, &creator)); | 1329 | assert!(owns_course(&course, &creator)); |
| 1327 | 1330 | ||
| 1328 | for role in [Role::Student, Role::Parent] { | 1331 | for role in [Role::Student, Role::Parent] { |
| 1329 | - let demoted = crate::service::user::set_role(&db, creator.get_id(), role).await.unwrap().0; | 1332 | + let demoted = crate::service::user::set_role(&db, creator.get_id(), role) |
| 1333 | + .await | ||
| 1334 | + .unwrap() | ||
| 1335 | + .0; | ||
| 1330 | assert!( | 1336 | assert!( |
| 1331 | !can_manage_course(&course, &demoted), | 1337 | !can_manage_course(&course, &demoted), |
| 1332 | "{role:?} creator still manages the course" | 1338 | "{role:?} creator still manages the course" |
| @@ -1354,7 +1360,10 @@ mod tests { | |||
| 1354 | // ...but never an owner, assigned or not. | 1360 | // ...but never an owner, assigned or not. |
| 1355 | assert!(!owns_course(&course, &assigned)); | 1361 | assert!(!owns_course(&course, &assigned)); |
| 1356 | 1362 | ||
| 1357 | - let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student).await.unwrap().0; | 1363 | + let demoted = crate::service::user::set_role(&db, assigned.get_id(), Role::Student) |
| 1364 | + .await | ||
| 1365 | + .unwrap() | ||
| 1366 | + .0; | ||
| 1358 | assert!(!can_manage_course(&course, &demoted)); | 1367 | assert!(!can_manage_course(&course, &demoted)); |
| 1359 | } | 1368 | } |
| 1360 | 1369 | ||
| @@ -1413,7 +1422,9 @@ mod tests { | |||
| 1413 | let db = init_mem().await.unwrap(); | 1422 | let db = init_mem().await.unwrap(); |
| 1414 | let creator = user("teacher", Role::Teacher, &db).await; | 1423 | let creator = user("teacher", Role::Teacher, &db).await; |
| 1415 | let course = course(&creator, &db).await; | 1424 | let course = course(&creator, &db).await; |
| 1416 | - crate::service::user::set_role(&db, creator.get_id(), Role::Student).await.unwrap(); | 1425 | + crate::service::user::set_role(&db, creator.get_id(), Role::Student) |
| 1426 | + .await | ||
| 1427 | + .unwrap(); | ||
| 1417 | 1428 | ||
| 1418 | for role in [Role::Manager, Role::Admin] { | 1429 | for role in [Role::Manager, Role::Admin] { |
| 1419 | let boss = user(&format!("boss{}", role.as_str()), role, &db).await; | 1430 | let boss = user(&format!("boss{}", role.as_str()), role, &db).await; |
src/web/homework.rsmodified+110 -371
| @@ -3,7 +3,9 @@ | |||
| 3 | //! files, the teacher's grading and roster, and the observer report. Creation | 3 | //! files, the teacher's grading and roster, and the observer report. Creation |
| 4 | //! and the per-course listing live under `/courses/{id}/homework` (see | 4 | //! and the per-course listing live under `/courses/{id}/homework` (see |
| 5 | //! [`super::courses`]); everything shares the visibility rule | 5 | //! [`super::courses`]); everything shares the visibility rule |
| 6 | -//! ([`Homework::student_sees`]) and the [`HOMEWORK_LOCK`]. | 6 | +//! ([`Homework::student_sees`](crate::domain::homework::Homework::student_sees)) |
| 7 | +//! and the [`HOMEWORK_LOCK`](crate::service::homework::HOMEWORK_LOCK), whose | ||
| 8 | +//! leases the workflows take in [`crate::service::homework`] and its siblings. | ||
| 7 | 9 | ||
| 8 | use crate::web::tenant_state::State; | 10 | use crate::web::tenant_state::State; |
| 9 | use axum::Json; | 11 | use axum::Json; |
| @@ -18,7 +20,6 @@ use utoipa_axum::routes; | |||
| 18 | 20 | ||
| 19 | use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | 21 | use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 20 | use crate::database::Database; | 22 | use crate::database::Database; |
| 21 | -use crate::domain::badge; | ||
| 22 | use crate::domain::course::{Course, CourseId}; | 23 | use crate::domain::course::{Course, CourseId}; |
| 23 | 24 | ||
| 24 | use crate::domain::exam_result::Mark; | 25 | use crate::domain::exam_result::Mark; |
| @@ -31,7 +32,7 @@ use crate::domain::homework_submission::{ | |||
| 31 | use crate::domain::note_file::{FileContentType, FileName}; | 32 | use crate::domain::note_file::{FileContentType, FileName}; |
| 32 | use crate::domain::role::Role; | 33 | use crate::domain::role::Role; |
| 33 | use crate::domain::timestamp::Timestamp; | 34 | use crate::domain::timestamp::Timestamp; |
| 34 | -use crate::domain::user::{User, UserId}; | 35 | +use crate::domain::user::UserId; |
| 35 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 36 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 36 | use crate::service; | 37 | use crate::service; |
| 37 | use crate::state::AppState; | 38 | use crate::state::AppState; |
| @@ -44,44 +45,6 @@ use super::{ | |||
| 44 | check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear, | 45 | check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear, |
| 45 | }; | 46 | }; |
| 46 | 47 | ||
| 47 | -/// Serializes the homework subsystem's cross-record check-then-writes, which | ||
| 48 | -/// `BEGIN…COMMIT` cannot (write skew) — the same reasoning as | ||
| 49 | -/// [`crate::service::exam_attempt::EXAM_LOCK`]. Every lease below is held across the | ||
| 50 | -/// database write it guards, so within this one process it does order a full | ||
| 51 | -/// round trip — but the freeze no longer *rests* on that: a graded submission | ||
| 52 | -/// used to stay unedited only because the "no grade yet" read and the write it | ||
| 53 | -/// licensed sat under one lease. That rule now lives in the database too — | ||
| 54 | -/// grading stamps [`crate::constant::SUBMISSION_GRADED_FIELD`] on the | ||
| 55 | -/// submission row and every student-side write carries `graded_by_result = | ||
| 56 | -/// NONE` as its own condition. The one case the stamp cannot cover — grading | ||
| 57 | -/// work with no submission row yet — falls back to the lease pair, so a write | ||
| 58 | -/// lease must never stop spanning its own database call (see | ||
| 59 | -/// [`crate::domain::homework_result::HomeworkResult::grade`]). | ||
| 60 | -/// | ||
| 61 | -/// What still leases it, honestly: | ||
| 62 | -/// - Write: the homework PATCH's orphan guard ([`update_homework`]), the | ||
| 63 | -/// homework-delete cascade ([`delete_homework`]), and grade/ungrade — whose | ||
| 64 | -/// freeze rule (the stamp landing on a submission that may be written in the | ||
| 65 | -/// same instant) is the one thing here still resting on the two leases being | ||
| 66 | -/// mutually exclusive. The *existence* half has left: a grade now moves a | ||
| 67 | -/// value on the homework row inside its own transaction | ||
| 68 | -/// ([`crate::domain::homework_result::HomeworkResult::grade`]), so a | ||
| 69 | -/// concurrent delete refuses it rather than being read around. | ||
| 70 | -/// - Read: the student's submission/file writes, which no longer gate the | ||
| 71 | -/// freeze but still must not land under a PATCH re-scoping the audience out | ||
| 72 | -/// from under them. | ||
| 73 | -/// | ||
| 74 | -/// The subject rule has left: creating a homework and re-tagging one move the | ||
| 75 | -/// subject's reference counter, and the subject delete is refused while that | ||
| 76 | -/// counter is non-zero ([`crate::domain::subject::Subject::delete`]), so | ||
| 77 | -/// neither the create ([`super::courses`]) nor the outside writer the subject | ||
| 78 | -/// delete used to take is on this list any more. | ||
| 79 | -/// | ||
| 80 | -/// Lock order, where both are taken: `HOMEWORK_LOCK` before the counter lock in | ||
| 81 | -/// [`crate::db::cap`], never the reverse. | ||
| 82 | -// corner-cut: global RwLock, shard per-homework if write latency ever matters. | ||
| 83 | -pub(crate) static HOMEWORK_LOCK: tokio::sync::RwLock<()> = tokio::sync::RwLock::const_new(()); | ||
| 84 | - | ||
| 85 | pub fn routes() -> OpenApiRouter<AppState> { | 48 | pub fn routes() -> OpenApiRouter<AppState> { |
| 86 | // The file-upload route carries a larger HTTP body cap than axum's 2 MB | 49 | // The file-upload route carries a larger HTTP body cap than axum's 2 MB |
| 87 | // default — the server-wide hard ceiling plus multipart framing headroom; | 50 | // default — the server-wide hard ceiling plus multipart framing headroom; |
| @@ -163,7 +126,7 @@ pub(crate) fn description_or_none(text: &str) -> Result<Option<HomeworkDescripti | |||
| 163 | /// The homework plus its course, or a 404 — every entity handler here gates on | 126 | /// The homework plus its course, or a 404 — every entity handler here gates on |
| 164 | /// the parent course, so they always travel together. | 127 | /// the parent course, so they always travel together. |
| 165 | async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Course), AppError> { | 128 | async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Course), AppError> { |
| 166 | - let homework = Homework::read(&HomeworkId::from_key(id), db) | 129 | + let homework = service::homework::read(db, &HomeworkId::from_key(id)) |
| 167 | .await? | 130 | .await? |
| 168 | .ok_or(AppError::NotFound)?; | 131 | .ok_or(AppError::NotFound)?; |
| 169 | let course = crate::service::course::read(db, homework.get_course()) | 132 | let course = crate::service::course::read(db, homework.get_course()) |
| @@ -201,7 +164,7 @@ async fn list_homework( | |||
| 201 | let manages_all = user.get_role().at_least(Role::Manager); | 164 | let manages_all = user.get_role().at_least(Role::Manager); |
| 202 | let mut managed: Vec<String> = Vec::new(); | 165 | let mut managed: Vec<String> = Vec::new(); |
| 203 | let homework = if manages_all { | 166 | let homework = if manages_all { |
| 204 | - Homework::list_all(&st.db).await? | 167 | + service::homework::list_all(&st.db).await? |
| 205 | } else { | 168 | } else { |
| 206 | let courses = visible_courses(&user, &st.db).await?; | 169 | let courses = visible_courses(&user, &st.db).await?; |
| 207 | let ids: Vec<_> = courses | 170 | let ids: Vec<_> = courses |
| @@ -216,7 +179,7 @@ async fn list_homework( | |||
| 216 | .filter(|course| can_manage_course(course, &user)) | 179 | .filter(|course| can_manage_course(course, &user)) |
| 217 | .map(|course| course.get_id().key().to_string()) | 180 | .map(|course| course.get_id().key().to_string()) |
| 218 | .collect(); | 181 | .collect(); |
| 219 | - let mut homework = Homework::list_for_courses(&ids, &st.db).await?; | 182 | + let mut homework = service::homework::list_for_courses(&st.db, &ids).await?; |
| 220 | homework.retain(|hw| { | 183 | homework.retain(|hw| { |
| 221 | managed.iter().any(|key| key == hw.get_course().key()) || hw.student_sees(user.get_id()) | 184 | managed.iter().any(|key| key == hw.get_course().key()) || hw.student_sees(user.get_id()) |
| 222 | }); | 185 | }); |
| @@ -347,13 +310,11 @@ async fn update_homework( | |||
| 347 | } | 310 | } |
| 348 | crate::service::course::require_open(&st.db, &course).await?; | 311 | crate::service::course::require_open(&st.db, &course).await?; |
| 349 | 312 | ||
| 350 | - // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the | 313 | + // The writer lease of [`HOMEWORK_LOCK`], the orphan guard, and the write |
| 351 | - // live submissions and results, and the row write depends on what it saw — | 314 | + // are one unit in [`service::homework::update`]: the guard reads the live |
| 315 | + // submissions and results, and the row write depends on what it saw — | ||
| 352 | // without the lease a submission (a reader) could land between the check | 316 | // without the lease a submission (a reader) could land between the check |
| 353 | - // and the write, orphaned by the narrowing that just missed it. The subject | 317 | + // and the write, orphaned by the narrowing that just missed it. |
| 354 | - // re-tag no longer needs it — it moves the two subjects' reference counters | ||
| 355 | - // inside `Homework::update`. | ||
| 356 | - let _guard = HOMEWORK_LOCK.write().await; | ||
| 357 | 318 | ||
| 358 | // Only what the request carried: an omitted field stays `None` and is never | 319 | // Only what the request carried: an omitted field stays `None` and is never |
| 359 | // written, so a concurrent PATCH of another field survives. The two | 320 | // written, so a concurrent PATCH of another field survives. The two |
| @@ -371,8 +332,8 @@ async fn update_homework( | |||
| 371 | let due_at = req.due_at.map(Timestamp::from_millis); | 332 | let due_at = req.due_at.map(Timestamp::from_millis); |
| 372 | // A kept (absent) due date may already be past; a newly set one may not be. | 333 | // A kept (absent) due date may already be past; a newly set one may not be. |
| 373 | check_not_past("due_at", due_at)?; | 334 | check_not_past("due_at", due_at)?; |
| 374 | - let subject = match req.subject_id { | 335 | + let subject = match &req.subject_id { |
| 375 | - Some(ref subject_id) => Some(subject_in_course(subject_id, course.get_id(), &st.db).await?), | 336 | + Some(subject_id) => Some(subject_in_course(subject_id, course.get_id(), &st.db).await?), |
| 376 | None => None, | 337 | None => None, |
| 377 | }; | 338 | }; |
| 378 | // The orphan guard runs on exactly the requests that re-scope the audience. | 339 | // The orphan guard runs on exactly the requests that re-scope the audience. |
| @@ -380,59 +341,23 @@ async fn update_homework( | |||
| 380 | // no narrowing can happen behind the guard's back — which the old "carry the | 341 | // no narrowing can happen behind the guard's back — which the old "carry the |
| 381 | // snapshot back" branch could do, re-narrowing over a concurrent widening. | 342 | // snapshot back" branch could do, re-narrowing over a concurrent widening. |
| 382 | let assigned = match req.assigned { | 343 | let assigned = match req.assigned { |
| 383 | - Some(assigned) => { | 344 | + Some(assigned) => Some(resolve_assigned(assigned, course.get_id(), &st.db).await?), |
| 384 | - let resolved = resolve_assigned(assigned, course.get_id(), &st.db).await?; | ||
| 385 | - ensure_no_orphans(&homework, resolved.as_deref(), &st.db).await?; | ||
| 386 | - Some(resolved) | ||
| 387 | - } | ||
| 388 | None => None, | 345 | None => None, |
| 389 | }; | 346 | }; |
| 390 | 347 | ||
| 391 | - let updated = homework | 348 | + let updated = service::homework::update( |
| 392 | - .update(subject, title, description, due_at, assigned, &st.db) | 349 | + &st.db, |
| 393 | - .await?; | 350 | + homework, |
| 351 | + subject, | ||
| 352 | + title, | ||
| 353 | + description, | ||
| 354 | + due_at, | ||
| 355 | + assigned, | ||
| 356 | + ) | ||
| 357 | + .await?; | ||
| 394 | Ok(Json(HomeworkResponse::new(&updated))) | 358 | Ok(Json(HomeworkResponse::new(&updated))) |
| 395 | } | 359 | } |
| 396 | 360 | ||
| 397 | -/// Refuse (409) a PATCH that would narrow `homework`'s audience so a student | ||
| 398 | -/// who already submitted or was graded falls outside it — their work would be | ||
| 399 | -/// stranded. `new_assigned` is the proposed subset (`None` = whole course, in | ||
| 400 | -/// which case no one can be orphaned). The blocking students are named in the | ||
| 401 | -/// message so the teacher knows whose work to clear (or whom to keep assigned) | ||
| 402 | -/// first. | ||
| 403 | -async fn ensure_no_orphans( | ||
| 404 | - homework: &Homework, | ||
| 405 | - new_assigned: Option<&[UserId]>, | ||
| 406 | - db: &Database, | ||
| 407 | -) -> Result<(), AppError> { | ||
| 408 | - // Whole-course covers everyone — no narrowing, no orphans. | ||
| 409 | - let Some(subset) = new_assigned else { | ||
| 410 | - return Ok(()); | ||
| 411 | - }; | ||
| 412 | - let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), db).await?; | ||
| 413 | - let results = HomeworkResult::list_for_homework(homework.get_id(), db).await?; | ||
| 414 | - let mut blocked: Vec<String> = Vec::new(); | ||
| 415 | - for user in submissions | ||
| 416 | - .iter() | ||
| 417 | - .map(HomeworkSubmission::get_user) | ||
| 418 | - .chain(results.iter().map(HomeworkResult::get_user)) | ||
| 419 | - { | ||
| 420 | - let key = user.key().to_string(); | ||
| 421 | - if !subset.contains(user) && !blocked.contains(&key) { | ||
| 422 | - blocked.push(key); | ||
| 423 | - } | ||
| 424 | - } | ||
| 425 | - if blocked.is_empty() { | ||
| 426 | - Ok(()) | ||
| 427 | - } else { | ||
| 428 | - Err(AppError::ConflictOwned(format!( | ||
| 429 | - "narrowing the assigned list would orphan existing work by {} student(s): {}", | ||
| 430 | - blocked.len(), | ||
| 431 | - blocked.join(", ") | ||
| 432 | - ))) | ||
| 433 | - } | ||
| 434 | -} | ||
| 435 | - | ||
| 436 | /// Delete a homework and everything under it — submissions, their files, and | 361 | /// Delete a homework and everything under it — submissions, their files, and |
| 437 | /// results — then unlink the file blobs from disk. Requires teacher+ and | 362 | /// results — then unlink the file blobs from disk. Requires teacher+ and |
| 438 | /// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease | 363 | /// management rights over its course. Held under [`HOMEWORK_LOCK`]'s write lease |
| @@ -466,73 +391,16 @@ async fn delete_homework( | |||
| 466 | )); | 391 | )); |
| 467 | } | 392 | } |
| 468 | crate::service::course::require_open(&st.db, &course).await?; | 393 | crate::service::course::require_open(&st.db, &course).await?; |
| 469 | - let _guard = HOMEWORK_LOCK.write().await; | 394 | + // The writer lease, the blob-key collection, and the cascade are |
| 470 | - let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; | 395 | + // [`service::homework::delete`]'s; unlinking the blobs stays here because |
| 471 | - homework.delete(&st.db).await?; | 396 | + // only the web layer knows `files_path`. |
| 397 | + let blob_keys = service::homework::delete(&st.db, homework).await?; | ||
| 472 | for key in &blob_keys { | 398 | for key in &blob_keys { |
| 473 | remove_blob(&st.files_path, key).await; | 399 | remove_blob(&st.files_path, key).await; |
| 474 | } | 400 | } |
| 475 | Ok(StatusCode::NO_CONTENT) | 401 | Ok(StatusCode::NO_CONTENT) |
| 476 | } | 402 | } |
| 477 | 403 | ||
| 478 | -/// A 403 unless `user` is enrolled in `course` — the homework twin of the exam | ||
| 479 | -/// sitting wall ([`crate::service::exam_attempt::ensure_enrolled`], which is `Exam`-shaped). | ||
| 480 | -/// Submitting is course content, so leaving the course closes it; re-checked on | ||
| 481 | -/// every submission and file write, so an unenrollment mid-task bites the next. | ||
| 482 | -async fn ensure_enrolled(course: &CourseId, user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 483 | - if service::enrollment::read_for_user(db, course, user) | ||
| 484 | - .await? | ||
| 485 | - .is_none() | ||
| 486 | - { | ||
| 487 | - return Err(AppError::Forbidden( | ||
| 488 | - "you are not enrolled in this homework's course", | ||
| 489 | - )); | ||
| 490 | - } | ||
| 491 | - Ok(()) | ||
| 492 | -} | ||
| 493 | - | ||
| 494 | -/// Read a homework and clear `user` to act on their own submission to it — the | ||
| 495 | -/// shared wall of the submission, file, and (student side of the) download | ||
| 496 | -/// paths. Three gates, in order: | ||
| 497 | -/// | ||
| 498 | -/// 1. Exact `Student` on the *live* role. Teachers assign homework, they never | ||
| 499 | -/// hand it in; the `RequireStudent` extractor's ≥Student would wave a | ||
| 500 | -/// promoted teacher through, so this checks the role `CurrentUser` read for | ||
| 501 | -/// this very request — the same reasoning as [`crate::service::exam_attempt::ensure_student`]. | ||
| 502 | -/// 2. Current enrollment in the course. | ||
| 503 | -/// 3. The audience check: a student a subset homework does not name gets a 404, | ||
| 504 | -/// never a 403, so a subset assignment never leaks to those left out (the | ||
| 505 | -/// no-leak idiom an unseen exam draft uses). | ||
| 506 | -async fn gate_own_submission(id: &str, user: &User, db: &Database) -> Result<Homework, AppError> { | ||
| 507 | - let homework = Homework::read(&HomeworkId::from_key(id), db) | ||
| 508 | - .await? | ||
| 509 | - .ok_or(AppError::NotFound)?; | ||
| 510 | - if user.get_role() != Role::Student { | ||
| 511 | - return Err(AppError::Forbidden( | ||
| 512 | - "only students have homework submissions", | ||
| 513 | - )); | ||
| 514 | - } | ||
| 515 | - ensure_enrolled(homework.get_course(), user.get_id(), db).await?; | ||
| 516 | - if !homework.student_sees(user.get_id()) { | ||
| 517 | - return Err(AppError::NotFound); | ||
| 518 | - } | ||
| 519 | - Ok(homework) | ||
| 520 | -} | ||
| 521 | - | ||
| 522 | -/// The term wall of the student side: an archived term makes past years | ||
| 523 | -/// read-only. Deliberately *not* inside [`gate_own_submission`] — that gate | ||
| 524 | -/// also fronts the download read, and an archived year is still browsable. So | ||
| 525 | -/// every student *write* calls this right after the gate, which keeps the | ||
| 526 | -/// order that matters: a student the homework never named is refused by the | ||
| 527 | -/// audience check with a 404 and never learns the homework exists. A course | ||
| 528 | -/// that vanished under us is the gates' own business, not this one's. | ||
| 529 | -async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { | ||
| 530 | - if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { | ||
| 531 | - crate::service::course::require_open(db, &course).await?; | ||
| 532 | - } | ||
| 533 | - Ok(()) | ||
| 534 | -} | ||
| 535 | - | ||
| 536 | /// One file attached to a submission — metadata only; the bytes download | 404 | /// One file attached to a submission — metadata only; the bytes download |
| 537 | /// separately from `GET /homework/{id}/submission/files/{fid}`. | 405 | /// separately from `GET /homework/{id}/submission/files/{fid}`. |
| 538 | #[derive(Serialize, ToSchema)] | 406 | #[derive(Serialize, ToSchema)] |
| @@ -676,62 +544,28 @@ async fn submit( | |||
| 676 | Json(req): Json<SubmitHomework>, | 544 | Json(req): Json<SubmitHomework>, |
| 677 | ) -> Result<(StatusCode, Json<SubmissionResponse>), AppError> { | 545 | ) -> Result<(StatusCode, Json<SubmissionResponse>), AppError> { |
| 678 | // Empty text stores as "no note", so a present-but-blank row is never left. | 546 | // Empty text stores as "no note", so a present-but-blank row is never left. |
| 679 | - let text = match req.text { | 547 | + let text = match &req.text { |
| 680 | - Some(ref text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), | 548 | + Some(text) if !text.is_empty() => Some(SubmissionText::try_new(text)?), |
| 681 | _ => None, | 549 | _ => None, |
| 682 | }; | 550 | }; |
| 683 | - // Reader lease of HOMEWORK_LOCK: no longer the freeze (that is the stamp on | 551 | + // The reader lease of [`HOMEWORK_LOCK`], the gate, the term wall, the |
| 684 | - // the row, below), but still the interlock against a PATCH re-scoping this | 552 | + // graded check, and the upsert are one unit in |
| 685 | - // homework's audience while the submission lands under it. Taken *before* | 553 | + // [`service::homework_submission::submit`] — the audience interlock, not |
| 686 | - // the gate read, as in `add_submission_file`: read first and the audience | 554 | + // the freeze (that is the stamp on the row). |
| 687 | - // this gate approved is one committed PATCH old, so the narrowing that just | 555 | + let landed = service::homework_submission::submit(&st.db, &user, &id, text).await?; |
| 688 | - // passed `ensure_no_orphans` (no submission yet) is followed by the very | 556 | + let files = |
| 689 | - // submission it would have refused. Holding the lease across gate *and* | 557 | + service::homework_file::list_for_submission(&st.db, landed.submission.get_id()).await?; |
| 690 | - // write is what makes the PATCH wait and then see the row. | 558 | + let status = if landed.existed { |
| 691 | - let _guard = HOMEWORK_LOCK.read().await; | ||
| 692 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | ||
| 693 | - require_open_term(&homework, &st.db).await?; | ||
| 694 | - // The graded gate, twice over. This read answers the common case — graded | ||
| 695 | - // minutes ago, and the student who never submitted has no row to carry the | ||
| 696 | - // freeze; the upsert's own `WHERE` (the grade stamp on the row) is what | ||
| 697 | - // holds when the grade lands *while* this request runs. | ||
| 698 | - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) | ||
| 699 | - .await? | ||
| 700 | - .is_some() | ||
| 701 | - { | ||
| 702 | - return Err(AppError::Conflict( | ||
| 703 | - "this homework has been graded — ask the teacher to remove the grade before editing your submission", | ||
| 704 | - )); | ||
| 705 | - } | ||
| 706 | - // 201-vs-200: a prior read is exact, where comparing the returned stamps | ||
| 707 | - // would misreport a same-millisecond re-submit as a create. | ||
| 708 | - let existed = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) | ||
| 709 | - .await? | ||
| 710 | - .is_some(); | ||
| 711 | - let Some(submission) = | ||
| 712 | - HomeworkSubmission::upsert(&homework, user.get_id(), text, &st.db).await? | ||
| 713 | - else { | ||
| 714 | - return Err(AppError::Conflict( | ||
| 715 | - "this homework has been graded — ask the teacher to remove the grade before editing your submission", | ||
| 716 | - )); | ||
| 717 | - }; | ||
| 718 | - // Only a first hand-in moved a counter, so only a first hand-in can have | ||
| 719 | - // earned anything — an edit re-runs nothing. | ||
| 720 | - if !existed { | ||
| 721 | - award_badges(user.get_id(), &st.db).await; | ||
| 722 | - } | ||
| 723 | - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; | ||
| 724 | - let status = if existed { | ||
| 725 | StatusCode::OK | 559 | StatusCode::OK |
| 726 | } else { | 560 | } else { |
| 727 | StatusCode::CREATED | 561 | StatusCode::CREATED |
| 728 | }; | 562 | }; |
| 729 | - // A result can't exist here — the gate above would have 409'd. | 563 | + // A result can't exist here — the gate would have 409'd. |
| 730 | Ok(( | 564 | Ok(( |
| 731 | status, | 565 | status, |
| 732 | Json(SubmissionResponse::new( | 566 | Json(SubmissionResponse::new( |
| 733 | - &homework, | 567 | + &landed.homework, |
| 734 | - &submission, | 568 | + &landed.submission, |
| 735 | &files, | 569 | &files, |
| 736 | None, | 570 | None, |
| 737 | )), | 571 | )), |
| @@ -759,12 +593,14 @@ async fn get_submission( | |||
| 759 | CurrentUser(user): CurrentUser, | 593 | CurrentUser(user): CurrentUser, |
| 760 | Path(id): Path<String>, | 594 | Path(id): Path<String>, |
| 761 | ) -> Result<Json<SubmissionResponse>, AppError> { | 595 | ) -> Result<Json<SubmissionResponse>, AppError> { |
| 762 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | 596 | + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 763 | - let submission = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) | 597 | + let submission = |
| 764 | - .await? | 598 | + service::homework_submission::read_for(&st.db, homework.get_id(), user.get_id()) |
| 765 | - .ok_or(AppError::NotFound)?; | 599 | + .await? |
| 766 | - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; | 600 | + .ok_or(AppError::NotFound)?; |
| 767 | - let result = HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db).await?; | 601 | + let files = service::homework_file::list_for_submission(&st.db, submission.get_id()).await?; |
| 602 | + let result = | ||
| 603 | + service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()).await?; | ||
| 768 | Ok(Json(SubmissionResponse::new( | 604 | Ok(Json(SubmissionResponse::new( |
| 769 | &homework, | 605 | &homework, |
| 770 | &submission, | 606 | &submission, |
| @@ -796,52 +632,16 @@ async fn delete_submission( | |||
| 796 | CurrentUser(user): CurrentUser, | 632 | CurrentUser(user): CurrentUser, |
| 797 | Path(id): Path<String>, | 633 | Path(id): Path<String>, |
| 798 | ) -> Result<StatusCode, AppError> { | 634 | ) -> Result<StatusCode, AppError> { |
| 799 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | 635 | + // Gate, term wall, graded check, and the cascade are |
| 800 | - require_open_term(&homework, &st.db).await?; | 636 | + // [`service::homework_submission::delete`]'s; the file rows it returns |
| 801 | - // Reader lease as in `submit` — the audience interlock, not the freeze. | 637 | + // carry the blob names to unlink now that the rows are gone. |
| 802 | - let _guard = HOMEWORK_LOCK.read().await; | 638 | + let files = service::homework_submission::delete(&st.db, &user, &id).await?; |
| 803 | - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) | ||
| 804 | - .await? | ||
| 805 | - .is_some() | ||
| 806 | - { | ||
| 807 | - return Err(AppError::Conflict( | ||
| 808 | - "this homework has been graded — ask the teacher to remove the grade before deleting your submission", | ||
| 809 | - )); | ||
| 810 | - } | ||
| 811 | - let submission = HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db) | ||
| 812 | - .await? | ||
| 813 | - .ok_or(AppError::NotFound)?; | ||
| 814 | - // Collect blob names before the cascade (submission.delete wipes the file | ||
| 815 | - // rows in the same transaction), then unlink after the rows are gone. | ||
| 816 | - let files = HomeworkFile::list_for_submission(submission.get_id(), &st.db).await?; | ||
| 817 | - // The delete carries the freeze as its own condition, so a grade landing | ||
| 818 | - // since the read above refuses it rather than wiping graded work. | ||
| 819 | - if submission.delete(&st.db).await?.is_none() { | ||
| 820 | - return Err(AppError::Conflict( | ||
| 821 | - "this homework has been graded — ask the teacher to remove the grade before deleting your submission", | ||
| 822 | - )); | ||
| 823 | - } | ||
| 824 | - // The counters just came down; a badge already earned stays earned (`sync` | ||
| 825 | - // only ever adds), so this is here to keep the award rows in step with the | ||
| 826 | - // *next* submission rather than to take anything back. | ||
| 827 | - award_badges(user.get_id(), &st.db).await; | ||
| 828 | for file in &files { | 639 | for file in &files { |
| 829 | remove_blob(&st.files_path, file.get_file()).await; | 640 | remove_blob(&st.files_path, file.get_file()).await; |
| 830 | } | 641 | } |
| 831 | Ok(StatusCode::NO_CONTENT) | 642 | Ok(StatusCode::NO_CONTENT) |
| 832 | } | 643 | } |
| 833 | 644 | ||
| 834 | -/// Bring one user's badge awards up to date after a write moved their counters | ||
| 835 | -/// — the student's after a submission, the grader's after a grade. Never fails | ||
| 836 | -/// the request it follows: a badge is a decoration on top | ||
| 837 | -/// of the work, and losing one to a transient database error is not worth | ||
| 838 | -/// refusing a hand-in over — the next counter move re-runs this and heals it. | ||
| 839 | -async fn award_badges(user: &UserId, db: &Database) { | ||
| 840 | - if let Err(err) = badge::sync(user, db).await { | ||
| 841 | - tracing::warn!("failed to sync badges for {}: {err}", user.key()); | ||
| 842 | - } | ||
| 843 | -} | ||
| 844 | - | ||
| 845 | /// Serve a submission file as a download — `Content-Disposition: attachment`, | 645 | /// Serve a submission file as a download — `Content-Disposition: attachment`, |
| 846 | /// never inline. Homework files take *any* content type (documents, photos — | 646 | /// never inline. Homework files take *any* content type (documents, photos — |
| 847 | /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only, | 647 | /// and so a `text/html` or `image/svg+xml` too), so, unlike the raster-only, |
| @@ -909,8 +709,8 @@ async fn upload_submission_file( | |||
| 909 | // Pre-flight, so a caller with no business here is refused before uploading | 709 | // Pre-flight, so a caller with no business here is refused before uploading |
| 910 | // 25 MiB; the gate that *licenses the write* is the one under the lease | 710 | // 25 MiB; the gate that *licenses the write* is the one under the lease |
| 911 | // below, because this snapshot goes stale while the body streams. | 711 | // below, because this snapshot goes stale while the body streams. |
| 912 | - let preflight = gate_own_submission(&id, &user, &st.db).await?; | 712 | + let preflight = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 913 | - require_open_term(&preflight, &st.db).await?; | 713 | + service::homework::require_open_term(&preflight, &st.db).await?; |
| 914 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); | 714 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); |
| 915 | // Consume the body before taking the lock — a slow upload must not stall the | 715 | // Consume the body before taking the lock — a slow upload must not stall the |
| 916 | // homework subsystem (mirrors the exam/note image uploads). | 716 | // homework subsystem (mirrors the exam/note image uploads). |
| @@ -922,9 +722,11 @@ async fn upload_submission_file( | |||
| 922 | "this homework has been graded — ask the teacher to remove the grade before adding files", | 722 | "this homework has been graded — ask the teacher to remove the grade before adding files", |
| 923 | ); | 723 | ); |
| 924 | // Reader lease as in `submit` — the audience interlock, not the freeze. | 724 | // Reader lease as in `submit` — the audience interlock, not the freeze. |
| 925 | - // Taken before the cap claim inside `insert`, never after (the lock order | 725 | + // Taken before the cap claim inside the insert, never after (the lock |
| 926 | - // is HOMEWORK_LOCK, then the counter lock). | 726 | + // order is HOMEWORK_LOCK, then the counter lock). The lock lives in |
| 927 | - let _guard = HOMEWORK_LOCK.read().await; | 727 | + // [`service::homework`]; the blob write stays here, inside the lease, |
| 728 | + // because the row's "stored row points at a real blob" ordering does. | ||
| 729 | + let _guard = service::homework::HOMEWORK_LOCK.read().await; | ||
| 928 | // Re-read the homework *under* the lease. Streaming the body takes as long | 730 | // Re-read the homework *under* the lease. Streaming the body takes as long |
| 929 | // as the client wants it to, and a homework delete (a writer) both takes | 731 | // as the client wants it to, and a homework delete (a writer) both takes |
| 930 | // and releases its lease inside that window — so the pre-flight snapshot | 732 | // and releases its lease inside that window — so the pre-flight snapshot |
| @@ -932,31 +734,10 @@ async fn upload_submission_file( | |||
| 932 | // auto-create a submission, credit the badge counters and write a file | 734 | // auto-create a submission, credit the badge counters and write a file |
| 933 | // under it, all unreachable afterwards. A gate read before the body is a | 735 | // under it, all unreachable afterwards. A gate read before the body is a |
| 934 | // pre-flight; a gate read after it is the decision. | 736 | // pre-flight; a gate read after it is the decision. |
| 935 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | 737 | + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 936 | // Re-walled too: the term can be archived while the body streams. | 738 | // Re-walled too: the term can be archived while the body streams. |
| 937 | - require_open_term(&homework, &st.db).await?; | 739 | + service::homework::require_open_term(&homework, &st.db).await?; |
| 938 | - // The common-case gate; the freeze itself rides on the writes below. | 740 | + let submission = service::homework_file::ensure_can_attach(&st.db, &user, &homework).await?; |
| 939 | - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) | ||
| 940 | - .await? | ||
| 941 | - .is_some() | ||
| 942 | - { | ||
| 943 | - return Err(GRADED); | ||
| 944 | - } | ||
| 945 | - // A submission row must exist to hang the file off; auto-create an empty one | ||
| 946 | - // for the photo-only case rather than force a separate text submit first. | ||
| 947 | - let submission = | ||
| 948 | - match HomeworkSubmission::read_for(homework.get_id(), user.get_id(), &st.db).await? { | ||
| 949 | - Some(existing) => existing, | ||
| 950 | - // A photo-only hand-in is a hand-in: it creates the row, so it moves | ||
| 951 | - // the counters, so it earns badges exactly as a text submit does. | ||
| 952 | - None => { | ||
| 953 | - let created = HomeworkSubmission::upsert(&homework, user.get_id(), None, &st.db) | ||
| 954 | - .await? | ||
| 955 | - .ok_or(GRADED)?; | ||
| 956 | - award_badges(user.get_id(), &st.db).await; | ||
| 957 | - created | ||
| 958 | - } | ||
| 959 | - }; | ||
| 960 | 741 | ||
| 961 | // Blob first, row second — a stored row always points at a real blob. The | 742 | // Blob first, row second — a stored row always points at a real blob. The |
| 962 | // 10-file cap and the freeze are one conditional write on the submission row | 743 | // 10-file cap and the freeze are one conditional write on the submission row |
| @@ -972,7 +753,7 @@ async fn upload_submission_file( | |||
| 972 | tokio::fs::write(&path, &upload.data) | 753 | tokio::fs::write(&path, &upload.data) |
| 973 | .await | 754 | .await |
| 974 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; | 755 | .map_err(|err| AppError::Internal(format!("failed to store the file blob: {err}")))?; |
| 975 | - let stored = match file.insert(&st.db).await { | 756 | + let stored = match service::homework_file::insert(&st.db, file).await { |
| 976 | Ok(Some(stored)) => stored, | 757 | Ok(Some(stored)) => stored, |
| 977 | // `None` is the freeze biting, an `Err` the file cap (or worse); either | 758 | // `None` is the freeze biting, an `Err` the file cap (or worse); either |
| 978 | // way the blob just written has no row and must go. | 759 | // way the blob just written has no row and must go. |
| @@ -982,7 +763,7 @@ async fn upload_submission_file( | |||
| 982 | } | 763 | } |
| 983 | }; | 764 | }; |
| 984 | // A landed file moves the submission's "last touched" clock (the late flag). | 765 | // A landed file moves the submission's "last touched" clock (the late flag). |
| 985 | - HomeworkSubmission::touch(submission.get_id(), &st.db).await?; | 766 | + service::homework_submission::touch(&st.db, submission.get_id()).await?; |
| 986 | Ok(( | 767 | Ok(( |
| 987 | StatusCode::CREATED, | 768 | StatusCode::CREATED, |
| 988 | Json(HomeworkFileResponse::new(&stored)), | 769 | Json(HomeworkFileResponse::new(&stored)), |
| @@ -1019,9 +800,9 @@ async fn download_submission_file( | |||
| 1019 | let file_id = HomeworkFileId::from_key(&fid); | 800 | let file_id = HomeworkFileId::from_key(&fid); |
| 1020 | let file = if user.get_role() == Role::Student { | 801 | let file = if user.get_role() == Role::Student { |
| 1021 | // Student: only their own file, behind the full submission gate. | 802 | // Student: only their own file, behind the full submission gate. |
| 1022 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | 803 | + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 1023 | let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); | 804 | let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); |
| 1024 | - HomeworkFile::read_for(&file_id, &submission, &st.db) | 805 | + service::homework_file::read_for(&st.db, &file_id, &submission) |
| 1025 | .await? | 806 | .await? |
| 1026 | .ok_or(AppError::NotFound)? | 807 | .ok_or(AppError::NotFound)? |
| 1027 | } else { | 808 | } else { |
| @@ -1032,7 +813,7 @@ async fn download_submission_file( | |||
| 1032 | "only the course creator, an assigned teacher, or a manager/admin can read submission files", | 813 | "only the course creator, an assigned teacher, or a manager/admin can read submission files", |
| 1033 | )); | 814 | )); |
| 1034 | } | 815 | } |
| 1035 | - HomeworkFile::read_in_homework(&file_id, homework.get_id(), &st.db) | 816 | + service::homework_file::read_in_homework(&st.db, &file_id, homework.get_id()) |
| 1036 | .await? | 817 | .await? |
| 1037 | .ok_or(AppError::NotFound)? | 818 | .ok_or(AppError::NotFound)? |
| 1038 | }; | 819 | }; |
| @@ -1064,28 +845,32 @@ async fn delete_submission_file( | |||
| 1064 | CurrentUser(user): CurrentUser, | 845 | CurrentUser(user): CurrentUser, |
| 1065 | Path((id, fid)): Path<(String, String)>, | 846 | Path((id, fid)): Path<(String, String)>, |
| 1066 | ) -> Result<StatusCode, AppError> { | 847 | ) -> Result<StatusCode, AppError> { |
| 1067 | - let homework = gate_own_submission(&id, &user, &st.db).await?; | 848 | + let homework = service::homework::gate_own_submission(&id, &user, &st.db).await?; |
| 1068 | - require_open_term(&homework, &st.db).await?; | 849 | + service::homework::require_open_term(&homework, &st.db).await?; |
| 1069 | const GRADED: AppError = AppError::Conflict( | 850 | const GRADED: AppError = AppError::Conflict( |
| 1070 | "this homework has been graded — ask the teacher to remove the grade before deleting files", | 851 | "this homework has been graded — ask the teacher to remove the grade before deleting files", |
| 1071 | ); | 852 | ); |
| 1072 | // Reader lease as in `submit` — the audience interlock, not the freeze. | 853 | // Reader lease as in `submit` — the audience interlock, not the freeze. |
| 1073 | - let _guard = HOMEWORK_LOCK.read().await; | 854 | + let _guard = service::homework::HOMEWORK_LOCK.read().await; |
| 1074 | - if HomeworkResult::read_for(homework.get_id(), user.get_id(), &st.db) | 855 | + if service::homework_result::read_for(&st.db, homework.get_id(), user.get_id()) |
| 1075 | .await? | 856 | .await? |
| 1076 | .is_some() | 857 | .is_some() |
| 1077 | { | 858 | { |
| 1078 | return Err(GRADED); | 859 | return Err(GRADED); |
| 1079 | } | 860 | } |
| 1080 | let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); | 861 | let submission = HomeworkSubmissionId::composite(homework.get_id(), user.get_id()); |
| 1081 | - let file = HomeworkFile::read_for(&HomeworkFileId::from_key(&fid), &submission, &st.db) | 862 | + let file = |
| 1082 | - .await? | 863 | + service::homework_file::read_for(&st.db, &HomeworkFileId::from_key(&fid), &submission) |
| 1083 | - .ok_or(AppError::NotFound)?; | 864 | + .await? |
| 865 | + .ok_or(AppError::NotFound)?; | ||
| 1084 | let blob = file.get_file().to_string(); | 866 | let blob = file.get_file().to_string(); |
| 1085 | // The delete's own transaction re-stamps the submission's "last touched" | 867 | // The delete's own transaction re-stamps the submission's "last touched" |
| 1086 | // clock (the late flag) as its freeze gate, so a refused delete moves | 868 | // clock (the late flag) as its freeze gate, so a refused delete moves |
| 1087 | // nothing and no separate touch is owed here. | 869 | // nothing and no separate touch is owed here. |
| 1088 | - if file.delete(&st.db).await?.is_none() { | 870 | + if service::homework_file::delete(&st.db, file) |
| 871 | + .await? | ||
| 872 | + .is_none() | ||
| 873 | + { | ||
| 1089 | return Err(GRADED); | 874 | return Err(GRADED); |
| 1090 | } | 875 | } |
| 1091 | remove_blob(&st.files_path, &blob).await; | 876 | remove_blob(&st.files_path, &blob).await; |
| @@ -1138,12 +923,12 @@ async fn grade_homework( | |||
| 1138 | Path(id): Path<String>, | 923 | Path(id): Path<String>, |
| 1139 | Json(req): Json<GradeHomework>, | 924 | Json(req): Json<GradeHomework>, |
| 1140 | ) -> Result<Json<HomeworkResultResponse>, AppError> { | 925 | ) -> Result<Json<HomeworkResultResponse>, AppError> { |
| 1141 | - // Writer lease of [`HOMEWORK_LOCK`], taken before the homework read: a | 926 | + // The grading gates and the writer lease of [`HOMEWORK_LOCK`] live in |
| 1142 | - // grade is what freezes a submission, so it must not interleave with the | 927 | + // [`service::homework_result::grade`]: a grade is what freezes a |
| 1143 | - // read side's gate-through-write submission edits — and reading the | 928 | + // submission, so it must not interleave with the read side's |
| 1144 | - // homework under the lease keeps a homework delete (a fellow writer) from | 929 | + // gate-through-write submission edits — and the homework is re-read under |
| 1145 | - // letting this upsert resurrect a result row under a vanished homework. | 930 | + // the lease there, which keeps a homework delete (a fellow writer) from |
| 1146 | - let _guard = HOMEWORK_LOCK.write().await; | 931 | + // letting the upsert resurrect a result row under a vanished homework. |
| 1147 | let (homework, course) = homework_with_course(&id, &st.db).await?; | 932 | let (homework, course) = homework_with_course(&id, &st.db).await?; |
| 1148 | if !can_manage_course(&course, &teacher) { | 933 | if !can_manage_course(&course, &teacher) { |
| 1149 | return Err(AppError::Forbidden( | 934 | return Err(AppError::Forbidden( |
| @@ -1156,62 +941,11 @@ async fn grade_homework( | |||
| 1156 | let mark = req.mark.map(Mark::try_new).transpose()?; | 941 | let mark = req.mark.map(Mark::try_new).transpose()?; |
| 1157 | let target = UserId::from_key(&req.user); | 942 | let target = UserId::from_key(&req.user); |
| 1158 | 943 | ||
| 1159 | - // Grading never targets oneself — no grader, whatever their role, may | 944 | + // The self-grade, target-exists, live-student, enrollment, and audience |
| 1160 | - // write their own grade. | 945 | + // gates run inside [`service::homework_result::grade`], under the lease. |
| 1161 | - if &target == teacher.get_id() { | 946 | + let result = |
| 1162 | - return Err(AppError::Forbidden("grading yourself is not allowed")); | 947 | + service::homework_result::grade(&st.db, homework.get_id(), &teacher, status, mark, &target) |
| 1163 | - } | 948 | + .await?; |
| 1164 | - | ||
| 1165 | - // Target user must exist. | ||
| 1166 | - let Some(target_user) = crate::service::user::read(&st.db, &target).await? else { | ||
| 1167 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 1168 | - field: "user", | ||
| 1169 | - reason: "target user does not exist", | ||
| 1170 | - })); | ||
| 1171 | - }; | ||
| 1172 | - | ||
| 1173 | - // Only students carry homework grades — the live role, so a stale | ||
| 1174 | - // enrollment left behind by a promotion can't reopen grading for staff. | ||
| 1175 | - if target_user.get_role() != Role::Student { | ||
| 1176 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 1177 | - field: "user", | ||
| 1178 | - reason: "only students can be graded", | ||
| 1179 | - })); | ||
| 1180 | - } | ||
| 1181 | - | ||
| 1182 | - // ... enrolled in the homework's course ... | ||
| 1183 | - if service::enrollment::read_for_user(&st.db, homework.get_course(), &target) | ||
| 1184 | - .await? | ||
| 1185 | - .is_none() | ||
| 1186 | - { | ||
| 1187 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 1188 | - field: "user", | ||
| 1189 | - reason: "target user is not enrolled in this course", | ||
| 1190 | - })); | ||
| 1191 | - } | ||
| 1192 | - | ||
| 1193 | - // ... and in the homework's audience — a subset assignment is also the | ||
| 1194 | - // grading roster, so a grade can't land on a student the homework never | ||
| 1195 | - // named. | ||
| 1196 | - if !homework.student_sees(&target) { | ||
| 1197 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 1198 | - field: "user", | ||
| 1199 | - reason: "target user is not in this homework's audience", | ||
| 1200 | - })); | ||
| 1201 | - } | ||
| 1202 | - | ||
| 1203 | - let result = HomeworkResult::grade( | ||
| 1204 | - homework.get_id(), | ||
| 1205 | - &target, | ||
| 1206 | - status, | ||
| 1207 | - mark, | ||
| 1208 | - teacher.get_id(), | ||
| 1209 | - &st.db, | ||
| 1210 | - ) | ||
| 1211 | - .await?; | ||
| 1212 | - // The grade credited the *grader*'s `marks_given`, not the student's — a | ||
| 1213 | - // homework grade moves no counter of the student's at all. | ||
| 1214 | - award_badges(teacher.get_id(), &st.db).await; | ||
| 1215 | Ok(Json(HomeworkResultResponse::new(&result))) | 949 | Ok(Json(HomeworkResultResponse::new(&result))) |
| 1216 | } | 950 | } |
| 1217 | 951 | ||
| @@ -1240,10 +974,9 @@ async fn remove_homework_result( | |||
| 1240 | RequireTeacher(user): RequireTeacher, | 974 | RequireTeacher(user): RequireTeacher, |
| 1241 | Path((id, target)): Path<(String, String)>, | 975 | Path((id, target)): Path<(String, String)>, |
| 1242 | ) -> Result<StatusCode, AppError> { | 976 | ) -> Result<StatusCode, AppError> { |
| 1243 | - // Writer lease, before the read — the twin of grading's: removing the | 977 | + // The writer lease of [`HOMEWORK_LOCK`] is [`service::homework_result::ungrade`]'s |
| 1244 | - // grade is what unfreezes the submission, so it must not straddle the read | 978 | + // — removing the grade is what unfreezes the submission, so it must not |
| 1245 | - // side's gate-through-write edits either. | 979 | + // straddle the read side's gate-through-write edits either. |
| 1246 | - let _guard = HOMEWORK_LOCK.write().await; | ||
| 1247 | let (homework, course) = homework_with_course(&id, &st.db).await?; | 980 | let (homework, course) = homework_with_course(&id, &st.db).await?; |
| 1248 | if !can_manage_course(&course, &user) { | 981 | if !can_manage_course(&course, &user) { |
| 1249 | return Err(AppError::Forbidden( | 982 | return Err(AppError::Forbidden( |
| @@ -1252,7 +985,8 @@ async fn remove_homework_result( | |||
| 1252 | } | 985 | } |
| 1253 | crate::service::course::require_open(&st.db, &course).await?; | 986 | crate::service::course::require_open(&st.db, &course).await?; |
| 1254 | let removed = | 987 | let removed = |
| 1255 | - HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; | 988 | + service::homework_result::ungrade(&st.db, homework.get_id(), &UserId::from_key(&target)) |
| 989 | + .await?; | ||
| 1256 | if removed.is_none() { | 990 | if removed.is_none() { |
| 1257 | return Err(AppError::NotFound); | 991 | return Err(AppError::NotFound); |
| 1258 | } | 992 | } |
| @@ -1280,9 +1014,10 @@ async fn my_homework_result( | |||
| 1280 | CurrentUser(user): CurrentUser, | 1014 | CurrentUser(user): CurrentUser, |
| 1281 | Path(id): Path<String>, | 1015 | Path(id): Path<String>, |
| 1282 | ) -> Result<Json<HomeworkResultResponse>, AppError> { | 1016 | ) -> Result<Json<HomeworkResultResponse>, AppError> { |
| 1283 | - let result = HomeworkResult::read_for(&HomeworkId::from_key(&id), user.get_id(), &st.db) | 1017 | + let result = |
| 1284 | - .await? | 1018 | + service::homework_result::read_for(&st.db, &HomeworkId::from_key(&id), user.get_id()) |
| 1285 | - .ok_or(AppError::NotFound)?; | 1019 | + .await? |
| 1020 | + .ok_or(AppError::NotFound)?; | ||
| 1286 | Ok(Json(HomeworkResultResponse::new(&result))) | 1021 | Ok(Json(HomeworkResultResponse::new(&result))) |
| 1287 | } | 1022 | } |
| 1288 | 1023 | ||
| @@ -1356,8 +1091,9 @@ async fn list_homework_submissions( | |||
| 1356 | "only the course creator, an assigned teacher, or a manager/admin can list submissions", | 1091 | "only the course creator, an assigned teacher, or a manager/admin can list submissions", |
| 1357 | )); | 1092 | )); |
| 1358 | } | 1093 | } |
| 1359 | - let submissions = HomeworkSubmission::list_for_homework(homework.get_id(), &st.db).await?; | 1094 | + let submissions = |
| 1360 | - let results = HomeworkResult::list_for_homework(homework.get_id(), &st.db).await?; | 1095 | + service::homework_submission::list_for_homework(&st.db, homework.get_id()).await?; |
| 1096 | + let results = service::homework_result::list_for_homework(&st.db, homework.get_id()).await?; | ||
| 1361 | let enrolled: Vec<String> = | 1097 | let enrolled: Vec<String> = |
| 1362 | service::enrollment::list_for_course(&st.db, course.get_id(), None, 0) | 1098 | service::enrollment::list_for_course(&st.db, course.get_id(), None, 0) |
| 1363 | .await? | 1099 | .await? |
| @@ -1402,7 +1138,7 @@ async fn list_homework_submissions( | |||
| 1402 | submitted_at: submission.get_submitted_at().as_millis(), | 1138 | submitted_at: submission.get_submitted_at().as_millis(), |
| 1403 | updated_at: submission.get_updated_at().as_millis(), | 1139 | updated_at: submission.get_updated_at().as_millis(), |
| 1404 | late: submission.get_updated_at() > homework.get_due_at(), | 1140 | late: submission.get_updated_at() > homework.get_due_at(), |
| 1405 | - files: HomeworkFile::list_for_submission(submission.get_id(), &st.db) | 1141 | + files: service::homework_file::list_for_submission(&st.db, submission.get_id()) |
| 1406 | .await? | 1142 | .await? |
| 1407 | .iter() | 1143 | .iter() |
| 1408 | .map(HomeworkFileResponse::new) | 1144 | .map(HomeworkFileResponse::new) |
| @@ -1491,15 +1227,18 @@ async fn homework_report( | |||
| 1491 | } | 1227 | } |
| 1492 | let mut rows = Vec::new(); | 1228 | let mut rows = Vec::new(); |
| 1493 | for course in &courses { | 1229 | for course in &courses { |
| 1494 | - rows.extend(Homework::list_for_user_in_course(course.get_id(), &target, &st.db).await?); | 1230 | + rows.extend( |
| 1231 | + service::homework::list_for_user_in_course(&st.db, course.get_id(), &target).await?, | ||
| 1232 | + ); | ||
| 1495 | } | 1233 | } |
| 1496 | let total = rows.len() as i64; | 1234 | let total = rows.len() as i64; |
| 1497 | // Join submissions and grades onto the page alone. | 1235 | // Join submissions and grades onto the page alone. |
| 1498 | let mut items = Vec::new(); | 1236 | let mut items = Vec::new(); |
| 1499 | // Paged in the web layer: the rows are gathered course by course. | 1237 | // Paged in the web layer: the rows are gathered course by course. |
| 1500 | for homework in paginate(&rows, limit, offset) { | 1238 | for homework in paginate(&rows, limit, offset) { |
| 1501 | - let submission = HomeworkSubmission::read_for(homework.get_id(), &target, &st.db).await?; | 1239 | + let submission = |
| 1502 | - let result = HomeworkResult::read_for(homework.get_id(), &target, &st.db).await?; | 1240 | + service::homework_submission::read_for(&st.db, homework.get_id(), &target).await?; |
| 1241 | + let result = service::homework_result::read_for(&st.db, homework.get_id(), &target).await?; | ||
| 1503 | items.push(HomeworkReportEntry { | 1242 | items.push(HomeworkReportEntry { |
| 1504 | course: homework.get_course().key().to_string(), | 1243 | course: homework.get_course().key().to_string(), |
| 1505 | homework: homework.get_id().key().to_string(), | 1244 | homework: homework.get_id().key().to_string(), |
tests/regress_homework_orphans.rsmodified+9 -7
| @@ -316,8 +316,9 @@ async fn an_upload_inside_an_audience_patch_is_refused() { | |||
| 316 | /// leaves behind. | 316 | /// leaves behind. |
| 317 | #[tokio::test] | 317 | #[tokio::test] |
| 318 | async fn a_submission_under_a_vanished_homework_is_refused() { | 318 | async fn a_submission_under_a_vanished_homework_is_refused() { |
| 319 | - use hezarfen_backend::domain::homework::{Homework, HomeworkId}; | 319 | + use hezarfen_backend::db::homework::read; |
| 320 | - use hezarfen_backend::domain::homework_submission::HomeworkSubmission; | 320 | + use hezarfen_backend::db::homework_submission::upsert; |
| 321 | + use hezarfen_backend::domain::homework::HomeworkId; | ||
| 321 | use hezarfen_backend::domain::user::UserId; | 322 | use hezarfen_backend::domain::user::UserId; |
| 322 | 323 | ||
| 323 | let (app, db) = app_and_db().await; | 324 | let (app, db) = app_and_db().await; |
| @@ -326,7 +327,7 @@ async fn a_submission_under_a_vanished_homework_is_refused() { | |||
| 326 | course_with_student(&app, &db, &teacher, "kimya").await; | 327 | course_with_student(&app, &db, &teacher, "kimya").await; |
| 327 | let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; | 328 | let hw = create_homework(&app, &teacher, &course, &subject, "deneme", far_future()).await; |
| 328 | // The stale snapshot a handler would still be holding. | 329 | // The stale snapshot a handler would still be holding. |
| 329 | - let stale = Homework::read(&HomeworkId::from_key(&hw), &db) | 330 | + let stale = read(&db, &HomeworkId::from_key(&hw)) |
| 330 | .await | 331 | .await |
| 331 | .unwrap() | 332 | .unwrap() |
| 332 | .expect("the homework exists"); | 333 | .expect("the homework exists"); |
| @@ -346,7 +347,7 @@ async fn a_submission_under_a_vanished_homework_is_refused() { | |||
| 346 | "delete the homework" | 347 | "delete the homework" |
| 347 | ); | 348 | ); |
| 348 | 349 | ||
| 349 | - let refused = HomeworkSubmission::upsert(&stale, &user, None, &db).await; | 350 | + let refused = upsert(&db, &stale, &user, None).await; |
| 350 | assert!( | 351 | assert!( |
| 351 | refused.is_err(), | 352 | refused.is_err(), |
| 352 | "a submission to a homework that is gone must be refused, got {refused:?}" | 353 | "a submission to a homework that is gone must be refused, got {refused:?}" |
| @@ -385,8 +386,9 @@ async fn a_submission_under_a_vanished_homework_is_refused() { | |||
| 385 | /// that holds when the lease does not, so no handler may be in the way of it. | 386 | /// that holds when the lease does not, so no handler may be in the way of it. |
| 386 | #[tokio::test] | 387 | #[tokio::test] |
| 387 | async fn a_grade_under_a_vanished_homework_is_refused() { | 388 | async fn a_grade_under_a_vanished_homework_is_refused() { |
| 389 | + use hezarfen_backend::db::homework_result::grade; | ||
| 388 | use hezarfen_backend::domain::homework::HomeworkId; | 390 | use hezarfen_backend::domain::homework::HomeworkId; |
| 389 | - use hezarfen_backend::domain::homework_result::{HomeworkResult, HomeworkStatus}; | 391 | + use hezarfen_backend::domain::homework_result::HomeworkStatus; |
| 390 | use hezarfen_backend::domain::user::UserId; | 392 | use hezarfen_backend::domain::user::UserId; |
| 391 | 393 | ||
| 392 | let (app, db) = app_and_db().await; | 394 | let (app, db) = app_and_db().await; |
| @@ -411,13 +413,13 @@ async fn a_grade_under_a_vanished_homework_is_refused() { | |||
| 411 | ); | 413 | ); |
| 412 | 414 | ||
| 413 | // The ids a handler mid-request would still be carrying. | 415 | // The ids a handler mid-request would still be carrying. |
| 414 | - let refused = HomeworkResult::grade( | 416 | + let refused = grade( |
| 417 | + &db, | ||
| 415 | &HomeworkId::from_key(&hw), | 418 | &HomeworkId::from_key(&hw), |
| 416 | &UserId::from_key(&student_id), | 419 | &UserId::from_key(&student_id), |
| 417 | HomeworkStatus::try_new("done").unwrap(), | 420 | HomeworkStatus::try_new("done").unwrap(), |
| 418 | None, | 421 | None, |
| 419 | &UserId::from_key(&teacher_id), | 422 | &UserId::from_key(&teacher_id), |
| 420 | - &db, | ||
| 421 | ) | 423 | ) |
| 422 | .await; | 424 | .await; |
| 423 | assert!( | 425 | assert!( |