π drain the whole-row save backlog
Browse files at this commit19ba18aec3eebe1ea1112e011db5bbbc1c749a31Parent: 4bea13f- fix
- π drain the whole-row save backlog
13 changed files +271 -60
- src/domain/answer_image.rs +1 -0
- src/domain/course.rs +49 -16
- src/domain/course_session.rs +17 -7
- src/domain/event.rs +18 -8
- src/domain/homework.rs +22 -13
- src/domain/homework_file.rs +1 -0
- src/domain/note.rs +12 -5
- src/domain/note_file.rs +1 -0
- src/domain/pool_question.rs +1 -0
- src/domain/solution.rs +1 -0
- src/domain/term.rs +17 -6
- src/domain/work_entry.rs +12 -5
- tests/integration.rs +119 -0
src/domain/answer_image.rsmodified+1 -0
| @@ -123,6 +123,7 @@ impl AnswerImage { | |||
| 123 | /// deterministic id makes this the whole "one drawing per student per | 123 | /// deterministic id makes this the whole "one drawing per student per |
| 124 | /// question" story. | 124 | /// question" story. |
| 125 | pub async fn upsert(self, db: &Database) -> Result<AnswerImage, AppError> { | 125 | pub async fn upsert(self, db: &Database) -> Result<AnswerImage, AppError> { |
| 126 | + // whole-row-save-ok: self is built in place from the request, never read back, and the (question, user, seq) id is deterministic β replacing the row *is* the operation | ||
| 126 | let written: Option<AnswerImage> = db.upsert(self.id.record()).content(self).await?; | 127 | let written: Option<AnswerImage> = db.upsert(self.id.record()).content(self).await?; |
| 127 | written.ok_or_else(|| AppError::Internal("failed to store answer image".into())) | 128 | written.ok_or_else(|| AppError::Internal("failed to store answer image".into())) |
| 128 | } | 129 | } |
src/domain/course.rsmodified+49 -16
| @@ -227,8 +227,14 @@ impl Course { | |||
| 227 | Ok(result.take::<Vec<Course>>(0)?) | 227 | Ok(result.take::<Vec<Course>>(0)?) |
| 228 | } | 228 | } |
| 229 | 229 | ||
| 230 | + /// Field-scoped: `teachers` is written by [`Self::assign_teacher`], | ||
| 231 | + /// [`Self::unassign_teacher`] and the demotion sweep, and nothing guards | ||
| 232 | + /// the course row across the handler's read and this write (its `TERM_LOCK` | ||
| 233 | + /// window guards the *term* it links, and the assign path takes no lock at | ||
| 234 | + /// all) β a whole-row save would revert an assignment that landed in | ||
| 235 | + /// between. | ||
| 230 | pub async fn update( | 236 | pub async fn update( |
| 231 | - mut self, | 237 | + self, |
| 232 | title: CourseTitle, | 238 | title: CourseTitle, |
| 233 | description: CourseDescription, | 239 | description: CourseDescription, |
| 234 | kind: CourseKind, | 240 | kind: CourseKind, |
| @@ -236,43 +242,70 @@ impl Course { | |||
| 236 | capacity: Option<i64>, | 242 | capacity: Option<i64>, |
| 237 | db: &Database, | 243 | db: &Database, |
| 238 | ) -> Result<Course, AppError> { | 244 | ) -> Result<Course, AppError> { |
| 239 | - self.title = title; | 245 | + let mut result = db |
| 240 | - self.description = description; | 246 | + .query( |
| 241 | - self.kind = kind; | 247 | + "UPDATE $id SET title = $title, description = $description, kind = $kind, |
| 242 | - self.term = term; | 248 | + term = $term, capacity = $capacity RETURN AFTER", |
| 243 | - self.capacity = capacity; | 249 | + ) |
| 244 | - let updated: Option<Course> = db.update(self.id.record()).content(self).await?; | 250 | + .bind(("id", self.id.record())) |
| 245 | - updated.ok_or(AppError::NotFound) | 251 | + .bind(("title", title)) |
| 252 | + .bind(("description", description)) | ||
| 253 | + .bind(("kind", kind)) | ||
| 254 | + .bind(("term", term.map(|term| term.record()))) | ||
| 255 | + .bind(("capacity", capacity)) | ||
| 256 | + .await? | ||
| 257 | + .check()?; | ||
| 258 | + result.take::<Vec<Course>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 246 | } | 259 | } |
| 247 | 260 | ||
| 248 | /// Assign `teacher` to run this course, or return the course untouched if | 261 | /// Assign `teacher` to run this course, or return the course untouched if |
| 249 | /// they already run it β assignment is idempotent, like enrollment. | 262 | /// they already run it β assignment is idempotent, like enrollment. |
| 263 | + /// Field-scoped, and the new list is folded server-side out of the *stored* | ||
| 264 | + /// one: a course PATCH awaits a term lookup between its read and its write, | ||
| 265 | + /// so a whole-row save from either side would revert the other. The | ||
| 266 | + /// `array::distinct` keeps the assignment idempotent even when two requests | ||
| 267 | + /// name the same teacher at once (the early return only sees a stale row). | ||
| 250 | pub async fn assign_teacher( | 268 | pub async fn assign_teacher( |
| 251 | - mut self, | 269 | + self, |
| 252 | teacher: &UserId, | 270 | teacher: &UserId, |
| 253 | db: &Database, | 271 | db: &Database, |
| 254 | ) -> Result<Course, AppError> { | 272 | ) -> Result<Course, AppError> { |
| 255 | if self.is_assigned(teacher) { | 273 | if self.is_assigned(teacher) { |
| 256 | return Ok(self); | 274 | return Ok(self); |
| 257 | } | 275 | } |
| 258 | - self.teachers.push(teacher.clone()); | 276 | + let mut result = db |
| 259 | - let updated: Option<Course> = db.update(self.id.record()).content(self).await?; | 277 | + .query( |
| 260 | - updated.ok_or(AppError::NotFound) | 278 | + "UPDATE $id SET teachers = array::distinct(array::append(teachers, $usr)) |
| 279 | + RETURN AFTER", | ||
| 280 | + ) | ||
| 281 | + .bind(("id", self.id.record())) | ||
| 282 | + .bind(("usr", teacher.record())) | ||
| 283 | + .await? | ||
| 284 | + .check()?; | ||
| 285 | + result.take::<Vec<Course>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 261 | } | 286 | } |
| 262 | 287 | ||
| 263 | /// Drop `teacher` from this course. `None` when they weren't assigned, so | 288 | /// Drop `teacher` from this course. `None` when they weren't assigned, so |
| 264 | /// the web layer can answer 404 instead of pretending it removed someone. | 289 | /// the web layer can answer 404 instead of pretending it removed someone. |
| 265 | pub async fn unassign_teacher( | 290 | pub async fn unassign_teacher( |
| 266 | - mut self, | 291 | + self, |
| 267 | teacher: &UserId, | 292 | teacher: &UserId, |
| 268 | db: &Database, | 293 | db: &Database, |
| 269 | ) -> Result<Option<Course>, AppError> { | 294 | ) -> Result<Option<Course>, AppError> { |
| 270 | if !self.is_assigned(teacher) { | 295 | if !self.is_assigned(teacher) { |
| 271 | return Ok(None); | 296 | return Ok(None); |
| 272 | } | 297 | } |
| 273 | - self.teachers.retain(|assigned| assigned != teacher); | 298 | + // Same field-scoped story as [`Self::assign_teacher`]; `-=` drops the |
| 274 | - let updated: Option<Course> = db.update(self.id.record()).content(self).await?; | 299 | + // one link off the stored list without touching the course's own text. |
| 275 | - updated.map(Some).ok_or(AppError::NotFound) | 300 | + let mut result = db |
| 301 | + .query("UPDATE $id SET teachers -= $usr RETURN AFTER") | ||
| 302 | + .bind(("id", self.id.record())) | ||
| 303 | + .bind(("usr", teacher.record())) | ||
| 304 | + .await? | ||
| 305 | + .check()?; | ||
| 306 | + Ok(Some( | ||
| 307 | + result.take::<Vec<Course>>(0)?.into_iter().next().ok_or(AppError::NotFound)?, | ||
| 308 | + )) | ||
| 276 | } | 309 | } |
| 277 | 310 | ||
| 278 | /// Strip `user` from every course they were assigned to β the sweep for a | 311 | /// Strip `user` from every course they were assigned to β the sweep for a |
src/domain/course_session.rsmodified+17 -7
| @@ -134,20 +134,30 @@ impl CourseSession { | |||
| 134 | Ok(result.take::<Vec<CourseSession>>(0)?) | 134 | Ok(result.take::<Vec<CourseSession>>(0)?) |
| 135 | } | 135 | } |
| 136 | 136 | ||
| 137 | + /// Field-scoped, like every other save in this codebase: the handler holds | ||
| 138 | + /// no lock across its read and this write, so a whole-row save would carry | ||
| 139 | + /// the whole stale row back over anything that landed in between. | ||
| 137 | pub async fn update( | 140 | pub async fn update( |
| 138 | - mut self, | 141 | + self, |
| 139 | teacher: UserId, | 142 | teacher: UserId, |
| 140 | topic: SessionTopic, | 143 | topic: SessionTopic, |
| 141 | starts_at: Timestamp, | 144 | starts_at: Timestamp, |
| 142 | ends_at: Option<Timestamp>, | 145 | ends_at: Option<Timestamp>, |
| 143 | db: &Database, | 146 | db: &Database, |
| 144 | ) -> Result<CourseSession, AppError> { | 147 | ) -> Result<CourseSession, AppError> { |
| 145 | - self.teacher = teacher; | 148 | + let mut result = db |
| 146 | - self.topic = topic; | 149 | + .query( |
| 147 | - self.starts_at = starts_at; | 150 | + "UPDATE $id SET teacher = $teacher, topic = $topic, |
| 148 | - self.ends_at = ends_at; | 151 | + starts_at = $starts_at, ends_at = $ends_at RETURN AFTER", |
| 149 | - let updated: Option<CourseSession> = db.update(self.id.record()).content(self).await?; | 152 | + ) |
| 150 | - updated.ok_or(AppError::NotFound) | 153 | + .bind(("id", self.id.record())) |
| 154 | + .bind(("teacher", teacher.record())) | ||
| 155 | + .bind(("topic", topic)) | ||
| 156 | + .bind(("starts_at", starts_at)) | ||
| 157 | + .bind(("ends_at", ends_at)) | ||
| 158 | + .await? | ||
| 159 | + .check()?; | ||
| 160 | + result.take::<Vec<CourseSession>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 151 | } | 161 | } |
| 152 | 162 | ||
| 153 | /// Delete the session and cascade-remove its roll-call rows. | 163 | /// Delete the session and cascade-remove its roll-call rows. |
src/domain/event.rsmodified+18 -8
| @@ -249,8 +249,11 @@ impl Event { | |||
| 249 | Ok(result.take::<Vec<Event>>(0)?) | 249 | Ok(result.take::<Vec<Event>>(0)?) |
| 250 | } | 250 | } |
| 251 | 251 | ||
| 252 | + /// Field-scoped: the handler reads the event, then awaits the clock and a | ||
| 253 | + /// course lookup before saving, holding no lock β a whole-row save would | ||
| 254 | + /// carry the stale `creator` and every other column back over the row. | ||
| 252 | pub async fn update( | 255 | pub async fn update( |
| 253 | - mut self, | 256 | + self, |
| 254 | title: EventTitle, | 257 | title: EventTitle, |
| 255 | description: EventDescription, | 258 | description: EventDescription, |
| 256 | audience: EventAudience, | 259 | audience: EventAudience, |
| @@ -258,13 +261,20 @@ impl Event { | |||
| 258 | ends_at: Option<Timestamp>, | 261 | ends_at: Option<Timestamp>, |
| 259 | db: &Database, | 262 | db: &Database, |
| 260 | ) -> Result<Event, AppError> { | 263 | ) -> Result<Event, AppError> { |
| 261 | - self.title = title; | 264 | + let mut result = db |
| 262 | - self.description = description; | 265 | + .query( |
| 263 | - self.audience = audience; | 266 | + "UPDATE $id SET title = $title, description = $description, |
| 264 | - self.starts_at = starts_at; | 267 | + audience = $audience, starts_at = $starts_at, ends_at = $ends_at RETURN AFTER", |
| 265 | - self.ends_at = ends_at; | 268 | + ) |
| 266 | - let updated: Option<Event> = db.update(self.id.record()).content(self).await?; | 269 | + .bind(("id", self.id.record())) |
| 267 | - updated.ok_or(AppError::NotFound) | 270 | + .bind(("title", title)) |
| 271 | + .bind(("description", description)) | ||
| 272 | + .bind(("audience", audience)) | ||
| 273 | + .bind(("starts_at", starts_at)) | ||
| 274 | + .bind(("ends_at", ends_at)) | ||
| 275 | + .await? | ||
| 276 | + .check()?; | ||
| 277 | + result.take::<Vec<Event>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 268 | } | 278 | } |
| 269 | 279 | ||
| 270 | /// Delete the event and cascade-remove its attendance and signup rows. | 280 | /// Delete the event and cascade-remove its attendance and signup rows. |
src/domain/homework.rsmodified+22 -13
| @@ -255,13 +255,14 @@ impl Homework { | |||
| 255 | } | 255 | } |
| 256 | 256 | ||
| 257 | /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. | 257 | /// Re-tag, re-title, re-describe, re-schedule, or re-scope the homework. |
| 258 | - /// `course`, `created_by`, and `created_at` are untouched β the write | 258 | + /// Field-scoped, so `course`, `created_by`, and `created_at` are never in |
| 259 | - /// re-sends them unchanged, which the `READONLY` schema permits (only a | 259 | + /// the write at all β no `READONLY` column is re-sent, and nothing the |
| 260 | - /// *changed* readonly value is refused). The web layer has already | 260 | + /// request didn't name can be carried back from a stale read. The web layer |
| 261 | - /// re-checked the new `due_at` against now and the new `subject` against | 261 | + /// has already re-checked the new `due_at` against now and the new |
| 262 | - /// the course, and refused a narrowing that would orphan a submission. | 262 | + /// `subject` against the course, and refused a narrowing that would orphan |
| 263 | + /// a submission. | ||
| 263 | pub async fn update( | 264 | pub async fn update( |
| 264 | - mut self, | 265 | + self, |
| 265 | subject: &SubjectId, | 266 | subject: &SubjectId, |
| 266 | title: HomeworkTitle, | 267 | title: HomeworkTitle, |
| 267 | description: Option<HomeworkDescription>, | 268 | description: Option<HomeworkDescription>, |
| @@ -269,13 +270,21 @@ impl Homework { | |||
| 269 | assigned: Option<Vec<UserId>>, | 270 | assigned: Option<Vec<UserId>>, |
| 270 | db: &Database, | 271 | db: &Database, |
| 271 | ) -> Result<Homework, AppError> { | 272 | ) -> Result<Homework, AppError> { |
| 272 | - self.subject = subject.clone(); | 273 | + let assigned = assigned.map(|users| users.iter().map(UserId::record).collect::<Vec<_>>()); |
| 273 | - self.title = title; | 274 | + let mut result = db |
| 274 | - self.description = description; | 275 | + .query( |
| 275 | - self.due_at = due_at; | 276 | + "UPDATE $id SET subject = $subject, title = $title, description = $description, |
| 276 | - self.assigned = assigned; | 277 | + due_at = $due_at, assigned = $assigned RETURN AFTER", |
| 277 | - let updated: Option<Homework> = db.update(self.id.record()).content(self).await?; | 278 | + ) |
| 278 | - updated.ok_or(AppError::NotFound) | 279 | + .bind(("id", self.id.record())) |
| 280 | + .bind(("subject", subject.record())) | ||
| 281 | + .bind(("title", title)) | ||
| 282 | + .bind(("description", description)) | ||
| 283 | + .bind(("due_at", due_at)) | ||
| 284 | + .bind(("assigned", assigned)) | ||
| 285 | + .await? | ||
| 286 | + .check()?; | ||
| 287 | + result.take::<Vec<Homework>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 279 | } | 288 | } |
| 280 | 289 | ||
| 281 | /// Delete the homework and cascade its submissions, their files, and its | 290 | /// Delete the homework and cascade its submissions, their files, and its |
src/domain/homework_file.rsmodified+1 -0
| @@ -131,6 +131,7 @@ impl HomeworkFile { | |||
| 131 | "the submission already holds the maximum of 10 files β delete one first", | 131 | "the submission already holds the maximum of 10 files β delete one first", |
| 132 | )); | 132 | )); |
| 133 | } | 133 | } |
| 134 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | ||
| 134 | let created: Option<HomeworkFile> = db.create(self.id.record()).content(self).await?; | 135 | let created: Option<HomeworkFile> = db.create(self.id.record()).content(self).await?; |
| 135 | created.ok_or_else(|| AppError::Internal("failed to create homework file".into())) | 136 | created.ok_or_else(|| AppError::Internal("failed to create homework file".into())) |
| 136 | } | 137 | } |
src/domain/note.rsmodified+12 -5
| @@ -115,16 +115,23 @@ impl Note { | |||
| 115 | Ok(result.take::<Vec<Note>>(0)?) | 115 | Ok(result.take::<Vec<Note>>(0)?) |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | + /// Field-scoped, mirroring [`crate::domain::subject::Subject::update`]: no | ||
| 119 | + /// lock spans the handler's read and this write, so only the two columns | ||
| 120 | + /// the request actually carries are written. | ||
| 118 | pub async fn update( | 121 | pub async fn update( |
| 119 | - mut self, | 122 | + self, |
| 120 | title: NoteTitle, | 123 | title: NoteTitle, |
| 121 | content: NoteContent, | 124 | content: NoteContent, |
| 122 | db: &Database, | 125 | db: &Database, |
| 123 | ) -> Result<Note, AppError> { | 126 | ) -> Result<Note, AppError> { |
| 124 | - self.title = title; | 127 | + let mut result = db |
| 125 | - self.content = content; | 128 | + .query("UPDATE $id SET title = $title, content = $content RETURN AFTER") |
| 126 | - let updated: Option<Note> = db.update(self.id.record()).content(self).await?; | 129 | + .bind(("id", self.id.record())) |
| 127 | - updated.ok_or(AppError::NotFound) | 130 | + .bind(("title", title)) |
| 131 | + .bind(("content", content)) | ||
| 132 | + .await? | ||
| 133 | + .check()?; | ||
| 134 | + result.take::<Vec<Note>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 128 | } | 135 | } |
| 129 | 136 | ||
| 130 | /// Delete the note and cascade-remove its attachment rows. Blob files on | 137 | /// Delete the note and cascade-remove its attachment rows. Blob files on |
src/domain/note_file.rsmodified+1 -0
| @@ -168,6 +168,7 @@ impl NoteFile { | |||
| 168 | "the note already holds the maximum of 10 files β delete one first", | 168 | "the note already holds the maximum of 10 files β delete one first", |
| 169 | )); | 169 | )); |
| 170 | } | 170 | } |
| 171 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | ||
| 171 | let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?; | 172 | let created: Option<NoteFile> = db.create(self.id.record()).content(self).await?; |
| 172 | created.ok_or_else(|| AppError::Internal("failed to create note file".into())) | 173 | created.ok_or_else(|| AppError::Internal("failed to create note file".into())) |
| 173 | } | 174 | } |
src/domain/pool_question.rsmodified+1 -0
| @@ -158,6 +158,7 @@ impl PoolQuestion { | |||
| 158 | } | 158 | } |
| 159 | 159 | ||
| 160 | pub async fn insert(self, db: &Database) -> Result<PoolQuestion, AppError> { | 160 | pub async fn insert(self, db: &Database) -> Result<PoolQuestion, AppError> { |
| 161 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | ||
| 161 | let created: Option<PoolQuestion> = db.create(self.id.record()).content(self).await?; | 162 | let created: Option<PoolQuestion> = db.create(self.id.record()).content(self).await?; |
| 162 | created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) | 163 | created.ok_or_else(|| AppError::Internal("failed to create pool question".into())) |
| 163 | } | 164 | } |
src/domain/solution.rsmodified+1 -0
| @@ -127,6 +127,7 @@ impl Solution { | |||
| 127 | } | 127 | } |
| 128 | 128 | ||
| 129 | pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { | 129 | pub async fn insert(self, db: &Database) -> Result<Solution, AppError> { |
| 130 | + // whole-row-save-ok: create of a fresh ULID row built in place by `new` β there is no prior row to clobber | ||
| 130 | let created: Option<Solution> = db.create(self.id.record()).content(self).await?; | 131 | let created: Option<Solution> = db.create(self.id.record()).content(self).await?; |
| 131 | created.ok_or_else(|| AppError::Internal("failed to create solution".into())) | 132 | created.ok_or_else(|| AppError::Internal("failed to create solution".into())) |
| 132 | } | 133 | } |
src/domain/term.rsmodified+17 -6
| @@ -121,18 +121,29 @@ impl Term { | |||
| 121 | Ok(result.take::<Vec<Term>>(0)?) | 121 | Ok(result.take::<Vec<Term>>(0)?) |
| 122 | } | 122 | } |
| 123 | 123 | ||
| 124 | + /// Field-scoped: the handler reads the term, then awaits validation before | ||
| 125 | + /// saving with no lock held ([`TERM_LOCK`] guards the delete's link check, | ||
| 126 | + /// not this), so the save states its own three columns instead of replaying | ||
| 127 | + /// a whole stale row. | ||
| 124 | pub async fn update( | 128 | pub async fn update( |
| 125 | - mut self, | 129 | + self, |
| 126 | name: TermName, | 130 | name: TermName, |
| 127 | starts_at: Timestamp, | 131 | starts_at: Timestamp, |
| 128 | ends_at: Timestamp, | 132 | ends_at: Timestamp, |
| 129 | db: &Database, | 133 | db: &Database, |
| 130 | ) -> Result<Term, AppError> { | 134 | ) -> Result<Term, AppError> { |
| 131 | - self.name = name; | 135 | + let mut result = db |
| 132 | - self.starts_at = starts_at; | 136 | + .query( |
| 133 | - self.ends_at = ends_at; | 137 | + "UPDATE $id SET name = $name, starts_at = $starts_at, |
| 134 | - let updated: Option<Term> = db.update(self.id.record()).content(self).await?; | 138 | + ends_at = $ends_at RETURN AFTER", |
| 135 | - updated.ok_or(AppError::NotFound) | 139 | + ) |
| 140 | + .bind(("id", self.id.record())) | ||
| 141 | + .bind(("name", name)) | ||
| 142 | + .bind(("starts_at", starts_at)) | ||
| 143 | + .bind(("ends_at", ends_at)) | ||
| 144 | + .await? | ||
| 145 | + .check()?; | ||
| 146 | + result.take::<Vec<Term>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 136 | } | 147 | } |
| 137 | 148 | ||
| 138 | /// True iff any course still links to this term β the delete guard. | 149 | /// True iff any course still links to this term β the delete guard. |
src/domain/work_entry.rsmodified+12 -5
| @@ -157,16 +157,23 @@ impl WorkEntry { | |||
| 157 | 157 | ||
| 158 | /// Persist corrected instants (manager fix-ups on closed entries; the web | 158 | /// Persist corrected instants (manager fix-ups on closed entries; the web |
| 159 | /// layer validates ordering and rejects open entries). | 159 | /// layer validates ordering and rejects open entries). |
| 160 | + /// Field-scoped: the stint's `user` is never part of a correction, so it is | ||
| 161 | + /// left out of the write rather than replayed from a struct the handler | ||
| 162 | + /// read before its validation awaits. | ||
| 160 | pub async fn update( | 163 | pub async fn update( |
| 161 | - mut self, | 164 | + self, |
| 162 | check_in: Timestamp, | 165 | check_in: Timestamp, |
| 163 | check_out: Timestamp, | 166 | check_out: Timestamp, |
| 164 | db: &Database, | 167 | db: &Database, |
| 165 | ) -> Result<WorkEntry, AppError> { | 168 | ) -> Result<WorkEntry, AppError> { |
| 166 | - self.check_in = check_in; | 169 | + let mut result = db |
| 167 | - self.check_out = Some(check_out); | 170 | + .query("UPDATE $id SET check_in = $check_in, check_out = $check_out RETURN AFTER") |
| 168 | - let updated: Option<WorkEntry> = db.update(self.id.record()).content(self).await?; | 171 | + .bind(("id", self.id.record())) |
| 169 | - updated.ok_or(AppError::NotFound) | 172 | + .bind(("check_in", check_in)) |
| 173 | + .bind(("check_out", check_out)) | ||
| 174 | + .await? | ||
| 175 | + .check()?; | ||
| 176 | + result.take::<Vec<WorkEntry>>(0)?.into_iter().next().ok_or(AppError::NotFound) | ||
| 170 | } | 177 | } |
| 171 | 178 | ||
| 172 | pub async fn remove(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> { | 179 | pub async fn remove(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> { |
tests/integration.rsmodified+119 -0
| @@ -18877,3 +18877,122 @@ async fn refreshing_a_question_recopies_its_template() { | |||
| 18877 | .await; | 18877 | .await; |
| 18878 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); | 18878 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{}", res.body); |
| 18879 | } | 18879 | } |
| 18880 | + | ||
| 18881 | +/// A course PATCH is a field-scoped write. The handler reads the course, then | ||
| 18882 | +/// awaits a term lookup (and its `TERM_LOCK`) before saving, holding nothing | ||
| 18883 | +/// over the course row itself β so a manager's teacher assignment can land in | ||
| 18884 | +/// that window. A whole-row save from the stale struct would silently revert | ||
| 18885 | +/// the staffing. Driven at the domain level: HTTP offers no way to interleave | ||
| 18886 | +/// inside the handler. | ||
| 18887 | +#[tokio::test] | ||
| 18888 | +async fn a_course_patch_does_not_clobber_a_concurrent_teacher_assignment() { | ||
| 18889 | + use hezarfen_backend::domain::course::{ | ||
| 18890 | + Course, CourseDescription, CourseId, CourseKind, CourseTitle, | ||
| 18891 | + }; | ||
| 18892 | + | ||
| 18893 | + let (app, db) = app_and_db().await; | ||
| 18894 | + let owner = login_as(&app, &db, "cclob_o", "teacher").await; | ||
| 18895 | + let helper = login_as(&app, &db, "cclob_h", "teacher").await; | ||
| 18896 | + let boss = login_as(&app, &db, "cclob_m", "manager").await; | ||
| 18897 | + let helper_id = me_id(&app, &helper).await; | ||
| 18898 | + let course = create_course(&app, &owner, "cclob_c").await; | ||
| 18899 | + | ||
| 18900 | + // The handler's read, then the assignment lands mid-window. | ||
| 18901 | + let stale = Course::read(&CourseId::from_key(&course), &db) | ||
| 18902 | + .await | ||
| 18903 | + .unwrap() | ||
| 18904 | + .expect("course exists"); | ||
| 18905 | + let res = send( | ||
| 18906 | + &app, | ||
| 18907 | + "POST", | ||
| 18908 | + &format!("/courses/{course}/teachers"), | ||
| 18909 | + Some(&boss), | ||
| 18910 | + Some(json!({ "user_id": helper_id })), | ||
| 18911 | + ) | ||
| 18912 | + .await; | ||
| 18913 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 18914 | + | ||
| 18915 | + let updated = stale | ||
| 18916 | + .update( | ||
| 18917 | + CourseTitle::try_new("renamed").unwrap(), | ||
| 18918 | + CourseDescription::try_new("").unwrap(), | ||
| 18919 | + CourseKind::course(), | ||
| 18920 | + None, | ||
| 18921 | + None, | ||
| 18922 | + &db, | ||
| 18923 | + ) | ||
| 18924 | + .await | ||
| 18925 | + .expect("update written"); | ||
| 18926 | + assert_eq!(updated.get_teachers().len(), 1, "the assignment was reverted"); | ||
| 18927 | + | ||
| 18928 | + // The rename landed and the assigned teacher stayed assigned. | ||
| 18929 | + let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await; | ||
| 18930 | + assert_eq!(res.body["title"], "renamed"); | ||
| 18931 | + assert_eq!(res.body["teachers"][0]["username"], "cclob_h"); | ||
| 18932 | +} | ||
| 18933 | + | ||
| 18934 | +/// The mirror image: staffing writes only `teachers`. `assign_teacher` reads | ||
| 18935 | +/// the course, then awaits the target user's row (a role check) before saving, | ||
| 18936 | +/// so a course PATCH can land in between β and a whole-row save would revert | ||
| 18937 | +/// the rename. `unassign_teacher` gets the same field-scoped treatment. | ||
| 18938 | +#[tokio::test] | ||
| 18939 | +async fn staffing_a_course_does_not_clobber_a_concurrent_edit() { | ||
| 18940 | + use hezarfen_backend::domain::course::{Course, CourseId}; | ||
| 18941 | + use hezarfen_backend::domain::user::UserId; | ||
| 18942 | + | ||
| 18943 | + let (app, db) = app_and_db().await; | ||
| 18944 | + let owner = login_as(&app, &db, "cstaff_o", "teacher").await; | ||
| 18945 | + let helper = login_as(&app, &db, "cstaff_h", "teacher").await; | ||
| 18946 | + let helper_id = me_id(&app, &helper).await; | ||
| 18947 | + let course = create_course(&app, &owner, "cstaff_c").await; | ||
| 18948 | + | ||
| 18949 | + // The handler's read, then someone else's edit lands mid-window. | ||
| 18950 | + let stale = Course::read(&CourseId::from_key(&course), &db) | ||
| 18951 | + .await | ||
| 18952 | + .unwrap() | ||
| 18953 | + .expect("course exists"); | ||
| 18954 | + let res = send( | ||
| 18955 | + &app, | ||
| 18956 | + "PATCH", | ||
| 18957 | + &format!("/courses/{course}"), | ||
| 18958 | + Some(&owner), | ||
| 18959 | + Some(json!({ "title": "edited by someone else", "capacity": 9 })), | ||
| 18960 | + ) | ||
| 18961 | + .await; | ||
| 18962 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 18963 | + | ||
| 18964 | + let assigned = stale | ||
| 18965 | + .assign_teacher(&UserId::from_key(&helper_id), &db) | ||
| 18966 | + .await | ||
| 18967 | + .expect("assignment written"); | ||
| 18968 | + assert_eq!(assigned.get_title().as_str(), "edited by someone else"); | ||
| 18969 | + assert_eq!(assigned.get_capacity(), Some(9)); | ||
| 18970 | + assert_eq!(assigned.get_teachers().len(), 1); | ||
| 18971 | + | ||
| 18972 | + // Unassigning from a struct read before another edit is just as safe. | ||
| 18973 | + let stale = Course::read(&CourseId::from_key(&course), &db) | ||
| 18974 | + .await | ||
| 18975 | + .unwrap() | ||
| 18976 | + .expect("course exists"); | ||
| 18977 | + let res = send( | ||
| 18978 | + &app, | ||
| 18979 | + "PATCH", | ||
| 18980 | + &format!("/courses/{course}"), | ||
| 18981 | + Some(&owner), | ||
| 18982 | + Some(json!({ "title": "edited again" })), | ||
| 18983 | + ) | ||
| 18984 | + .await; | ||
| 18985 | + assert_eq!(res.status, StatusCode::OK, "{}", res.body); | ||
| 18986 | + let dropped = stale | ||
| 18987 | + .unassign_teacher(&UserId::from_key(&helper_id), &db) | ||
| 18988 | + .await | ||
| 18989 | + .expect("unassignment written") | ||
| 18990 | + .expect("teacher was assigned"); | ||
| 18991 | + assert_eq!(dropped.get_title().as_str(), "edited again"); | ||
| 18992 | + assert!(dropped.get_teachers().is_empty()); | ||
| 18993 | + | ||
| 18994 | + let res = send(&app, "GET", &format!("/courses/{course}"), Some(&owner), None).await; | ||
| 18995 | + assert_eq!(res.body["title"], "edited again"); | ||
| 18996 | + assert_eq!(res.body["capacity"], 9); | ||
| 18997 | + assert_eq!(res.body["teachers"].as_array().unwrap().len(), 0); | ||
| 18998 | +} | ||