Merge branch 'layer-split/course'
Browse files at this commit49 changed files +1484 -1294
- src/ai/server.rs +2 -2
- src/db/course.rs +1025 -0
- src/db/mod.rs +1 -0
- src/db/note.rs +1 -1
- src/domain/bank_question.rs +1 -1
- src/domain/class_blueprint.rs +1 -1
- src/domain/class_course.rs +5 -3
- src/domain/class_group.rs +9 -9
- src/domain/class_member.rs +3 -3
- src/domain/course.rs +15 -998
- src/domain/course_note.rs +3 -3
- src/domain/course_note_file.rs +3 -3
- src/domain/course_session.rs +4 -6
- src/domain/enrollment.rs +5 -5
- src/domain/event.rs +1 -1
- src/domain/exam.rs +10 -12
- src/domain/exam_answer.rs +1 -1
- src/domain/exam_attempt.rs +2 -2
- src/domain/exam_question.rs +2 -2
- src/domain/homework.rs +1 -1
- src/domain/homework_file.rs +1 -1
- src/domain/homework_result.rs +1 -1
- src/domain/homework_submission.rs +1 -1
- src/domain/rag_output.rs +3 -3
- src/domain/session_attendance.rs +1 -1
- src/domain/subject.rs +7 -9
- src/domain/term.rs +11 -8
- src/service/course.rs +181 -0
- src/service/mod.rs +1 -0
- src/web/attendance.rs +1 -1
- src/web/boards.rs +2 -2
- src/web/classes.rs +10 -8
- src/web/course_notes.rs +9 -9
- src/web/courses.rs +54 -99
- src/web/events.rs +2 -2
- src/web/exam_ws.rs +2 -2
- src/web/exams/attempts.rs +3 -3
- src/web/exams/images.rs +3 -3
- src/web/exams/mod.rs +5 -5
- src/web/exams/questions.rs +6 -6
- src/web/homework.rs +8 -8
- src/web/marks.rs +2 -2
- src/web/mod.rs +16 -13
- src/web/sessions.rs +5 -5
- src/web/subjects.rs +3 -3
- src/web/users.rs +3 -3
- tests/integration.rs +20 -21
- tests/regress_course_child_orphans.rs +21 -18
- tests/regress_course_delete.rs +7 -3
src/ai/server.rsmodified+2 -2
| @@ -26,7 +26,7 @@ use crate::constant::{ | |||
| 26 | REQUEST_TIMEOUT_SECS, | 26 | REQUEST_TIMEOUT_SECS, |
| 27 | }; | 27 | }; |
| 28 | use crate::database::Database; | 28 | use crate::database::Database; |
| 29 | -use crate::domain::course::Course; | 29 | + |
| 30 | use crate::domain::course_note::CourseNote; | 30 | use crate::domain::course_note::CourseNote; |
| 31 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; | 31 | use crate::domain::course_note_file::{CourseNoteFile, CourseNoteFileId}; |
| 32 | use crate::domain::user::{User, UserId}; | 32 | use crate::domain::user::{User, UserId}; |
| @@ -639,7 +639,7 @@ async fn open_blob( | |||
| 639 | .await | 639 | .await |
| 640 | .map_err(unavailable)? | 640 | .map_err(unavailable)? |
| 641 | .ok_or_else(missing)?; | 641 | .ok_or_else(missing)?; |
| 642 | - let course = Course::read(note.get_course(), &db) | 642 | + let course = crate::service::course::read(&db, note.get_course()) |
| 643 | .await | 643 | .await |
| 644 | .map_err(unavailable)? | 644 | .map_err(unavailable)? |
| 645 | .ok_or_else(missing)?; | 645 | .ok_or_else(missing)?; |
src/db/course.rsadded+1025 -0
| @@ -0,0 +1,1025 @@ | |||
| 1 | +//! The `course` table: the unit exams, sessions, subjects and enrollments | ||
| 2 | +//! hang off. Listed newest first; deleted with its whole subtree in one | ||
| 3 | +use surrealdb::types::{RecordId, SurrealValue}; | ||
| 4 | + | ||
| 5 | +use crate::constant::{ | ||
| 6 | + CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, ENROLLMENT_COUNT_FIELD, REF_COUNT_FIELD, | ||
| 7 | +}; | ||
| 8 | +use crate::database::{Database, transaction_with_retry}; | ||
| 9 | +use crate::db::cap; | ||
| 10 | +use crate::db::field_update::FieldUpdate; | ||
| 11 | +use crate::db::page::PagedList; | ||
| 12 | +use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | ||
| 13 | +use crate::domain::term::{self, TermId}; | ||
| 14 | +use crate::domain::user::UserId; | ||
| 15 | +use crate::error::AppError; | ||
| 16 | + | ||
| 17 | +/// The `THROW` marker the delete guard aborts with — a roster that is not | ||
| 18 | +/// empty, or a course row that is no longer there. | ||
| 19 | +const ROSTER_MARK: &str = "course_roster"; | ||
| 20 | + | ||
| 21 | +/// Create the course, claiming a reference on the term it links (if any) in | ||
| 22 | +/// the *same transaction* as the row: the claim is a conditional write on | ||
| 23 | +/// the term row, so it fails when the term is already gone and it makes the | ||
| 24 | +/// term undeletable the instant this link exists — and a crash can never | ||
| 25 | +/// leave one without the other, which a claim sent as its own query could | ||
| 26 | +/// (the count would strand and the term be undeletable forever). | ||
| 27 | +pub async fn create( | ||
| 28 | + db: &Database, | ||
| 29 | + creator: &UserId, | ||
| 30 | + title: CourseTitle, | ||
| 31 | + description: CourseDescription, | ||
| 32 | + kind: CourseKind, | ||
| 33 | + term: Option<TermId>, | ||
| 34 | + capacity: Option<i64>, | ||
| 35 | +) -> Result<Course, AppError> { | ||
| 36 | + let course = Course { | ||
| 37 | + id: CourseId::generate(), | ||
| 38 | + creator: creator.clone(), | ||
| 39 | + teachers: Vec::new(), | ||
| 40 | + term, | ||
| 41 | + capacity, | ||
| 42 | + title, | ||
| 43 | + description, | ||
| 44 | + kind, | ||
| 45 | + }; | ||
| 46 | + let id = course.id.record(); | ||
| 47 | + let Some(term) = course.term.clone() else { | ||
| 48 | + let created: Option<Course> = db.create(id).content(course).await?; | ||
| 49 | + return created.ok_or_else(|| AppError::Internal("failed to create course".into())); | ||
| 50 | + }; | ||
| 51 | + match cap::claim_and_create( | ||
| 52 | + &term.record(), | ||
| 53 | + COURSE_COUNT_FIELD, | ||
| 54 | + cap::UNLIMITED, | ||
| 55 | + &id, | ||
| 56 | + &course, | ||
| 57 | + db, | ||
| 58 | + ) | ||
| 59 | + .await? | ||
| 60 | + { | ||
| 61 | + cap::Claimed::Made(created) => Ok(created), | ||
| 62 | + // Uncapped, so "full" can only mean the conditional write matched no | ||
| 63 | + // term row at all — the existence check the pre-flight lookup makes. | ||
| 64 | + cap::Claimed::Full => Err(term::gone_error()), | ||
| 65 | + // Unreachable: the id is a ULID this call just generated. | ||
| 66 | + cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> { | ||
| 71 | + Ok(db.select(id.record()).await?) | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 75 | + let mut result = db | ||
| 76 | + .query("SELECT * FROM course ORDER BY id DESC") | ||
| 77 | + .await? | ||
| 78 | + .check()?; | ||
| 79 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// The courses `user` is enrolled in — the spine of `/courses/me` and the | ||
| 83 | +/// marks report. | ||
| 84 | +pub async fn list_enrolled( | ||
| 85 | + db: &Database, | ||
| 86 | + user: &UserId, | ||
| 87 | + limit: Option<i64>, | ||
| 88 | + offset: i64, | ||
| 89 | +) -> Result<(Vec<Course>, i64), AppError> { | ||
| 90 | + PagedList::new( | ||
| 91 | + "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", | ||
| 92 | + "ORDER BY id DESC", | ||
| 93 | + ) | ||
| 94 | + .bind("usr", user.record()) | ||
| 95 | + .run(limit, offset, db) | ||
| 96 | + .await | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// The courses `user` runs — the ones they created plus the ones a manager | ||
| 100 | +/// assigned them to. A teacher's slice of the catalog. | ||
| 101 | +/// | ||
| 102 | +/// corner-cut: unpaged full table scan, and it stays one — every profile read | ||
| 103 | +/// of a teacher pays it, so the ceiling is the course table's size. It | ||
| 104 | +/// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone | ||
| 105 | +/// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the | ||
| 106 | +/// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is | ||
| 107 | +/// *wrong*, not merely useless — with it, `$usr IN teachers` and | ||
| 108 | +/// `teachers CONTAINS $usr` return **no rows at all**, which is what the | ||
| 109 | +/// integration test `assigned_teacher_manages_course_without_owning_it` | ||
| 110 | +/// catches. A plain `FIELDS teachers` index is correct but unused. The | ||
| 111 | +/// upgrade path is structural: a `course_teacher` link table indexed on | ||
| 112 | +/// `user`, the shape `enrollment` already has, turning this into two | ||
| 113 | +/// index-backed reads. | ||
| 114 | +pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> { | ||
| 115 | + let mut result = db | ||
| 116 | + .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") | ||
| 117 | + .bind(("usr", user.record())) | ||
| 118 | + .await? | ||
| 119 | + .check()?; | ||
| 120 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Load every course behind `ids` (one query) — the join half of the | ||
| 124 | +/// attendance report's per-course blocks. | ||
| 125 | +pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, AppError> { | ||
| 126 | + if ids.is_empty() { | ||
| 127 | + return Ok(Vec::new()); | ||
| 128 | + } | ||
| 129 | + let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect(); | ||
| 130 | + let mut result = db | ||
| 131 | + .query("SELECT * FROM course WHERE id IN $ids") | ||
| 132 | + .bind(("ids", records)) | ||
| 133 | + .await? | ||
| 134 | + .check()?; | ||
| 135 | + Ok(result.take::<Vec<Course>>(0)?) | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// Request-scoped: `teachers` is written by [`assign_teacher`], | ||
| 139 | +/// [`unassign_teacher`] and the demotion sweep, and nothing guards | ||
| 140 | +/// the course row across the handler's read and this write (its `TERM_LOCK` | ||
| 141 | +/// window guards the *term* it links, and the assign path takes no lock at | ||
| 142 | +/// all) — so a field the request omitted (`None`) is not written at all. | ||
| 143 | +/// Sending the snapshot's value back instead would revert a concurrent | ||
| 144 | +/// edit of that field; scoping the `SET` alone does not stop that, the | ||
| 145 | +/// values have to come from the request. `term` and `capacity` are | ||
| 146 | +/// nullable, so they take the outer/inner `Option<Option<_>>`: `None` = | ||
| 147 | +/// omitted (keep), `Some(None)` = clear. | ||
| 148 | +pub async fn update( | ||
| 149 | + db: &Database, | ||
| 150 | + course: Course, | ||
| 151 | + title: Option<CourseTitle>, | ||
| 152 | + description: Option<CourseDescription>, | ||
| 153 | + kind: Option<CourseKind>, | ||
| 154 | + term: Option<Option<TermId>>, | ||
| 155 | + capacity: Option<Option<i64>>, | ||
| 156 | +) -> Result<Course, AppError> { | ||
| 157 | + // A term move claims the new term and releases the old one inside the | ||
| 158 | + // very transaction that moves the link, so no crash can leave a count | ||
| 159 | + // without its link (the term would be undeletable forever) or a link | ||
| 160 | + // without its count. A PATCH that carried no `term_id`, or re-stated the | ||
| 161 | + // link it already had, moves neither counter. | ||
| 162 | + let (claim, release) = term::ref_move(course.term.as_ref(), &term); | ||
| 163 | + let expected = course.term.as_ref().map(TermId::record); | ||
| 164 | + FieldUpdate::new(course.id.record()) | ||
| 165 | + .set("title", title) | ||
| 166 | + .set("description", description) | ||
| 167 | + .set("kind", kind) | ||
| 168 | + .set("term", term.map(|term| term.map(|term| term.record()))) | ||
| 169 | + .set("capacity", capacity) | ||
| 170 | + .refcount( | ||
| 171 | + COURSE_COUNT_FIELD, | ||
| 172 | + "term", | ||
| 173 | + expected, | ||
| 174 | + claim, | ||
| 175 | + release, | ||
| 176 | + term::gone_error(), | ||
| 177 | + ) | ||
| 178 | + .run::<Course>(db) | ||
| 179 | + .await | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +/// Assign `teacher` to run this course, or return the course untouched if | ||
| 183 | +/// they already run it — assignment is idempotent, like enrollment. | ||
| 184 | +/// Field-scoped, and the new list is folded server-side out of the *stored* | ||
| 185 | +/// one: a course PATCH awaits a term lookup between its read and its write, | ||
| 186 | +/// so a whole-row save from either side would revert the other. The | ||
| 187 | +/// `array::distinct` keeps the assignment idempotent even when two requests | ||
| 188 | +/// name the same teacher at once (the early return only sees a stale row). | ||
| 189 | +pub async fn assign_teacher( | ||
| 190 | + db: &Database, | ||
| 191 | + course: Course, | ||
| 192 | + teacher: &UserId, | ||
| 193 | +) -> Result<Course, AppError> { | ||
| 194 | + if course.is_assigned(teacher) { | ||
| 195 | + return Ok(course); | ||
| 196 | + } | ||
| 197 | + let mut result = db | ||
| 198 | + .query( | ||
| 199 | + "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) | ||
| 200 | + RETURN AFTER", | ||
| 201 | + ) | ||
| 202 | + .bind(("id", course.id.record())) | ||
| 203 | + .bind(("usr", teacher.record())) | ||
| 204 | + .await? | ||
| 205 | + .check()?; | ||
| 206 | + result | ||
| 207 | + .take::<Vec<Course>>(0)? | ||
| 208 | + .into_iter() | ||
| 209 | + .next() | ||
| 210 | + .ok_or(AppError::NotFound) | ||
| 211 | +} | ||
| 212 | + | ||
| 213 | +/// Drop `teacher` from this course. `None` when they weren't assigned, so | ||
| 214 | +/// the web layer can answer 404 instead of pretending it removed someone. | ||
| 215 | +pub async fn unassign_teacher( | ||
| 216 | + db: &Database, | ||
| 217 | + course: Course, | ||
| 218 | + teacher: &UserId, | ||
| 219 | +) -> Result<Option<Course>, AppError> { | ||
| 220 | + if !course.is_assigned(teacher) { | ||
| 221 | + return Ok(None); | ||
| 222 | + } | ||
| 223 | + // Same field-scoped story as [`assign_teacher`]; `-=` drops the | ||
| 224 | + // one link off the stored list without touching the course's own text. | ||
| 225 | + let mut result = db | ||
| 226 | + .query("UPDATE $id SET teachers -= $usr RETURN AFTER") | ||
| 227 | + .bind(("id", course.id.record())) | ||
| 228 | + .bind(("usr", teacher.record())) | ||
| 229 | + .await? | ||
| 230 | + .check()?; | ||
| 231 | + Ok(Some( | ||
| 232 | + result | ||
| 233 | + .take::<Vec<Course>>(0)? | ||
| 234 | + .into_iter() | ||
| 235 | + .next() | ||
| 236 | + .ok_or(AppError::NotFound)?, | ||
| 237 | + )) | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +/// Strip `user` from every course they were assigned to — the sweep for a | ||
| 241 | +/// user demoted below `teacher`, who may no longer run anything. | ||
| 242 | +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 243 | + db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers") | ||
| 244 | + .bind(("usr", user.record())) | ||
| 245 | + .await? | ||
| 246 | + .check()?; | ||
| 247 | + Ok(()) | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +/// Delete the course and cascade-remove everything inside it: results, | ||
| 251 | +/// attempts, answers, and question/answer images of its exams, its | ||
| 252 | +/// homework with their submissions, submission files, and grades, its | ||
| 253 | +/// enrollments, the class attachments that pumped some of them (each class | ||
| 254 | +/// gets its count back, or it would be undeletable over rows pointing at | ||
| 255 | +/// nothing), its sessions with their roll call, its subjects, and the | ||
| 256 | +/// exams themselves. The children go in one transaction so a crash can't | ||
| 257 | +/// leave an exam pointing at a deleted course. The image and | ||
| 258 | +/// homework-file *blobs* are the web layer's to remove — it collects | ||
| 259 | +/// their names before calling this. | ||
| 260 | +/// | ||
| 261 | +/// **Bank templates** survive it — they are a separate, reusable library | ||
| 262 | +/// spanning every course — so their `source_exam` and `subject` links are | ||
| 263 | +/// cleared instead, in this same transaction, exactly as | ||
| 264 | +/// [`crate::domain::exam::Exam::delete`] and | ||
| 265 | +/// [`crate::domain::subject::Subject::delete`] clear them one level down. | ||
| 266 | +/// Deleting a course must leave the bank where deleting each of its exams | ||
| 267 | +/// and subjects by hand would have left it, or a template is left pointing | ||
| 268 | +/// at a dead exam (permanently: nothing else ever visits that column) and | ||
| 269 | +/// at a dead subject the next `PATCH` omitting `subject_id` writes straight | ||
| 270 | +/// back. | ||
| 271 | +/// | ||
| 272 | +/// The **grade blueprints** naming it are swept in that same transaction. | ||
| 273 | +/// Nothing else can reach them — a blueprint holds its courses as a list on | ||
| 274 | +/// its own row, not as link rows this cascade could delete — and an id left | ||
| 275 | +/// behind is permanent rather than merely stale: the pump's own | ||
| 276 | +/// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only | ||
| 277 | +/// while walking a section, so a grade with no sections can never drop one, | ||
| 278 | +/// and every `PATCH` of that template is refused for naming a course that | ||
| 279 | +/// does not exist, which is precisely the call documented as the repair. | ||
| 280 | +/// | ||
| 281 | +/// It is a table scan, deliberately unindexed: `class_blueprint` holds one | ||
| 282 | +/// row per grade label the school uses (a dozen), a course delete is rare, | ||
| 283 | +/// and the per-element index the `WHERE` would want | ||
| 284 | +/// (`FIELDS courses[*]`) is the one this store answers with **no rows at | ||
| 285 | +/// all** — the trap [`list_for_teacher`] documents. | ||
| 286 | +/// | ||
| 287 | +/// The marks going with it give their exam kinds' references back, counted | ||
| 288 | +/// per kind inside this same transaction — the mirror of `Exam::delete`. | ||
| 289 | +/// Skipping it would leave every kind the course graded under counted | ||
| 290 | +/// forever, and a counted kind can never leave the school's settings. | ||
| 291 | +/// | ||
| 292 | +/// `false` = refused, nothing was written: someone is still enrolled. The | ||
| 293 | +/// roster is read off the course's own `enrollment_count`, so the check and | ||
| 294 | +/// the delete are one conditional write on one record — an enroll racing | ||
| 295 | +/// this either takes its seat first (and the delete is refused) or finds | ||
| 296 | +/// the row gone (and is refused itself). `Err(NotFound)` | ||
| 297 | +/// keeps the answer a concurrent *delete* used to get. | ||
| 298 | +pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> { | ||
| 299 | + let sql = format!( | ||
| 300 | + "BEGIN TRANSACTION; | ||
| 301 | + LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); | ||
| 302 | + IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; | ||
| 303 | + FOR $row IN $gone {{ | ||
| 304 | + IF $row.term != NONE {{ | ||
| 305 | + UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ | ||
| 306 | + math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 307 | + }}; | ||
| 308 | + }}; | ||
| 309 | + FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result | ||
| 310 | + WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) | ||
| 311 | + GROUP BY kind) ?? []) {{ | ||
| 312 | + UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ | ||
| 313 | + math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) | ||
| 314 | + }}; | ||
| 315 | + DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 316 | + DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 317 | + DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 318 | + DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 319 | + DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 320 | + DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 321 | + DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); | ||
| 322 | + DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); | ||
| 323 | + DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); | ||
| 324 | + DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course); | ||
| 325 | + DELETE course_note WHERE course = $course; | ||
| 326 | + LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); | ||
| 327 | + FOR $row IN ($detached ?? []) {{ | ||
| 328 | + UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ | ||
| 329 | + math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 330 | + }}; | ||
| 331 | + UPDATE class_blueprint SET courses -= $course WHERE $course IN courses; | ||
| 332 | + DELETE session_attendance WHERE course = $course; | ||
| 333 | + DELETE course_session WHERE course = $course; | ||
| 334 | + DELETE enrollment WHERE course = $course; | ||
| 335 | + UPDATE bank_question SET subject = NONE | ||
| 336 | + WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); | ||
| 337 | + DELETE subject WHERE course = $course; | ||
| 338 | + DELETE homework WHERE course = $course; | ||
| 339 | + UPDATE bank_question SET source_exam = NONE | ||
| 340 | + WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 341 | + DELETE exam WHERE course = $course; | ||
| 342 | + COMMIT TRANSACTION;" | ||
| 343 | + ); | ||
| 344 | + // An aborted transaction errors *every* slot, most with a generic "not | ||
| 345 | + // executed" — only the THROW's own slot names the marker, and a lost | ||
| 346 | + // round is re-sent rather than reported (see [`transaction_with_retry`]). | ||
| 347 | + let (_, mut errors) = transaction_with_retry( | ||
| 348 | + db, | ||
| 349 | + &sql, | ||
| 350 | + &[("course".into(), course.id.record().into_value())], | ||
| 351 | + &[ROSTER_MARK], | ||
| 352 | + ) | ||
| 353 | + .await?; | ||
| 354 | + if errors | ||
| 355 | + .values() | ||
| 356 | + .any(|error| error.to_string().contains(ROSTER_MARK)) | ||
| 357 | + { | ||
| 358 | + // Full stop or already gone: the guard cannot tell those apart, and | ||
| 359 | + // only the refusal path pays for the extra read that can. | ||
| 360 | + return match read(db, &course.id).await? { | ||
| 361 | + Some(_) => Ok(false), | ||
| 362 | + None => Err(AppError::NotFound), | ||
| 363 | + }; | ||
| 364 | + } | ||
| 365 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 366 | + return Err(error.into()); | ||
| 367 | + } | ||
| 368 | + Ok(true) | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +/// A real course row, for the tests of every child that must now prove its | ||
| 372 | +/// parent exists (`Exam`, `CourseSession`, `Subject` — see | ||
| 373 | +/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the | ||
| 374 | +/// way a minted subject id already is for an exam question. | ||
| 375 | +#[cfg(test)] | ||
| 376 | +pub(crate) async fn a_test_course(db: &Database) -> CourseId { | ||
| 377 | + create( | ||
| 378 | + db, | ||
| 379 | + &UserId::generate(), | ||
| 380 | + CourseTitle::try_new("test course").unwrap(), | ||
| 381 | + CourseDescription::try_new("").unwrap(), | ||
| 382 | + CourseKind::course(), | ||
| 383 | + None, | ||
| 384 | + None, | ||
| 385 | + ) | ||
| 386 | + .await | ||
| 387 | + .unwrap() | ||
| 388 | + .id | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +/// The race half of "a child of a course must not survive its deletion", run | ||
| 392 | +/// for one child table: [`delete`] is held open by the schema and | ||
| 393 | +/// `make` fires its create inside that window, four rounds. | ||
| 394 | +/// | ||
| 395 | +/// The harness lives here, beside the cascade being raced, and each child names | ||
| 396 | +/// its own pin in its own module (`exam`, `course_session`, `subject`) — the | ||
| 397 | +/// loop, the window and the verdict are one fact about *this* delete, and three | ||
| 398 | +/// copies of it would drift into three different tests of three different | ||
| 399 | +/// things. The sequential half — a create against a course that is already gone | ||
| 400 | +/// — is `tests/regress_course_child_orphans.rs`, which needs no server. | ||
| 401 | +/// | ||
| 402 | +/// The window is opened by the database rather than by a lucky interleaving: a | ||
| 403 | +/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the | ||
| 404 | +/// instant the row goes, so the `SLEEP` lands between the delete and its | ||
| 405 | +/// `DELETE <child> WHERE course = $course` sweep every time — and a create | ||
| 406 | +/// fired into it reads a course that is still there (removed, uncommitted) | ||
| 407 | +/// while the sweep already ran on a snapshot without its row. | ||
| 408 | +/// | ||
| 409 | +/// One child per round, for the reason the menu and `class_course` twins | ||
| 410 | +/// document: a second writer makes the delete lose and re-send, and the re-sent | ||
| 411 | +/// sweep clears the evidence. | ||
| 412 | +/// | ||
| 413 | +/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the | ||
| 414 | +/// store's conflict detection, which `init_mem`'s embedded engine does not | ||
| 415 | +/// have — it commits both sides and answers `Ok` to each, so this passes there | ||
| 416 | +/// on broken code. | ||
| 417 | +#[cfg(test)] | ||
| 418 | +pub(crate) async fn assert_no_child_outlives_a_course_delete( | ||
| 419 | + scratch: &str, | ||
| 420 | + table: &str, | ||
| 421 | + make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>, | ||
| 422 | +) { | ||
| 423 | + // The guard is held for the whole test: these bursts are sub-millisecond, | ||
| 424 | + // and a sibling race test's burst pushes a delete clean out of its window. | ||
| 425 | + let (db, _serialized) = crate::database::init_test_server(scratch).await; | ||
| 426 | + db.query( | ||
| 427 | + "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ | ||
| 428 | + THEN { SLEEP 1s; };", | ||
| 429 | + ) | ||
| 430 | + .await | ||
| 431 | + .expect("define the window event") | ||
| 432 | + .check() | ||
| 433 | + .expect("check the window event"); | ||
| 434 | + | ||
| 435 | + let (mut swept, mut orphans) = (0, 0); | ||
| 436 | + for round in 0..4 { | ||
| 437 | + let course = a_test_course(&db).await; | ||
| 438 | + let drop_it = { | ||
| 439 | + let (course, db) = (course.clone(), db.clone()); | ||
| 440 | + tokio::spawn(async move { | ||
| 441 | + delete( | ||
| 442 | + &db, | ||
| 443 | + read(&db, &course) | ||
| 444 | + .await | ||
| 445 | + .unwrap() | ||
| 446 | + .expect("the course is there"), | ||
| 447 | + ) | ||
| 448 | + .await | ||
| 449 | + }) | ||
| 450 | + }; | ||
| 451 | + // The create starts inside the held window. | ||
| 452 | + tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 453 | + let child = make(course.clone(), db.clone()).await.unwrap(); | ||
| 454 | + let dropped = drop_it.await.unwrap(); | ||
| 455 | + | ||
| 456 | + // A 404 for the create, or a refusal for the delete, is a correct | ||
| 457 | + // answer — the only defect is stored state. Nothing may 500. | ||
| 458 | + assert!( | ||
| 459 | + !matches!(child, Err(AppError::Db(_))), | ||
| 460 | + "{table} round {round}: a raced create must be answered, not 500: {child:?}" | ||
| 461 | + ); | ||
| 462 | + assert!( | ||
| 463 | + !matches!(dropped, Err(AppError::Db(_))), | ||
| 464 | + "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" | ||
| 465 | + ); | ||
| 466 | + | ||
| 467 | + // Stored state is the whole verdict; a return value is not evidence. | ||
| 468 | + if read(&db, &course).await.unwrap().is_none() { | ||
| 469 | + swept += 1; | ||
| 470 | + let mut left = db | ||
| 471 | + .query(format!( | ||
| 472 | + "SELECT VALUE id FROM {table} WHERE course = $course" | ||
| 473 | + )) | ||
| 474 | + .bind(("course", course.record())) | ||
| 475 | + .await | ||
| 476 | + .unwrap() | ||
| 477 | + .check() | ||
| 478 | + .unwrap(); | ||
| 479 | + orphans += left.take::<Vec<RecordId>>(0).unwrap().len(); | ||
| 480 | + } else if matches!(dropped, Ok(true)) { | ||
| 481 | + panic!("{table} round {round}: the delete reported success, the course is still there"); | ||
| 482 | + } | ||
| 483 | + } | ||
| 484 | + eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); | ||
| 485 | + assert!( | ||
| 486 | + swept > 0, | ||
| 487 | + "{table}: no round ever deleted the course, so the window was never reached" | ||
| 488 | + ); | ||
| 489 | + assert_eq!(orphans, 0, "{table}: a child outlived its course"); | ||
| 490 | +} | ||
| 491 | + | ||
| 492 | +#[cfg(test)] | ||
| 493 | +mod tests { | ||
| 494 | + use super::*; | ||
| 495 | + use crate::domain::term::{Term, TermName}; | ||
| 496 | + | ||
| 497 | + async fn course_on(term: Option<TermId>, db: &Database) -> Course { | ||
| 498 | + create( | ||
| 499 | + db, | ||
| 500 | + &UserId::from_key("teacher"), | ||
| 501 | + CourseTitle::try_new("algebra").unwrap(), | ||
| 502 | + CourseDescription::try_new("").unwrap(), | ||
| 503 | + CourseKind::course(), | ||
| 504 | + term, | ||
| 505 | + None, | ||
| 506 | + ) | ||
| 507 | + .await | ||
| 508 | + .unwrap() | ||
| 509 | + } | ||
| 510 | + | ||
| 511 | + /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the | ||
| 512 | + /// roster check is now the `WHERE` on the delete itself, so only the guard | ||
| 513 | + /// can refuse — and it must refuse having written nothing, cascade | ||
| 514 | + /// included. A `>= 0` guard passes the roster branch and fails here. | ||
| 515 | + #[tokio::test] | ||
| 516 | + async fn a_course_with_a_roster_refuses_to_delete() { | ||
| 517 | + use crate::domain::enrollment::Enrollment; | ||
| 518 | + | ||
| 519 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 520 | + let teacher = UserId::from_key("teacher"); | ||
| 521 | + let student = UserId::from_key("student"); | ||
| 522 | + let course = course_on(None, &db).await; | ||
| 523 | + Enrollment::enroll(course.get_id(), &student, &teacher, &db) | ||
| 524 | + .await | ||
| 525 | + .unwrap(); | ||
| 526 | + | ||
| 527 | + assert!( | ||
| 528 | + !delete(&db, course.clone()).await.unwrap(), | ||
| 529 | + "a non-empty roster must refuse the delete" | ||
| 530 | + ); | ||
| 531 | + assert!( | ||
| 532 | + read(&db, course.get_id()).await.unwrap().is_some(), | ||
| 533 | + "a refused delete may write nothing" | ||
| 534 | + ); | ||
| 535 | + assert!( | ||
| 536 | + Enrollment::read_for_user(course.get_id(), &student, &db) | ||
| 537 | + .await | ||
| 538 | + .unwrap() | ||
| 539 | + .is_some(), | ||
| 540 | + "…the cascade least of all" | ||
| 541 | + ); | ||
| 542 | + | ||
| 543 | + Enrollment::remove(course.get_id(), &student, &db) | ||
| 544 | + .await | ||
| 545 | + .unwrap(); | ||
| 546 | + assert!(delete(&db, course.clone()).await.unwrap()); | ||
| 547 | + assert!(read(&db, course.get_id()).await.unwrap().is_none()); | ||
| 548 | + | ||
| 549 | + // The other half of the same guard: once the course row is gone the | ||
| 550 | + // seat claim matches nothing, so a late enroll is a 404 rather than a | ||
| 551 | + // roster row that outlived its course. | ||
| 552 | + let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) | ||
| 553 | + .await | ||
| 554 | + .expect_err("enrolling into a deleted course must fail"); | ||
| 555 | + assert!(matches!(late, AppError::NotFound), "got {late:?}"); | ||
| 556 | + } | ||
| 557 | + | ||
| 558 | + /// The bite test for the refcount that replaced `TERM_LOCK`: a term is | ||
| 559 | + /// undeletable exactly while a course links it, and every way a link can | ||
| 560 | + /// end — PATCH away, and the course's own delete — gives the reference | ||
| 561 | + /// back. Dropping the release in `delete` leaves the term deletable never. | ||
| 562 | + #[tokio::test] | ||
| 563 | + async fn a_term_is_deletable_only_once_no_course_links_it() { | ||
| 564 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 565 | + let at = crate::domain::timestamp::Timestamp::from_millis; | ||
| 566 | + let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) | ||
| 567 | + .await | ||
| 568 | + .unwrap(); | ||
| 569 | + | ||
| 570 | + let linked = course_on(Some(term.get_id().clone()), &db).await; | ||
| 571 | + let patched = course_on(Some(term.get_id().clone()), &db).await; | ||
| 572 | + assert!( | ||
| 573 | + !term.clone().delete(&db).await.unwrap(), | ||
| 574 | + "two linked courses must refuse the delete" | ||
| 575 | + ); | ||
| 576 | + | ||
| 577 | + update(&db, patched, None, None, None, Some(None), None) | ||
| 578 | + .await | ||
| 579 | + .unwrap(); | ||
| 580 | + assert!( | ||
| 581 | + !term.clone().delete(&db).await.unwrap(), | ||
| 582 | + "one link is still one link" | ||
| 583 | + ); | ||
| 584 | + | ||
| 585 | + assert!(delete(&db, linked).await.unwrap()); | ||
| 586 | + assert!( | ||
| 587 | + term.clone().delete(&db).await.unwrap(), | ||
| 588 | + "the last link gone, the term may go" | ||
| 589 | + ); | ||
| 590 | + let again = term.delete(&db).await; | ||
| 591 | + assert!( | ||
| 592 | + matches!(again, Err(AppError::NotFound)), | ||
| 593 | + "a second delete is a 404, not a refusal: {again:?}" | ||
| 594 | + ); | ||
| 595 | + } | ||
| 596 | + | ||
| 597 | + /// The claim doubles as the existence check the lock used to make safe: | ||
| 598 | + /// a term that is already gone cannot be linked, with the same 400 the | ||
| 599 | + /// web layer's pre-flight lookup gives. | ||
| 600 | + #[tokio::test] | ||
| 601 | + async fn a_course_cannot_link_a_term_that_is_gone() { | ||
| 602 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 603 | + let error = create( | ||
| 604 | + &db, | ||
| 605 | + &UserId::from_key("teacher"), | ||
| 606 | + CourseTitle::try_new("algebra").unwrap(), | ||
| 607 | + CourseDescription::try_new("").unwrap(), | ||
| 608 | + CourseKind::course(), | ||
| 609 | + Some(TermId::from_key("gone")), | ||
| 610 | + None, | ||
| 611 | + ) | ||
| 612 | + .await | ||
| 613 | + .expect_err("a missing term must not be linkable"); | ||
| 614 | + assert!(error.to_string().contains("term does not exist")); | ||
| 615 | + } | ||
| 616 | + | ||
| 617 | + /// The stored `course_count` on one term, absent counting as zero. | ||
| 618 | + async fn count_on(term: &TermId, db: &Database) -> i64 { | ||
| 619 | + let mut result = db | ||
| 620 | + .query(format!( | ||
| 621 | + "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" | ||
| 622 | + )) | ||
| 623 | + .bind(("term", term.record())) | ||
| 624 | + .await | ||
| 625 | + .unwrap() | ||
| 626 | + .check() | ||
| 627 | + .unwrap(); | ||
| 628 | + result | ||
| 629 | + .take::<Vec<i64>>(0) | ||
| 630 | + .unwrap() | ||
| 631 | + .first() | ||
| 632 | + .copied() | ||
| 633 | + .unwrap_or(0) | ||
| 634 | + } | ||
| 635 | + | ||
| 636 | + /// How many rows `sql` selects ids for. | ||
| 637 | + async fn rows(sql: &str, db: &Database) -> usize { | ||
| 638 | + let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 639 | + result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 640 | + } | ||
| 641 | + | ||
| 642 | + async fn a_term(name: &str, db: &Database) -> Term { | ||
| 643 | + let at = crate::domain::timestamp::Timestamp::from_millis; | ||
| 644 | + Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) | ||
| 645 | + .await | ||
| 646 | + .unwrap() | ||
| 647 | + } | ||
| 648 | + | ||
| 649 | + /// The invariant, on the create path: a claim and the row it accounts for | ||
| 650 | + /// commit together or not at all. A refused create must therefore leave | ||
| 651 | + /// *neither* — no course row, and no count stranded on a term (which is | ||
| 652 | + /// worse than it sounds: the term's delete guard reads that count, so a | ||
| 653 | + /// stray one makes the term undeletable forever). | ||
| 654 | + #[tokio::test] | ||
| 655 | + async fn a_refused_create_writes_neither_row_nor_count() { | ||
| 656 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 657 | + let term = a_term("2026", &db).await; | ||
| 658 | + let id = term.get_id().clone(); | ||
| 659 | + assert!(term.delete(&db).await.unwrap()); | ||
| 660 | + | ||
| 661 | + let error = create( | ||
| 662 | + &db, | ||
| 663 | + &UserId::from_key("teacher"), | ||
| 664 | + CourseTitle::try_new("algebra").unwrap(), | ||
| 665 | + CourseDescription::try_new("").unwrap(), | ||
| 666 | + CourseKind::course(), | ||
| 667 | + Some(id), | ||
| 668 | + None, | ||
| 669 | + ) | ||
| 670 | + .await | ||
| 671 | + .expect_err("a term that is gone must not be linkable"); | ||
| 672 | + assert!(error.to_string().contains("term does not exist")); | ||
| 673 | + assert_eq!( | ||
| 674 | + rows("SELECT VALUE id FROM course", &db).await, | ||
| 675 | + 0, | ||
| 676 | + "a refused create may write no row" | ||
| 677 | + ); | ||
| 678 | + assert_eq!( | ||
| 679 | + rows("SELECT VALUE id FROM term", &db).await, | ||
| 680 | + 0, | ||
| 681 | + "…and least of all a count on a term it just brought back" | ||
| 682 | + ); | ||
| 683 | + } | ||
| 684 | + | ||
| 685 | + /// The invariant on the PATCH path, both directions: a move carries the new | ||
| 686 | + /// term's claim and the old term's release with the link itself. | ||
| 687 | + #[tokio::test] | ||
| 688 | + async fn a_term_move_moves_the_count() { | ||
| 689 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 690 | + let from = a_term("2026", &db).await; | ||
| 691 | + let to = a_term("2027", &db).await; | ||
| 692 | + let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 693 | + assert_eq!(count_on(from.get_id(), &db).await, 1); | ||
| 694 | + | ||
| 695 | + let moved = update( | ||
| 696 | + &db, | ||
| 697 | + course, | ||
| 698 | + None, | ||
| 699 | + None, | ||
| 700 | + None, | ||
| 701 | + Some(Some(to.get_id().clone())), | ||
| 702 | + None, | ||
| 703 | + ) | ||
| 704 | + .await | ||
| 705 | + .unwrap(); | ||
| 706 | + assert_eq!(moved.get_term(), Some(to.get_id())); | ||
| 707 | + assert_eq!( | ||
| 708 | + count_on(from.get_id(), &db).await, | ||
| 709 | + 0, | ||
| 710 | + "the old term is free" | ||
| 711 | + ); | ||
| 712 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | ||
| 713 | + assert!(from.clone().delete(&db).await.unwrap()); | ||
| 714 | + assert!(!to.clone().delete(&db).await.unwrap()); | ||
| 715 | + } | ||
| 716 | + | ||
| 717 | + /// The double-claim guard. Both movers compute their claim and release from | ||
| 718 | + /// the row as *they* read it, so two PATCHes moving the same course off the | ||
| 719 | + /// same term both release it and both claim their target — two counts for | ||
| 720 | + /// one link, and the loser's target is undeletable forever. The second call | ||
| 721 | + /// here runs on the struct read before the first one landed, which is that | ||
| 722 | + /// race with the interleaving pinned: it must be refused outright, and the | ||
| 723 | + /// counts must read as if it never ran. | ||
| 724 | + #[tokio::test] | ||
| 725 | + async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 726 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 727 | + let from = a_term("2026", &db).await; | ||
| 728 | + let to = a_term("2027", &db).await; | ||
| 729 | + let other = a_term("2028", &db).await; | ||
| 730 | + let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 731 | + let stale = course.clone(); | ||
| 732 | + update( | ||
| 733 | + &db, | ||
| 734 | + course, | ||
| 735 | + None, | ||
| 736 | + None, | ||
| 737 | + None, | ||
| 738 | + Some(Some(to.get_id().clone())), | ||
| 739 | + None, | ||
| 740 | + ) | ||
| 741 | + .await | ||
| 742 | + .unwrap(); | ||
| 743 | + | ||
| 744 | + let error = update( | ||
| 745 | + &db, | ||
| 746 | + stale.clone(), | ||
| 747 | + None, | ||
| 748 | + None, | ||
| 749 | + None, | ||
| 750 | + Some(Some(other.get_id().clone())), | ||
| 751 | + None, | ||
| 752 | + ) | ||
| 753 | + .await | ||
| 754 | + .expect_err("a mover that read a link it no longer holds must be refused"); | ||
| 755 | + assert!( | ||
| 756 | + matches!(error, AppError::Conflict(_)), | ||
| 757 | + "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 758 | + ); | ||
| 759 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 760 | + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); | ||
| 761 | + assert_eq!( | ||
| 762 | + count_on(from.get_id(), &db).await, | ||
| 763 | + 0, | ||
| 764 | + "released once, not twice" | ||
| 765 | + ); | ||
| 766 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); | ||
| 767 | + assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); | ||
| 768 | + | ||
| 769 | + // Same race from the other end: the snapshot says *no* link, so the CAS | ||
| 770 | + // is against an absent column — the shape a bound `NONE` has to match. | ||
| 771 | + let unlinked = course_on(None, &db).await; | ||
| 772 | + let stale = unlinked.clone(); | ||
| 773 | + update( | ||
| 774 | + &db, | ||
| 775 | + unlinked, | ||
| 776 | + None, | ||
| 777 | + None, | ||
| 778 | + None, | ||
| 779 | + Some(Some(to.get_id().clone())), | ||
| 780 | + None, | ||
| 781 | + ) | ||
| 782 | + .await | ||
| 783 | + .unwrap(); | ||
| 784 | + let error = update( | ||
| 785 | + &db, | ||
| 786 | + stale.clone(), | ||
| 787 | + None, | ||
| 788 | + None, | ||
| 789 | + None, | ||
| 790 | + Some(Some(other.get_id().clone())), | ||
| 791 | + None, | ||
| 792 | + ) | ||
| 793 | + .await | ||
| 794 | + .expect_err("a mover that read an absent link someone else filled must be refused"); | ||
| 795 | + assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 796 | + assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); | ||
| 797 | + assert_eq!( | ||
| 798 | + count_on(other.get_id(), &db).await, | ||
| 799 | + 0, | ||
| 800 | + "still never claimed" | ||
| 801 | + ); | ||
| 802 | + // …and the unraced set still lands, so the CAS did not just break moves. | ||
| 803 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 804 | + assert_eq!(stored.get_term(), Some(to.get_id())); | ||
| 805 | + } | ||
| 806 | + | ||
| 807 | + /// The same race with the counters taken out of it. A PATCH that re-states | ||
| 808 | + /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands | ||
| 809 | + /// back no claim and no release — so if the guard were armed off the counter | ||
| 810 | + /// move it would not be armed here at all, and the write would land: the | ||
| 811 | + /// winner's link silently dragged back, its claim stranded on a term nothing | ||
| 812 | + /// points at (undeletable forever) and the reverted-to term linked at a | ||
| 813 | + /// count of zero (deletable while linked). The guard is armed by the request | ||
| 814 | + /// *carrying* the column instead, which is why this is refused. | ||
| 815 | + #[tokio::test] | ||
| 816 | + async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 817 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 818 | + let from = a_term("2026", &db).await; | ||
| 819 | + let to = a_term("2027", &db).await; | ||
| 820 | + let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 821 | + let stale = course.clone(); | ||
| 822 | + update( | ||
| 823 | + &db, | ||
| 824 | + course, | ||
| 825 | + None, | ||
| 826 | + None, | ||
| 827 | + None, | ||
| 828 | + Some(Some(to.get_id().clone())), | ||
| 829 | + None, | ||
| 830 | + ) | ||
| 831 | + .await | ||
| 832 | + .unwrap(); | ||
| 833 | + | ||
| 834 | + let error = update( | ||
| 835 | + &db, | ||
| 836 | + stale.clone(), | ||
| 837 | + None, | ||
| 838 | + None, | ||
| 839 | + None, | ||
| 840 | + Some(Some(from.get_id().clone())), | ||
| 841 | + None, | ||
| 842 | + ) | ||
| 843 | + .await | ||
| 844 | + .expect_err("re-stating a link someone else moved must be refused"); | ||
| 845 | + assert!( | ||
| 846 | + matches!(error, AppError::Conflict(_)), | ||
| 847 | + "a lost CAS is a conflict, not a silent 200: {error:?}" | ||
| 848 | + ); | ||
| 849 | + let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 850 | + assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); | ||
| 851 | + assert_eq!( | ||
| 852 | + count_on(from.get_id(), &db).await, | ||
| 853 | + 0, | ||
| 854 | + "the reverted-to term must not end up linked at zero" | ||
| 855 | + ); | ||
| 856 | + assert_eq!( | ||
| 857 | + count_on(to.get_id(), &db).await, | ||
| 858 | + 1, | ||
| 859 | + "…nor the winner's term counted with nothing pointing at it" | ||
| 860 | + ); | ||
| 861 | + | ||
| 862 | + // A *genuine* no-op re-state — nobody moved underneath it — still lands, | ||
| 863 | + // and still moves no counter: the CAS passes trivially. | ||
| 864 | + let fresh = read(&db, stale.get_id()).await.unwrap().unwrap(); | ||
| 865 | + let same = update( | ||
| 866 | + &db, | ||
| 867 | + fresh, | ||
| 868 | + None, | ||
| 869 | + None, | ||
| 870 | + None, | ||
| 871 | + Some(Some(to.get_id().clone())), | ||
| 872 | + None, | ||
| 873 | + ) | ||
| 874 | + .await | ||
| 875 | + .expect("re-stating the link the row really holds is not a conflict"); | ||
| 876 | + assert_eq!(same.get_term(), Some(to.get_id())); | ||
| 877 | + assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); | ||
| 878 | + assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); | ||
| 879 | + } | ||
| 880 | + | ||
| 881 | + /// The rollback proof. The transaction releases the old term *before* it | ||
| 882 | + /// claims the new one, so a move to a term that is gone has already | ||
| 883 | + /// decremented when the claim throws — the old count still being 1 is the | ||
| 884 | + /// abort undoing a write that really happened, not a branch that never ran. | ||
| 885 | + /// The title moves in the same PATCH, and must not stick either. | ||
| 886 | + #[tokio::test] | ||
| 887 | + async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { | ||
| 888 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 889 | + let from = a_term("2026", &db).await; | ||
| 890 | + let dead = a_term("2027", &db).await; | ||
| 891 | + let dead_id = dead.get_id().clone(); | ||
| 892 | + assert!(dead.delete(&db).await.unwrap()); | ||
| 893 | + let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 894 | + | ||
| 895 | + let error = update( | ||
| 896 | + &db, | ||
| 897 | + course.clone(), | ||
| 898 | + Some(CourseTitle::try_new("moved").unwrap()), | ||
| 899 | + None, | ||
| 900 | + None, | ||
| 901 | + Some(Some(dead_id)), | ||
| 902 | + None, | ||
| 903 | + ) | ||
| 904 | + .await | ||
| 905 | + .expect_err("a term that is gone must not be linkable"); | ||
| 906 | + assert!(error.to_string().contains("term does not exist")); | ||
| 907 | + | ||
| 908 | + let stored = read(&db, course.get_id()).await.unwrap().unwrap(); | ||
| 909 | + assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); | ||
| 910 | + assert_eq!( | ||
| 911 | + stored.get_title().as_str(), | ||
| 912 | + "algebra", | ||
| 913 | + "…and so does the row" | ||
| 914 | + ); | ||
| 915 | + assert_eq!( | ||
| 916 | + count_on(from.get_id(), &db).await, | ||
| 917 | + 1, | ||
| 918 | + "the release must roll back with the abort" | ||
| 919 | + ); | ||
| 920 | + assert_eq!( | ||
| 921 | + rows("SELECT VALUE id FROM term", &db).await, | ||
| 922 | + 1, | ||
| 923 | + "the dead term must not be resurrected by the claim" | ||
| 924 | + ); | ||
| 925 | + } | ||
| 926 | + | ||
| 927 | + /// MEASUREMENT — the one race test that actually measures the retry, and | ||
| 928 | + /// the only one of the four that does. The other three (subject, term, | ||
| 929 | + /// exam) are status-code guards; each says so on itself. | ||
| 930 | + /// | ||
| 931 | + /// [`delete`] is one `BEGIN…COMMIT` whose guard reads | ||
| 932 | + /// `enrollment_count` off the very record a concurrent enroll increments, | ||
| 933 | + /// so the two contend by design, and its cascade is long enough that a | ||
| 934 | + /// rival's write lands mid-transaction. Losing that round writes nothing, | ||
| 935 | + /// which is what makes re-sending it the recovery. Without | ||
| 936 | + /// [`crate::database::transaction_with_retry`] a lost round comes out as a | ||
| 937 | + /// 500: mutation-tested by cutting that retry loop to one attempt, which | ||
| 938 | + /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is | ||
| 939 | + /// real but narrow, so a single green run under the mutation means nothing). | ||
| 940 | + /// | ||
| 941 | + /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and | ||
| 942 | + /// must not fail this test: the only defect is `AppError::Db`. | ||
| 943 | + /// | ||
| 944 | + /// The rate is counted over the whole loop instead of asserted per round, | ||
| 945 | + /// because a per-round `assert!` aborts at the first hit and would report | ||
| 946 | + /// "1 of 1" for a bug the point of this test is to *quantify*. | ||
| 947 | + /// | ||
| 948 | + /// Multi-threaded and on a real server for the reasons spelled out on | ||
| 949 | + /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the | ||
| 950 | + /// current-thread runtime never interleaves the two, and the embedded | ||
| 951 | + /// engine does not conflict-check concurrent writes to one record at all. | ||
| 952 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 953 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 954 | + async fn a_delete_racing_an_enroll_never_answers_500() { | ||
| 955 | + use crate::domain::enrollment::Enrollment; | ||
| 956 | + let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; | ||
| 957 | + let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); | ||
| 958 | + let (mut last_delete, mut last_enroll) = (String::new(), String::new()); | ||
| 959 | + for round in 0..20 { | ||
| 960 | + let course = course_on(None, &db).await; | ||
| 961 | + | ||
| 962 | + // A *burst* of enrolls, and a delete held back by a sweeping beat. | ||
| 963 | + // Released together the delete is one statement while an enroll | ||
| 964 | + // spends two round trips reading before it claims, so it wins every | ||
| 965 | + // round and the guard is never contended at all (measured: 0/20 | ||
| 966 | + // seats placed). Six racers over a 0-3ms sweep put the single | ||
| 967 | + // statement somewhere inside the counter writes instead. | ||
| 968 | + let drop_it = { | ||
| 969 | + let (course, db) = (course.clone(), db.clone()); | ||
| 970 | + let beat = std::time::Duration::from_millis(round % 4); | ||
| 971 | + tokio::spawn(async move { | ||
| 972 | + tokio::time::sleep(beat).await; | ||
| 973 | + delete(&db, course).await | ||
| 974 | + }) | ||
| 975 | + }; | ||
| 976 | + let joins: Vec<_> = (0..6) | ||
| 977 | + .map(|seat| { | ||
| 978 | + let (id, db) = (course.get_id().clone(), db.clone()); | ||
| 979 | + let student = UserId::from_key(&format!("stu{round}_{seat}")); | ||
| 980 | + tokio::spawn(async move { | ||
| 981 | + Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await | ||
| 982 | + }) | ||
| 983 | + }) | ||
| 984 | + .collect(); | ||
| 985 | + let drop_it = drop_it.await.unwrap(); | ||
| 986 | + if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 987 | + delete_500 += 1; | ||
| 988 | + last_delete = format!("{drop_it:?}"); | ||
| 989 | + } | ||
| 990 | + for join in joins { | ||
| 991 | + let join = join.await.unwrap(); | ||
| 992 | + if matches!(join, Err(AppError::Db(_))) { | ||
| 993 | + enroll_500 += 1; | ||
| 994 | + last_enroll = format!("{join:?}"); | ||
| 995 | + } | ||
| 996 | + } | ||
| 997 | + // Stored state, not the return values: a seat that landed is what | ||
| 998 | + // the guard had to see. | ||
| 999 | + if !Enrollment::list_for_course(course.get_id(), None, 0, &db) | ||
| 1000 | + .await | ||
| 1001 | + .unwrap() | ||
| 1002 | + .0 | ||
| 1003 | + .is_empty() | ||
| 1004 | + { | ||
| 1005 | + enrolled += 1; | ||
| 1006 | + } | ||
| 1007 | + } | ||
| 1008 | + eprintln!( | ||
| 1009 | + "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ | ||
| 1010 | + {enrolled}/20 rounds with a seat placed" | ||
| 1011 | + ); | ||
| 1012 | + assert!( | ||
| 1013 | + enrolled > 0, | ||
| 1014 | + "no round ever placed an enrollment, so the delete guard was never contended" | ||
| 1015 | + ); | ||
| 1016 | + assert_eq!( | ||
| 1017 | + delete_500, 0, | ||
| 1018 | + "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | ||
| 1019 | + ); | ||
| 1020 | + assert_eq!( | ||
| 1021 | + enroll_500, 0, | ||
| 1022 | + "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" | ||
| 1023 | + ); | ||
| 1024 | + } | ||
| 1025 | +} | ||
src/db/mod.rsmodified+1 -0
| @@ -2,6 +2,7 @@ | |||
| 2 | 2 | ||
| 3 | pub mod appointment; | 3 | pub mod appointment; |
| 4 | pub mod cap; | 4 | pub mod cap; |
| 5 | +pub mod course; | ||
| 5 | pub mod field_update; | 6 | pub mod field_update; |
| 6 | pub mod note; | 7 | pub mod note; |
| 7 | pub mod page; | 8 | pub mod page; |
src/db/note.rsmodified+1 -1
| @@ -86,7 +86,7 @@ pub async fn update( | |||
| 86 | /// row pointing at nothing. | 86 | /// row pointing at nothing. |
| 87 | /// | 87 | /// |
| 88 | /// Children first, in one transaction, the way | 88 | /// Children first, in one transaction, the way |
| 89 | -/// [`crate::domain::course::Course::delete`] does it: as two queries, an | 89 | +/// [`crate::db::course::delete`] does it: as two queries, an |
| 90 | /// upload that committed in between kept its row while the note went, and | 90 | /// upload that committed in between kept its row while the note went, and |
| 91 | /// nothing could ever list or delete it again. | 91 | /// nothing could ever list or delete it again. |
| 92 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { | 92 | pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> { |
src/domain/bank_question.rsmodified+1 -1
| @@ -846,7 +846,7 @@ mod tests { | |||
| 846 | // A real subject row: an exam question claims a reference on its | 846 | // A real subject row: an exam question claims a reference on its |
| 847 | // subject, so a minted id it never wrote would be refused. | 847 | // subject, so a minted id it never wrote would be refused. |
| 848 | let subject = crate::domain::subject::Subject::create( | 848 | let subject = crate::domain::subject::Subject::create( |
| 849 | - &crate::domain::course::a_test_course(&db).await, | 849 | + &crate::db::course::a_test_course(&db).await, |
| 850 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), | 850 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 851 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), | 851 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 852 | &db, | 852 | &db, |
src/domain/class_blueprint.rsmodified+1 -1
| @@ -702,7 +702,7 @@ impl ClassBlueprint { | |||
| 702 | /// Drop a course that no longer exists out of this blueprint's list. | 702 | /// Drop a course that no longer exists out of this blueprint's list. |
| 703 | /// | 703 | /// |
| 704 | /// The delete does this itself now: | 704 | /// The delete does this itself now: |
| 705 | - /// [`crate::domain::course::Course::delete`] sweeps `class_blueprint` in | 705 | + /// [`crate::db::course::delete`] sweeps `class_blueprint` in |
| 706 | /// the same cascade that takes the course's `class_course` links, so a | 706 | /// the same cascade that takes the course's `class_course` links, so a |
| 707 | /// template stops naming a course the instant that course goes. This used | 707 | /// template stops naming a course the instant that course goes. This used |
| 708 | /// to be the *only* thing that could remove such an id, and that was the | 708 | /// to be the *only* thing that could remove such an id, and that was the |
src/domain/class_course.rsmodified+5 -3
| @@ -239,7 +239,6 @@ mod tests { | |||
| 239 | use super::*; | 239 | use super::*; |
| 240 | use crate::domain::class_member::ClassMember; | 240 | use crate::domain::class_member::ClassMember; |
| 241 | use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; | 241 | use crate::domain::class_member::tests::{a_class, a_course, counter, exists, rows, source_of}; |
| 242 | - use crate::domain::course::Course; | ||
| 243 | use crate::domain::enrollment::Enrollment; | 242 | use crate::domain::enrollment::Enrollment; |
| 244 | 243 | ||
| 245 | /// Attaching seeds the course from the roster the class already holds. | 244 | /// Attaching seeds the course from the roster the class already holds. |
| @@ -532,11 +531,14 @@ mod tests { | |||
| 532 | for round in 0..4 { | 531 | for round in 0..4 { |
| 533 | let class = a_class(&format!("9-{round}"), &db).await; | 532 | let class = a_class(&format!("9-{round}"), &db).await; |
| 534 | let algebra = a_course(&format!("algebra{round}"), None, &db).await; | 533 | let algebra = a_course(&format!("algebra{round}"), None, &db).await; |
| 535 | - let course = Course::read(&algebra, &db).await.unwrap().unwrap(); | 534 | + let course = crate::db::course::read(&db, &algebra) |
| 535 | + .await | ||
| 536 | + .unwrap() | ||
| 537 | + .unwrap(); | ||
| 536 | 538 | ||
| 537 | let drop_it = { | 539 | let drop_it = { |
| 538 | let db = db.clone(); | 540 | let db = db.clone(); |
| 539 | - tokio::spawn(async move { course.delete(&db).await }) | 541 | + tokio::spawn(async move { crate::db::course::delete(&db, course).await }) |
| 540 | }; | 542 | }; |
| 541 | // The attach starts inside the held window — the course row is gone | 543 | // The attach starts inside the held window — the course row is gone |
| 542 | // but uncommitted, which is exactly what a course read believes. | 544 | // but uncommitted, which is exactly what a course read believes. |
src/domain/class_group.rsmodified+9 -9
| @@ -146,7 +146,7 @@ impl ClassGroup { | |||
| 146 | 146 | ||
| 147 | /// Create the class, claiming a reference on the term it links (if any) in | 147 | /// Create the class, claiming a reference on the term it links (if any) in |
| 148 | /// the *same transaction* as the row, exactly as | 148 | /// the *same transaction* as the row, exactly as |
| 149 | - /// [`crate::domain::course::Course::create`] does: the claim is a | 149 | + /// [`crate::db::course::create`] does: the claim is a |
| 150 | /// conditional write on the term row, so it fails when the term is already | 150 | /// conditional write on the term row, so it fails when the term is already |
| 151 | /// gone, it makes the term undeletable the instant this link exists, and no | 151 | /// gone, it makes the term undeletable the instant this link exists, and no |
| 152 | /// crash can leave either half without the other. | 152 | /// crash can leave either half without the other. |
| @@ -230,7 +230,7 @@ impl ClassGroup { | |||
| 230 | /// | 230 | /// |
| 231 | /// A term move claims the new term and releases the old one inside the very | 231 | /// A term move claims the new term and releases the old one inside the very |
| 232 | /// transaction that moves the link, exactly as in | 232 | /// transaction that moves the link, exactly as in |
| 233 | - /// [`crate::domain::course::Course::update`]: both counters and the link | 233 | + /// [`crate::db::course::update`]: both counters and the link |
| 234 | /// commit together, so no crash can strand a count on a term nothing links. | 234 | /// commit together, so no crash can strand a count on a term nothing links. |
| 235 | pub async fn update( | 235 | pub async fn update( |
| 236 | self, | 236 | self, |
| @@ -301,7 +301,7 @@ impl ClassGroup { | |||
| 301 | 301 | ||
| 302 | /// Strip `user` from every class they were the homeroom teacher of — the | 302 | /// Strip `user` from every class they were the homeroom teacher of — the |
| 303 | /// sweep for a user demoted below `teacher`, who may no longer hold one. | 303 | /// sweep for a user demoted below `teacher`, who may no longer hold one. |
| 304 | - /// The mirror of [`crate::domain::course::Course::unassign_everywhere`]; | 304 | + /// The mirror of [`crate::db::course::unassign_everywhere`]; |
| 305 | /// nothing is counted on this column, so there is no reference to give back. | 305 | /// nothing is counted on this column, so there is no reference to give back. |
| 306 | pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { | 306 | pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { |
| 307 | db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") | 307 | db.query("UPDATE class_group SET teacher = NONE WHERE teacher = $usr") |
| @@ -677,7 +677,7 @@ mod tests { | |||
| 677 | } | 677 | } |
| 678 | 678 | ||
| 679 | /// The class mirror of | 679 | /// The class mirror of |
| 680 | - /// [`crate::domain::course::Course`]'s move tests: a term move carries both | 680 | + /// [`crate::db::course`]'s move tests: a term move carries both |
| 681 | /// counters with the link, and a move to a term that is gone rolls the | 681 | /// counters with the link, and a move to a term that is gone rolls the |
| 682 | /// release back with the abort (the transaction releases before it claims, | 682 | /// release back with the abort (the transaction releases before it claims, |
| 683 | /// so the old count would be 0 if the abort did not undo it). | 683 | /// so the old count would be 0 if the abort did not undo it). |
| @@ -794,24 +794,24 @@ mod tests { | |||
| 794 | assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); | 794 | assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); |
| 795 | } | 795 | } |
| 796 | 796 | ||
| 797 | - /// [`crate::domain::course::Course::delete`]'s class sweep: deleting a course | 797 | + /// [`crate::db::course::delete`]'s class sweep: deleting a course |
| 798 | /// takes its `class_course` attachments with it and gives each class its | 798 | /// takes its `class_course` attachments with it and gives each class its |
| 799 | /// count back, or the classes would be undeletable forever over rows that | 799 | /// count back, or the classes would be undeletable forever over rows that |
| 800 | /// point at nothing. | 800 | /// point at nothing. |
| 801 | #[tokio::test] | 801 | #[tokio::test] |
| 802 | async fn deleting_a_course_sweeps_its_class_attachments() { | 802 | async fn deleting_a_course_sweeps_its_class_attachments() { |
| 803 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 803 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 804 | 804 | ||
| 805 | let db = crate::database::init_mem().await.unwrap(); | 805 | let db = crate::database::init_mem().await.unwrap(); |
| 806 | let manager = UserId::from_key("manager"); | 806 | let manager = UserId::from_key("manager"); |
| 807 | - let course = Course::create( | 807 | + let course = crate::db::course::create( |
| 808 | + &db, | ||
| 808 | &manager, | 809 | &manager, |
| 809 | CourseTitle::try_new("algebra").unwrap(), | 810 | CourseTitle::try_new("algebra").unwrap(), |
| 810 | CourseDescription::try_new("").unwrap(), | 811 | CourseDescription::try_new("").unwrap(), |
| 811 | CourseKind::course(), | 812 | CourseKind::course(), |
| 812 | None, | 813 | None, |
| 813 | None, | 814 | None, |
| 814 | - &db, | ||
| 815 | ) | 815 | ) |
| 816 | .await | 816 | .await |
| 817 | .unwrap(); | 817 | .unwrap(); |
| @@ -828,7 +828,7 @@ mod tests { | |||
| 828 | .check() | 828 | .check() |
| 829 | .unwrap(); | 829 | .unwrap(); |
| 830 | 830 | ||
| 831 | - assert!(course.delete(&db).await.unwrap()); | 831 | + assert!(crate::db::course::delete(&db, course).await.unwrap()); |
| 832 | assert_eq!( | 832 | assert_eq!( |
| 833 | rows("SELECT VALUE id FROM class_course", &db).await, | 833 | rows("SELECT VALUE id FROM class_course", &db).await, |
| 834 | 0, | 834 | 0, |
src/domain/class_member.rsmodified+3 -3
| @@ -217,7 +217,7 @@ pub(crate) mod tests { | |||
| 217 | use super::*; | 217 | use super::*; |
| 218 | use crate::domain::class_course::ClassCourse; | 218 | use crate::domain::class_course::ClassCourse; |
| 219 | use crate::domain::class_group::{ClassGroup, ClassName}; | 219 | use crate::domain::class_group::{ClassGroup, ClassName}; |
| 220 | - use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | 220 | + use crate::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 221 | use crate::domain::enrollment::Enrollment; | 221 | use crate::domain::enrollment::Enrollment; |
| 222 | 222 | ||
| 223 | pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { | 223 | pub(crate) async fn a_class(name: &str, db: &Database) -> ClassGroupId { |
| @@ -236,14 +236,14 @@ pub(crate) mod tests { | |||
| 236 | } | 236 | } |
| 237 | 237 | ||
| 238 | pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId { | 238 | pub(crate) async fn a_course(title: &str, capacity: Option<i64>, db: &Database) -> CourseId { |
| 239 | - Course::create( | 239 | + crate::db::course::create( |
| 240 | + db, | ||
| 240 | &UserId::from_key("manager"), | 241 | &UserId::from_key("manager"), |
| 241 | CourseTitle::try_new(title).unwrap(), | 242 | CourseTitle::try_new(title).unwrap(), |
| 242 | CourseDescription::try_new("").unwrap(), | 243 | CourseDescription::try_new("").unwrap(), |
| 243 | CourseKind::course(), | 244 | CourseKind::course(), |
| 244 | None, | 245 | None, |
| 245 | capacity, | 246 | capacity, |
| 246 | - db, | ||
| 247 | ) | 247 | ) |
| 248 | .await | 248 | .await |
| 249 | .unwrap() | 249 | .unwrap() |
src/domain/course.rsmodified+15 -998
| @@ -1,29 +1,18 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | ||
| 3 | -use crate::constant::{ | 3 | +use crate::constant::{COURSE_TABLE, MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN}; |
| 4 | - CLASS_COURSE_COUNT_FIELD, COURSE_COUNT_FIELD, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, | ||
| 5 | - MAX_COURSE_DESCRIPTION_LEN, MAX_COURSE_TITLE_LEN, REF_COUNT_FIELD, | ||
| 6 | -}; | ||
| 7 | -use crate::database::{Database, transaction_with_retry}; | ||
| 8 | -use crate::db::cap; | ||
| 9 | -use crate::db::field_update::FieldUpdate; | ||
| 10 | use crate::domain::monotonic_id::next_ulid; | 4 | use crate::domain::monotonic_id::next_ulid; |
| 11 | -use crate::db::page::PagedList; | 5 | +use crate::domain::term::TermId; |
| 12 | -use crate::domain::term::{self, TermId}; | ||
| 13 | use crate::domain::user::UserId; | 6 | use crate::domain::user::UserId; |
| 14 | -use crate::error::{AppError, ValidationError}; | 7 | +use crate::error::ValidationError; |
| 15 | use crate::validate::{validate_course_kind, validate_optional, validate_required}; | 8 | use crate::validate::{validate_course_kind, validate_optional, validate_required}; |
| 16 | 9 | ||
| 17 | -/// The `THROW` marker the delete guard aborts with — a roster that is not | ||
| 18 | -/// empty, or a course row that is no longer there. | ||
| 19 | -const ROSTER_MARK: &str = "course_roster"; | ||
| 20 | - | ||
| 21 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 10 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| 22 | pub struct CourseId(RecordId); | 11 | pub struct CourseId(RecordId); |
| 23 | 12 | ||
| 24 | impl CourseId { | 13 | impl CourseId { |
| 25 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: | 14 | /// Minted from the process-wide monotonic generator, not `Ulid::new()`: |
| 26 | - /// courses list `id DESC` (newest first, [`Course::list_all`]), | 15 | + /// courses list `id DESC` (newest first, [`crate::db::course::list_all`]), |
| 27 | /// and a random low half scrambles rows minted in the same millisecond. | 16 | /// and a random low half scrambles rows minted in the same millisecond. |
| 28 | pub fn generate() -> Self { | 17 | pub fn generate() -> Self { |
| 29 | Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) | 18 | Self(RecordId::new(COURSE_TABLE, next_ulid().to_string())) |
| @@ -106,17 +95,20 @@ impl CourseKind { | |||
| 106 | /// it. `teachers` are the staff a manager assigned to run it: full management | 95 | /// it. `teachers` are the staff a manager assigned to run it: full management |
| 107 | /// rights inside the course, no power to delete it or change the assignment | 96 | /// rights inside the course, no power to delete it or change the assignment |
| 108 | /// list. Rows written before the field existed decode with nobody assigned. | 97 | /// list. Rows written before the field existed decode with nobody assigned. |
| 98 | +/// | ||
| 99 | +/// Fields are crate-visible: [`crate::db::course`] mints the rows on create | ||
| 100 | +/// and reads the id when updating and cascading a delete. | ||
| 109 | #[derive(Debug, Clone, SurrealValue)] | 101 | #[derive(Debug, Clone, SurrealValue)] |
| 110 | pub struct Course { | 102 | pub struct Course { |
| 111 | - id: CourseId, | 103 | + pub(crate) id: CourseId, |
| 112 | - creator: UserId, | 104 | + pub(crate) creator: UserId, |
| 113 | #[surreal(default)] | 105 | #[surreal(default)] |
| 114 | - teachers: Vec<UserId>, | 106 | + pub(crate) teachers: Vec<UserId>, |
| 115 | - title: CourseTitle, | 107 | + pub(crate) title: CourseTitle, |
| 116 | - description: CourseDescription, | 108 | + pub(crate) description: CourseDescription, |
| 117 | - kind: CourseKind, | 109 | + pub(crate) kind: CourseKind, |
| 118 | - term: Option<TermId>, | 110 | + pub(crate) term: Option<TermId>, |
| 119 | - capacity: Option<i64>, | 111 | + pub(crate) capacity: Option<i64>, |
| 120 | } | 112 | } |
| 121 | 113 | ||
| 122 | impl Course { | 114 | impl Course { |
| @@ -144,16 +136,6 @@ impl Course { | |||
| 144 | self.term.as_ref() | 136 | self.term.as_ref() |
| 145 | } | 137 | } |
| 146 | 138 | ||
| 147 | - /// Refuse the write when this course's term is archived — a pre-flight guard, | ||
| 148 | - /// accepted race (see README concurrency model): a term archived after this | ||
| 149 | - /// read still lets the write through. | ||
| 150 | - pub async fn require_open(&self, db: &Database) -> Result<(), AppError> { | ||
| 151 | - match self.get_term() { | ||
| 152 | - None => Ok(()), | ||
| 153 | - Some(term) => term::Term::require_open(term, db).await, | ||
| 154 | - } | ||
| 155 | - } | ||
| 156 | - | ||
| 157 | /// The seat cap enforced at enroll time; `None` = unlimited. | 139 | /// The seat cap enforced at enroll time; `None` = unlimited. |
| 158 | pub fn get_capacity(&self) -> Option<i64> { | 140 | pub fn get_capacity(&self) -> Option<i64> { |
| 159 | self.capacity | 141 | self.capacity |
| @@ -173,877 +155,11 @@ impl Course { | |||
| 173 | pub fn is_assigned(&self, user: &UserId) -> bool { | 155 | pub fn is_assigned(&self, user: &UserId) -> bool { |
| 174 | self.teachers.contains(user) | 156 | self.teachers.contains(user) |
| 175 | } | 157 | } |
| 176 | - | ||
| 177 | - /// Create the course, claiming a reference on the term it links (if any) in | ||
| 178 | - /// the *same transaction* as the row: the claim is a conditional write on | ||
| 179 | - /// the term row, so it fails when the term is already gone and it makes the | ||
| 180 | - /// term undeletable the instant this link exists — and a crash can never | ||
| 181 | - /// leave one without the other, which a claim sent as its own query could | ||
| 182 | - /// (the count would strand and the term be undeletable forever). | ||
| 183 | - pub async fn create( | ||
| 184 | - creator: &UserId, | ||
| 185 | - title: CourseTitle, | ||
| 186 | - description: CourseDescription, | ||
| 187 | - kind: CourseKind, | ||
| 188 | - term: Option<TermId>, | ||
| 189 | - capacity: Option<i64>, | ||
| 190 | - db: &Database, | ||
| 191 | - ) -> Result<Course, AppError> { | ||
| 192 | - let course = Course { | ||
| 193 | - id: CourseId::generate(), | ||
| 194 | - creator: creator.clone(), | ||
| 195 | - teachers: Vec::new(), | ||
| 196 | - term, | ||
| 197 | - capacity, | ||
| 198 | - title, | ||
| 199 | - description, | ||
| 200 | - kind, | ||
| 201 | - }; | ||
| 202 | - let id = course.id.record(); | ||
| 203 | - let Some(term) = course.term.clone() else { | ||
| 204 | - let created: Option<Course> = db.create(id).content(course).await?; | ||
| 205 | - return created.ok_or_else(|| AppError::Internal("failed to create course".into())); | ||
| 206 | - }; | ||
| 207 | - match cap::claim_and_create( | ||
| 208 | - &term.record(), | ||
| 209 | - COURSE_COUNT_FIELD, | ||
| 210 | - cap::UNLIMITED, | ||
| 211 | - &id, | ||
| 212 | - &course, | ||
| 213 | - db, | ||
| 214 | - ) | ||
| 215 | - .await? | ||
| 216 | - { | ||
| 217 | - cap::Claimed::Made(created) => Ok(created), | ||
| 218 | - // Uncapped, so "full" can only mean the conditional write matched no | ||
| 219 | - // term row at all — the existence check the pre-flight lookup makes. | ||
| 220 | - cap::Claimed::Full => Err(term::gone_error()), | ||
| 221 | - // Unreachable: the id is a ULID this call just generated. | ||
| 222 | - cap::Claimed::Duplicate => Err(AppError::Internal("failed to create course".into())), | ||
| 223 | - } | ||
| 224 | - } | ||
| 225 | - | ||
| 226 | - pub async fn read(id: &CourseId, db: &Database) -> Result<Option<Course>, AppError> { | ||
| 227 | - Ok(db.select(id.record()).await?) | ||
| 228 | - } | ||
| 229 | - | ||
| 230 | - pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 231 | - let mut result = db | ||
| 232 | - .query("SELECT * FROM course ORDER BY id DESC") | ||
| 233 | - .await? | ||
| 234 | - .check()?; | ||
| 235 | - Ok(result.take::<Vec<Course>>(0)?) | ||
| 236 | - } | ||
| 237 | - | ||
| 238 | - /// The courses `user` is enrolled in — the spine of `/courses/me` and the | ||
| 239 | - /// marks report. | ||
| 240 | - pub async fn list_enrolled( | ||
| 241 | - user: &UserId, | ||
| 242 | - limit: Option<i64>, | ||
| 243 | - offset: i64, | ||
| 244 | - db: &Database, | ||
| 245 | - ) -> Result<(Vec<Course>, i64), AppError> { | ||
| 246 | - PagedList::new( | ||
| 247 | - "course WHERE id IN (SELECT VALUE course FROM enrollment WHERE user = $usr)", | ||
| 248 | - "ORDER BY id DESC", | ||
| 249 | - ) | ||
| 250 | - .bind("usr", user.record()) | ||
| 251 | - .run(limit, offset, db) | ||
| 252 | - .await | ||
| 253 | - } | ||
| 254 | - | ||
| 255 | - /// The courses `user` runs — the ones they created plus the ones a manager | ||
| 256 | - /// assigned them to. A teacher's slice of the catalog. | ||
| 257 | - /// | ||
| 258 | - /// corner-cut: unpaged full table scan, and it stays one — every profile read | ||
| 259 | - /// of a teacher pays it, so the ceiling is the course table's size. It | ||
| 260 | - /// cannot be indexed away on SurrealDB 3.2.3: an index on `creator` alone | ||
| 261 | - /// leaves the `OR` a `TableScan` (EXPLAIN), and the per-element index the | ||
| 262 | - /// membership half would need (`DEFINE INDEX ... FIELDS teachers[*]`) is | ||
| 263 | - /// *wrong*, not merely useless — with it, `$usr IN teachers` and | ||
| 264 | - /// `teachers CONTAINS $usr` return **no rows at all**, which is what the | ||
| 265 | - /// integration test `assigned_teacher_manages_course_without_owning_it` | ||
| 266 | - /// catches. A plain `FIELDS teachers` index is correct but unused. The | ||
| 267 | - /// upgrade path is structural: a `course_teacher` link table indexed on | ||
| 268 | - /// `user`, the shape `enrollment` already has, turning this into two | ||
| 269 | - /// index-backed reads. | ||
| 270 | - pub async fn list_for_teacher(user: &UserId, db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 271 | - let mut result = db | ||
| 272 | - .query("SELECT * FROM course WHERE creator = $usr OR $usr IN teachers ORDER BY id DESC") | ||
| 273 | - .bind(("usr", user.record())) | ||
| 274 | - .await? | ||
| 275 | - .check()?; | ||
| 276 | - Ok(result.take::<Vec<Course>>(0)?) | ||
| 277 | - } | ||
| 278 | - | ||
| 279 | - /// Load every course behind `ids` (one query) — the join half of the | ||
| 280 | - /// attendance report's per-course blocks. | ||
| 281 | - pub async fn list_by_ids(ids: &[CourseId], db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 282 | - if ids.is_empty() { | ||
| 283 | - return Ok(Vec::new()); | ||
| 284 | - } | ||
| 285 | - let records: Vec<RecordId> = ids.iter().map(CourseId::record).collect(); | ||
| 286 | - let mut result = db | ||
| 287 | - .query("SELECT * FROM course WHERE id IN $ids") | ||
| 288 | - .bind(("ids", records)) | ||
| 289 | - .await? | ||
| 290 | - .check()?; | ||
| 291 | - Ok(result.take::<Vec<Course>>(0)?) | ||
| 292 | - } | ||
| 293 | - | ||
| 294 | - /// Request-scoped: `teachers` is written by [`Self::assign_teacher`], | ||
| 295 | - /// [`Self::unassign_teacher`] and the demotion sweep, and nothing guards | ||
| 296 | - /// the course row across the handler's read and this write (its `TERM_LOCK` | ||
| 297 | - /// window guards the *term* it links, and the assign path takes no lock at | ||
| 298 | - /// all) — so a field the request omitted (`None`) is not written at all. | ||
| 299 | - /// Sending the snapshot's value back instead would revert a concurrent | ||
| 300 | - /// edit of that field; scoping the `SET` alone does not stop that, the | ||
| 301 | - /// values have to come from the request. `term` and `capacity` are | ||
| 302 | - /// nullable, so they take the outer/inner `Option<Option<_>>`: `None` = | ||
| 303 | - /// omitted (keep), `Some(None)` = clear. | ||
| 304 | - pub async fn update( | ||
| 305 | - self, | ||
| 306 | - title: Option<CourseTitle>, | ||
| 307 | - description: Option<CourseDescription>, | ||
| 308 | - kind: Option<CourseKind>, | ||
| 309 | - term: Option<Option<TermId>>, | ||
| 310 | - capacity: Option<Option<i64>>, | ||
| 311 | - db: &Database, | ||
| 312 | - ) -> Result<Course, AppError> { | ||
| 313 | - // A term move claims the new term and releases the old one inside the | ||
| 314 | - // very transaction that moves the link, so no crash can leave a count | ||
| 315 | - // without its link (the term would be undeletable forever) or a link | ||
| 316 | - // without its count. A PATCH that carried no `term_id`, or re-stated the | ||
| 317 | - // link it already had, moves neither counter. | ||
| 318 | - let (claim, release) = term::ref_move(self.term.as_ref(), &term); | ||
| 319 | - let expected = self.term.as_ref().map(TermId::record); | ||
| 320 | - FieldUpdate::new(self.id.record()) | ||
| 321 | - .set("title", title) | ||
| 322 | - .set("description", description) | ||
| 323 | - .set("kind", kind) | ||
| 324 | - .set("term", term.map(|term| term.map(|term| term.record()))) | ||
| 325 | - .set("capacity", capacity) | ||
| 326 | - .refcount( | ||
| 327 | - COURSE_COUNT_FIELD, | ||
| 328 | - "term", | ||
| 329 | - expected, | ||
| 330 | - claim, | ||
| 331 | - release, | ||
| 332 | - term::gone_error(), | ||
| 333 | - ) | ||
| 334 | - .run::<Course>(db) | ||
| 335 | - .await | ||
| 336 | - } | ||
| 337 | - | ||
| 338 | - /// Assign `teacher` to run this course, or return the course untouched if | ||
| 339 | - /// they already run it — assignment is idempotent, like enrollment. | ||
| 340 | - /// Field-scoped, and the new list is folded server-side out of the *stored* | ||
| 341 | - /// one: a course PATCH awaits a term lookup between its read and its write, | ||
| 342 | - /// so a whole-row save from either side would revert the other. The | ||
| 343 | - /// `array::distinct` keeps the assignment idempotent even when two requests | ||
| 344 | - /// name the same teacher at once (the early return only sees a stale row). | ||
| 345 | - pub async fn assign_teacher(self, teacher: &UserId, db: &Database) -> Result<Course, AppError> { | ||
| 346 | - if self.is_assigned(teacher) { | ||
| 347 | - return Ok(self); | ||
| 348 | - } | ||
| 349 | - let mut result = db | ||
| 350 | - .query( | ||
| 351 | - "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) | ||
| 352 | - RETURN AFTER", | ||
| 353 | - ) | ||
| 354 | - .bind(("id", self.id.record())) | ||
| 355 | - .bind(("usr", teacher.record())) | ||
| 356 | - .await? | ||
| 357 | - .check()?; | ||
| 358 | - result | ||
| 359 | - .take::<Vec<Course>>(0)? | ||
| 360 | - .into_iter() | ||
| 361 | - .next() | ||
| 362 | - .ok_or(AppError::NotFound) | ||
| 363 | - } | ||
| 364 | - | ||
| 365 | - /// Drop `teacher` from this course. `None` when they weren't assigned, so | ||
| 366 | - /// the web layer can answer 404 instead of pretending it removed someone. | ||
| 367 | - pub async fn unassign_teacher( | ||
| 368 | - self, | ||
| 369 | - teacher: &UserId, | ||
| 370 | - db: &Database, | ||
| 371 | - ) -> Result<Option<Course>, AppError> { | ||
| 372 | - if !self.is_assigned(teacher) { | ||
| 373 | - return Ok(None); | ||
| 374 | - } | ||
| 375 | - // Same field-scoped story as [`Self::assign_teacher`]; `-=` drops the | ||
| 376 | - // one link off the stored list without touching the course's own text. | ||
| 377 | - let mut result = db | ||
| 378 | - .query("UPDATE $id SET teachers -= $usr RETURN AFTER") | ||
| 379 | - .bind(("id", self.id.record())) | ||
| 380 | - .bind(("usr", teacher.record())) | ||
| 381 | - .await? | ||
| 382 | - .check()?; | ||
| 383 | - Ok(Some( | ||
| 384 | - result | ||
| 385 | - .take::<Vec<Course>>(0)? | ||
| 386 | - .into_iter() | ||
| 387 | - .next() | ||
| 388 | - .ok_or(AppError::NotFound)?, | ||
| 389 | - )) | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | - /// Strip `user` from every course they were assigned to — the sweep for a | ||
| 393 | - /// user demoted below `teacher`, who may no longer run anything. | ||
| 394 | - pub async fn unassign_everywhere(user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 395 | - db.query("UPDATE course SET teachers -= $usr WHERE $usr IN teachers") | ||
| 396 | - .bind(("usr", user.record())) | ||
| 397 | - .await? | ||
| 398 | - .check()?; | ||
| 399 | - Ok(()) | ||
| 400 | - } | ||
| 401 | - | ||
| 402 | - /// Delete the course and cascade-remove everything inside it: results, | ||
| 403 | - /// attempts, answers, and question/answer images of its exams, its | ||
| 404 | - /// homework with their submissions, submission files, and grades, its | ||
| 405 | - /// enrollments, the class attachments that pumped some of them (each class | ||
| 406 | - /// gets its count back, or it would be undeletable over rows pointing at | ||
| 407 | - /// nothing), its sessions with their roll call, its subjects, and the | ||
| 408 | - /// exams themselves. The children go in one transaction so a crash can't | ||
| 409 | - /// leave an exam pointing at a deleted course. The image and | ||
| 410 | - /// homework-file *blobs* are the web layer's to remove — it collects | ||
| 411 | - /// their names before calling this. | ||
| 412 | - /// | ||
| 413 | - /// **Bank templates** survive it — they are a separate, reusable library | ||
| 414 | - /// spanning every course — so their `source_exam` and `subject` links are | ||
| 415 | - /// cleared instead, in this same transaction, exactly as | ||
| 416 | - /// [`crate::domain::exam::Exam::delete`] and | ||
| 417 | - /// [`crate::domain::subject::Subject::delete`] clear them one level down. | ||
| 418 | - /// Deleting a course must leave the bank where deleting each of its exams | ||
| 419 | - /// and subjects by hand would have left it, or a template is left pointing | ||
| 420 | - /// at a dead exam (permanently: nothing else ever visits that column) and | ||
| 421 | - /// at a dead subject the next `PATCH` omitting `subject_id` writes straight | ||
| 422 | - /// back. | ||
| 423 | - /// | ||
| 424 | - /// The **grade blueprints** naming it are swept in that same transaction. | ||
| 425 | - /// Nothing else can reach them — a blueprint holds its courses as a list on | ||
| 426 | - /// its own row, not as link rows this cascade could delete — and an id left | ||
| 427 | - /// behind is permanent rather than merely stale: the pump's own | ||
| 428 | - /// [`crate::domain::class_blueprint::ClassBlueprint::prune`] fires only | ||
| 429 | - /// while walking a section, so a grade with no sections can never drop one, | ||
| 430 | - /// and every `PATCH` of that template is refused for naming a course that | ||
| 431 | - /// does not exist, which is precisely the call documented as the repair. | ||
| 432 | - /// | ||
| 433 | - /// It is a table scan, deliberately unindexed: `class_blueprint` holds one | ||
| 434 | - /// row per grade label the school uses (a dozen), a course delete is rare, | ||
| 435 | - /// and the per-element index the `WHERE` would want | ||
| 436 | - /// (`FIELDS courses[*]`) is the one this store answers with **no rows at | ||
| 437 | - /// all** — the trap [`Self::list_for_teacher`] documents. | ||
| 438 | - /// | ||
| 439 | - /// The marks going with it give their exam kinds' references back, counted | ||
| 440 | - /// per kind inside this same transaction — the mirror of `Exam::delete`. | ||
| 441 | - /// Skipping it would leave every kind the course graded under counted | ||
| 442 | - /// forever, and a counted kind can never leave the school's settings. | ||
| 443 | - /// | ||
| 444 | - /// `false` = refused, nothing was written: someone is still enrolled. The | ||
| 445 | - /// roster is read off the course's own `enrollment_count`, so the check and | ||
| 446 | - /// the delete are one conditional write on one record — an enroll racing | ||
| 447 | - /// this either takes its seat first (and the delete is refused) or finds | ||
| 448 | - /// the row gone (and is refused itself). `Err(NotFound)` | ||
| 449 | - /// keeps the answer a concurrent *delete* used to get. | ||
| 450 | - pub async fn delete(self, db: &Database) -> Result<bool, AppError> { | ||
| 451 | - let sql = format!( | ||
| 452 | - "BEGIN TRANSACTION; | ||
| 453 | - LET $gone = (DELETE $course WHERE ({ENROLLMENT_COUNT_FIELD} ?? 0) = 0 RETURN BEFORE); | ||
| 454 | - IF array::len($gone) = 0 {{ THROW '{ROSTER_MARK}' }}; | ||
| 455 | - FOR $row IN $gone {{ | ||
| 456 | - IF $row.term != NONE {{ | ||
| 457 | - UPDATE $row.term SET {COURSE_COUNT_FIELD} = \ | ||
| 458 | - math::max([({COURSE_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 459 | - }}; | ||
| 460 | - }}; | ||
| 461 | - FOR $row IN ((SELECT exam.kind AS kind, count() AS n FROM exam_result | ||
| 462 | - WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course) | ||
| 463 | - GROUP BY kind) ?? []) {{ | ||
| 464 | - UPDATE type::record('kind_ref', $row.kind) SET {REF_COUNT_FIELD} = \ | ||
| 465 | - math::max([({REF_COUNT_FIELD} ?? 0) - $row.n, 0]) | ||
| 466 | - }}; | ||
| 467 | - DELETE exam_result WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 468 | - DELETE exam_attempt WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 469 | - DELETE exam_answer WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 470 | - DELETE answer_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 471 | - DELETE question_image WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 472 | - DELETE exam_question WHERE exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 473 | - DELETE homework_file WHERE submission IN (SELECT VALUE id FROM homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course)); | ||
| 474 | - DELETE homework_submission WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); | ||
| 475 | - DELETE homework_result WHERE homework IN (SELECT VALUE id FROM homework WHERE course = $course); | ||
| 476 | - DELETE course_note_file WHERE course_note IN (SELECT VALUE id FROM course_note WHERE course = $course); | ||
| 477 | - DELETE course_note WHERE course = $course; | ||
| 478 | - LET $detached = (DELETE class_course WHERE course = $course RETURN BEFORE); | ||
| 479 | - FOR $row IN ($detached ?? []) {{ | ||
| 480 | - UPDATE $row.class SET {CLASS_COURSE_COUNT_FIELD} = \ | ||
| 481 | - math::max([({CLASS_COURSE_COUNT_FIELD} ?? 0) - 1, 0]); | ||
| 482 | - }}; | ||
| 483 | - UPDATE class_blueprint SET courses -= $course WHERE $course IN courses; | ||
| 484 | - DELETE session_attendance WHERE course = $course; | ||
| 485 | - DELETE course_session WHERE course = $course; | ||
| 486 | - DELETE enrollment WHERE course = $course; | ||
| 487 | - UPDATE bank_question SET subject = NONE | ||
| 488 | - WHERE subject IN (SELECT VALUE id FROM subject WHERE course = $course); | ||
| 489 | - DELETE subject WHERE course = $course; | ||
| 490 | - DELETE homework WHERE course = $course; | ||
| 491 | - UPDATE bank_question SET source_exam = NONE | ||
| 492 | - WHERE source_exam IN (SELECT VALUE id FROM exam WHERE course = $course); | ||
| 493 | - DELETE exam WHERE course = $course; | ||
| 494 | - COMMIT TRANSACTION;" | ||
| 495 | - ); | ||
| 496 | - // An aborted transaction errors *every* slot, most with a generic "not | ||
| 497 | - // executed" — only the THROW's own slot names the marker, and a lost | ||
| 498 | - // round is re-sent rather than reported (see [`transaction_with_retry`]). | ||
| 499 | - let (_, mut errors) = transaction_with_retry( | ||
| 500 | - db, | ||
| 501 | - &sql, | ||
| 502 | - &[("course".into(), self.id.record().into_value())], | ||
| 503 | - &[ROSTER_MARK], | ||
| 504 | - ) | ||
| 505 | - .await?; | ||
| 506 | - if errors | ||
| 507 | - .values() | ||
| 508 | - .any(|error| error.to_string().contains(ROSTER_MARK)) | ||
| 509 | - { | ||
| 510 | - // Full stop or already gone: the guard cannot tell those apart, and | ||
| 511 | - // only the refusal path pays for the extra read that can. | ||
| 512 | - return match Self::read(&self.id, db).await? { | ||
| 513 | - Some(_) => Ok(false), | ||
| 514 | - None => Err(AppError::NotFound), | ||
| 515 | - }; | ||
| 516 | - } | ||
| 517 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 518 | - return Err(error.into()); | ||
| 519 | - } | ||
| 520 | - Ok(true) | ||
| 521 | - } | ||
| 522 | -} | ||
| 523 | - | ||
| 524 | -/// A real course row, for the tests of every child that must now prove its | ||
| 525 | -/// parent exists (`Exam`, `CourseSession`, `Subject` — see | ||
| 526 | -/// [`cap::touch_and_create`]). A minted id nothing wrote is a 404 there, the | ||
| 527 | -/// way a minted subject id already is for an exam question. | ||
| 528 | -#[cfg(test)] | ||
| 529 | -pub(crate) async fn a_test_course(db: &Database) -> CourseId { | ||
| 530 | - Course::create( | ||
| 531 | - &UserId::generate(), | ||
| 532 | - CourseTitle::try_new("test course").unwrap(), | ||
| 533 | - CourseDescription::try_new("").unwrap(), | ||
| 534 | - CourseKind::course(), | ||
| 535 | - None, | ||
| 536 | - None, | ||
| 537 | - db, | ||
| 538 | - ) | ||
| 539 | - .await | ||
| 540 | - .unwrap() | ||
| 541 | - .id | ||
| 542 | -} | ||
| 543 | - | ||
| 544 | -/// The race half of "a child of a course must not survive its deletion", run | ||
| 545 | -/// for one child table: [`Course::delete`] is held open by the schema and | ||
| 546 | -/// `make` fires its create inside that window, four rounds. | ||
| 547 | -/// | ||
| 548 | -/// The harness lives here, beside the cascade being raced, and each child names | ||
| 549 | -/// its own pin in its own module (`exam`, `course_session`, `subject`) — the | ||
| 550 | -/// loop, the window and the verdict are one fact about *this* delete, and three | ||
| 551 | -/// copies of it would drift into three different tests of three different | ||
| 552 | -/// things. The sequential half — a create against a course that is already gone | ||
| 553 | -/// — is `tests/regress_course_child_orphans.rs`, which needs no server. | ||
| 554 | -/// | ||
| 555 | -/// The window is opened by the database rather than by a lucky interleaving: a | ||
| 556 | -/// `DEFINE EVENT` on `course` fires *inside* the delete's own transaction the | ||
| 557 | -/// instant the row goes, so the `SLEEP` lands between the delete and its | ||
| 558 | -/// `DELETE <child> WHERE course = $course` sweep every time — and a create | ||
| 559 | -/// fired into it reads a course that is still there (removed, uncommitted) | ||
| 560 | -/// while the sweep already ran on a snapshot without its row. | ||
| 561 | -/// | ||
| 562 | -/// One child per round, for the reason the menu and `class_course` twins | ||
| 563 | -/// document: a second writer makes the delete lose and re-send, and the re-sent | ||
| 564 | -/// sweep clears the evidence. | ||
| 565 | -/// | ||
| 566 | -/// Real server, and every caller is `#[ignore]`d for it: the subject *is* the | ||
| 567 | -/// store's conflict detection, which `init_mem`'s embedded engine does not | ||
| 568 | -/// have — it commits both sides and answers `Ok` to each, so this passes there | ||
| 569 | -/// on broken code. | ||
| 570 | -#[cfg(test)] | ||
| 571 | -pub(crate) async fn assert_no_child_outlives_a_course_delete( | ||
| 572 | - scratch: &str, | ||
| 573 | - table: &str, | ||
| 574 | - make: fn(CourseId, Database) -> tokio::task::JoinHandle<Result<(), AppError>>, | ||
| 575 | -) { | ||
| 576 | - // The guard is held for the whole test: these bursts are sub-millisecond, | ||
| 577 | - // and a sibling race test's burst pushes a delete clean out of its window. | ||
| 578 | - let (db, _serialized) = crate::database::init_test_server(scratch).await; | ||
| 579 | - db.query( | ||
| 580 | - "DEFINE EVENT hold_the_window ON TABLE course WHEN $event = 'DELETE' \ | ||
| 581 | - THEN { SLEEP 1s; };", | ||
| 582 | - ) | ||
| 583 | - .await | ||
| 584 | - .expect("define the window event") | ||
| 585 | - .check() | ||
| 586 | - .expect("check the window event"); | ||
| 587 | - | ||
| 588 | - let (mut swept, mut orphans) = (0, 0); | ||
| 589 | - for round in 0..4 { | ||
| 590 | - let course = a_test_course(&db).await; | ||
| 591 | - let drop_it = { | ||
| 592 | - let (course, db) = (course.clone(), db.clone()); | ||
| 593 | - tokio::spawn(async move { | ||
| 594 | - Course::read(&course, &db) | ||
| 595 | - .await | ||
| 596 | - .unwrap() | ||
| 597 | - .expect("the course is there") | ||
| 598 | - .delete(&db) | ||
| 599 | - .await | ||
| 600 | - }) | ||
| 601 | - }; | ||
| 602 | - // The create starts inside the held window. | ||
| 603 | - tokio::time::sleep(std::time::Duration::from_millis(300)).await; | ||
| 604 | - let child = make(course.clone(), db.clone()).await.unwrap(); | ||
| 605 | - let dropped = drop_it.await.unwrap(); | ||
| 606 | - | ||
| 607 | - // A 404 for the create, or a refusal for the delete, is a correct | ||
| 608 | - // answer — the only defect is stored state. Nothing may 500. | ||
| 609 | - assert!( | ||
| 610 | - !matches!(child, Err(AppError::Db(_))), | ||
| 611 | - "{table} round {round}: a raced create must be answered, not 500: {child:?}" | ||
| 612 | - ); | ||
| 613 | - assert!( | ||
| 614 | - !matches!(dropped, Err(AppError::Db(_))), | ||
| 615 | - "{table} round {round}: a raced delete must be answered, not 500: {dropped:?}" | ||
| 616 | - ); | ||
| 617 | - | ||
| 618 | - // Stored state is the whole verdict; a return value is not evidence. | ||
| 619 | - if Course::read(&course, &db).await.unwrap().is_none() { | ||
| 620 | - swept += 1; | ||
| 621 | - let mut left = db | ||
| 622 | - .query(format!( | ||
| 623 | - "SELECT VALUE id FROM {table} WHERE course = $course" | ||
| 624 | - )) | ||
| 625 | - .bind(("course", course.record())) | ||
| 626 | - .await | ||
| 627 | - .unwrap() | ||
| 628 | - .check() | ||
| 629 | - .unwrap(); | ||
| 630 | - orphans += left.take::<Vec<RecordId>>(0).unwrap().len(); | ||
| 631 | - } else if matches!(dropped, Ok(true)) { | ||
| 632 | - panic!("{table} round {round}: the delete reported success, the course is still there"); | ||
| 633 | - } | ||
| 634 | - } | ||
| 635 | - eprintln!("Course::delete raced by a {table} create: {swept}/4 rounds deleted the course"); | ||
| 636 | - assert!( | ||
| 637 | - swept > 0, | ||
| 638 | - "{table}: no round ever deleted the course, so the window was never reached" | ||
| 639 | - ); | ||
| 640 | - assert_eq!(orphans, 0, "{table}: a child outlived its course"); | ||
| 641 | } | 158 | } |
| 642 | 159 | ||
| 643 | #[cfg(test)] | 160 | #[cfg(test)] |
| 644 | mod tests { | 161 | mod tests { |
| 645 | use super::*; | 162 | use super::*; |
| 646 | - use crate::domain::term::{Term, TermName}; | ||
| 647 | - | ||
| 648 | - async fn course_on(term: Option<TermId>, db: &Database) -> Course { | ||
| 649 | - Course::create( | ||
| 650 | - &UserId::from_key("teacher"), | ||
| 651 | - CourseTitle::try_new("algebra").unwrap(), | ||
| 652 | - CourseDescription::try_new("").unwrap(), | ||
| 653 | - CourseKind::course(), | ||
| 654 | - term, | ||
| 655 | - None, | ||
| 656 | - db, | ||
| 657 | - ) | ||
| 658 | - .await | ||
| 659 | - .unwrap() | ||
| 660 | - } | ||
| 661 | - | ||
| 662 | - /// The bite test for the delete guard that replaced `ENROLL_LOCK`: the | ||
| 663 | - /// roster check is now the `WHERE` on the delete itself, so only the guard | ||
| 664 | - /// can refuse — and it must refuse having written nothing, cascade | ||
| 665 | - /// included. A `>= 0` guard passes the roster branch and fails here. | ||
| 666 | - #[tokio::test] | ||
| 667 | - async fn a_course_with_a_roster_refuses_to_delete() { | ||
| 668 | - use crate::domain::enrollment::Enrollment; | ||
| 669 | - | ||
| 670 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 671 | - let teacher = UserId::from_key("teacher"); | ||
| 672 | - let student = UserId::from_key("student"); | ||
| 673 | - let course = course_on(None, &db).await; | ||
| 674 | - Enrollment::enroll(course.get_id(), &student, &teacher, &db) | ||
| 675 | - .await | ||
| 676 | - .unwrap(); | ||
| 677 | - | ||
| 678 | - assert!( | ||
| 679 | - !course.clone().delete(&db).await.unwrap(), | ||
| 680 | - "a non-empty roster must refuse the delete" | ||
| 681 | - ); | ||
| 682 | - assert!( | ||
| 683 | - Course::read(course.get_id(), &db).await.unwrap().is_some(), | ||
| 684 | - "a refused delete may write nothing" | ||
| 685 | - ); | ||
| 686 | - assert!( | ||
| 687 | - Enrollment::read_for_user(course.get_id(), &student, &db) | ||
| 688 | - .await | ||
| 689 | - .unwrap() | ||
| 690 | - .is_some(), | ||
| 691 | - "…the cascade least of all" | ||
| 692 | - ); | ||
| 693 | - | ||
| 694 | - Enrollment::remove(course.get_id(), &student, &db) | ||
| 695 | - .await | ||
| 696 | - .unwrap(); | ||
| 697 | - assert!(course.clone().delete(&db).await.unwrap()); | ||
| 698 | - assert!(Course::read(course.get_id(), &db).await.unwrap().is_none()); | ||
| 699 | - | ||
| 700 | - // The other half of the same guard: once the course row is gone the | ||
| 701 | - // seat claim matches nothing, so a late enroll is a 404 rather than a | ||
| 702 | - // roster row that outlived its course. | ||
| 703 | - let late = Enrollment::enroll(course.get_id(), &student, &teacher, &db) | ||
| 704 | - .await | ||
| 705 | - .expect_err("enrolling into a deleted course must fail"); | ||
| 706 | - assert!(matches!(late, AppError::NotFound), "got {late:?}"); | ||
| 707 | - } | ||
| 708 | - | ||
| 709 | - /// The bite test for the refcount that replaced `TERM_LOCK`: a term is | ||
| 710 | - /// undeletable exactly while a course links it, and every way a link can | ||
| 711 | - /// end — PATCH away, and the course's own delete — gives the reference | ||
| 712 | - /// back. Dropping the release in `delete` leaves the term deletable never. | ||
| 713 | - #[tokio::test] | ||
| 714 | - async fn a_term_is_deletable_only_once_no_course_links_it() { | ||
| 715 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 716 | - let at = crate::domain::timestamp::Timestamp::from_millis; | ||
| 717 | - let term = Term::create(TermName::try_new("2026").unwrap(), at(100), at(200), &db) | ||
| 718 | - .await | ||
| 719 | - .unwrap(); | ||
| 720 | - | ||
| 721 | - let linked = course_on(Some(term.get_id().clone()), &db).await; | ||
| 722 | - let patched = course_on(Some(term.get_id().clone()), &db).await; | ||
| 723 | - assert!( | ||
| 724 | - !term.clone().delete(&db).await.unwrap(), | ||
| 725 | - "two linked courses must refuse the delete" | ||
| 726 | - ); | ||
| 727 | - | ||
| 728 | - patched | ||
| 729 | - .update(None, None, None, Some(None), None, &db) | ||
| 730 | - .await | ||
| 731 | - .unwrap(); | ||
| 732 | - assert!( | ||
| 733 | - !term.clone().delete(&db).await.unwrap(), | ||
| 734 | - "one link is still one link" | ||
| 735 | - ); | ||
| 736 | - | ||
| 737 | - assert!(linked.delete(&db).await.unwrap()); | ||
| 738 | - assert!( | ||
| 739 | - term.clone().delete(&db).await.unwrap(), | ||
| 740 | - "the last link gone, the term may go" | ||
| 741 | - ); | ||
| 742 | - let again = term.delete(&db).await; | ||
| 743 | - assert!( | ||
| 744 | - matches!(again, Err(AppError::NotFound)), | ||
| 745 | - "a second delete is a 404, not a refusal: {again:?}" | ||
| 746 | - ); | ||
| 747 | - } | ||
| 748 | - | ||
| 749 | - /// The claim doubles as the existence check the lock used to make safe: | ||
| 750 | - /// a term that is already gone cannot be linked, with the same 400 the | ||
| 751 | - /// web layer's pre-flight lookup gives. | ||
| 752 | - #[tokio::test] | ||
| 753 | - async fn a_course_cannot_link_a_term_that_is_gone() { | ||
| 754 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 755 | - let error = Course::create( | ||
| 756 | - &UserId::from_key("teacher"), | ||
| 757 | - CourseTitle::try_new("algebra").unwrap(), | ||
| 758 | - CourseDescription::try_new("").unwrap(), | ||
| 759 | - CourseKind::course(), | ||
| 760 | - Some(TermId::from_key("gone")), | ||
| 761 | - None, | ||
| 762 | - &db, | ||
| 763 | - ) | ||
| 764 | - .await | ||
| 765 | - .expect_err("a missing term must not be linkable"); | ||
| 766 | - assert!(error.to_string().contains("term does not exist")); | ||
| 767 | - } | ||
| 768 | - | ||
| 769 | - /// The stored `course_count` on one term, absent counting as zero. | ||
| 770 | - async fn count_on(term: &TermId, db: &Database) -> i64 { | ||
| 771 | - let mut result = db | ||
| 772 | - .query(format!( | ||
| 773 | - "SELECT VALUE ({COURSE_COUNT_FIELD} ?? 0) FROM $term" | ||
| 774 | - )) | ||
| 775 | - .bind(("term", term.record())) | ||
| 776 | - .await | ||
| 777 | - .unwrap() | ||
| 778 | - .check() | ||
| 779 | - .unwrap(); | ||
| 780 | - result | ||
| 781 | - .take::<Vec<i64>>(0) | ||
| 782 | - .unwrap() | ||
| 783 | - .first() | ||
| 784 | - .copied() | ||
| 785 | - .unwrap_or(0) | ||
| 786 | - } | ||
| 787 | - | ||
| 788 | - /// How many rows `sql` selects ids for. | ||
| 789 | - async fn rows(sql: &str, db: &Database) -> usize { | ||
| 790 | - let mut result = db.query(sql).await.unwrap().check().unwrap(); | ||
| 791 | - result.take::<Vec<RecordId>>(0).unwrap().len() | ||
| 792 | - } | ||
| 793 | - | ||
| 794 | - async fn a_term(name: &str, db: &Database) -> Term { | ||
| 795 | - let at = crate::domain::timestamp::Timestamp::from_millis; | ||
| 796 | - Term::create(TermName::try_new(name).unwrap(), at(100), at(200), db) | ||
| 797 | - .await | ||
| 798 | - .unwrap() | ||
| 799 | - } | ||
| 800 | - | ||
| 801 | - /// The invariant, on the create path: a claim and the row it accounts for | ||
| 802 | - /// commit together or not at all. A refused create must therefore leave | ||
| 803 | - /// *neither* — no course row, and no count stranded on a term (which is | ||
| 804 | - /// worse than it sounds: the term's delete guard reads that count, so a | ||
| 805 | - /// stray one makes the term undeletable forever). | ||
| 806 | - #[tokio::test] | ||
| 807 | - async fn a_refused_create_writes_neither_row_nor_count() { | ||
| 808 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 809 | - let term = a_term("2026", &db).await; | ||
| 810 | - let id = term.get_id().clone(); | ||
| 811 | - assert!(term.delete(&db).await.unwrap()); | ||
| 812 | - | ||
| 813 | - let error = Course::create( | ||
| 814 | - &UserId::from_key("teacher"), | ||
| 815 | - CourseTitle::try_new("algebra").unwrap(), | ||
| 816 | - CourseDescription::try_new("").unwrap(), | ||
| 817 | - CourseKind::course(), | ||
| 818 | - Some(id), | ||
| 819 | - None, | ||
| 820 | - &db, | ||
| 821 | - ) | ||
| 822 | - .await | ||
| 823 | - .expect_err("a term that is gone must not be linkable"); | ||
| 824 | - assert!(error.to_string().contains("term does not exist")); | ||
| 825 | - assert_eq!( | ||
| 826 | - rows("SELECT VALUE id FROM course", &db).await, | ||
| 827 | - 0, | ||
| 828 | - "a refused create may write no row" | ||
| 829 | - ); | ||
| 830 | - assert_eq!( | ||
| 831 | - rows("SELECT VALUE id FROM term", &db).await, | ||
| 832 | - 0, | ||
| 833 | - "…and least of all a count on a term it just brought back" | ||
| 834 | - ); | ||
| 835 | - } | ||
| 836 | - | ||
| 837 | - /// The invariant on the PATCH path, both directions: a move carries the new | ||
| 838 | - /// term's claim and the old term's release with the link itself. | ||
| 839 | - #[tokio::test] | ||
| 840 | - async fn a_term_move_moves_the_count() { | ||
| 841 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 842 | - let from = a_term("2026", &db).await; | ||
| 843 | - let to = a_term("2027", &db).await; | ||
| 844 | - let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 845 | - assert_eq!(count_on(from.get_id(), &db).await, 1); | ||
| 846 | - | ||
| 847 | - let moved = course | ||
| 848 | - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 849 | - .await | ||
| 850 | - .unwrap(); | ||
| 851 | - assert_eq!(moved.get_term(), Some(to.get_id())); | ||
| 852 | - assert_eq!( | ||
| 853 | - count_on(from.get_id(), &db).await, | ||
| 854 | - 0, | ||
| 855 | - "the old term is free" | ||
| 856 | - ); | ||
| 857 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); | ||
| 858 | - assert!(from.clone().delete(&db).await.unwrap()); | ||
| 859 | - assert!(!to.clone().delete(&db).await.unwrap()); | ||
| 860 | - } | ||
| 861 | - | ||
| 862 | - /// The double-claim guard. Both movers compute their claim and release from | ||
| 863 | - /// the row as *they* read it, so two PATCHes moving the same course off the | ||
| 864 | - /// same term both release it and both claim their target — two counts for | ||
| 865 | - /// one link, and the loser's target is undeletable forever. The second call | ||
| 866 | - /// here runs on the struct read before the first one landed, which is that | ||
| 867 | - /// race with the interleaving pinned: it must be refused outright, and the | ||
| 868 | - /// counts must read as if it never ran. | ||
| 869 | - #[tokio::test] | ||
| 870 | - async fn a_stale_mover_is_refused_and_claims_nothing() { | ||
| 871 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 872 | - let from = a_term("2026", &db).await; | ||
| 873 | - let to = a_term("2027", &db).await; | ||
| 874 | - let other = a_term("2028", &db).await; | ||
| 875 | - let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 876 | - let stale = course.clone(); | ||
| 877 | - course | ||
| 878 | - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 879 | - .await | ||
| 880 | - .unwrap(); | ||
| 881 | - | ||
| 882 | - let error = stale | ||
| 883 | - .clone() | ||
| 884 | - .update( | ||
| 885 | - None, | ||
| 886 | - None, | ||
| 887 | - None, | ||
| 888 | - Some(Some(other.get_id().clone())), | ||
| 889 | - None, | ||
| 890 | - &db, | ||
| 891 | - ) | ||
| 892 | - .await | ||
| 893 | - .expect_err("a mover that read a link it no longer holds must be refused"); | ||
| 894 | - assert!( | ||
| 895 | - matches!(error, AppError::Conflict(_)), | ||
| 896 | - "a lost CAS is a conflict, not a 404 or a 500: {error:?}" | ||
| 897 | - ); | ||
| 898 | - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 899 | - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); | ||
| 900 | - assert_eq!( | ||
| 901 | - count_on(from.get_id(), &db).await, | ||
| 902 | - 0, | ||
| 903 | - "released once, not twice" | ||
| 904 | - ); | ||
| 905 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); | ||
| 906 | - assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); | ||
| 907 | - | ||
| 908 | - // Same race from the other end: the snapshot says *no* link, so the CAS | ||
| 909 | - // is against an absent column — the shape a bound `NONE` has to match. | ||
| 910 | - let unlinked = course_on(None, &db).await; | ||
| 911 | - let stale = unlinked.clone(); | ||
| 912 | - unlinked | ||
| 913 | - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 914 | - .await | ||
| 915 | - .unwrap(); | ||
| 916 | - let error = stale | ||
| 917 | - .clone() | ||
| 918 | - .update( | ||
| 919 | - None, | ||
| 920 | - None, | ||
| 921 | - None, | ||
| 922 | - Some(Some(other.get_id().clone())), | ||
| 923 | - None, | ||
| 924 | - &db, | ||
| 925 | - ) | ||
| 926 | - .await | ||
| 927 | - .expect_err("a mover that read an absent link someone else filled must be refused"); | ||
| 928 | - assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); | ||
| 929 | - assert_eq!(count_on(to.get_id(), &db).await, 2, "one claim per link"); | ||
| 930 | - assert_eq!( | ||
| 931 | - count_on(other.get_id(), &db).await, | ||
| 932 | - 0, | ||
| 933 | - "still never claimed" | ||
| 934 | - ); | ||
| 935 | - // …and the unraced set still lands, so the CAS did not just break moves. | ||
| 936 | - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 937 | - assert_eq!(stored.get_term(), Some(to.get_id())); | ||
| 938 | - } | ||
| 939 | - | ||
| 940 | - /// The same race with the counters taken out of it. A PATCH that re-states | ||
| 941 | - /// the term its snapshot showed shifts *nothing* — [`term::ref_move`] hands | ||
| 942 | - /// back no claim and no release — so if the guard were armed off the counter | ||
| 943 | - /// move it would not be armed here at all, and the write would land: the | ||
| 944 | - /// winner's link silently dragged back, its claim stranded on a term nothing | ||
| 945 | - /// points at (undeletable forever) and the reverted-to term linked at a | ||
| 946 | - /// count of zero (deletable while linked). The guard is armed by the request | ||
| 947 | - /// *carrying* the column instead, which is why this is refused. | ||
| 948 | - #[tokio::test] | ||
| 949 | - async fn a_stale_re_stater_is_refused_and_reverts_nothing() { | ||
| 950 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 951 | - let from = a_term("2026", &db).await; | ||
| 952 | - let to = a_term("2027", &db).await; | ||
| 953 | - let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 954 | - let stale = course.clone(); | ||
| 955 | - course | ||
| 956 | - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 957 | - .await | ||
| 958 | - .unwrap(); | ||
| 959 | - | ||
| 960 | - let error = stale | ||
| 961 | - .clone() | ||
| 962 | - .update( | ||
| 963 | - None, | ||
| 964 | - None, | ||
| 965 | - None, | ||
| 966 | - Some(Some(from.get_id().clone())), | ||
| 967 | - None, | ||
| 968 | - &db, | ||
| 969 | - ) | ||
| 970 | - .await | ||
| 971 | - .expect_err("re-stating a link someone else moved must be refused"); | ||
| 972 | - assert!( | ||
| 973 | - matches!(error, AppError::Conflict(_)), | ||
| 974 | - "a lost CAS is a conflict, not a silent 200: {error:?}" | ||
| 975 | - ); | ||
| 976 | - let stored = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 977 | - assert_eq!(stored.get_term(), Some(to.get_id()), "the winner's link"); | ||
| 978 | - assert_eq!( | ||
| 979 | - count_on(from.get_id(), &db).await, | ||
| 980 | - 0, | ||
| 981 | - "the reverted-to term must not end up linked at zero" | ||
| 982 | - ); | ||
| 983 | - assert_eq!( | ||
| 984 | - count_on(to.get_id(), &db).await, | ||
| 985 | - 1, | ||
| 986 | - "…nor the winner's term counted with nothing pointing at it" | ||
| 987 | - ); | ||
| 988 | - | ||
| 989 | - // A *genuine* no-op re-state — nobody moved underneath it — still lands, | ||
| 990 | - // and still moves no counter: the CAS passes trivially. | ||
| 991 | - let fresh = Course::read(stale.get_id(), &db).await.unwrap().unwrap(); | ||
| 992 | - let same = fresh | ||
| 993 | - .update(None, None, None, Some(Some(to.get_id().clone())), None, &db) | ||
| 994 | - .await | ||
| 995 | - .expect("re-stating the link the row really holds is not a conflict"); | ||
| 996 | - assert_eq!(same.get_term(), Some(to.get_id())); | ||
| 997 | - assert_eq!(count_on(from.get_id(), &db).await, 0, "nothing moved"); | ||
| 998 | - assert_eq!(count_on(to.get_id(), &db).await, 1, "…in either direction"); | ||
| 999 | - } | ||
| 1000 | - | ||
| 1001 | - /// The rollback proof. The transaction releases the old term *before* it | ||
| 1002 | - /// claims the new one, so a move to a term that is gone has already | ||
| 1003 | - /// decremented when the claim throws — the old count still being 1 is the | ||
| 1004 | - /// abort undoing a write that really happened, not a branch that never ran. | ||
| 1005 | - /// The title moves in the same PATCH, and must not stick either. | ||
| 1006 | - #[tokio::test] | ||
| 1007 | - async fn a_term_move_to_a_dead_term_leaves_everything_untouched() { | ||
| 1008 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 1009 | - let from = a_term("2026", &db).await; | ||
| 1010 | - let dead = a_term("2027", &db).await; | ||
| 1011 | - let dead_id = dead.get_id().clone(); | ||
| 1012 | - assert!(dead.delete(&db).await.unwrap()); | ||
| 1013 | - let course = course_on(Some(from.get_id().clone()), &db).await; | ||
| 1014 | - | ||
| 1015 | - let error = course | ||
| 1016 | - .clone() | ||
| 1017 | - .update( | ||
| 1018 | - Some(CourseTitle::try_new("moved").unwrap()), | ||
| 1019 | - None, | ||
| 1020 | - None, | ||
| 1021 | - Some(Some(dead_id)), | ||
| 1022 | - None, | ||
| 1023 | - &db, | ||
| 1024 | - ) | ||
| 1025 | - .await | ||
| 1026 | - .expect_err("a term that is gone must not be linkable"); | ||
| 1027 | - assert!(error.to_string().contains("term does not exist")); | ||
| 1028 | - | ||
| 1029 | - let stored = Course::read(course.get_id(), &db).await.unwrap().unwrap(); | ||
| 1030 | - assert_eq!(stored.get_term(), Some(from.get_id()), "the link stays put"); | ||
| 1031 | - assert_eq!( | ||
| 1032 | - stored.get_title().as_str(), | ||
| 1033 | - "algebra", | ||
| 1034 | - "…and so does the row" | ||
| 1035 | - ); | ||
| 1036 | - assert_eq!( | ||
| 1037 | - count_on(from.get_id(), &db).await, | ||
| 1038 | - 1, | ||
| 1039 | - "the release must roll back with the abort" | ||
| 1040 | - ); | ||
| 1041 | - assert_eq!( | ||
| 1042 | - rows("SELECT VALUE id FROM term", &db).await, | ||
| 1043 | - 1, | ||
| 1044 | - "the dead term must not be resurrected by the claim" | ||
| 1045 | - ); | ||
| 1046 | - } | ||
| 1047 | 163 | ||
| 1048 | #[tokio::test] | 164 | #[tokio::test] |
| 1049 | async fn title_is_required() { | 165 | async fn title_is_required() { |
| @@ -1120,103 +236,4 @@ mod tests { | |||
| 1120 | assert!(decoded.get_teachers().is_empty()); | 236 | assert!(decoded.get_teachers().is_empty()); |
| 1121 | assert!(!decoded.is_assigned(&assigned)); | 237 | assert!(!decoded.is_assigned(&assigned)); |
| 1122 | } | 238 | } |
| 1123 | - | ||
| 1124 | - /// MEASUREMENT — the one race test that actually measures the retry, and | ||
| 1125 | - /// the only one of the four that does. The other three (subject, term, | ||
| 1126 | - /// exam) are status-code guards; each says so on itself. | ||
| 1127 | - /// | ||
| 1128 | - /// `Course::delete` is one `BEGIN…COMMIT` whose guard reads | ||
| 1129 | - /// `enrollment_count` off the very record a concurrent enroll increments, | ||
| 1130 | - /// so the two contend by design, and its cascade is long enough that a | ||
| 1131 | - /// rival's write lands mid-transaction. Losing that round writes nothing, | ||
| 1132 | - /// which is what makes re-sending it the recovery. Without | ||
| 1133 | - /// [`crate::database::transaction_with_retry`] a lost round comes out as a | ||
| 1134 | - /// 500: mutation-tested by cutting that retry loop to one attempt, which | ||
| 1135 | - /// turns this test red at 1-2 of 20 rounds (3 runs in 5 — the window is | ||
| 1136 | - /// real but narrow, so a single green run under the mutation means nothing). | ||
| 1137 | - /// | ||
| 1138 | - /// A refusal (`Ok(false)`) or an `Err(NotFound)` is *correct* here and | ||
| 1139 | - /// must not fail this test: the only defect is `AppError::Db`. | ||
| 1140 | - /// | ||
| 1141 | - /// The rate is counted over the whole loop instead of asserted per round, | ||
| 1142 | - /// because a per-round `assert!` aborts at the first hit and would report | ||
| 1143 | - /// "1 of 1" for a bug the point of this test is to *quantify*. | ||
| 1144 | - /// | ||
| 1145 | - /// Multi-threaded and on a real server for the reasons spelled out on | ||
| 1146 | - /// [`crate::domain::fee_plan_assignment`]'s pair of race tests: the | ||
| 1147 | - /// current-thread runtime never interleaves the two, and the embedded | ||
| 1148 | - /// engine does not conflict-check concurrent writes to one record at all. | ||
| 1149 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 1150 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 1151 | - async fn a_delete_racing_an_enroll_never_answers_500() { | ||
| 1152 | - use crate::domain::enrollment::Enrollment; | ||
| 1153 | - let (db, _serialized) = crate::database::init_test_server("course_delete_race").await; | ||
| 1154 | - let (mut delete_500, mut enroll_500, mut enrolled) = (0, 0, 0); | ||
| 1155 | - let (mut last_delete, mut last_enroll) = (String::new(), String::new()); | ||
| 1156 | - for round in 0..20 { | ||
| 1157 | - let course = course_on(None, &db).await; | ||
| 1158 | - | ||
| 1159 | - // A *burst* of enrolls, and a delete held back by a sweeping beat. | ||
| 1160 | - // Released together the delete is one statement while an enroll | ||
| 1161 | - // spends two round trips reading before it claims, so it wins every | ||
| 1162 | - // round and the guard is never contended at all (measured: 0/20 | ||
| 1163 | - // seats placed). Six racers over a 0-3ms sweep put the single | ||
| 1164 | - // statement somewhere inside the counter writes instead. | ||
| 1165 | - let drop_it = { | ||
| 1166 | - let (course, db) = (course.clone(), db.clone()); | ||
| 1167 | - let beat = std::time::Duration::from_millis(round % 4); | ||
| 1168 | - tokio::spawn(async move { | ||
| 1169 | - tokio::time::sleep(beat).await; | ||
| 1170 | - course.delete(&db).await | ||
| 1171 | - }) | ||
| 1172 | - }; | ||
| 1173 | - let joins: Vec<_> = (0..6) | ||
| 1174 | - .map(|seat| { | ||
| 1175 | - let (id, db) = (course.get_id().clone(), db.clone()); | ||
| 1176 | - let student = UserId::from_key(&format!("stu{round}_{seat}")); | ||
| 1177 | - tokio::spawn(async move { | ||
| 1178 | - Enrollment::enroll(&id, &student, &UserId::from_key("mgr"), &db).await | ||
| 1179 | - }) | ||
| 1180 | - }) | ||
| 1181 | - .collect(); | ||
| 1182 | - let drop_it = drop_it.await.unwrap(); | ||
| 1183 | - if matches!(drop_it, Err(AppError::Db(_))) { | ||
| 1184 | - delete_500 += 1; | ||
| 1185 | - last_delete = format!("{drop_it:?}"); | ||
| 1186 | - } | ||
| 1187 | - for join in joins { | ||
| 1188 | - let join = join.await.unwrap(); | ||
| 1189 | - if matches!(join, Err(AppError::Db(_))) { | ||
| 1190 | - enroll_500 += 1; | ||
| 1191 | - last_enroll = format!("{join:?}"); | ||
| 1192 | - } | ||
| 1193 | - } | ||
| 1194 | - // Stored state, not the return values: a seat that landed is what | ||
| 1195 | - // the guard had to see. | ||
| 1196 | - if !Enrollment::list_for_course(course.get_id(), None, 0, &db) | ||
| 1197 | - .await | ||
| 1198 | - .unwrap() | ||
| 1199 | - .0 | ||
| 1200 | - .is_empty() | ||
| 1201 | - { | ||
| 1202 | - enrolled += 1; | ||
| 1203 | - } | ||
| 1204 | - } | ||
| 1205 | - eprintln!( | ||
| 1206 | - "Course::delete raced: {delete_500}/20 delete 500s, {enroll_500} enroll 500s, \ | ||
| 1207 | - {enrolled}/20 rounds with a seat placed" | ||
| 1208 | - ); | ||
| 1209 | - assert!( | ||
| 1210 | - enrolled > 0, | ||
| 1211 | - "no round ever placed an enrollment, so the delete guard was never contended" | ||
| 1212 | - ); | ||
| 1213 | - assert_eq!( | ||
| 1214 | - delete_500, 0, | ||
| 1215 | - "a raced delete must be refused, not 500: {delete_500}/20 rounds, last {last_delete}" | ||
| 1216 | - ); | ||
| 1217 | - assert_eq!( | ||
| 1218 | - enroll_500, 0, | ||
| 1219 | - "a raced enroll must retry, not 500: {enroll_500}/20 rounds, last {last_enroll}" | ||
| 1220 | - ); | ||
| 1221 | - } | ||
| 1222 | } | 239 | } |
src/domain/course_note.rsmodified+3 -3
| @@ -225,19 +225,19 @@ mod tests { | |||
| 225 | /// been taken, which is the row whose blob used to leak. | 225 | /// been taken, which is the row whose blob used to leak. |
| 226 | #[tokio::test] | 226 | #[tokio::test] |
| 227 | async fn delete_returns_the_attachment_rows_it_removed() { | 227 | async fn delete_returns_the_attachment_rows_it_removed() { |
| 228 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 228 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 229 | use crate::domain::course_note_file::{FileContentType, FileName}; | 229 | use crate::domain::course_note_file::{FileContentType, FileName}; |
| 230 | 230 | ||
| 231 | let db = crate::database::init_mem().await.unwrap(); | 231 | let db = crate::database::init_mem().await.unwrap(); |
| 232 | let creator = crate::domain::user::UserId::generate(); | 232 | let creator = crate::domain::user::UserId::generate(); |
| 233 | - let course = Course::create( | 233 | + let course = crate::db::course::create( |
| 234 | + &db, | ||
| 234 | &creator, | 235 | &creator, |
| 235 | CourseTitle::try_new("Math").unwrap(), | 236 | CourseTitle::try_new("Math").unwrap(), |
| 236 | CourseDescription::try_new("").unwrap(), | 237 | CourseDescription::try_new("").unwrap(), |
| 237 | CourseKind::try_new("course").unwrap(), | 238 | CourseKind::try_new("course").unwrap(), |
| 238 | None, | 239 | None, |
| 239 | None, | 240 | None, |
| 240 | - &db, | ||
| 241 | ) | 241 | ) |
| 242 | .await | 242 | .await |
| 243 | .unwrap(); | 243 | .unwrap(); |
src/domain/course_note_file.rsmodified+3 -3
| @@ -219,19 +219,19 @@ impl CourseNoteFile { | |||
| 219 | #[cfg(test)] | 219 | #[cfg(test)] |
| 220 | mod tests { | 220 | mod tests { |
| 221 | use super::*; | 221 | use super::*; |
| 222 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 222 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 223 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 223 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; |
| 224 | 224 | ||
| 225 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 225 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 226 | let creator = crate::domain::user::UserId::generate(); | 226 | let creator = crate::domain::user::UserId::generate(); |
| 227 | - let course = Course::create( | 227 | + let course = crate::db::course::create( |
| 228 | + db, | ||
| 228 | &creator, | 229 | &creator, |
| 229 | CourseTitle::try_new("c").unwrap(), | 230 | CourseTitle::try_new("c").unwrap(), |
| 230 | CourseDescription::try_new("").unwrap(), | 231 | CourseDescription::try_new("").unwrap(), |
| 231 | CourseKind::try_new("course").unwrap(), | 232 | CourseKind::try_new("course").unwrap(), |
| 232 | None, | 233 | None, |
| 233 | None, | 234 | None, |
| 234 | - db, | ||
| 235 | ) | 235 | ) |
| 236 | .await | 236 | .await |
| 237 | .unwrap(); | 237 | .unwrap(); |
src/domain/course_session.rsmodified+4 -6
| @@ -222,7 +222,7 @@ mod tests { | |||
| 222 | /// [`CourseSession::create`] therefore *writes* the course row rather than | 222 | /// [`CourseSession::create`] therefore *writes* the course row rather than |
| 223 | /// reading it ([`cap::touch_and_create`]); the harness and the window it | 223 | /// reading it ([`cap::touch_and_create`]); the harness and the window it |
| 224 | /// races in are documented on | 224 | /// races in are documented on |
| 225 | - /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. | 225 | + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. |
| 226 | /// Mutation-tested: with the bare `db.create` this shipped with, all four | 226 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 227 | /// rounds orphan. | 227 | /// rounds orphan. |
| 228 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 228 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| @@ -242,11 +242,9 @@ mod tests { | |||
| 242 | .map(|_| ()) | 242 | .map(|_| ()) |
| 243 | }) | 243 | }) |
| 244 | } | 244 | } |
| 245 | - crate::domain::course::assert_no_child_outlives_a_course_delete( | 245 | + crate::db::course::assert_no_child_outlives_a_course_delete("session_orphan_race", |
| 246 | - "session_orphan_race", | 246 | + COURSE_SESSION_TABLE, |
| 247 | - COURSE_SESSION_TABLE, | 247 | + make,) |
| 248 | - make, | ||
| 249 | - ) | ||
| 250 | .await; | 248 | .await; |
| 251 | } | 249 | } |
| 252 | 250 | ||
src/domain/enrollment.rsmodified+5 -5
| @@ -4,7 +4,7 @@ use crate::constant::{ENROLLMENT_COUNT_FIELD, ENROLLMENT_TABLE}; | |||
| 4 | use crate::database::{Database, transaction_with_retry}; | 4 | use crate::database::{Database, transaction_with_retry}; |
| 5 | use crate::db::cap; | 5 | use crate::db::cap; |
| 6 | use crate::domain::class_group::ClassGroupId; | 6 | use crate::domain::class_group::ClassGroupId; |
| 7 | -use crate::domain::course::{Course, CourseId}; | 7 | +use crate::domain::course::CourseId; |
| 8 | use crate::db::page::PagedList; | 8 | use crate::db::page::PagedList; |
| 9 | use crate::domain::role::Role; | 9 | use crate::domain::role::Role; |
| 10 | use crate::domain::user::UserId; | 10 | use crate::domain::user::UserId; |
| @@ -203,7 +203,7 @@ impl Enrollment { | |||
| 203 | .values() | 203 | .values() |
| 204 | .any(|error| error.to_string().contains(FULL_MARK)) | 204 | .any(|error| error.to_string().contains(FULL_MARK)) |
| 205 | { | 205 | { |
| 206 | - return match Course::read(course, db).await? { | 206 | + return match crate::db::course::read(db, course).await? { |
| 207 | Some(_) => Err(AppError::Conflict("the course is full")), | 207 | Some(_) => Err(AppError::Conflict("the course is full")), |
| 208 | None => Err(AppError::NotFound), | 208 | None => Err(AppError::NotFound), |
| 209 | }; | 209 | }; |
| @@ -416,18 +416,18 @@ mod tests { | |||
| 416 | /// never wrote. Asserted on the stored row, not the returned one. | 416 | /// never wrote. Asserted on the stored row, not the returned one. |
| 417 | #[tokio::test] | 417 | #[tokio::test] |
| 418 | async fn a_hand_placed_enrollment_stores_no_source_key() { | 418 | async fn a_hand_placed_enrollment_stores_no_source_key() { |
| 419 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 419 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 420 | 420 | ||
| 421 | let db = crate::database::init_mem().await.unwrap(); | 421 | let db = crate::database::init_mem().await.unwrap(); |
| 422 | let teacher = UserId::from_key("teacher"); | 422 | let teacher = UserId::from_key("teacher"); |
| 423 | - let course = Course::create( | 423 | + let course = crate::db::course::create( |
| 424 | + &db, | ||
| 424 | &teacher, | 425 | &teacher, |
| 425 | CourseTitle::try_new("algebra").unwrap(), | 426 | CourseTitle::try_new("algebra").unwrap(), |
| 426 | CourseDescription::try_new("").unwrap(), | 427 | CourseDescription::try_new("").unwrap(), |
| 427 | CourseKind::course(), | 428 | CourseKind::course(), |
| 428 | None, | 429 | None, |
| 429 | None, | 430 | None, |
| 430 | - &db, | ||
| 431 | ) | 431 | ) |
| 432 | .await | 432 | .await |
| 433 | .unwrap(); | 433 | .unwrap(); |
src/domain/event.rsmodified+1 -1
| @@ -311,7 +311,7 @@ impl Event { | |||
| 311 | /// Delete the event and cascade-remove its attendance and signup rows. | 311 | /// Delete the event and cascade-remove its attendance and signup rows. |
| 312 | /// | 312 | /// |
| 313 | /// Children first, and all of it in one transaction the way | 313 | /// Children first, and all of it in one transaction the way |
| 314 | - /// [`crate::domain::course::Course::delete`] does it: run as two queries, a | 314 | + /// [`crate::db::course::delete`] does it: run as two queries, a |
| 315 | /// registration or a mark that committed in between outlived its event — | 315 | /// registration or a mark that committed in between outlived its event — |
| 316 | /// an orphan no read path can ever reach and no delete can ever reclaim, | 316 | /// an orphan no read path can ever reach and no delete can ever reclaim, |
| 317 | /// since every one of them is keyed on the event that is now gone. | 317 | /// since every one of them is keyed on the event that is now gone. |
src/domain/exam.rsmodified+10 -12
| @@ -692,7 +692,7 @@ pub(crate) async fn published_exam(db: &Database) -> Exam { | |||
| 692 | .to_vec(); | 692 | .to_vec(); |
| 693 | Exam::create( | 693 | Exam::create( |
| 694 | &UserId::generate(), | 694 | &UserId::generate(), |
| 695 | - &crate::domain::course::a_test_course(db).await, | 695 | + &crate::db::course::a_test_course(db).await, |
| 696 | ExamTitle::try_new("midterm").unwrap(), | 696 | ExamTitle::try_new("midterm").unwrap(), |
| 697 | ExamDescription::try_new("").unwrap(), | 697 | ExamDescription::try_new("").unwrap(), |
| 698 | ExamKind::try_new("midterm", &allowed).unwrap(), | 698 | ExamKind::try_new("midterm", &allowed).unwrap(), |
| @@ -723,7 +723,7 @@ mod tests { | |||
| 723 | /// [`Exam::create`] therefore *writes* the course row rather than reading | 723 | /// [`Exam::create`] therefore *writes* the course row rather than reading |
| 724 | /// it ([`cap::touch_and_create`]); the harness and the window it races in | 724 | /// it ([`cap::touch_and_create`]); the harness and the window it races in |
| 725 | /// are documented on | 725 | /// are documented on |
| 726 | - /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. | 726 | + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. |
| 727 | /// Mutation-tested: with the bare `db.create` this shipped with, all four | 727 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 728 | /// rounds orphan. | 728 | /// rounds orphan. |
| 729 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 729 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| @@ -751,11 +751,9 @@ mod tests { | |||
| 751 | .map(|_| ()) | 751 | .map(|_| ()) |
| 752 | }) | 752 | }) |
| 753 | } | 753 | } |
| 754 | - crate::domain::course::assert_no_child_outlives_a_course_delete( | 754 | + crate::db::course::assert_no_child_outlives_a_course_delete("exam_orphan_race", |
| 755 | - "exam_orphan_race", | 755 | + EXAM_TABLE, |
| 756 | - EXAM_TABLE, | 756 | + make,) |
| 757 | - make, | ||
| 758 | - ) | ||
| 759 | .await; | 757 | .await; |
| 760 | } | 758 | } |
| 761 | 759 | ||
| @@ -968,7 +966,7 @@ mod tests { | |||
| 968 | 966 | ||
| 969 | /// GUARD, not a retry measurement — read the last paragraph before | 967 | /// GUARD, not a retry measurement — read the last paragraph before |
| 970 | /// trusting this test with the retry. See | 968 | /// trusting this test with the retry. See |
| 971 | - /// [`crate::domain::course::Course::delete`]'s race test for why the rate is | 969 | + /// [`crate::db::course::delete`]'s race test for why the rate is |
| 972 | /// counted rather than asserted per round. | 970 | /// counted rather than asserted per round. |
| 973 | /// | 971 | /// |
| 974 | /// This site has no `THROW` marker at all: it ends `.check()?`, which | 972 | /// This site has no `THROW` marker at all: it ends `.check()?`, which |
| @@ -995,7 +993,7 @@ mod tests { | |||
| 995 | /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly | 993 | /// attempt — the grades serialize behind `cap`'s claim lock, so they mostly |
| 996 | /// queue rather than collide. So this guards the status codes and the | 994 | /// queue rather than collide. So this guards the status codes and the |
| 997 | /// cascade (marks either survive whole or are swept whole, never a 500). | 995 | /// cascade (marks either survive whole or are swept whole, never a 500). |
| 998 | - /// The retry is measured on [`crate::domain::course::Course::delete`]. | 996 | + /// The retry is measured on [`crate::db::course::delete`]. |
| 999 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 997 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 1000 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | 998 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 1001 | async fn a_delete_racing_a_mark_never_answers_500() { | 999 | async fn a_delete_racing_a_mark_never_answers_500() { |
| @@ -1011,7 +1009,7 @@ mod tests { | |||
| 1011 | // A burst of marks and a delete held back by a sweeping beat: this | 1009 | // A burst of marks and a delete held back by a sweeping beat: this |
| 1012 | // site has no guard to lose to, so a single racer released with it | 1010 | // site has no guard to lose to, so a single racer released with it |
| 1013 | // simply finishes on one side of it. Same recipe as | 1011 | // simply finishes on one side of it. Same recipe as |
| 1014 | - // [`crate::domain::course::Course::delete`]'s race test. | 1012 | + // [`crate::db::course::delete`]'s race test. |
| 1015 | let drop_it = { | 1013 | let drop_it = { |
| 1016 | let (exam, db) = (exam.clone(), db.clone()); | 1014 | let (exam, db) = (exam.clone(), db.clone()); |
| 1017 | // A wide sweep, not the 0-3ms the other three use: each grade | 1015 | // A wide sweep, not the 0-3ms the other three use: each grade |
| @@ -1124,7 +1122,7 @@ mod tests { | |||
| 1124 | ) | 1122 | ) |
| 1125 | .unwrap(); | 1123 | .unwrap(); |
| 1126 | let subject = crate::domain::subject::Subject::create( | 1124 | let subject = crate::domain::subject::Subject::create( |
| 1127 | - &crate::domain::course::a_test_course(db).await, | 1125 | + &crate::db::course::a_test_course(db).await, |
| 1128 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), | 1126 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 1129 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), | 1127 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 1130 | db, | 1128 | db, |
| @@ -1268,7 +1266,7 @@ mod tests { | |||
| 1268 | let exam = published(&db).await; | 1266 | let exam = published(&db).await; |
| 1269 | let id = exam.get_id().clone(); | 1267 | let id = exam.get_id().clone(); |
| 1270 | let subject = Subject::create( | 1268 | let subject = Subject::create( |
| 1271 | - &crate::domain::course::a_test_course(&db).await, | 1269 | + &crate::db::course::a_test_course(&db).await, |
| 1272 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), | 1270 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 1273 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), | 1271 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 1274 | &db, | 1272 | &db, |
src/domain/exam_answer.rsmodified+1 -1
| @@ -508,7 +508,7 @@ mod tests { | |||
| 508 | .to_vec(); | 508 | .to_vec(); |
| 509 | let exam = Exam::create( | 509 | let exam = Exam::create( |
| 510 | &student(), | 510 | &student(), |
| 511 | - &crate::domain::course::a_test_course(&db).await, | 511 | + &crate::db::course::a_test_course(&db).await, |
| 512 | ExamTitle::try_new("quiz").unwrap(), | 512 | ExamTitle::try_new("quiz").unwrap(), |
| 513 | ExamDescription::try_new("").unwrap(), | 513 | ExamDescription::try_new("").unwrap(), |
| 514 | ExamKind::try_new("quiz", &kinds).unwrap(), | 514 | ExamKind::try_new("quiz", &kinds).unwrap(), |
src/domain/exam_attempt.rsmodified+2 -2
| @@ -543,7 +543,7 @@ mod tests { | |||
| 543 | /// rows to exercise the attempt lifecycle without the HTTP layer. | 543 | /// rows to exercise the attempt lifecycle without the HTTP layer. |
| 544 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { | 544 | async fn open_exam_with_question(db: &Database, max_attempts: i64) -> (Exam, ExamQuestion) { |
| 545 | let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); | 545 | let creator = UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"); |
| 546 | - let course = crate::domain::course::a_test_course(db).await; | 546 | + let course = crate::db::course::a_test_course(db).await; |
| 547 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 547 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 548 | let exam = Exam::create( | 548 | let exam = Exam::create( |
| 549 | &creator, | 549 | &creator, |
| @@ -580,7 +580,7 @@ mod tests { | |||
| 580 | // A real subject row, not a minted id: a question claims a reference on | 580 | // A real subject row, not a minted id: a question claims a reference on |
| 581 | // its subject and is refused if that subject does not exist. | 581 | // its subject and is refused if that subject does not exist. |
| 582 | let subject = crate::domain::subject::Subject::create( | 582 | let subject = crate::domain::subject::Subject::create( |
| 583 | - &crate::domain::course::a_test_course(db).await, | 583 | + &crate::db::course::a_test_course(db).await, |
| 584 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), | 584 | crate::domain::subject::SubjectName::try_new("topic").unwrap(), |
| 585 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), | 585 | crate::domain::subject::SubjectDescription::try_new("").unwrap(), |
| 586 | db, | 586 | db, |
src/domain/exam_question.rsmodified+2 -2
| @@ -1094,7 +1094,7 @@ mod tests { | |||
| 1094 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); | 1094 | let kinds = Settings::defaults().get_exam_kinds().to_vec(); |
| 1095 | Exam::create( | 1095 | Exam::create( |
| 1096 | &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), | 1096 | &UserId::from_key("01TESTTEACHERAAAAAAAAAAAAA"), |
| 1097 | - &crate::domain::course::a_test_course(db).await, | 1097 | + &crate::db::course::a_test_course(db).await, |
| 1098 | ExamTitle::try_new("practice").unwrap(), | 1098 | ExamTitle::try_new("practice").unwrap(), |
| 1099 | ExamDescription::try_new("").unwrap(), | 1099 | ExamDescription::try_new("").unwrap(), |
| 1100 | ExamKind::try_new("quiz", &kinds).unwrap(), | 1100 | ExamKind::try_new("quiz", &kinds).unwrap(), |
| @@ -1112,7 +1112,7 @@ mod tests { | |||
| 1112 | 1112 | ||
| 1113 | async fn a_subject(db: &Database) -> Subject { | 1113 | async fn a_subject(db: &Database) -> Subject { |
| 1114 | Subject::create( | 1114 | Subject::create( |
| 1115 | - &crate::domain::course::a_test_course(db).await, | 1115 | + &crate::db::course::a_test_course(db).await, |
| 1116 | SubjectName::try_new("topic").unwrap(), | 1116 | SubjectName::try_new("topic").unwrap(), |
| 1117 | SubjectDescription::try_new("").unwrap(), | 1117 | SubjectDescription::try_new("").unwrap(), |
| 1118 | db, | 1118 | db, |
src/domain/homework.rsmodified+1 -1
| @@ -422,7 +422,7 @@ mod tests { | |||
| 422 | 422 | ||
| 423 | async fn a_subject(name: &str, db: &Database) -> Subject { | 423 | async fn a_subject(name: &str, db: &Database) -> Subject { |
| 424 | Subject::create( | 424 | Subject::create( |
| 425 | - &crate::domain::course::a_test_course(db).await, | 425 | + &crate::db::course::a_test_course(db).await, |
| 426 | SubjectName::try_new(name).unwrap(), | 426 | SubjectName::try_new(name).unwrap(), |
| 427 | SubjectDescription::try_new("").unwrap(), | 427 | SubjectDescription::try_new("").unwrap(), |
| 428 | db, | 428 | db, |
src/domain/homework_file.rsmodified+1 -1
| @@ -330,7 +330,7 @@ mod tests { | |||
| 330 | use crate::domain::homework::{Homework, HomeworkTitle}; | 330 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 331 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | 331 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; |
| 332 | 332 | ||
| 333 | - let course = crate::domain::course::a_test_course(db).await; | 333 | + let course = crate::db::course::a_test_course(db).await; |
| 334 | let subject = Subject::create( | 334 | let subject = Subject::create( |
| 335 | &course, | 335 | &course, |
| 336 | SubjectName::try_new("topic").unwrap(), | 336 | SubjectName::try_new("topic").unwrap(), |
src/domain/homework_result.rsmodified+1 -1
| @@ -375,7 +375,7 @@ mod tests { | |||
| 375 | use crate::domain::homework::{Homework, HomeworkTitle}; | 375 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 376 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | 376 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; |
| 377 | 377 | ||
| 378 | - let course = crate::domain::course::a_test_course(db).await; | 378 | + let course = crate::db::course::a_test_course(db).await; |
| 379 | let subject = Subject::create( | 379 | let subject = Subject::create( |
| 380 | &course, | 380 | &course, |
| 381 | SubjectName::try_new("topic").unwrap(), | 381 | SubjectName::try_new("topic").unwrap(), |
src/domain/homework_submission.rsmodified+1 -1
| @@ -376,7 +376,7 @@ mod tests { | |||
| 376 | /// A real homework row (and the subject it must reference) due at `due_at` — | 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. | 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 { | 378 | async fn a_homework(due_at: Timestamp, db: &Database) -> Homework { |
| 379 | - let course = crate::domain::course::a_test_course(db).await; | 379 | + let course = crate::db::course::a_test_course(db).await; |
| 380 | let subject = Subject::create( | 380 | let subject = Subject::create( |
| 381 | &course, | 381 | &course, |
| 382 | SubjectName::try_new("topic").unwrap(), | 382 | SubjectName::try_new("topic").unwrap(), |
src/domain/rag_output.rsmodified+3 -3
| @@ -185,21 +185,21 @@ impl RagOutput { | |||
| 185 | #[cfg(test)] | 185 | #[cfg(test)] |
| 186 | mod tests { | 186 | mod tests { |
| 187 | use super::*; | 187 | use super::*; |
| 188 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 188 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 189 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 189 | use crate::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; |
| 190 | use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 190 | use crate::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; |
| 191 | use serde_json::json; | 191 | use serde_json::json; |
| 192 | 192 | ||
| 193 | async fn note_of(db: &Database, title: &str) -> CourseNote { | 193 | async fn note_of(db: &Database, title: &str) -> CourseNote { |
| 194 | let creator = crate::domain::user::UserId::generate(); | 194 | let creator = crate::domain::user::UserId::generate(); |
| 195 | - let course = Course::create( | 195 | + let course = crate::db::course::create( |
| 196 | + db, | ||
| 196 | &creator, | 197 | &creator, |
| 197 | CourseTitle::try_new("c").unwrap(), | 198 | CourseTitle::try_new("c").unwrap(), |
| 198 | CourseDescription::try_new("").unwrap(), | 199 | CourseDescription::try_new("").unwrap(), |
| 199 | CourseKind::try_new("course").unwrap(), | 200 | CourseKind::try_new("course").unwrap(), |
| 200 | None, | 201 | None, |
| 201 | None, | 202 | None, |
| 202 | - db, | ||
| 203 | ) | 203 | ) |
| 204 | .await | 204 | .await |
| 205 | .unwrap(); | 205 | .unwrap(); |
src/domain/session_attendance.rsmodified+1 -1
| @@ -385,7 +385,7 @@ mod tests { | |||
| 385 | 385 | ||
| 386 | async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { | 386 | async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { |
| 387 | CourseSession::create( | 387 | CourseSession::create( |
| 388 | - &crate::domain::course::a_test_course(db).await, | 388 | + &crate::db::course::a_test_course(db).await, |
| 389 | teacher, | 389 | teacher, |
| 390 | SessionTopic::try_new("limits").unwrap(), | 390 | SessionTopic::try_new("limits").unwrap(), |
| 391 | Timestamp::from_millis(starts_at), | 391 | Timestamp::from_millis(starts_at), |
src/domain/subject.rsmodified+7 -9
| @@ -263,7 +263,7 @@ mod tests { | |||
| 263 | /// [`Subject::create`] therefore *writes* the course row rather than | 263 | /// [`Subject::create`] therefore *writes* the course row rather than |
| 264 | /// reading it ([`cap::touch_and_create`]); the harness and the window it | 264 | /// reading it ([`cap::touch_and_create`]); the harness and the window it |
| 265 | /// races in are documented on | 265 | /// races in are documented on |
| 266 | - /// [`crate::domain::course::assert_no_child_outlives_a_course_delete`]. | 266 | + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. |
| 267 | /// Mutation-tested: with the bare `db.create` this shipped with, all four | 267 | /// Mutation-tested: with the bare `db.create` this shipped with, all four |
| 268 | /// rounds orphan. | 268 | /// rounds orphan. |
| 269 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 269 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| @@ -281,11 +281,9 @@ mod tests { | |||
| 281 | .map(|_| ()) | 281 | .map(|_| ()) |
| 282 | }) | 282 | }) |
| 283 | } | 283 | } |
| 284 | - crate::domain::course::assert_no_child_outlives_a_course_delete( | 284 | + crate::db::course::assert_no_child_outlives_a_course_delete("subject_orphan_race", |
| 285 | - "subject_orphan_race", | 285 | + SUBJECT_TABLE, |
| 286 | - SUBJECT_TABLE, | 286 | + make,) |
| 287 | - make, | ||
| 288 | - ) | ||
| 289 | .await; | 287 | .await; |
| 290 | } | 288 | } |
| 291 | 289 | ||
| @@ -320,7 +318,7 @@ mod tests { | |||
| 320 | 318 | ||
| 321 | /// GUARD, not a retry measurement — read the last paragraph before | 319 | /// GUARD, not a retry measurement — read the last paragraph before |
| 322 | /// trusting this test with the retry. See | 320 | /// trusting this test with the retry. See |
| 323 | - /// [`crate::domain::course::Course::delete`]'s race test for why the rate | 321 | + /// [`crate::db::course::delete`]'s race test for why the rate |
| 324 | /// is counted rather than asserted per round, and why this needs the real | 322 | /// is counted rather than asserted per round, and why this needs the real |
| 325 | /// server and a multi-threaded runtime. | 323 | /// server and a multi-threaded runtime. |
| 326 | /// | 324 | /// |
| @@ -341,7 +339,7 @@ mod tests { | |||
| 341 | /// racers all failed to open the window (they only move which side wins). | 339 | /// racers all failed to open the window (they only move which side wins). |
| 342 | /// So this is a status-code-and-cascade guard: a raced delete answers 409 or | 340 | /// So this is a status-code-and-cascade guard: a raced delete answers 409 or |
| 343 | /// 404 and never 500, and a landed question survives it. The retry itself is | 341 | /// 404 and never 500, and a landed question survives it. The retry itself is |
| 344 | - /// measured on [`crate::domain::course::Course::delete`], whose cascade is | 342 | + /// measured on [`crate::db::course::delete`], whose cascade is |
| 345 | /// long enough to lose a round (1-2 of 20, red under the same mutation). | 343 | /// long enough to lose a round (1-2 of 20, red under the same mutation). |
| 346 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 344 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 347 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | 345 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| @@ -354,7 +352,7 @@ mod tests { | |||
| 354 | let (mut landed, mut wiped) = (0, 0); | 352 | let (mut landed, mut wiped) = (0, 0); |
| 355 | let (mut last_delete, mut last_question) = (String::new(), String::new()); | 353 | let (mut last_delete, mut last_question) = (String::new(), String::new()); |
| 356 | for round in 0..20 { | 354 | for round in 0..20 { |
| 357 | - let course = crate::domain::course::a_test_course(&db).await; | 355 | + let course = crate::db::course::a_test_course(&db).await; |
| 358 | // A real exam row per round: a question write moves its exam's | 356 | // A real exam row per round: a question write moves its exam's |
| 359 | // counter, so a minted id nothing wrote is a 404 and no round would | 357 | // counter, so a minted id nothing wrote is a 404 and no round would |
| 360 | // reach the subject race this test is about. | 358 | // reach the subject race this test is about. |
src/domain/term.rsmodified+11 -8
| @@ -193,7 +193,7 @@ impl Term { | |||
| 193 | /// nothing here unlinks or cascades. `false` = refused, nothing was written. | 193 | /// nothing here unlinks or cascades. `false` = refused, nothing was written. |
| 194 | /// | 194 | /// |
| 195 | /// The roster of linking courses is the term's own `course_count` | 195 | /// The roster of linking courses is the term's own `course_count` |
| 196 | - /// refcount, claimed by [`crate::domain::course::Course::create`] and | 196 | + /// refcount, claimed by [`crate::db::course::create`] and |
| 197 | /// `update` *before* they write a link, so the check and the delete are one | 197 | /// `update` *before* they write a link, so the check and the delete are one |
| 198 | /// conditional write on one record: a course write racing this either | 198 | /// conditional write on one record: a course write racing this either |
| 199 | /// claims first (and the delete is refused) or finds the row gone (and is | 199 | /// claims first (and the delete is refused) or finds the row gone (and is |
| @@ -363,7 +363,7 @@ mod tests { | |||
| 363 | 363 | ||
| 364 | /// GUARD, not a retry measurement — read the last paragraph before | 364 | /// GUARD, not a retry measurement — read the last paragraph before |
| 365 | /// trusting this test with the retry. See | 365 | /// trusting this test with the retry. See |
| 366 | - /// [`crate::domain::course::Course::delete`]'s race test for why the rate is | 366 | + /// [`crate::db::course::delete`]'s race test for why the rate is |
| 367 | /// counted rather than asserted per round. | 367 | /// counted rather than asserted per round. |
| 368 | /// | 368 | /// |
| 369 | /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no | 369 | /// One conditional `DELETE … RETURN BEFORE` and a bare `.check()?`: no |
| @@ -372,7 +372,7 @@ mod tests { | |||
| 372 | /// through. A store answering "conflict, retry" therefore comes out as a | 372 | /// through. A store answering "conflict, retry" therefore comes out as a |
| 373 | /// 500 instead of the 404 or 409 the request owes. | 373 | /// 500 instead of the 404 or 409 the request owes. |
| 374 | /// | 374 | /// |
| 375 | - /// The racer is [`crate::domain::course::Course::create`] against this | 375 | + /// The racer is [`crate::db::course::create`] against this |
| 376 | /// term: it claims `course_count` on the term row before it writes the | 376 | /// term: it claims `course_count` on the term row before it writes the |
| 377 | /// link, which is the same record and the same column the guard reads. Both | 377 | /// link, which is the same record and the same column the guard reads. Both |
| 378 | /// sides are swept across each other sub-millisecond, exactly as in | 378 | /// sides are swept across each other sub-millisecond, exactly as in |
| @@ -388,11 +388,11 @@ mod tests { | |||
| 388 | /// conflicts in 100 raced rounds, green with the retry loop cut to a single | 388 | /// conflicts in 100 raced rounds, green with the retry loop cut to a single |
| 389 | /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and | 389 | /// attempt. A status-code guard, then: a raced delete answers 409 or 404 and |
| 390 | /// never 500, and a course that got linked survives it. The retry is | 390 | /// never 500, and a course that got linked survives it. The retry is |
| 391 | - /// measured on [`crate::domain::course::Course::delete`]. | 391 | + /// measured on [`crate::db::course::delete`]. |
| 392 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | 392 | #[tokio::test(flavor = "multi_thread", worker_threads = 4)] |
| 393 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | 393 | #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] |
| 394 | async fn a_delete_racing_a_course_create_never_answers_500() { | 394 | async fn a_delete_racing_a_course_create_never_answers_500() { |
| 395 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 395 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 396 | use crate::domain::user::UserId; | 396 | use crate::domain::user::UserId; |
| 397 | let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; | 397 | let (db, _serialized) = crate::database::init_test_server("term_delete_race").await; |
| 398 | let (mut delete_500, mut create_500) = (0, 0); | 398 | let (mut delete_500, mut create_500) = (0, 0); |
| @@ -433,14 +433,14 @@ mod tests { | |||
| 433 | }; | 433 | }; |
| 434 | tokio::spawn(async move { | 434 | tokio::spawn(async move { |
| 435 | tokio::time::sleep(head_start).await; | 435 | tokio::time::sleep(head_start).await; |
| 436 | - Course::create( | 436 | + crate::db::course::create( |
| 437 | + &db, | ||
| 437 | &UserId::from_key("teacher"), | 438 | &UserId::from_key("teacher"), |
| 438 | CourseTitle::try_new("algebra").unwrap(), | 439 | CourseTitle::try_new("algebra").unwrap(), |
| 439 | CourseDescription::try_new("").unwrap(), | 440 | CourseDescription::try_new("").unwrap(), |
| 440 | CourseKind::course(), | 441 | CourseKind::course(), |
| 441 | Some(id), | 442 | Some(id), |
| 442 | None, | 443 | None, |
| 443 | - &db, | ||
| 444 | ) | 444 | ) |
| 445 | .await | 445 | .await |
| 446 | }) | 446 | }) |
| @@ -461,7 +461,10 @@ mod tests { | |||
| 461 | last_create = format!("{make:?}"); | 461 | last_create = format!("{make:?}"); |
| 462 | } | 462 | } |
| 463 | if let Ok(course) = &make | 463 | if let Ok(course) = &make |
| 464 | - && Course::read(course.get_id(), &db).await.unwrap().is_some() | 464 | + && crate::db::course::read(&db, course.get_id()) |
| 465 | + .await | ||
| 466 | + .unwrap() | ||
| 467 | + .is_some() | ||
| 465 | { | 468 | { |
| 466 | landed = true; | 469 | landed = true; |
| 467 | } | 470 | } |
src/service/course.rsadded+181 -0
| @@ -0,0 +1,181 @@ | |||
| 1 | +//! Course workflows: the archived-term gate every course-scoped write pays, | ||
| 2 | +//! the staffing changes a manager makes, and the delete that collects the | ||
| 3 | +//! image/homework/note-file blob keys under the exam and homework locks | ||
| 4 | +//! before the cascade sweeps those rows. The queries live in | ||
| 5 | +//! [`crate::db::course`]. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::course; | ||
| 9 | +use crate::domain::answer_image::AnswerImage; | ||
| 10 | +use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | ||
| 11 | +use crate::domain::course_note_file::CourseNoteFile; | ||
| 12 | +use crate::domain::homework_file::HomeworkFile; | ||
| 13 | +use crate::domain::question_image::QuestionImage; | ||
| 14 | +use crate::domain::term::{self, TermId}; | ||
| 15 | +use crate::domain::role::Role; | ||
| 16 | +use crate::domain::user::{User, UserId}; | ||
| 17 | +use crate::error::{AppError, ValidationError}; | ||
| 18 | + | ||
| 19 | +/// Refuse the write when this course's term is archived — a pre-flight guard, | ||
| 20 | +/// accepted race (see README concurrency model): a term archived after this | ||
| 21 | +/// read still lets the write through. | ||
| 22 | +pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> { | ||
| 23 | + match course.get_term() { | ||
| 24 | + None => Ok(()), | ||
| 25 | + Some(term) => term::Term::require_open(term, db).await, | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +pub async fn create( | ||
| 30 | + db: &Database, | ||
| 31 | + creator: &UserId, | ||
| 32 | + title: CourseTitle, | ||
| 33 | + description: CourseDescription, | ||
| 34 | + kind: CourseKind, | ||
| 35 | + term: Option<TermId>, | ||
| 36 | + capacity: Option<i64>, | ||
| 37 | +) -> Result<Course, AppError> { | ||
| 38 | + course::create(db, creator, title, description, kind, term, capacity).await | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> { | ||
| 42 | + course::read(db, id).await | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> { | ||
| 46 | + course::list_all(db).await | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +pub async fn list_enrolled( | ||
| 50 | + db: &Database, | ||
| 51 | + user: &UserId, | ||
| 52 | + limit: Option<i64>, | ||
| 53 | + offset: i64, | ||
| 54 | +) -> Result<(Vec<Course>, i64), AppError> { | ||
| 55 | + course::list_enrolled(db, user, limit, offset).await | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> { | ||
| 59 | + course::list_for_teacher(db, user).await | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>, AppError> { | ||
| 63 | + course::list_by_ids(db, ids).await | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// Only what the request carried is written: an omitted field (`None`) is | ||
| 67 | +/// not stored at all, so a concurrent PATCH of that field survives. | ||
| 68 | +pub async fn update( | ||
| 69 | + db: &Database, | ||
| 70 | + course: Course, | ||
| 71 | + title: Option<CourseTitle>, | ||
| 72 | + description: Option<CourseDescription>, | ||
| 73 | + kind: Option<CourseKind>, | ||
| 74 | + term: Option<Option<TermId>>, | ||
| 75 | + capacity: Option<Option<i64>>, | ||
| 76 | +) -> Result<Course, AppError> { | ||
| 77 | + course::update(db, course, title, description, kind, term, capacity).await | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/// Assign `target` to run `course`, or return the course untouched if they | ||
| 81 | +/// already run it — assignment is idempotent, like enrollment. | ||
| 82 | +/// | ||
| 83 | +/// The assignee must already hold the `teacher` role or higher: assignment | ||
| 84 | +/// hands out course-management rights, which every gate behind it re-checks | ||
| 85 | +/// against the `teacher` bar — assigning anyone below it would write a row | ||
| 86 | +/// that can never be used. | ||
| 87 | +pub async fn assign_teacher( | ||
| 88 | + db: &Database, | ||
| 89 | + course: &Course, | ||
| 90 | + target: &UserId, | ||
| 91 | +) -> Result<Course, AppError> { | ||
| 92 | + require_open(db, course).await?; | ||
| 93 | + let Some(target_user) = User::read(target, db).await? else { | ||
| 94 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 95 | + field: "user_id", | ||
| 96 | + reason: "target user does not exist", | ||
| 97 | + })); | ||
| 98 | + }; | ||
| 99 | + if !target_user.get_role().at_least(Role::Teacher) { | ||
| 100 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 101 | + field: "user_id", | ||
| 102 | + reason: "assigned teacher must hold the teacher role or higher", | ||
| 103 | + })); | ||
| 104 | + } | ||
| 105 | + course::assign_teacher(db, course.clone(), target).await | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +/// Drop `target` from this course's assigned teachers. `None` when they | ||
| 109 | +/// weren't assigned, so the web layer can answer 404 instead of pretending | ||
| 110 | +/// it removed someone. | ||
| 111 | +pub async fn unassign_teacher( | ||
| 112 | + db: &Database, | ||
| 113 | + course: &Course, | ||
| 114 | + target: &UserId, | ||
| 115 | +) -> Result<Option<Course>, AppError> { | ||
| 116 | + require_open(db, course).await?; | ||
| 117 | + course::unassign_teacher(db, course.clone(), target).await | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/// Strip `user` from every course they were assigned to — the sweep for a | ||
| 121 | +/// user demoted below `teacher`, who may no longer run anything. | ||
| 122 | +pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 123 | + course::unassign_everywhere(db, user).await | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +/// What [`delete`] did: whether the course went, and the blob keys of the | ||
| 127 | +/// rows its cascade removed — exactly whose files the web layer may unlink. | ||
| 128 | +#[derive(Debug)] | ||
| 129 | +pub struct DeleteOutcome { | ||
| 130 | + /// `false` = refused, nothing was written: someone is still enrolled. | ||
| 131 | + pub deleted: bool, | ||
| 132 | + pub image_files: Vec<String>, | ||
| 133 | + pub answer_image_files: Vec<String>, | ||
| 134 | + pub homework_files: Vec<String>, | ||
| 135 | + pub course_note_files: Vec<String>, | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +/// Delete the course: collect the image/homework/note-file blob keys, then | ||
| 139 | +/// run the cascading delete. | ||
| 140 | +/// | ||
| 141 | +/// Writer lease of [`crate::web::exams::EXAM_LOCK`] (moving to | ||
| 142 | +/// `crate::service::exam_attempt` with the exam lane's split), for | ||
| 143 | +/// `delete_exam`'s reason: this cascade sweeps the course's exams *and their | ||
| 144 | +/// attempts*, and an attempt is the one exam child whose write cannot | ||
| 145 | +/// collide with the sweep (its claim lands on the student's row, never the | ||
| 146 | +/// exam's). Narrower here — the delete is refused while anyone is enrolled, | ||
| 147 | +/// so a start would have to pass its enrollment gate and then have that | ||
| 148 | +/// enrollment removed under it — but the hole is the same one and so is the | ||
| 149 | +/// lease. | ||
| 150 | +/// | ||
| 151 | +/// And the homework half of the same cascade, for | ||
| 152 | +/// [`crate::web::homework::delete_homework`]'s reason: it sweeps the | ||
| 153 | +/// course's homework with its submissions, files and results, and grading | ||
| 154 | +/// ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a | ||
| 155 | +/// result row against a homework it only *read*, which a delete committing | ||
| 156 | +/// alongside is invisible to. Without this lease the grade lands behind the | ||
| 157 | +/// sweep: an orphan `homework_result` under a vanished homework, plus a | ||
| 158 | +/// `marks_given_total` on the grader no ungrade can reach. Lock order here | ||
| 159 | +/// is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. | ||
| 160 | +/// | ||
| 161 | +/// The keys are read before the delete because it takes their rows with it; | ||
| 162 | +/// a refused delete just drops them unused. Unlinking the blobs stays the | ||
| 163 | +/// web layer's job — a crash in between strands at worst an unreachable | ||
| 164 | +/// blob. | ||
| 165 | +pub async fn delete(db: &Database, course: &Course) -> Result<DeleteOutcome, AppError> { | ||
| 166 | + require_open(db, course).await?; | ||
| 167 | + let _guard = crate::web::exams::EXAM_LOCK.write().await; | ||
| 168 | + let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; | ||
| 169 | + let image_files = QuestionImage::file_keys_for_course(course.get_id(), db).await?; | ||
| 170 | + let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), db).await?; | ||
| 171 | + let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), db).await?; | ||
| 172 | + let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), db).await?; | ||
| 173 | + let deleted = course::delete(db, course.clone()).await?; | ||
| 174 | + Ok(DeleteOutcome { | ||
| 175 | + deleted, | ||
| 176 | + image_files, | ||
| 177 | + answer_image_files, | ||
| 178 | + homework_files, | ||
| 179 | + course_note_files, | ||
| 180 | + }) | ||
| 181 | +} | ||
src/service/mod.rsmodified+1 -0
| @@ -2,6 +2,7 @@ | |||
| 2 | //! SurrealQL text. | 2 | //! SurrealQL text. |
| 3 | 3 | ||
| 4 | pub mod appointment; | 4 | pub mod appointment; |
| 5 | +pub mod course; | ||
| 5 | pub mod note; | 6 | pub mod note; |
| 6 | pub mod payment_ledger; | 7 | pub mod payment_ledger; |
| 7 | pub mod session; | 8 | pub mod session; |
src/web/attendance.rsmodified+1 -1
| @@ -117,7 +117,7 @@ async fn build_report( | |||
| 117 | by_course.entry(key).or_default().push(row); | 117 | by_course.entry(key).or_default().push(row); |
| 118 | } | 118 | } |
| 119 | 119 | ||
| 120 | - let courses = Course::list_by_ids(&course_ids, db).await?; | 120 | + let courses = crate::service::course::list_by_ids(db, &course_ids).await?; |
| 121 | let course_by_key: HashMap<&str, &Course> = | 121 | let course_by_key: HashMap<&str, &Course> = |
| 122 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); | 122 | courses.iter().map(|c| (c.get_id().key(), c)).collect(); |
| 123 | let people = person_map(courses.iter().flat_map(course_people), db).await?; | 123 | let people = person_map(courses.iter().flat_map(course_people), db).await?; |
src/web/boards.rsmodified+2 -2
| @@ -34,7 +34,7 @@ use crate::domain::board::{BOARD_ROSTER_LOCK, Board, BoardId, BoardTitle}; | |||
| 34 | use crate::domain::board_stroke::BoardStroke; | 34 | use crate::domain::board_stroke::BoardStroke; |
| 35 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; | 35 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 36 | use crate::domain::class_member::ClassMember; | 36 | use crate::domain::class_member::ClassMember; |
| 37 | -use crate::domain::course::{Course, CourseId}; | 37 | +use crate::domain::course::CourseId; |
| 38 | use crate::domain::enrollment::Enrollment; | 38 | use crate::domain::enrollment::Enrollment; |
| 39 | use crate::domain::event::{Event, EventId}; | 39 | use crate::domain::event::{Event, EventId}; |
| 40 | use crate::domain::role::Role; | 40 | use crate::domain::role::Role; |
| @@ -742,7 +742,7 @@ impl InviteSource { | |||
| 742 | .collect()) | 742 | .collect()) |
| 743 | } | 743 | } |
| 744 | InviteSource::Course { course } => { | 744 | InviteSource::Course { course } => { |
| 745 | - let course = Course::read(&CourseId::from_key(&course), db) | 745 | + let course = crate::service::course::read(db, &CourseId::from_key(&course)) |
| 746 | .await? | 746 | .await? |
| 747 | .ok_or(AppError::Validation(ValidationError::Invalid { | 747 | .ok_or(AppError::Validation(ValidationError::Invalid { |
| 748 | field: "course", | 748 | field: "course", |
src/web/classes.rsmodified+10 -8
| @@ -21,7 +21,7 @@ use crate::domain::class_blueprint::{ClassBlueprint, ClassBlueprintId, Pumped, S | |||
| 21 | use crate::domain::class_course::ClassCourse; | 21 | use crate::domain::class_course::ClassCourse; |
| 22 | use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; | 22 | use crate::domain::class_group::{ClassGrade, ClassGroup, ClassGroupId, ClassName}; |
| 23 | use crate::domain::class_member::ClassMember; | 23 | use crate::domain::class_member::ClassMember; |
| 24 | -use crate::domain::course::{Course, CourseId}; | 24 | +use crate::domain::course::CourseId; |
| 25 | use crate::domain::role::Role; | 25 | use crate::domain::role::Role; |
| 26 | use crate::domain::user::{User, UserId}; | 26 | use crate::domain::user::{User, UserId}; |
| 27 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 27 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -872,7 +872,9 @@ async fn attach_course( | |||
| 872 | Json(req): Json<AttachCourse>, | 872 | Json(req): Json<AttachCourse>, |
| 873 | ) -> Result<(StatusCode, Json<ClassCourseResponse>), AppError> { | 873 | ) -> Result<(StatusCode, Json<ClassCourseResponse>), AppError> { |
| 874 | let class = class_or_404(&id, &st.db).await?; | 874 | let class = class_or_404(&id, &st.db).await?; |
| 875 | - let Some(course) = Course::read(&CourseId::from_key(&req.course_id), &st.db).await? else { | 875 | + let Some(course) = crate::service::course::read(&st.db, &CourseId::from_key(&req.course_id)) |
| 876 | + .await? | ||
| 877 | + else { | ||
| 876 | return Err(AppError::Validation(ValidationError::Invalid { | 878 | return Err(AppError::Validation(ValidationError::Invalid { |
| 877 | field: "course_id", | 879 | field: "course_id", |
| 878 | reason: "course does not exist", | 880 | reason: "course does not exist", |
| @@ -885,7 +887,7 @@ async fn attach_course( | |||
| 885 | } | 887 | } |
| 886 | // Both ends: neither a class nor a course on a past year takes a new link. | 888 | // Both ends: neither a class nor a course on a past year takes a new link. |
| 887 | class.require_open(&st.db).await?; | 889 | class.require_open(&st.db).await?; |
| 888 | - course.require_open(&st.db).await?; | 890 | + crate::service::course::require_open(&st.db, &course).await?; |
| 889 | 891 | ||
| 890 | let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; | 892 | let link = ClassCourse::attach(class.get_id(), course.get_id(), user.get_id(), &st.db).await?; |
| 891 | let people = PersonRef::map_of(&[&user]); | 893 | let people = PersonRef::map_of(&[&user]); |
| @@ -966,7 +968,7 @@ async fn detach_course( | |||
| 966 | // route answered 404 forever — which also left the class undeletable, its | 968 | // route answered 404 forever — which also left the class undeletable, its |
| 967 | // attachment counter counting a row nothing could sweep. There is no roster | 969 | // attachment counter counting a row nothing could sweep. There is no roster |
| 968 | // left to protect, and the caller is already teacher+. | 970 | // left to protect, and the caller is already teacher+. |
| 969 | - let row = Course::read(&course, &st.db).await?; | 971 | + let row = crate::service::course::read(&st.db, &course).await?; |
| 970 | if let Some(row) = row.as_ref() | 972 | if let Some(row) = row.as_ref() |
| 971 | && !can_manage_course(row, &user) | 973 | && !can_manage_course(row, &user) |
| 972 | { | 974 | { |
| @@ -978,7 +980,7 @@ async fn detach_course( | |||
| 978 | // has no term to read, and sweeping it is the whole point of the route. | 980 | // has no term to read, and sweeping it is the whole point of the route. |
| 979 | class.require_open(&st.db).await?; | 981 | class.require_open(&st.db).await?; |
| 980 | if let Some(row) = row.as_ref() { | 982 | if let Some(row) = row.as_ref() { |
| 981 | - row.require_open(&st.db).await?; | 983 | + crate::service::course::require_open(&st.db, row).await?; |
| 982 | } | 984 | } |
| 983 | ClassCourse::detach(class.get_id(), &course, &st.db).await?; | 985 | ClassCourse::detach(class.get_id(), &course, &st.db).await?; |
| 984 | Ok(StatusCode::NO_CONTENT) | 986 | Ok(StatusCode::NO_CONTENT) |
| @@ -1150,7 +1152,7 @@ async fn resolve_courses(ids: &[String], db: &Database) -> Result<Vec<CourseId>, | |||
| 1150 | let mut courses = Vec::with_capacity(ids.len()); | 1152 | let mut courses = Vec::with_capacity(ids.len()); |
| 1151 | for id in ids { | 1153 | for id in ids { |
| 1152 | let course = CourseId::from_key(id); | 1154 | let course = CourseId::from_key(id); |
| 1153 | - if Course::read(&course, db).await?.is_none() { | 1155 | + if crate::service::course::read(db, &course).await?.is_none() { |
| 1154 | return Err(AppError::Validation(ValidationError::Invalid { | 1156 | return Err(AppError::Validation(ValidationError::Invalid { |
| 1155 | field: "course_ids", | 1157 | field: "course_ids", |
| 1156 | reason: "one of these courses does not exist", | 1158 | reason: "one of these courses does not exist", |
| @@ -1454,8 +1456,8 @@ async fn apply_blueprint( | |||
| 1454 | // already gone is the pump's own `skipped` business, not a term refusal. | 1456 | // already gone is the pump's own `skipped` business, not a term refusal. |
| 1455 | class.require_open(&st.db).await?; | 1457 | class.require_open(&st.db).await?; |
| 1456 | for id in blueprint.get_courses() { | 1458 | for id in blueprint.get_courses() { |
| 1457 | - if let Some(course) = Course::read(id, &st.db).await? { | 1459 | + if let Some(course) = crate::service::course::read(&st.db, id).await? { |
| 1458 | - course.require_open(&st.db).await?; | 1460 | + crate::service::course::require_open(&st.db, &course).await?; |
| 1459 | } | 1461 | } |
| 1460 | } | 1462 | } |
| 1461 | let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; | 1463 | let skipped = blueprint.apply_to(&class, user.get_id(), &st.db).await?; |
src/web/course_notes.rsmodified+9 -9
| @@ -60,7 +60,7 @@ async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course | |||
| 60 | let note = CourseNote::read(&CourseNoteId::from_key(id), db) | 60 | let note = CourseNote::read(&CourseNoteId::from_key(id), db) |
| 61 | .await? | 61 | .await? |
| 62 | .ok_or(AppError::NotFound)?; | 62 | .ok_or(AppError::NotFound)?; |
| 63 | - let course = Course::read(note.get_course(), db) | 63 | + let course = crate::service::course::read(db, note.get_course()) |
| 64 | .await? | 64 | .await? |
| 65 | .ok_or(AppError::NotFound)?; | 65 | .ok_or(AppError::NotFound)?; |
| 66 | Ok((note, course)) | 66 | Ok((note, course)) |
| @@ -130,7 +130,7 @@ async fn create( | |||
| 130 | RequireTeacher(user): RequireTeacher, | 130 | RequireTeacher(user): RequireTeacher, |
| 131 | Json(req): Json<CreateCourseNote>, | 131 | Json(req): Json<CreateCourseNote>, |
| 132 | ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> { | 132 | ) -> Result<(StatusCode, Json<CourseNoteResponse>), AppError> { |
| 133 | - let course = Course::read(&CourseId::from_key(&req.course), &st.db) | 133 | + let course = crate::service::course::read(&st.db, &CourseId::from_key(&req.course)) |
| 134 | .await? | 134 | .await? |
| 135 | .ok_or(AppError::NotFound)?; | 135 | .ok_or(AppError::NotFound)?; |
| 136 | if !can_manage_course(&course, &user) { | 136 | if !can_manage_course(&course, &user) { |
| @@ -138,7 +138,7 @@ async fn create( | |||
| 138 | "only the course creator, an assigned teacher, or a manager/admin can add a course note", | 138 | "only the course creator, an assigned teacher, or a manager/admin can add a course note", |
| 139 | )); | 139 | )); |
| 140 | } | 140 | } |
| 141 | - course.require_open(&st.db).await?; | 141 | + crate::service::course::require_open(&st.db, &course).await?; |
| 142 | let title = CourseNoteTitle::try_new(&req.title)?; | 142 | let title = CourseNoteTitle::try_new(&req.title)?; |
| 143 | let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; | 143 | let content = CourseNoteContent::try_new(&req.content.unwrap_or_default())?; |
| 144 | let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; | 144 | let note = CourseNote::create(course.get_id(), user.get_id(), title, content, &st.db).await?; |
| @@ -179,7 +179,7 @@ async fn list( | |||
| 179 | Query(filter): Query<CourseFilter>, | 179 | Query(filter): Query<CourseFilter>, |
| 180 | Query(page): Query<PageParams>, | 180 | Query(page): Query<PageParams>, |
| 181 | ) -> Result<Json<Page<CourseNoteResponse>>, AppError> { | 181 | ) -> Result<Json<Page<CourseNoteResponse>>, AppError> { |
| 182 | - let course = Course::read(&CourseId::from_key(&filter.course), &st.db) | 182 | + let course = crate::service::course::read(&st.db, &CourseId::from_key(&filter.course)) |
| 183 | .await? | 183 | .await? |
| 184 | .ok_or(AppError::NotFound)?; | 184 | .ok_or(AppError::NotFound)?; |
| 185 | if !can_view_course(&course, &user, &st.db).await? { | 185 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -254,7 +254,7 @@ async fn update( | |||
| 254 | "only the course creator, an assigned teacher, or a manager/admin can edit this course note", | 254 | "only the course creator, an assigned teacher, or a manager/admin can edit this course note", |
| 255 | )); | 255 | )); |
| 256 | } | 256 | } |
| 257 | - course.require_open(&st.db).await?; | 257 | + crate::service::course::require_open(&st.db, &course).await?; |
| 258 | 258 | ||
| 259 | let title = req | 259 | let title = req |
| 260 | .title | 260 | .title |
| @@ -300,7 +300,7 @@ async fn delete_one( | |||
| 300 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note", | 300 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note", |
| 301 | )); | 301 | )); |
| 302 | } | 302 | } |
| 303 | - course.require_open(&st.db).await?; | 303 | + crate::service::course::require_open(&st.db, &course).await?; |
| 304 | // Derived rows first, outside the note's own cascade transaction: they are | 304 | // Derived rows first, outside the note's own cascade transaction: they are |
| 305 | // disposable, so failing here leaves the note intact and the 500 truthful, | 305 | // disposable, so failing here leaves the note intact and the 500 truthful, |
| 306 | // whereas dropping them after the note would strand every blob on an error | 306 | // whereas dropping them after the note would strand every blob on an error |
| @@ -378,7 +378,7 @@ async fn upload_file( | |||
| 378 | "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", | 378 | "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note", |
| 379 | )); | 379 | )); |
| 380 | } | 380 | } |
| 381 | - course.require_open(&st.db).await?; | 381 | + crate::service::course::require_open(&st.db, &course).await?; |
| 382 | // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and | 382 | // The 10-file cap is enforced inside `CourseNoteFile::insert` (count and |
| 383 | // create under one lock) — checking it here too would just race. | 383 | // create under one lock) — checking it here too would just race. |
| 384 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); | 384 | let limit = service::settings::load(&st.db).await?.get_max_file_bytes(); |
| @@ -533,7 +533,7 @@ async fn delete_file( | |||
| 533 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", | 533 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files", |
| 534 | )); | 534 | )); |
| 535 | } | 535 | } |
| 536 | - course.require_open(&st.db).await?; | 536 | + crate::service::course::require_open(&st.db, &course).await?; |
| 537 | let file = | 537 | let file = |
| 538 | CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) | 538 | CourseNoteFile::read_for(&CourseNoteFileId::from_key(&file_id), note.get_id(), &st.db) |
| 539 | .await? | 539 | .await? |
| @@ -648,7 +648,7 @@ async fn delete_rag( | |||
| 648 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs", | 648 | "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs", |
| 649 | )); | 649 | )); |
| 650 | } | 650 | } |
| 651 | - course.require_open(&st.db).await?; | 651 | + crate::service::course::require_open(&st.db, &course).await?; |
| 652 | // Scoped to the note in the path, like `CourseNoteFile::read_for`: an | 652 | // Scoped to the note in the path, like `CourseNoteFile::read_for`: an |
| 653 | // output of another note is a 404 here, never a cross-note delete. | 653 | // output of another note is a 404 here, never a cross-note delete. |
| 654 | let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) | 654 | let output = RagOutput::read(&RagOutputId::from_key(&output_id), &st.db) |
src/web/courses.rsmodified+54 -99
| @@ -10,9 +10,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 10 | use utoipa_axum::routes; | 10 | use utoipa_axum::routes; |
| 11 | 11 | ||
| 12 | use crate::database::Database; | 12 | use crate::database::Database; |
| 13 | -use crate::domain::answer_image::AnswerImage; | ||
| 14 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | 13 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 15 | -use crate::domain::course_note_file::CourseNoteFile; | ||
| 16 | use crate::domain::course_session::{CourseSession, SessionTopic}; | 14 | use crate::domain::course_session::{CourseSession, SessionTopic}; |
| 17 | use crate::domain::enrollment::Enrollment; | 15 | use crate::domain::enrollment::Enrollment; |
| 18 | use crate::domain::exam::{ | 16 | use crate::domain::exam::{ |
| @@ -20,8 +18,6 @@ use crate::domain::exam::{ | |||
| 20 | ExamTitle, | 18 | ExamTitle, |
| 21 | }; | 19 | }; |
| 22 | use crate::domain::homework::{Homework, HomeworkTitle}; | 20 | use crate::domain::homework::{Homework, HomeworkTitle}; |
| 23 | -use crate::domain::homework_file::HomeworkFile; | ||
| 24 | -use crate::domain::question_image::QuestionImage; | ||
| 25 | use crate::domain::role::Role; | 21 | use crate::domain::role::Role; |
| 26 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; | 22 | use crate::domain::subject::{Subject, SubjectDescription, SubjectName}; |
| 27 | use crate::domain::timestamp::Timestamp; | 23 | use crate::domain::timestamp::Timestamp; |
| @@ -262,14 +258,14 @@ pub(crate) async fn can_view_course( | |||
| 262 | /// visible only the way it is to any other student: by enrollment. | 258 | /// visible only the way it is to any other student: by enrollment. |
| 263 | pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> { | 259 | pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Course>, AppError> { |
| 264 | if user.get_role().at_least(Role::Manager) { | 260 | if user.get_role().at_least(Role::Manager) { |
| 265 | - return Course::list_all(db).await; | 261 | + return service::course::list_all(db).await; |
| 266 | } | 262 | } |
| 267 | let mut courses = if user.get_role().at_least(Role::Teacher) { | 263 | let mut courses = if user.get_role().at_least(Role::Teacher) { |
| 268 | - Course::list_for_teacher(user.get_id(), db).await? | 264 | + service::course::list_for_teacher(db, user.get_id()).await? |
| 269 | } else { | 265 | } else { |
| 270 | Vec::new() | 266 | Vec::new() |
| 271 | }; | 267 | }; |
| 272 | - for course in Course::list_enrolled(user.get_id(), None, 0, db).await?.0 { | 268 | + for course in service::course::list_enrolled(db, user.get_id(), None, 0).await?.0 { |
| 273 | if !courses | 269 | if !courses |
| 274 | .iter() | 270 | .iter() |
| 275 | .any(|known| known.get_id() == course.get_id()) | 271 | .any(|known| known.get_id() == course.get_id()) |
| @@ -326,19 +322,19 @@ async fn create_course( | |||
| 326 | Some(ref kind) => CourseKind::try_new(kind)?, | 322 | Some(ref kind) => CourseKind::try_new(kind)?, |
| 327 | None => CourseKind::course(), | 323 | None => CourseKind::course(), |
| 328 | }; | 324 | }; |
| 329 | - // Pre-flight only: [`Course::create`] claims a reference on the term before | 325 | + // Pre-flight only: the create itself claims a reference on the term before |
| 330 | // it writes the link, and a term deleted in between fails that claim with | 326 | // it writes the link, and a term deleted in between fails that claim with |
| 331 | // this very error — so an unknown id reads the same whichever side wins. | 327 | // this very error — so an unknown id reads the same whichever side wins. |
| 332 | let term = resolve_term(req.term_id.as_deref(), &st.db).await?; | 328 | let term = resolve_term(req.term_id.as_deref(), &st.db).await?; |
| 333 | check_capacity(req.capacity)?; | 329 | check_capacity(req.capacity)?; |
| 334 | - let course = Course::create( | 330 | + let course = service::course::create( |
| 331 | + &st.db, | ||
| 335 | user.get_id(), | 332 | user.get_id(), |
| 336 | title, | 333 | title, |
| 337 | description, | 334 | description, |
| 338 | kind, | 335 | kind, |
| 339 | term, | 336 | term, |
| 340 | req.capacity, | 337 | req.capacity, |
| 341 | - &st.db, | ||
| 342 | ) | 338 | ) |
| 343 | .await?; | 339 | .await?; |
| 344 | // The creator is the caller — already loaded, no extra lookup. | 340 | // The creator is the caller — already loaded, no extra lookup. |
| @@ -405,7 +401,7 @@ async fn my_courses( | |||
| 405 | Query(page): Query<PageParams>, | 401 | Query(page): Query<PageParams>, |
| 406 | ) -> Result<Json<Page<CourseResponse>>, AppError> { | 402 | ) -> Result<Json<Page<CourseResponse>>, AppError> { |
| 407 | let (limit, offset) = page.resolve()?; | 403 | let (limit, offset) = page.resolve()?; |
| 408 | - let (courses, total) = Course::list_enrolled(user.get_id(), limit, offset, &st.db).await?; | 404 | + let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; |
| 409 | let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; | 405 | let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; |
| 410 | let items = courses | 406 | let items = courses |
| 411 | .iter() | 407 | .iter() |
| @@ -436,7 +432,7 @@ async fn get_course( | |||
| 436 | CurrentUser(user): CurrentUser, | 432 | CurrentUser(user): CurrentUser, |
| 437 | Path(id): Path<String>, | 433 | Path(id): Path<String>, |
| 438 | ) -> Result<Json<CourseResponse>, AppError> { | 434 | ) -> Result<Json<CourseResponse>, AppError> { |
| 439 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 435 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 440 | .await? | 436 | .await? |
| 441 | .ok_or(AppError::NotFound)?; | 437 | .ok_or(AppError::NotFound)?; |
| 442 | if !can_view_course(&course, &user, &st.db).await? { | 438 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -474,7 +470,7 @@ async fn update_course( | |||
| 474 | Path(id): Path<String>, | 470 | Path(id): Path<String>, |
| 475 | Json(req): Json<UpdateCourse>, | 471 | Json(req): Json<UpdateCourse>, |
| 476 | ) -> Result<Json<CourseResponse>, AppError> { | 472 | ) -> Result<Json<CourseResponse>, AppError> { |
| 477 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 473 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 478 | .await? | 474 | .await? |
| 479 | .ok_or(AppError::NotFound)?; | 475 | .ok_or(AppError::NotFound)?; |
| 480 | if !can_manage_course(&course, &user) { | 476 | if !can_manage_course(&course, &user) { |
| @@ -482,7 +478,7 @@ async fn update_course( | |||
| 482 | "only the course creator, an assigned teacher, or a manager/admin can edit this course", | 478 | "only the course creator, an assigned teacher, or a manager/admin can edit this course", |
| 483 | )); | 479 | )); |
| 484 | } | 480 | } |
| 485 | - course.require_open(&st.db).await?; | 481 | + service::course::require_open(&st.db, &course).await?; |
| 486 | 482 | ||
| 487 | // Only what the request actually carried is validated and written — an | 483 | // Only what the request actually carried is validated and written — an |
| 488 | // omitted field stays `None` so the save never re-sends this snapshot's | 484 | // omitted field stays `None` so the save never re-sends this snapshot's |
| @@ -505,9 +501,8 @@ async fn update_course( | |||
| 505 | check_capacity(req.capacity.flatten())?; | 501 | check_capacity(req.capacity.flatten())?; |
| 506 | let capacity = req.capacity; | 502 | let capacity = req.capacity; |
| 507 | 503 | ||
| 508 | - let updated = course | 504 | + let updated = |
| 509 | - .update(title, description, kind, term, capacity, &st.db) | 505 | + service::course::update(&st.db, course, title, description, kind, term, capacity).await?; |
| 510 | - .await?; | ||
| 511 | let people = person_map(course_people(&updated), &st.db).await?; | 506 | let people = person_map(course_people(&updated), &st.db).await?; |
| 512 | Ok(Json(CourseResponse::new(&updated, &people))) | 507 | Ok(Json(CourseResponse::new(&updated, &people))) |
| 513 | } | 508 | } |
| @@ -542,7 +537,7 @@ async fn delete_course( | |||
| 542 | RequireTeacher(user): RequireTeacher, | 537 | RequireTeacher(user): RequireTeacher, |
| 543 | Path(id): Path<String>, | 538 | Path(id): Path<String>, |
| 544 | ) -> Result<StatusCode, AppError> { | 539 | ) -> Result<StatusCode, AppError> { |
| 545 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 540 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 546 | .await? | 541 | .await? |
| 547 | .ok_or(AppError::NotFound)?; | 542 | .ok_or(AppError::NotFound)?; |
| 548 | if !owns_course(&course, &user) { | 543 | if !owns_course(&course, &user) { |
| @@ -550,43 +545,21 @@ async fn delete_course( | |||
| 550 | "only the course creator or a manager/admin can delete this course", | 545 | "only the course creator or a manager/admin can delete this course", |
| 551 | )); | 546 | )); |
| 552 | } | 547 | } |
| 553 | - course.require_open(&st.db).await?; | 548 | + // The workflow — archived-term gate, EXAM_LOCK and HOMEWORK_LOCK writer |
| 554 | - // Writer lease of [`EXAM_LOCK`], for `delete_exam`'s reason: this cascade | 549 | + // leases, blob-key collection, cascade — is [`service::course::delete`]'s. |
| 555 | - // sweeps the course's exams *and their attempts*, and an attempt is the one | 550 | + // Blob unlinking stays here because only the web layer knows `files_path`. |
| 556 | - // exam child whose write cannot collide with the sweep (its claim lands on | 551 | + let outcome = service::course::delete(&st.db, &course).await?; |
| 557 | - // the student's row, never the exam's). Narrower here — the delete is | 552 | + if !outcome.deleted { |
| 558 | - // refused while anyone is enrolled, so a start would have to pass its | ||
| 559 | - // enrollment gate and then have that enrollment removed under it — but the | ||
| 560 | - // hole is the same one and so is the lease. | ||
| 561 | - let _guard = crate::web::exams::EXAM_LOCK.write().await; | ||
| 562 | - // And the homework half of the same cascade, for | ||
| 563 | - // [`crate::web::homework::delete_homework`]'s reason: it sweeps the | ||
| 564 | - // course's homework with its submissions, files and results, and grading | ||
| 565 | - // ([`crate::domain::homework_result::HomeworkResult::grade`]) writes a | ||
| 566 | - // result row against a homework it only *read*, which a delete committing | ||
| 567 | - // alongside is invisible to. Without this lease the grade lands behind the | ||
| 568 | - // sweep: an orphan `homework_result` under a vanished homework, plus a | ||
| 569 | - // `marks_given_total` on the grader no ungrade can reach. Lock order here | ||
| 570 | - // is EXAM_LOCK then HOMEWORK_LOCK, the only path that takes both. | ||
| 571 | - let _homework_guard = crate::web::homework::HOMEWORK_LOCK.write().await; | ||
| 572 | - // Rows go first (the delete cascades them), blobs after — a crash in | ||
| 573 | - // between strands at worst an unreachable blob. The keys are read before | ||
| 574 | - // the delete because it takes their rows with it; a refused delete just | ||
| 575 | - // drops them unused. | ||
| 576 | - let image_files = QuestionImage::file_keys_for_course(course.get_id(), &st.db).await?; | ||
| 577 | - let answer_image_files = AnswerImage::file_keys_for_course(course.get_id(), &st.db).await?; | ||
| 578 | - let homework_files = HomeworkFile::file_keys_for_course(course.get_id(), &st.db).await?; | ||
| 579 | - let course_note_files = CourseNoteFile::file_keys_for_course(course.get_id(), &st.db).await?; | ||
| 580 | - if !course.delete(&st.db).await? { | ||
| 581 | return Err(AppError::Conflict( | 553 | return Err(AppError::Conflict( |
| 582 | "students are still enrolled in this course — remove them first", | 554 | "students are still enrolled in this course — remove them first", |
| 583 | )); | 555 | )); |
| 584 | } | 556 | } |
| 585 | - for file in image_files | 557 | + for file in outcome |
| 558 | + .image_files | ||
| 586 | .iter() | 559 | .iter() |
| 587 | - .chain(&answer_image_files) | 560 | + .chain(&outcome.answer_image_files) |
| 588 | - .chain(&homework_files) | 561 | + .chain(&outcome.homework_files) |
| 589 | - .chain(&course_note_files) | 562 | + .chain(&outcome.course_note_files) |
| 590 | { | 563 | { |
| 591 | remove_blob(&st.files_path, file).await; | 564 | remove_blob(&st.files_path, file).await; |
| 592 | } | 565 | } |
| @@ -624,29 +597,11 @@ async fn assign_teacher( | |||
| 624 | Path(id): Path<String>, | 597 | Path(id): Path<String>, |
| 625 | Json(req): Json<AssignTeacher>, | 598 | Json(req): Json<AssignTeacher>, |
| 626 | ) -> Result<Json<CourseResponse>, AppError> { | 599 | ) -> Result<Json<CourseResponse>, AppError> { |
| 627 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 600 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 628 | .await? | 601 | .await? |
| 629 | .ok_or(AppError::NotFound)?; | 602 | .ok_or(AppError::NotFound)?; |
| 630 | - course.require_open(&st.db).await?; | ||
| 631 | - | ||
| 632 | let target = UserId::from_key(&req.user_id); | 603 | let target = UserId::from_key(&req.user_id); |
| 633 | - let Some(target_user) = User::read(&target, &st.db).await? else { | 604 | + let updated = service::course::assign_teacher(&st.db, &course, &target).await?; |
| 634 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 635 | - field: "user_id", | ||
| 636 | - reason: "target user does not exist", | ||
| 637 | - })); | ||
| 638 | - }; | ||
| 639 | - // Assignment hands out course-management rights, which every gate behind | ||
| 640 | - // it re-checks against the `teacher` bar — assigning anyone below it would | ||
| 641 | - // write a row that can never be used. | ||
| 642 | - if !target_user.get_role().at_least(Role::Teacher) { | ||
| 643 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 644 | - field: "user_id", | ||
| 645 | - reason: "assigned teacher must hold the teacher role or higher", | ||
| 646 | - })); | ||
| 647 | - } | ||
| 648 | - | ||
| 649 | - let updated = course.assign_teacher(&target, &st.db).await?; | ||
| 650 | // The row is written; a demotion that raced the bar above swept the list | 605 | // The row is written; a demotion that raced the bar above swept the list |
| 651 | // before this assignment was in it, and nothing re-sweeps (see | 606 | // before this assignment was in it, and nothing re-sweeps (see |
| 652 | // [`super::undo_if_demoted`]). | 607 | // [`super::undo_if_demoted`]). |
| @@ -680,13 +635,11 @@ async fn unassign_teacher( | |||
| 680 | RequireManager(_manager): RequireManager, | 635 | RequireManager(_manager): RequireManager, |
| 681 | Path((id, target)): Path<(String, String)>, | 636 | Path((id, target)): Path<(String, String)>, |
| 682 | ) -> Result<StatusCode, AppError> { | 637 | ) -> Result<StatusCode, AppError> { |
| 683 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 638 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 684 | .await? | 639 | .await? |
| 685 | .ok_or(AppError::NotFound)?; | 640 | .ok_or(AppError::NotFound)?; |
| 686 | - course.require_open(&st.db).await?; | 641 | + let removed = |
| 687 | - let removed = course | 642 | + service::course::unassign_teacher(&st.db, &course, &UserId::from_key(&target)).await?; |
| 688 | - .unassign_teacher(&UserId::from_key(&target), &st.db) | ||
| 689 | - .await?; | ||
| 690 | if removed.is_none() { | 643 | if removed.is_none() { |
| 691 | return Err(AppError::NotFound); | 644 | return Err(AppError::NotFound); |
| 692 | } | 645 | } |
| @@ -726,7 +679,7 @@ async fn enroll( | |||
| 726 | Path(id): Path<String>, | 679 | Path(id): Path<String>, |
| 727 | Json(req): Json<EnrollUser>, | 680 | Json(req): Json<EnrollUser>, |
| 728 | ) -> Result<Json<EnrollmentResponse>, AppError> { | 681 | ) -> Result<Json<EnrollmentResponse>, AppError> { |
| 729 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 682 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 730 | .await? | 683 | .await? |
| 731 | .ok_or(AppError::NotFound)?; | 684 | .ok_or(AppError::NotFound)?; |
| 732 | if !can_manage_course(&course, &user) { | 685 | if !can_manage_course(&course, &user) { |
| @@ -734,7 +687,7 @@ async fn enroll( | |||
| 734 | "only the course creator, an assigned teacher, or a manager/admin can enroll users", | 687 | "only the course creator, an assigned teacher, or a manager/admin can enroll users", |
| 735 | )); | 688 | )); |
| 736 | } | 689 | } |
| 737 | - course.require_open(&st.db).await?; | 690 | + service::course::require_open(&st.db, &course).await?; |
| 738 | 691 | ||
| 739 | let target = UserId::from_key(&req.user_id); | 692 | let target = UserId::from_key(&req.user_id); |
| 740 | let Some(target_user) = User::read(&target, &st.db).await? else { | 693 | let Some(target_user) = User::read(&target, &st.db).await? else { |
| @@ -785,7 +738,7 @@ async fn list_roster( | |||
| 785 | ) -> Result<Json<Page<EnrollmentResponse>>, AppError> { | 738 | ) -> Result<Json<Page<EnrollmentResponse>>, AppError> { |
| 786 | let (limit, offset) = page.resolve()?; | 739 | let (limit, offset) = page.resolve()?; |
| 787 | // Course must exist — a missing course is a 404, not an empty roster. | 740 | // Course must exist — a missing course is a 404, not an empty roster. |
| 788 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 741 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 789 | .await? | 742 | .await? |
| 790 | .ok_or(AppError::NotFound)?; | 743 | .ok_or(AppError::NotFound)?; |
| 791 | if !can_manage_course(&course, &user) { | 744 | if !can_manage_course(&course, &user) { |
| @@ -833,7 +786,7 @@ async fn unenroll( | |||
| 833 | RequireTeacher(user): RequireTeacher, | 786 | RequireTeacher(user): RequireTeacher, |
| 834 | Path((id, target)): Path<(String, String)>, | 787 | Path((id, target)): Path<(String, String)>, |
| 835 | ) -> Result<StatusCode, AppError> { | 788 | ) -> Result<StatusCode, AppError> { |
| 836 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 789 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 837 | .await? | 790 | .await? |
| 838 | .ok_or(AppError::NotFound)?; | 791 | .ok_or(AppError::NotFound)?; |
| 839 | if !can_manage_course(&course, &user) { | 792 | if !can_manage_course(&course, &user) { |
| @@ -841,7 +794,7 @@ async fn unenroll( | |||
| 841 | "only the course creator, an assigned teacher, or a manager/admin can unenroll users", | 794 | "only the course creator, an assigned teacher, or a manager/admin can unenroll users", |
| 842 | )); | 795 | )); |
| 843 | } | 796 | } |
| 844 | - course.require_open(&st.db).await?; | 797 | + service::course::require_open(&st.db, &course).await?; |
| 845 | let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; | 798 | let removed = Enrollment::remove(course.get_id(), &UserId::from_key(&target), &st.db).await?; |
| 846 | if removed.is_none() { | 799 | if removed.is_none() { |
| 847 | return Err(AppError::NotFound); | 800 | return Err(AppError::NotFound); |
| @@ -884,7 +837,7 @@ async fn create_exam_in_course( | |||
| 884 | Path(id): Path<String>, | 837 | Path(id): Path<String>, |
| 885 | Json(req): Json<CreateExamInCourse>, | 838 | Json(req): Json<CreateExamInCourse>, |
| 886 | ) -> Result<(StatusCode, Json<ExamResponse>), AppError> { | 839 | ) -> Result<(StatusCode, Json<ExamResponse>), AppError> { |
| 887 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 840 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 888 | .await? | 841 | .await? |
| 889 | .ok_or(AppError::NotFound)?; | 842 | .ok_or(AppError::NotFound)?; |
| 890 | if !can_manage_course(&course, &user) { | 843 | if !can_manage_course(&course, &user) { |
| @@ -892,7 +845,7 @@ async fn create_exam_in_course( | |||
| 892 | "only the course creator, an assigned teacher, or a manager/admin can add exams to this course", | 845 | "only the course creator, an assigned teacher, or a manager/admin can add exams to this course", |
| 893 | )); | 846 | )); |
| 894 | } | 847 | } |
| 895 | - course.require_open(&st.db).await?; | 848 | + service::course::require_open(&st.db, &course).await?; |
| 896 | 849 | ||
| 897 | let title = ExamTitle::try_new(&req.title)?; | 850 | let title = ExamTitle::try_new(&req.title)?; |
| 898 | let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; | 851 | let description = ExamDescription::try_new(&req.description.unwrap_or_default())?; |
| @@ -955,7 +908,7 @@ async fn list_course_exams( | |||
| 955 | ) -> Result<Json<Page<ExamResponse>>, AppError> { | 908 | ) -> Result<Json<Page<ExamResponse>>, AppError> { |
| 956 | let (limit, offset) = page.resolve()?; | 909 | let (limit, offset) = page.resolve()?; |
| 957 | // Course must exist — a missing course is a 404, not an empty exam list. | 910 | // Course must exist — a missing course is a 404, not an empty exam list. |
| 958 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 911 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 959 | .await? | 912 | .await? |
| 960 | .ok_or(AppError::NotFound)?; | 913 | .ok_or(AppError::NotFound)?; |
| 961 | if !can_view_course(&course, &user, &st.db).await? { | 914 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -1015,7 +968,7 @@ async fn create_subject_in_course( | |||
| 1015 | Path(id): Path<String>, | 968 | Path(id): Path<String>, |
| 1016 | Json(req): Json<CreateSubject>, | 969 | Json(req): Json<CreateSubject>, |
| 1017 | ) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { | 970 | ) -> Result<(StatusCode, Json<SubjectResponse>), AppError> { |
| 1018 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 971 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1019 | .await? | 972 | .await? |
| 1020 | .ok_or(AppError::NotFound)?; | 973 | .ok_or(AppError::NotFound)?; |
| 1021 | if !can_manage_course(&course, &user) { | 974 | if !can_manage_course(&course, &user) { |
| @@ -1023,7 +976,7 @@ async fn create_subject_in_course( | |||
| 1023 | "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course", | 976 | "only the course creator, an assigned teacher, or a manager/admin can add subjects to this course", |
| 1024 | )); | 977 | )); |
| 1025 | } | 978 | } |
| 1026 | - course.require_open(&st.db).await?; | 979 | + service::course::require_open(&st.db, &course).await?; |
| 1027 | 980 | ||
| 1028 | let name = SubjectName::try_new(&req.name)?; | 981 | let name = SubjectName::try_new(&req.name)?; |
| 1029 | let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; | 982 | let description = SubjectDescription::try_new(&req.description.unwrap_or_default())?; |
| @@ -1057,7 +1010,7 @@ async fn list_course_subjects( | |||
| 1057 | ) -> Result<Json<Page<SubjectResponse>>, AppError> { | 1010 | ) -> Result<Json<Page<SubjectResponse>>, AppError> { |
| 1058 | let (limit, offset) = page.resolve()?; | 1011 | let (limit, offset) = page.resolve()?; |
| 1059 | // Course must exist — a missing course is a 404, not an empty list. | 1012 | // Course must exist — a missing course is a 404, not an empty list. |
| 1060 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 1013 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1061 | .await? | 1014 | .await? |
| 1062 | .ok_or(AppError::NotFound)?; | 1015 | .ok_or(AppError::NotFound)?; |
| 1063 | if !can_view_course(&course, &user, &st.db).await? { | 1016 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -1125,7 +1078,7 @@ async fn create_homework_in_course( | |||
| 1125 | Path(id): Path<String>, | 1078 | Path(id): Path<String>, |
| 1126 | Json(req): Json<CreateHomework>, | 1079 | Json(req): Json<CreateHomework>, |
| 1127 | ) -> Result<(StatusCode, Json<HomeworkResponse>), AppError> { | 1080 | ) -> Result<(StatusCode, Json<HomeworkResponse>), AppError> { |
| 1128 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 1081 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1129 | .await? | 1082 | .await? |
| 1130 | .ok_or(AppError::NotFound)?; | 1083 | .ok_or(AppError::NotFound)?; |
| 1131 | if !can_manage_course(&course, &user) { | 1084 | if !can_manage_course(&course, &user) { |
| @@ -1133,7 +1086,7 @@ async fn create_homework_in_course( | |||
| 1133 | "only the course creator, an assigned teacher, or a manager/admin can add homework to this course", | 1086 | "only the course creator, an assigned teacher, or a manager/admin can add homework to this course", |
| 1134 | )); | 1087 | )); |
| 1135 | } | 1088 | } |
| 1136 | - course.require_open(&st.db).await?; | 1089 | + service::course::require_open(&st.db, &course).await?; |
| 1137 | 1090 | ||
| 1138 | let title = HomeworkTitle::try_new(&req.title)?; | 1091 | let title = HomeworkTitle::try_new(&req.title)?; |
| 1139 | let description = match req.description.as_deref() { | 1092 | let description = match req.description.as_deref() { |
| @@ -1189,7 +1142,7 @@ async fn list_course_homework( | |||
| 1189 | ) -> Result<Json<Page<HomeworkResponse>>, AppError> { | 1142 | ) -> Result<Json<Page<HomeworkResponse>>, AppError> { |
| 1190 | let (limit, offset) = page.resolve()?; | 1143 | let (limit, offset) = page.resolve()?; |
| 1191 | // Course must exist — a missing course is a 404, not an empty homework list. | 1144 | // Course must exist — a missing course is a 404, not an empty homework list. |
| 1192 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 1145 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1193 | .await? | 1146 | .await? |
| 1194 | .ok_or(AppError::NotFound)?; | 1147 | .ok_or(AppError::NotFound)?; |
| 1195 | if !can_view_course(&course, &user, &st.db).await? { | 1148 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -1263,7 +1216,7 @@ async fn create_session_in_course( | |||
| 1263 | Path(id): Path<String>, | 1216 | Path(id): Path<String>, |
| 1264 | Json(req): Json<CreateSessionInCourse>, | 1217 | Json(req): Json<CreateSessionInCourse>, |
| 1265 | ) -> Result<(StatusCode, Json<SessionResponse>), AppError> { | 1218 | ) -> Result<(StatusCode, Json<SessionResponse>), AppError> { |
| 1266 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 1219 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1267 | .await? | 1220 | .await? |
| 1268 | .ok_or(AppError::NotFound)?; | 1221 | .ok_or(AppError::NotFound)?; |
| 1269 | if !can_manage_course(&course, &user) { | 1222 | if !can_manage_course(&course, &user) { |
| @@ -1271,7 +1224,7 @@ async fn create_session_in_course( | |||
| 1271 | "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course", | 1224 | "only the course creator, an assigned teacher, or a manager/admin can add sessions to this course", |
| 1272 | )); | 1225 | )); |
| 1273 | } | 1226 | } |
| 1274 | - course.require_open(&st.db).await?; | 1227 | + service::course::require_open(&st.db, &course).await?; |
| 1275 | 1228 | ||
| 1276 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; | 1229 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; |
| 1277 | let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; | 1230 | let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; |
| @@ -1323,7 +1276,7 @@ async fn list_course_sessions( | |||
| 1323 | ) -> Result<Json<Page<SessionResponse>>, AppError> { | 1276 | ) -> Result<Json<Page<SessionResponse>>, AppError> { |
| 1324 | let (limit, offset) = page.resolve()?; | 1277 | let (limit, offset) = page.resolve()?; |
| 1325 | // Course must exist — a missing course is a 404, not an empty list. | 1278 | // Course must exist — a missing course is a 404, not an empty list. |
| 1326 | - let course = Course::read(&CourseId::from_key(&id), &st.db) | 1279 | + let course = service::course::read(&st.db, &CourseId::from_key(&id)) |
| 1327 | .await? | 1280 | .await? |
| 1328 | .ok_or(AppError::NotFound)?; | 1281 | .ok_or(AppError::NotFound)?; |
| 1329 | if !can_view_course(&course, &user, &st.db).await? { | 1282 | if !can_view_course(&course, &user, &st.db).await? { |
| @@ -1363,14 +1316,14 @@ mod tests { | |||
| 1363 | 1316 | ||
| 1364 | /// A course `creator` made, with nobody assigned. | 1317 | /// A course `creator` made, with nobody assigned. |
| 1365 | async fn course(creator: &User, db: &Database) -> Course { | 1318 | async fn course(creator: &User, db: &Database) -> Course { |
| 1366 | - Course::create( | 1319 | + service::course::create( |
| 1320 | + db, | ||
| 1367 | creator.get_id(), | 1321 | creator.get_id(), |
| 1368 | CourseTitle::try_new("Matematik").unwrap(), | 1322 | CourseTitle::try_new("Matematik").unwrap(), |
| 1369 | CourseDescription::try_new("").unwrap(), | 1323 | CourseDescription::try_new("").unwrap(), |
| 1370 | CourseKind::try_new("course").unwrap(), | 1324 | CourseKind::try_new("course").unwrap(), |
| 1371 | None, | 1325 | None, |
| 1372 | None, | 1326 | None, |
| 1373 | - db, | ||
| 1374 | ) | 1327 | ) |
| 1375 | .await | 1328 | .await |
| 1376 | .unwrap() | 1329 | .unwrap() |
| @@ -1406,11 +1359,13 @@ mod tests { | |||
| 1406 | let db = init_mem().await.unwrap(); | 1359 | let db = init_mem().await.unwrap(); |
| 1407 | let creator = user("creator", Role::Teacher, &db).await; | 1360 | let creator = user("creator", Role::Teacher, &db).await; |
| 1408 | let assigned = user("assigned", Role::Teacher, &db).await; | 1361 | let assigned = user("assigned", Role::Teacher, &db).await; |
| 1409 | - let course = course(&creator, &db) | 1362 | + let course = service::course::assign_teacher( |
| 1410 | - .await | 1363 | + &db, |
| 1411 | - .assign_teacher(assigned.get_id(), &db) | 1364 | + &course(&creator, &db).await, |
| 1412 | - .await | 1365 | + assigned.get_id(), |
| 1413 | - .unwrap(); | 1366 | + ) |
| 1367 | + .await | ||
| 1368 | + .unwrap(); | ||
| 1414 | // Still teacher+: untouched by the floor. | 1369 | // Still teacher+: untouched by the floor. |
| 1415 | assert!(can_manage_course(&course, &assigned)); | 1370 | assert!(can_manage_course(&course, &assigned)); |
| 1416 | // ...but never an owner, assigned or not. | 1371 | // ...but never an owner, assigned or not. |
src/web/events.rsmodified+2 -2
| @@ -12,7 +12,7 @@ use utoipa_axum::routes; | |||
| 12 | use crate::database::Database; | 12 | use crate::database::Database; |
| 13 | use crate::domain::attendance::{Attendance, AttendanceStatus}; | 13 | use crate::domain::attendance::{Attendance, AttendanceStatus}; |
| 14 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; | 14 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 15 | -use crate::domain::course::{Course, CourseId}; | 15 | +use crate::domain::course::CourseId; |
| 16 | use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; | 16 | use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; |
| 17 | use crate::domain::registration::Registration; | 17 | use crate::domain::registration::Registration; |
| 18 | use crate::domain::role::Role; | 18 | use crate::domain::role::Role; |
| @@ -91,7 +91,7 @@ impl AudienceDto { | |||
| 91 | }), | 91 | }), |
| 92 | AudienceDto::Course { course } => { | 92 | AudienceDto::Course { course } => { |
| 93 | let course = CourseId::from_key(&course); | 93 | let course = CourseId::from_key(&course); |
| 94 | - if Course::read(&course, db).await?.is_none() { | 94 | + if crate::service::course::read(db, &course).await?.is_none() { |
| 95 | return Err(AppError::Validation(ValidationError::Invalid { | 95 | return Err(AppError::Validation(ValidationError::Invalid { |
| 96 | field: "audience", | 96 | field: "audience", |
| 97 | reason: "course does not exist", | 97 | reason: "course does not exist", |
src/web/exam_ws.rsmodified+2 -2
| @@ -152,7 +152,7 @@ pub async fn attempt_ws( | |||
| 152 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; | 152 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 153 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; | 153 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 154 | check_rejoin(&exam, &attempt)?; | 154 | check_rejoin(&exam, &attempt)?; |
| 155 | - course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 155 | + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; |
| 156 | 156 | ||
| 157 | let user_id = user.get_id().clone(); | 157 | let user_id = user.get_id().clone(); |
| 158 | Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) | 158 | Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id))) |
| @@ -463,7 +463,7 @@ async fn handle_message( | |||
| 463 | // same error frame as every other conflict. | 463 | // same error frame as every other conflict. |
| 464 | async { | 464 | async { |
| 465 | let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; | 465 | let attempt = writable_room_attempt(&exam, attempt_id, user, db).await?; |
| 466 | - course_of(&exam, db).await?.require_open(db).await?; | 466 | + crate::service::course::require_open(db, &course_of(&exam, db).await?).await?; |
| 467 | attempt.finish(db).await | 467 | attempt.finish(db).await |
| 468 | } | 468 | } |
| 469 | .await | 469 | .await |
src/web/exams/attempts.rsmodified+3 -3
| @@ -180,7 +180,7 @@ pub(crate) async fn start_attempt( | |||
| 180 | ensure_sittable(&exam)?; | 180 | ensure_sittable(&exam)?; |
| 181 | ensure_student(&user)?; | 181 | ensure_student(&user)?; |
| 182 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; | 182 | ensure_enrolled(&exam, user.get_id(), &st.db).await?; |
| 183 | - course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 183 | + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; |
| 184 | let now = Timestamp::now(); | 184 | let now = Timestamp::now(); |
| 185 | if let Some(starts_at) = exam.get_starts_at() | 185 | if let Some(starts_at) = exam.get_starts_at() |
| 186 | && now < starts_at | 186 | && now < starts_at |
| @@ -307,7 +307,7 @@ pub(crate) async fn finish_attempt( | |||
| 307 | { | 307 | { |
| 308 | return Err(AppError::Conflict("time is up — the attempt has expired")); | 308 | return Err(AppError::Conflict("time is up — the attempt has expired")); |
| 309 | } | 309 | } |
| 310 | - course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 310 | + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; |
| 311 | 311 | ||
| 312 | // Deliberately no rejoin check: a student locked out of the room may | 312 | // Deliberately no rejoin check: a student locked out of the room may |
| 313 | // still submit what they saved — finishing answers nothing new. | 313 | // still submit what they saved — finishing answers nothing new. |
| @@ -699,7 +699,7 @@ pub(crate) async fn save_answer_in( | |||
| 699 | ensure_student_now(attempt.get_user(), db).await?; | 699 | ensure_student_now(attempt.get_user(), db).await?; |
| 700 | ensure_enrolled(exam, attempt.get_user(), db).await?; | 700 | ensure_enrolled(exam, attempt.get_user(), db).await?; |
| 701 | check_rejoin(exam, attempt)?; | 701 | check_rejoin(exam, attempt)?; |
| 702 | - course_of(exam, db).await?.require_open(db).await?; | 702 | + crate::service::course::require_open(db, &course_of(exam, db).await?).await?; |
| 703 | let question = question_of_exam(exam.get_id(), question_id, db).await?; | 703 | let question = question_of_exam(exam.get_id(), question_id, db).await?; |
| 704 | ExamAnswer::save( | 704 | ExamAnswer::save( |
| 705 | &question, | 705 | &question, |
src/web/exams/images.rsmodified+3 -3
| @@ -99,7 +99,7 @@ pub(crate) async fn image_managed_exam( | |||
| 99 | "only the course creator, an assigned teacher, or a manager/admin can manage question images", | 99 | "only the course creator, an assigned teacher, or a manager/admin can manage question images", |
| 100 | )); | 100 | )); |
| 101 | } | 101 | } |
| 102 | - course.require_open(&st.db).await?; | 102 | + crate::service::course::require_open(&st.db, &course).await?; |
| 103 | Ok(exam) | 103 | Ok(exam) |
| 104 | } | 104 | } |
| 105 | 105 | ||
| @@ -460,7 +460,7 @@ pub(crate) async fn upload_answer_image( | |||
| 460 | ensure_student(&user)?; | 460 | ensure_student(&user)?; |
| 461 | // Before the body is read: an archived term refuses the upload without | 461 | // Before the body is read: an archived term refuses the upload without |
| 462 | // making the client push its bytes first. | 462 | // making the client push its bytes first. |
| 463 | - course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 463 | + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; |
| 464 | // The body is consumed before the lock — a client's slow upload must not | 464 | // The body is consumed before the lock — a client's slow upload must not |
| 465 | // stall the exam subsystem (mirrors the question-image upload). | 465 | // stall the exam subsystem (mirrors the question-image upload). |
| 466 | let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; | 466 | let ImageUpload { content_type, data } = read_image_upload(&st, &mut multipart).await?; |
| @@ -540,7 +540,7 @@ pub(crate) async fn delete_answer_image( | |||
| 540 | .await? | 540 | .await? |
| 541 | .ok_or(AppError::NotFound)?; | 541 | .ok_or(AppError::NotFound)?; |
| 542 | ensure_student(&user)?; | 542 | ensure_student(&user)?; |
| 543 | - course_of(&exam, &st.db).await?.require_open(&st.db).await?; | 543 | + crate::service::course::require_open(&st.db, &course_of(&exam, &st.db).await?).await?; |
| 544 | let _guard = EXAM_LOCK.read().await; | 544 | let _guard = EXAM_LOCK.read().await; |
| 545 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; | 545 | let attempt = writable_attempt(&exam, user.get_id(), &st.db).await?; |
| 546 | ensure_student_now(attempt.get_user(), &st.db).await?; | 546 | ensure_student_now(attempt.get_user(), &st.db).await?; |
src/web/exams/mod.rsmodified+5 -5
| @@ -266,7 +266,7 @@ struct ExamStatisticsResponse { | |||
| 266 | /// The course an exam belongs to. A dangling reference means the course-delete | 266 | /// The course an exam belongs to. A dangling reference means the course-delete |
| 267 | /// cascade was violated — surface it loudly as a 500, not a user-facing 404. | 267 | /// cascade was violated — surface it loudly as a 500, not a user-facing 404. |
| 268 | pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { | 268 | pub(crate) async fn course_of(exam: &Exam, db: &Database) -> Result<Course, AppError> { |
| 269 | - Course::read(exam.get_course(), db) | 269 | + crate::service::course::read(db, exam.get_course()) |
| 270 | .await? | 270 | .await? |
| 271 | .ok_or_else(|| AppError::Internal("exam references a missing course".into())) | 271 | .ok_or_else(|| AppError::Internal("exam references a missing course".into())) |
| 272 | } | 272 | } |
| @@ -433,7 +433,7 @@ async fn update_exam( | |||
| 433 | "only the course creator, an assigned teacher, or a manager/admin can edit this exam", | 433 | "only the course creator, an assigned teacher, or a manager/admin can edit this exam", |
| 434 | )); | 434 | )); |
| 435 | } | 435 | } |
| 436 | - course.require_open(&st.db).await?; | 436 | + crate::service::course::require_open(&st.db, &course).await?; |
| 437 | 437 | ||
| 438 | let title = match req.title { | 438 | let title = match req.title { |
| 439 | Some(ref title) => ExamTitle::try_new(title)?, | 439 | Some(ref title) => ExamTitle::try_new(title)?, |
| @@ -591,7 +591,7 @@ async fn delete_exam( | |||
| 591 | "only the course creator, an assigned teacher, or a manager/admin can delete this exam", | 591 | "only the course creator, an assigned teacher, or a manager/admin can delete this exam", |
| 592 | )); | 592 | )); |
| 593 | } | 593 | } |
| 594 | - course.require_open(&st.db).await?; | 594 | + crate::service::course::require_open(&st.db, &course).await?; |
| 595 | // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names | 595 | // *Writer* lease of [`EXAM_LOCK`] across the whole cascade, blob names |
| 596 | // included — the lease `delete_homework` has always held, and its absence | 596 | // included — the lease `delete_homework` has always held, and its absence |
| 597 | // here is what made a sitting able to start inside this delete. Every other | 597 | // here is what made a sitting able to start inside this delete. Every other |
| @@ -676,7 +676,7 @@ async fn grade( | |||
| 676 | "only the course creator, an assigned teacher, or a manager/admin can grade this exam", | 676 | "only the course creator, an assigned teacher, or a manager/admin can grade this exam", |
| 677 | )); | 677 | )); |
| 678 | } | 678 | } |
| 679 | - course.require_open(&st.db).await?; | 679 | + crate::service::course::require_open(&st.db, &course).await?; |
| 680 | // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own | 680 | // Pre-flight: `ExamResult::grade` re-makes this check inside the mark's own |
| 681 | // transaction, so a re-draft landing after this read cannot leave a mark on | 681 | // transaction, so a re-draft landing after this read cannot leave a mark on |
| 682 | // a hidden exam. | 682 | // a hidden exam. |
| @@ -883,7 +883,7 @@ async fn remove_result( | |||
| 883 | "only the course creator, an assigned teacher, or a manager/admin can remove results", | 883 | "only the course creator, an assigned teacher, or a manager/admin can remove results", |
| 884 | )); | 884 | )); |
| 885 | } | 885 | } |
| 886 | - course.require_open(&st.db).await?; | 886 | + crate::service::course::require_open(&st.db, &course).await?; |
| 887 | let removed = ExamResult::remove( | 887 | let removed = ExamResult::remove( |
| 888 | exam.get_id(), | 888 | exam.get_id(), |
| 889 | &UserId::from_key(&target), | 889 | &UserId::from_key(&target), |
src/web/exams/questions.rsmodified+6 -6
| @@ -219,7 +219,7 @@ pub(crate) async fn create_question( | |||
| 219 | "only the course creator, an assigned teacher, or a manager/admin can author questions", | 219 | "only the course creator, an assigned teacher, or a manager/admin can author questions", |
| 220 | )); | 220 | )); |
| 221 | } | 221 | } |
| 222 | - course.require_open(&st.db).await?; | 222 | + crate::service::course::require_open(&st.db, &course).await?; |
| 223 | // No lease: the subject check below is only a pre-flight for the message, | 223 | // No lease: the subject check below is only a pre-flight for the message, |
| 224 | // and the insert takes the subject's reference counter in the same breath — | 224 | // and the insert takes the subject's reference counter in the same breath — |
| 225 | // a subject delete lands either wholly before it (400) or is refused. The | 225 | // a subject delete lands either wholly before it (400) or is refused. The |
| @@ -358,7 +358,7 @@ pub(crate) async fn update_question( | |||
| 358 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", | 358 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", |
| 359 | )); | 359 | )); |
| 360 | } | 360 | } |
| 361 | - course.require_open(&st.db).await?; | 361 | + crate::service::course::require_open(&st.db, &course).await?; |
| 362 | // No lease — see `create_question`; a re-tag moves the subject's reference | 362 | // No lease — see `create_question`; a re-tag moves the subject's reference |
| 363 | // counter, and the freeze gate rides in the update's transaction. | 363 | // counter, and the freeze gate rides in the update's transaction. |
| 364 | ensure_questions_editable(exam.get_id(), &st.db).await?; | 364 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -446,7 +446,7 @@ pub(crate) async fn delete_question( | |||
| 446 | "only the course creator, an assigned teacher, or a manager/admin can delete questions", | 446 | "only the course creator, an assigned teacher, or a manager/admin can delete questions", |
| 447 | )); | 447 | )); |
| 448 | } | 448 | } |
| 449 | - course.require_open(&st.db).await?; | 449 | + crate::service::course::require_open(&st.db, &course).await?; |
| 450 | // No lock: the freeze gate is part of the delete's own transaction, and | 450 | // No lock: the freeze gate is part of the delete's own transaction, and |
| 451 | // this path checks no subject. The pre-flight below is the fast 409. | 451 | // this path checks no subject. The pre-flight below is the fast 409. |
| 452 | ensure_questions_editable(exam.get_id(), &st.db).await?; | 452 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -518,7 +518,7 @@ pub(crate) async fn question_from_bank( | |||
| 518 | "only the course creator, an assigned teacher, or a manager/admin can author questions", | 518 | "only the course creator, an assigned teacher, or a manager/admin can author questions", |
| 519 | )); | 519 | )); |
| 520 | } | 520 | } |
| 521 | - course.require_open(&st.db).await?; | 521 | + crate::service::course::require_open(&st.db, &course).await?; |
| 522 | // No lease — same reasoning as `create_question`. The freeze gate rides in | 522 | // No lease — same reasoning as `create_question`. The freeze gate rides in |
| 523 | // the insert's transaction. | 523 | // the insert's transaction. |
| 524 | ensure_questions_editable(exam.get_id(), &st.db).await?; | 524 | ensure_questions_editable(exam.get_id(), &st.db).await?; |
| @@ -649,7 +649,7 @@ pub(crate) async fn question_refresh_from_bank( | |||
| 649 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", | 649 | "only the course creator, an assigned teacher, or a manager/admin can edit questions", |
| 650 | )); | 650 | )); |
| 651 | } | 651 | } |
| 652 | - course.require_open(&st.db).await?; | 652 | + crate::service::course::require_open(&st.db, &course).await?; |
| 653 | // No lock: the question keeps its own subject here, so there is nothing to | 653 | // No lock: the question keeps its own subject here, so there is nothing to |
| 654 | // pair with a subject delete, and the freeze gate rides in the overwrite's | 654 | // pair with a subject delete, and the freeze gate rides in the overwrite's |
| 655 | // transaction. | 655 | // transaction. |
| @@ -774,7 +774,7 @@ pub(crate) async fn question_to_bank( | |||
| 774 | "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", | 774 | "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank", |
| 775 | )); | 775 | )); |
| 776 | } | 776 | } |
| 777 | - course.require_open(&st.db).await?; | 777 | + crate::service::course::require_open(&st.db, &course).await?; |
| 778 | // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and | 778 | // No lease: `BANK_LOCK` is gone with the subject delete's writer lease, and |
| 779 | // a template left holding a deleted subject reads as an empty | 779 | // a template left holding a deleted subject reads as an empty |
| 780 | // `subject_name` either way (see [`crate::web::bank_questions`]). | 780 | // `subject_name` either way (see [`crate::web::bank_questions`]). |
src/web/homework.rsmodified+8 -8
| @@ -166,7 +166,7 @@ async fn homework_with_course(id: &str, db: &Database) -> Result<(Homework, Cour | |||
| 166 | let homework = Homework::read(&HomeworkId::from_key(id), db) | 166 | let homework = Homework::read(&HomeworkId::from_key(id), db) |
| 167 | .await? | 167 | .await? |
| 168 | .ok_or(AppError::NotFound)?; | 168 | .ok_or(AppError::NotFound)?; |
| 169 | - let course = Course::read(homework.get_course(), db) | 169 | + let course = crate::service::course::read(db, homework.get_course()) |
| 170 | .await? | 170 | .await? |
| 171 | .ok_or(AppError::NotFound)?; | 171 | .ok_or(AppError::NotFound)?; |
| 172 | Ok((homework, course)) | 172 | Ok((homework, course)) |
| @@ -345,7 +345,7 @@ async fn update_homework( | |||
| 345 | "only the course creator, an assigned teacher, or a manager/admin can edit this homework", | 345 | "only the course creator, an assigned teacher, or a manager/admin can edit this homework", |
| 346 | )); | 346 | )); |
| 347 | } | 347 | } |
| 348 | - course.require_open(&st.db).await?; | 348 | + crate::service::course::require_open(&st.db, &course).await?; |
| 349 | 349 | ||
| 350 | // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the | 350 | // Writer lease of [`HOMEWORK_LOCK`]: `ensure_no_orphans` below reads the |
| 351 | // live submissions and results, and the row write depends on what it saw — | 351 | // live submissions and results, and the row write depends on what it saw — |
| @@ -465,7 +465,7 @@ async fn delete_homework( | |||
| 465 | "only the course creator, an assigned teacher, or a manager/admin can delete this homework", | 465 | "only the course creator, an assigned teacher, or a manager/admin can delete this homework", |
| 466 | )); | 466 | )); |
| 467 | } | 467 | } |
| 468 | - course.require_open(&st.db).await?; | 468 | + crate::service::course::require_open(&st.db, &course).await?; |
| 469 | let _guard = HOMEWORK_LOCK.write().await; | 469 | let _guard = HOMEWORK_LOCK.write().await; |
| 470 | let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; | 470 | let blob_keys = HomeworkFile::file_keys_for_homework(homework.get_id(), &st.db).await?; |
| 471 | homework.delete(&st.db).await?; | 471 | homework.delete(&st.db).await?; |
| @@ -524,8 +524,8 @@ async fn gate_own_submission(id: &str, user: &User, db: &Database) -> Result<Hom | |||
| 524 | /// audience check with a 404 and never learns the homework exists. A course | 524 | /// audience check with a 404 and never learns the homework exists. A course |
| 525 | /// that vanished under us is the gates' own business, not this one's. | 525 | /// that vanished under us is the gates' own business, not this one's. |
| 526 | async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { | 526 | async fn require_open_term(homework: &Homework, db: &Database) -> Result<(), AppError> { |
| 527 | - if let Some(course) = Course::read(homework.get_course(), db).await? { | 527 | + if let Some(course) = crate::service::course::read(db, homework.get_course()).await? { |
| 528 | - course.require_open(db).await?; | 528 | + crate::service::course::require_open(db, &course).await?; |
| 529 | } | 529 | } |
| 530 | Ok(()) | 530 | Ok(()) |
| 531 | } | 531 | } |
| @@ -1147,7 +1147,7 @@ async fn grade_homework( | |||
| 1147 | "only the course creator, an assigned teacher, or a manager/admin can grade this homework", | 1147 | "only the course creator, an assigned teacher, or a manager/admin can grade this homework", |
| 1148 | )); | 1148 | )); |
| 1149 | } | 1149 | } |
| 1150 | - course.require_open(&st.db).await?; | 1150 | + crate::service::course::require_open(&st.db, &course).await?; |
| 1151 | 1151 | ||
| 1152 | let status = HomeworkStatus::try_new(&req.status)?; | 1152 | let status = HomeworkStatus::try_new(&req.status)?; |
| 1153 | let mark = req.mark.map(Mark::try_new).transpose()?; | 1153 | let mark = req.mark.map(Mark::try_new).transpose()?; |
| @@ -1247,7 +1247,7 @@ async fn remove_homework_result( | |||
| 1247 | "only the course creator, an assigned teacher, or a manager/admin can remove grades", | 1247 | "only the course creator, an assigned teacher, or a manager/admin can remove grades", |
| 1248 | )); | 1248 | )); |
| 1249 | } | 1249 | } |
| 1250 | - course.require_open(&st.db).await?; | 1250 | + crate::service::course::require_open(&st.db, &course).await?; |
| 1251 | let removed = | 1251 | let removed = |
| 1252 | HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; | 1252 | HomeworkResult::remove(homework.get_id(), &UserId::from_key(&target), &st.db).await?; |
| 1253 | if removed.is_none() { | 1253 | if removed.is_none() { |
| @@ -1481,7 +1481,7 @@ async fn homework_report( | |||
| 1481 | .ok_or(AppError::NotFound)?; | 1481 | .ok_or(AppError::NotFound)?; |
| 1482 | // Only an exactly-teacher caller is narrowed to their managed courses; | 1482 | // Only an exactly-teacher caller is narrowed to their managed courses; |
| 1483 | // manager+ and a linked parent read the full report (the marks idiom). | 1483 | // manager+ and a linked parent read the full report (the marks idiom). |
| 1484 | - let (mut courses, _) = Course::list_enrolled(&target, None, 0, &st.db).await?; | 1484 | + let (mut courses, _) = crate::service::course::list_enrolled(&st.db, &target, None, 0).await?; |
| 1485 | if caller.get_role() == Role::Teacher { | 1485 | if caller.get_role() == Role::Teacher { |
| 1486 | courses.retain(|course| can_manage_course(course, &caller)); | 1486 | courses.retain(|course| can_manage_course(course, &caller)); |
| 1487 | } | 1487 | } |
src/web/marks.rsmodified+2 -2
| @@ -9,7 +9,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 9 | use utoipa_axum::routes; | 9 | use utoipa_axum::routes; |
| 10 | 10 | ||
| 11 | use crate::database::Database; | 11 | use crate::database::Database; |
| 12 | -use crate::domain::course::Course; | 12 | + |
| 13 | use crate::domain::exam::Exam; | 13 | use crate::domain::exam::Exam; |
| 14 | use crate::domain::exam_result::ExamResult; | 14 | use crate::domain::exam_result::ExamResult; |
| 15 | use crate::domain::role::Role; | 15 | use crate::domain::role::Role; |
| @@ -96,7 +96,7 @@ async fn build_report( | |||
| 96 | viewer: Option<&User>, | 96 | viewer: Option<&User>, |
| 97 | db: &Database, | 97 | db: &Database, |
| 98 | ) -> Result<MarksReport, AppError> { | 98 | ) -> Result<MarksReport, AppError> { |
| 99 | - let (mut courses, _) = Course::list_enrolled(user, None, 0, db).await?; | 99 | + let (mut courses, _) = crate::service::course::list_enrolled(db, user, None, 0).await?; |
| 100 | if let Some(viewer) = viewer { | 100 | if let Some(viewer) = viewer { |
| 101 | courses.retain(|course| can_manage_course(course, viewer)); | 101 | courses.retain(|course| can_manage_course(course, viewer)); |
| 102 | } | 102 | } |
src/web/mod.rsmodified+16 -13
| @@ -138,7 +138,7 @@ pub(crate) async fn undo_if_demoted(target: &UserId, db: &Database) -> Result<() | |||
| 138 | return Ok(()); | 138 | return Ok(()); |
| 139 | } | 139 | } |
| 140 | crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?; | 140 | crate::domain::class_group::ClassGroup::unassign_everywhere(target, db).await?; |
| 141 | - crate::domain::course::Course::unassign_everywhere(target, db).await?; | 141 | + crate::service::course::unassign_everywhere(db, target).await?; |
| 142 | Err(AppError::Conflict( | 142 | Err(AppError::Conflict( |
| 143 | "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry", | 143 | "that user was demoted below teacher while this request ran — the assignment was undone; re-read their role and retry", |
| 144 | )) | 144 | )) |
| @@ -409,7 +409,7 @@ mod tests { | |||
| 409 | #[tokio::test] | 409 | #[tokio::test] |
| 410 | async fn undo_if_demoted_repairs_both_assignments_or_neither() { | 410 | async fn undo_if_demoted_repairs_both_assignments_or_neither() { |
| 411 | use crate::domain::class_group::{ClassGroup, ClassName}; | 411 | use crate::domain::class_group::{ClassGroup, ClassName}; |
| 412 | - use crate::domain::course::{Course, CourseDescription, CourseKind, CourseTitle}; | 412 | + use crate::domain::course::{CourseDescription, CourseKind, CourseTitle}; |
| 413 | use crate::domain::user::{Password, Username}; | 413 | use crate::domain::user::{Password, Username}; |
| 414 | 414 | ||
| 415 | let db = crate::database::init_mem().await.unwrap(); | 415 | let db = crate::database::init_mem().await.unwrap(); |
| @@ -441,19 +441,22 @@ mod tests { | |||
| 441 | ) | 441 | ) |
| 442 | .await | 442 | .await |
| 443 | .unwrap(); | 443 | .unwrap(); |
| 444 | - let course = Course::create( | 444 | + let course = crate::service::course::assign_teacher( |
| 445 | - &office, | ||
| 446 | - CourseTitle::try_new("algebra").unwrap(), | ||
| 447 | - CourseDescription::try_new("").unwrap(), | ||
| 448 | - CourseKind::course(), | ||
| 449 | - None, | ||
| 450 | - None, | ||
| 451 | db, | 445 | db, |
| 446 | + &crate::service::course::create( | ||
| 447 | + db, | ||
| 448 | + &office, | ||
| 449 | + CourseTitle::try_new("algebra").unwrap(), | ||
| 450 | + CourseDescription::try_new("").unwrap(), | ||
| 451 | + CourseKind::course(), | ||
| 452 | + None, | ||
| 453 | + None, | ||
| 454 | + ) | ||
| 455 | + .await | ||
| 456 | + .unwrap(), | ||
| 457 | + teacher.get_id(), | ||
| 452 | ) | 458 | ) |
| 453 | .await | 459 | .await |
| 454 | - .unwrap() | ||
| 455 | - .assign_teacher(teacher.get_id(), db) | ||
| 456 | - .await | ||
| 457 | .unwrap(); | 460 | .unwrap(); |
| 458 | (class, course) | 461 | (class, course) |
| 459 | }; | 462 | }; |
| @@ -470,7 +473,7 @@ mod tests { | |||
| 470 | .unwrap() | 473 | .unwrap() |
| 471 | .get_teacher() | 474 | .get_teacher() |
| 472 | .cloned(), | 475 | .cloned(), |
| 473 | - Course::read(course, db) | 476 | + crate::service::course::read(db, course) |
| 474 | .await | 477 | .await |
| 475 | .unwrap() | 478 | .unwrap() |
| 476 | .unwrap() | 479 | .unwrap() |
src/web/sessions.rsmodified+5 -5
| @@ -122,7 +122,7 @@ async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, | |||
| 122 | let session = CourseSession::read(&CourseSessionId::from_key(id), db) | 122 | let session = CourseSession::read(&CourseSessionId::from_key(id), db) |
| 123 | .await? | 123 | .await? |
| 124 | .ok_or(AppError::NotFound)?; | 124 | .ok_or(AppError::NotFound)?; |
| 125 | - let course = Course::read(session.get_course(), db) | 125 | + let course = crate::service::course::read(db, session.get_course()) |
| 126 | .await? | 126 | .await? |
| 127 | .ok_or(AppError::NotFound)?; | 127 | .ok_or(AppError::NotFound)?; |
| 128 | Ok((session, course)) | 128 | Ok((session, course)) |
| @@ -219,7 +219,7 @@ async fn update_session( | |||
| 219 | "only the course creator, an assigned teacher, or a manager/admin can edit this session", | 219 | "only the course creator, an assigned teacher, or a manager/admin can edit this session", |
| 220 | )); | 220 | )); |
| 221 | } | 221 | } |
| 222 | - course.require_open(&st.db).await?; | 222 | + crate::service::course::require_open(&st.db, &course).await?; |
| 223 | 223 | ||
| 224 | let topic = req | 224 | let topic = req |
| 225 | .topic | 225 | .topic |
| @@ -277,7 +277,7 @@ async fn delete_session( | |||
| 277 | "only the course creator, an assigned teacher, or a manager/admin can delete this session", | 277 | "only the course creator, an assigned teacher, or a manager/admin can delete this session", |
| 278 | )); | 278 | )); |
| 279 | } | 279 | } |
| 280 | - course.require_open(&st.db).await?; | 280 | + crate::service::course::require_open(&st.db, &course).await?; |
| 281 | session.delete(&st.db).await?; | 281 | session.delete(&st.db).await?; |
| 282 | Ok(StatusCode::NO_CONTENT) | 282 | Ok(StatusCode::NO_CONTENT) |
| 283 | } | 283 | } |
| @@ -318,7 +318,7 @@ async fn mark_roll_call( | |||
| 318 | "only the session's teacher or a course manager can take roll call", | 318 | "only the session's teacher or a course manager can take roll call", |
| 319 | )); | 319 | )); |
| 320 | } | 320 | } |
| 321 | - course.require_open(&st.db).await?; | 321 | + crate::service::course::require_open(&st.db, &course).await?; |
| 322 | 322 | ||
| 323 | let school = service::settings::load(&st.db).await?; | 323 | let school = service::settings::load(&st.db).await?; |
| 324 | let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; | 324 | let status = AttendanceStatus::try_new(&req.status, school.get_attendance_statuses())?; |
| @@ -458,7 +458,7 @@ async fn remove_roll_call( | |||
| 458 | "only the session's teacher or a course manager can take roll call", | 458 | "only the session's teacher or a course manager can take roll call", |
| 459 | )); | 459 | )); |
| 460 | } | 460 | } |
| 461 | - course.require_open(&st.db).await?; | 461 | + crate::service::course::require_open(&st.db, &course).await?; |
| 462 | let target = UserId::from_key(&target); | 462 | let target = UserId::from_key(&target); |
| 463 | // A staff row is management's to remove, keyed on the *target's live role* | 463 | // A staff row is management's to remove, keyed on the *target's live role* |
| 464 | // rather than on `is_teacher`: reassigning a session's teacher used to hand | 464 | // rather than on `is_teacher`: reassigning a session's teacher used to hand |
src/web/subjects.rsmodified+3 -3
| @@ -74,7 +74,7 @@ async fn subject_with_course(id: &str, db: &Database) -> Result<(Subject, Course | |||
| 74 | let subject = Subject::read(&SubjectId::from_key(id), db) | 74 | let subject = Subject::read(&SubjectId::from_key(id), db) |
| 75 | .await? | 75 | .await? |
| 76 | .ok_or(AppError::NotFound)?; | 76 | .ok_or(AppError::NotFound)?; |
| 77 | - let course = Course::read(subject.get_course(), db) | 77 | + let course = crate::service::course::read(db, subject.get_course()) |
| 78 | .await? | 78 | .await? |
| 79 | .ok_or(AppError::NotFound)?; | 79 | .ok_or(AppError::NotFound)?; |
| 80 | Ok((subject, course)) | 80 | Ok((subject, course)) |
| @@ -142,7 +142,7 @@ async fn update_subject( | |||
| 142 | "only the course creator, an assigned teacher, or a manager/admin can edit this subject", | 142 | "only the course creator, an assigned teacher, or a manager/admin can edit this subject", |
| 143 | )); | 143 | )); |
| 144 | } | 144 | } |
| 145 | - course.require_open(&st.db).await?; | 145 | + crate::service::course::require_open(&st.db, &course).await?; |
| 146 | 146 | ||
| 147 | // Only what the request actually carried is validated and written — an | 147 | // Only what the request actually carried is validated and written — an |
| 148 | // omitted field stays `None` so the save never re-sends this snapshot's | 148 | // omitted field stays `None` so the save never re-sends this snapshot's |
| @@ -193,7 +193,7 @@ async fn delete_subject( | |||
| 193 | "only the course creator, an assigned teacher, or a manager/admin can delete this subject", | 193 | "only the course creator, an assigned teacher, or a manager/admin can delete this subject", |
| 194 | )); | 194 | )); |
| 195 | } | 195 | } |
| 196 | - course.require_open(&st.db).await?; | 196 | + crate::service::course::require_open(&st.db, &course).await?; |
| 197 | // No locks: the two checks *are* the delete's `WHERE`, decided against the | 197 | // No locks: the two checks *are* the delete's `WHERE`, decided against the |
| 198 | // subject's own reference counters inside one statement. This used to be | 198 | // subject's own reference counters inside one statement. This used to be |
| 199 | // three process-wide locks (the only site that held more than one) around | 199 | // three process-wide locks (the only site that held more than one) around |
src/web/users.rsmodified+3 -3
| @@ -16,7 +16,7 @@ use crate::database::Database; | |||
| 16 | use crate::domain::badge::{self, BadgeAward}; | 16 | use crate::domain::badge::{self, BadgeAward}; |
| 17 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; | 17 | use crate::domain::class_group::{ClassGroup, ClassGroupId}; |
| 18 | use crate::domain::class_member::ClassMember; | 18 | use crate::domain::class_member::ClassMember; |
| 19 | -use crate::domain::course::Course; | 19 | + |
| 20 | use crate::domain::parent_link::ParentLink; | 20 | use crate::domain::parent_link::ParentLink; |
| 21 | use crate::domain::preferences::{Language, PaletteColor, Theme}; | 21 | use crate::domain::preferences::{Language, PaletteColor, Theme}; |
| 22 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; | 22 | use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats}; |
| @@ -926,14 +926,14 @@ async fn profile_of( | |||
| 926 | let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { | 926 | let (mut courses, course_total) = match user.get_role().at_least(Role::Teacher) { |
| 927 | // The teacher read is unpaged, so the total is what came back. | 927 | // The teacher read is unpaged, so the total is what came back. |
| 928 | true => { | 928 | true => { |
| 929 | - let courses = Course::list_for_teacher(id, &st.db).await?; | 929 | + let courses = crate::service::course::list_for_teacher(&st.db, id).await?; |
| 930 | let total = courses.len() as i64; | 930 | let total = courses.len() as i64; |
| 931 | (courses, total) | 931 | (courses, total) |
| 932 | } | 932 | } |
| 933 | // Unfiltered readers can take the window from the database. | 933 | // Unfiltered readers can take the window from the database. |
| 934 | false => { | 934 | false => { |
| 935 | let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); | 935 | let window = readable.is_none().then_some(MAX_PROFILE_COURSES as i64); |
| 936 | - Course::list_enrolled(id, window, 0, &st.db).await? | 936 | + crate::service::course::list_enrolled(&st.db, id, window, 0).await? |
| 937 | } | 937 | } |
| 938 | }; | 938 | }; |
| 939 | if let Some(readable) = &readable { | 939 | if let Some(readable) = &readable { |
tests/integration.rsmodified+20 -21
| @@ -21298,8 +21298,9 @@ async fn refreshing_a_question_recopies_its_template() { | |||
| 21298 | /// inside the handler. | 21298 | /// inside the handler. |
| 21299 | #[tokio::test] | 21299 | #[tokio::test] |
| 21300 | async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | 21300 | async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { |
| 21301 | + use hezarfen_backend::db::course; | ||
| 21301 | use hezarfen_backend::domain::course::{ | 21302 | use hezarfen_backend::domain::course::{ |
| 21302 | - Course, CourseDescription, CourseId, CourseKind, CourseTitle, | 21303 | + CourseDescription, CourseId, CourseKind, CourseTitle, |
| 21303 | }; | 21304 | }; |
| 21304 | 21305 | ||
| 21305 | let (app, db) = app_and_db().await; | 21306 | let (app, db) = app_and_db().await; |
| @@ -21310,7 +21311,7 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | |||
| 21310 | let course = create_course(&app, &owner, "cclob_c").await; | 21311 | let course = create_course(&app, &owner, "cclob_c").await; |
| 21311 | 21312 | ||
| 21312 | // The handler's read, then the assignment lands mid-window. | 21313 | // The handler's read, then the assignment lands mid-window. |
| 21313 | - let stale = Course::read(&CourseId::from_key(&course), &db) | 21314 | + let stale = course::read(&db, &CourseId::from_key(&course)) |
| 21314 | .await | 21315 | .await |
| 21315 | .unwrap() | 21316 | .unwrap() |
| 21316 | .expect("course exists"); | 21317 | .expect("course exists"); |
| @@ -21324,17 +21325,17 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | |||
| 21324 | .await; | 21325 | .await; |
| 21325 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 21326 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21326 | 21327 | ||
| 21327 | - let updated = stale | 21328 | + let updated = course::update( |
| 21328 | - .update( | 21329 | + &db, |
| 21329 | - Some(CourseTitle::try_new("renamed").unwrap()), | 21330 | + stale, |
| 21330 | - Some(CourseDescription::try_new("").unwrap()), | 21331 | + Some(CourseTitle::try_new("renamed").unwrap()), |
| 21331 | - Some(CourseKind::course()), | 21332 | + Some(CourseDescription::try_new("").unwrap()), |
| 21332 | - None, | 21333 | + Some(CourseKind::course()), |
| 21333 | - None, | 21334 | + None, |
| 21334 | - &db, | 21335 | + None, |
| 21335 | - ) | 21336 | + ) |
| 21336 | - .await | 21337 | + .await |
| 21337 | - .expect("update written"); | 21338 | + .expect("update written"); |
| 21338 | assert_eq!( | 21339 | assert_eq!( |
| 21339 | updated.get_teachers().len(), | 21340 | updated.get_teachers().len(), |
| 21340 | 1, | 21341 | 1, |
| @@ -21360,8 +21361,8 @@ async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | |||
| 21360 | /// the rename. `unassign_teacher` gets the same field-scoped treatment. | 21361 | /// the rename. `unassign_teacher` gets the same field-scoped treatment. |
| 21361 | #[tokio::test] | 21362 | #[tokio::test] |
| 21362 | async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | 21363 | async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { |
| 21363 | - use hezarfen_backend::domain::course::{Course, CourseId}; | 21364 | + use hezarfen_backend::db::course; |
| 21364 | - use hezarfen_backend::domain::user::UserId; | 21365 | + use hezarfen_backend::domain::course::CourseId; |
| 21365 | 21366 | ||
| 21366 | let (app, db) = app_and_db().await; | 21367 | let (app, db) = app_and_db().await; |
| 21367 | let owner = login_as(&app, &db, "cstaff_o", "teacher").await; | 21368 | let owner = login_as(&app, &db, "cstaff_o", "teacher").await; |
| @@ -21370,7 +21371,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | |||
| 21370 | let course = create_course(&app, &owner, "cstaff_c").await; | 21371 | let course = create_course(&app, &owner, "cstaff_c").await; |
| 21371 | 21372 | ||
| 21372 | // The handler's read, then someone else's edit lands mid-window. | 21373 | // The handler's read, then someone else's edit lands mid-window. |
| 21373 | - let stale = Course::read(&CourseId::from_key(&course), &db) | 21374 | + let stale = course::read(&db, &CourseId::from_key(&course)) |
| 21374 | .await | 21375 | .await |
| 21375 | .unwrap() | 21376 | .unwrap() |
| 21376 | .expect("course exists"); | 21377 | .expect("course exists"); |
| @@ -21384,8 +21385,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | |||
| 21384 | .await; | 21385 | .await; |
| 21385 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 21386 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21386 | 21387 | ||
| 21387 | - let assigned = stale | 21388 | + let assigned = course::assign_teacher(&db, stale, &UserId::from_key(&helper_id)) |
| 21388 | - .assign_teacher(&UserId::from_key(&helper_id), &db) | ||
| 21389 | .await | 21389 | .await |
| 21390 | .expect("assignment written"); | 21390 | .expect("assignment written"); |
| 21391 | assert_eq!(assigned.get_title().as_str(), "edited by someone else"); | 21391 | assert_eq!(assigned.get_title().as_str(), "edited by someone else"); |
| @@ -21393,7 +21393,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | |||
| 21393 | assert_eq!(assigned.get_teachers().len(), 1); | 21393 | assert_eq!(assigned.get_teachers().len(), 1); |
| 21394 | 21394 | ||
| 21395 | // Unassigning from a struct read before another edit is just as safe. | 21395 | // Unassigning from a struct read before another edit is just as safe. |
| 21396 | - let stale = Course::read(&CourseId::from_key(&course), &db) | 21396 | + let stale = course::read(&db, &CourseId::from_key(&course)) |
| 21397 | .await | 21397 | .await |
| 21398 | .unwrap() | 21398 | .unwrap() |
| 21399 | .expect("course exists"); | 21399 | .expect("course exists"); |
| @@ -21406,8 +21406,7 @@ async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | |||
| 21406 | ) | 21406 | ) |
| 21407 | .await; | 21407 | .await; |
| 21408 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 21408 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 21409 | - let dropped = stale | 21409 | + let dropped = course::unassign_teacher(&db, stale, &UserId::from_key(&helper_id)) |
| 21410 | - .unassign_teacher(&UserId::from_key(&helper_id), &db) | ||
| 21411 | .await | 21410 | .await |
| 21412 | .expect("unassignment written") | 21411 | .expect("unassignment written") |
| 21413 | .expect("teacher was assigned"); | 21412 | .expect("teacher was assigned"); |
tests/regress_course_child_orphans.rsmodified+21 -18
| @@ -48,9 +48,8 @@ mod common; | |||
| 48 | use axum::http::StatusCode; | 48 | use axum::http::StatusCode; |
| 49 | use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; | 49 | use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; |
| 50 | use hezarfen_backend::database::{self, Database}; | 50 | use hezarfen_backend::database::{self, Database}; |
| 51 | -use hezarfen_backend::domain::course::{ | 51 | +use hezarfen_backend::db::course; |
| 52 | - Course, CourseDescription, CourseId, CourseKind, CourseTitle, | 52 | +use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 53 | -}; | ||
| 54 | use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 53 | use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; |
| 55 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 54 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; |
| 56 | use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; | 55 | use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; |
| @@ -70,14 +69,14 @@ fn teacher() -> UserId { | |||
| 70 | } | 69 | } |
| 71 | 70 | ||
| 72 | async fn a_course(db: &Database) -> CourseId { | 71 | async fn a_course(db: &Database) -> CourseId { |
| 73 | - Course::create( | 72 | + course::create( |
| 73 | + db, | ||
| 74 | &teacher(), | 74 | &teacher(), |
| 75 | CourseTitle::try_new("Fizik").unwrap(), | 75 | CourseTitle::try_new("Fizik").unwrap(), |
| 76 | CourseDescription::try_new("").unwrap(), | 76 | CourseDescription::try_new("").unwrap(), |
| 77 | CourseKind::course(), | 77 | CourseKind::course(), |
| 78 | None, | 78 | None, |
| 79 | None, | 79 | None, |
| 80 | - db, | ||
| 81 | ) | 80 | ) |
| 82 | .await | 81 | .await |
| 83 | .unwrap() | 82 | .unwrap() |
| @@ -86,12 +85,14 @@ async fn a_course(db: &Database) -> CourseId { | |||
| 86 | } | 85 | } |
| 87 | 86 | ||
| 88 | async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError> { | 87 | async fn drop_course(course: &CourseId, db: &Database) -> Result<bool, AppError> { |
| 89 | - Course::read(course, db) | 88 | + course::delete( |
| 90 | - .await | 89 | + db, |
| 91 | - .unwrap() | 90 | + course::read(db, course) |
| 92 | - .expect("the course is there") | 91 | + .await |
| 93 | - .delete(db) | 92 | + .unwrap() |
| 94 | - .await | 93 | + .expect("the course is there"), |
| 94 | + ) | ||
| 95 | + .await | ||
| 95 | } | 96 | } |
| 96 | 97 | ||
| 97 | // --- the three creates, each as one spawnable unit ------------------------- | 98 | // --- the three creates, each as one spawnable unit ------------------------- |
| @@ -324,13 +325,15 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { | |||
| 324 | .await | 325 | .await |
| 325 | .unwrap(); | 326 | .unwrap(); |
| 326 | assert!( | 327 | assert!( |
| 327 | - Course::read(&course, &db) | 328 | + course::delete( |
| 328 | - .await | 329 | + &db, |
| 329 | - .unwrap() | 330 | + course::read(&db, &course) |
| 330 | - .unwrap() | 331 | + .await |
| 331 | - .delete(&db) | 332 | + .unwrap() |
| 332 | - .await | 333 | + .unwrap() |
| 333 | - .unwrap(), | 334 | + ) |
| 335 | + .await | ||
| 336 | + .unwrap(), | ||
| 334 | "the course, and its note with it, goes" | 337 | "the course, and its note with it, goes" |
| 335 | ); | 338 | ); |
| 336 | 339 | ||
tests/regress_course_delete.rsmodified+7 -3
| @@ -27,18 +27,22 @@ use common::{ | |||
| 27 | app_and_db, create_course, create_exam, create_exam_with, create_subject, enroll, id_of, login, | 27 | app_and_db, create_course, create_exam, create_exam_with, create_subject, enroll, id_of, login, |
| 28 | login_as, me_id, send, unenroll, | 28 | login_as, me_id, send, unenroll, |
| 29 | }; | 29 | }; |
| 30 | -use hezarfen_backend::domain::course::{Course, CourseId}; | 30 | +use hezarfen_backend::db::course; |
| 31 | +use hezarfen_backend::domain::course::CourseId; | ||
| 31 | use hezarfen_backend::domain::exam::ExamId; | 32 | use hezarfen_backend::domain::exam::ExamId; |
| 32 | use hezarfen_backend::domain::exam_attempt::ExamAttempt; | 33 | use hezarfen_backend::domain::exam_attempt::ExamAttempt; |
| 33 | use serde_json::json; | 34 | use serde_json::json; |
| 34 | 35 | ||
| 35 | /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. | 36 | /// Delete `course` the way the handler would, minus its `EXAM_LOCK` lease. |
| 36 | async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { | 37 | async fn drop_course(db: &hezarfen_backend::database::Database, course: &str) { |
| 37 | - let row = Course::read(&CourseId::from_key(course), db) | 38 | + let row = course::read(db, &CourseId::from_key(course)) |
| 38 | .await | 39 | .await |
| 39 | .expect("read the course") | 40 | .expect("read the course") |
| 40 | .expect("the course exists"); | 41 | .expect("the course exists"); |
| 41 | - assert!(row.delete(db).await.expect("delete the course"), "refused"); | 42 | + assert!( |
| 43 | + course::delete(db, row).await.expect("delete the course"), | ||
| 44 | + "refused" | ||
| 45 | + ); | ||
| 42 | } | 46 | } |
| 43 | 47 | ||
| 44 | /// A bank template outlives the course it was saved out of — it is a separate, | 48 | /// A bank template outlives the course it was saved out of — it is a separate, |