Merge branch 'layer-split/course_session'
Browse files at this commit11 changed files +334 -237
- src/db/course_session.rs +169 -0
- src/db/mod.rs +1 -0
- src/domain/course_session.rs +11 -159
- src/domain/event.rs +2 -2
- src/domain/session_attendance.rs +19 -11
- src/service/course_session.rs +96 -0
- src/service/mod.rs +1 -0
- src/web/courses.rs +17 -15
- src/web/sessions.rs +7 -35
- tests/regress_attendance.rs +3 -2
- tests/regress_course_child_orphans.rs +8 -13
src/db/course_session.rsadded+169 -0
| @@ -0,0 +1,169 @@ | |||
| 1 | +//! The `course_session` table: reads, a course's timetable listing, the | ||
| 2 | +//! request-scoped field update, and the delete that sweeps roll-call rows in | ||
| 3 | +//! one transaction. Creation writes the course row through | ||
| 4 | +//! [`cap::touch_and_create`] so a lesson can never outlive its course; the | ||
| 5 | +//! web-facing doors and the teacher-resolution rule live in | ||
| 6 | +//! [`crate::service::course_session`]. | ||
| 7 | + | ||
| 8 | +use surrealdb::types::SurrealValue; | ||
| 9 | + | ||
| 10 | +use crate::constant::ENROLLMENT_COUNT_FIELD; | ||
| 11 | +use crate::database::{Database, transaction_with_retry}; | ||
| 12 | +use crate::db::cap; | ||
| 13 | +use crate::db::field_update::FieldUpdate; | ||
| 14 | +use crate::db::page::PagedList; | ||
| 15 | +use crate::domain::course::CourseId; | ||
| 16 | +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; | ||
| 17 | +use crate::domain::timestamp::{Timestamp, range_error}; | ||
| 18 | +use crate::domain::user::UserId; | ||
| 19 | +use crate::error::AppError; | ||
| 20 | + | ||
| 21 | +pub async fn create( | ||
| 22 | + db: &Database, | ||
| 23 | + course: &CourseId, | ||
| 24 | + teacher: &UserId, | ||
| 25 | + topic: SessionTopic, | ||
| 26 | + starts_at: Timestamp, | ||
| 27 | + ends_at: Option<Timestamp>, | ||
| 28 | +) -> Result<CourseSession, AppError> { | ||
| 29 | + let session = CourseSession { | ||
| 30 | + id: CourseSessionId::generate(), | ||
| 31 | + course: course.clone(), | ||
| 32 | + teacher: teacher.clone(), | ||
| 33 | + topic, | ||
| 34 | + starts_at, | ||
| 35 | + ends_at, | ||
| 36 | + }; | ||
| 37 | + // The course row is *written* (bumped and put back), not read, so this | ||
| 38 | + // collides with `Course::delete`'s cascade: a lesson that outlives its | ||
| 39 | + // course 404s through `session_with_course` forever — unreadable, | ||
| 40 | + // unpatchable, undeletable. See [`cap::touch_and_create`]. | ||
| 41 | + cap::touch_and_create( | ||
| 42 | + &course.record(), | ||
| 43 | + ENROLLMENT_COUNT_FIELD, | ||
| 44 | + &session.id.record(), | ||
| 45 | + &session, | ||
| 46 | + db, | ||
| 47 | + ) | ||
| 48 | + .await? | ||
| 49 | + .ok_or(AppError::NotFound) | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> { | ||
| 53 | + Ok(db.select(id.record()).await?) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +/// A course's sessions, most recent lesson first. Ordered by `starts_at` | ||
| 57 | +/// (not id): a timetable is read by when the lesson happens, not by when | ||
| 58 | +/// the row was created. | ||
| 59 | +pub async fn list_for_course( | ||
| 60 | + db: &Database, | ||
| 61 | + course: &CourseId, | ||
| 62 | + limit: Option<i64>, | ||
| 63 | + offset: i64, | ||
| 64 | +) -> Result<(Vec<CourseSession>, i64), AppError> { | ||
| 65 | + PagedList::new( | ||
| 66 | + "course_session WHERE course = $course", | ||
| 67 | + "ORDER BY starts_at DESC, id DESC", | ||
| 68 | + ) | ||
| 69 | + .bind("course", course.record()) | ||
| 70 | + .run(limit, offset, db) | ||
| 71 | + .await | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +/// Request-scoped: the handler holds nothing across its read and this | ||
| 75 | +/// write — the range check rides in the `WHERE` — so a field the request | ||
| 76 | +/// omitted (`None`) is not written at all. Re-sending the snapshot's value | ||
| 77 | +/// instead would revert a concurrent PATCH of that field — scoping the | ||
| 78 | +/// `SET` alone does not stop that, the values have to come from the | ||
| 79 | +/// request. `ends_at` is nullable, so it takes the outer/inner | ||
| 80 | +/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear. | ||
| 81 | +pub async fn update( | ||
| 82 | + db: &Database, | ||
| 83 | + session: CourseSession, | ||
| 84 | + teacher: Option<UserId>, | ||
| 85 | + topic: Option<SessionTopic>, | ||
| 86 | + starts_at: Option<Timestamp>, | ||
| 87 | + ends_at: Option<Option<Timestamp>>, | ||
| 88 | +) -> Result<CourseSession, AppError> { | ||
| 89 | + FieldUpdate::new(session.id.record()) | ||
| 90 | + .set("teacher", teacher.map(|teacher| teacher.record())) | ||
| 91 | + .set("topic", topic) | ||
| 92 | + .set("starts_at", starts_at) | ||
| 93 | + .set("ends_at", ends_at) | ||
| 94 | + .ordered("starts_at", "ends_at", range_error()) | ||
| 95 | + .run::<CourseSession>(db) | ||
| 96 | + .await | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +/// Delete the session and cascade-remove its roll-call rows, in one | ||
| 100 | +/// transaction: as two unbatched queries a failure between them stranded | ||
| 101 | +/// roll-call rows on a session that was already gone. The other half of | ||
| 102 | +/// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], | ||
| 103 | +/// which proves the session still exists inside its own write — a | ||
| 104 | +/// transaction here cannot stop a mark that commits *after* this one. | ||
| 105 | +pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> { | ||
| 106 | + let (mut result, mut errors) = transaction_with_retry( | ||
| 107 | + db, | ||
| 108 | + "BEGIN TRANSACTION; | ||
| 109 | + DELETE session_attendance WHERE session = $s; | ||
| 110 | + LET $before = (DELETE $s RETURN BEFORE); | ||
| 111 | + RETURN $before; | ||
| 112 | + COMMIT TRANSACTION;", | ||
| 113 | + &[("s".into(), session.id.record().into_value())], | ||
| 114 | + // No THROW of its own — an unconditional cascade, so the only | ||
| 115 | + // error worth telling apart is a lost round (see | ||
| 116 | + // [`crate::domain::exam::Exam::delete`]). | ||
| 117 | + &[], | ||
| 118 | + ) | ||
| 119 | + .await?; | ||
| 120 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 121 | + return Err(error.into()); | ||
| 122 | + } | ||
| 123 | + // Read through the trailing `RETURN`, never a hand-counted slot. | ||
| 124 | + let slot = result.num_statements().saturating_sub(2); | ||
| 125 | + let deleted: Option<CourseSession> = | ||
| 126 | + result.take::<Vec<CourseSession>>(slot)?.into_iter().next(); | ||
| 127 | + deleted.ok_or(AppError::NotFound) | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +#[cfg(test)] | ||
| 131 | +mod tests { | ||
| 132 | + use super::*; | ||
| 133 | + use crate::constant::COURSE_SESSION_TABLE; | ||
| 134 | + | ||
| 135 | + /// A lesson must not outlive the course it is a lesson of: an orphan 404s | ||
| 136 | + /// forever through `session_with_course` — unreadable, unpatchable, | ||
| 137 | + /// undeletable. | ||
| 138 | + /// | ||
| 139 | + /// [`create`] therefore *writes* the course row rather than | ||
| 140 | + /// reading it ([`cap::touch_and_create`]); the harness and the window it | ||
| 141 | + /// races in are documented on | ||
| 142 | + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. | ||
| 143 | + /// Mutation-tested: with the bare `db.create` this shipped with, all four | ||
| 144 | + /// rounds orphan. | ||
| 145 | + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 146 | + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 147 | + async fn a_session_never_outlives_its_course() { | ||
| 148 | + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { | ||
| 149 | + tokio::spawn(async move { | ||
| 150 | + create( | ||
| 151 | + &db, | ||
| 152 | + &course, | ||
| 153 | + &UserId::generate(), | ||
| 154 | + SessionTopic::try_new("limits").unwrap(), | ||
| 155 | + Timestamp::from_millis(1), | ||
| 156 | + None, | ||
| 157 | + ) | ||
| 158 | + .await | ||
| 159 | + .map(|_| ()) | ||
| 160 | + }) | ||
| 161 | + } | ||
| 162 | + crate::db::course::assert_no_child_outlives_a_course_delete( | ||
| 163 | + "session_orphan_race", | ||
| 164 | + COURSE_SESSION_TABLE, | ||
| 165 | + make, | ||
| 166 | + ) | ||
| 167 | + .await; | ||
| 168 | + } | ||
| 169 | +} | ||
src/db/mod.rsmodified+1 -0
| @@ -5,6 +5,7 @@ pub mod appointment_slot; | |||
| 5 | pub mod cap; | 5 | pub mod cap; |
| 6 | pub mod class_blueprint; | 6 | pub mod class_blueprint; |
| 7 | pub mod course; | 7 | pub mod course; |
| 8 | +pub mod course_session; | ||
| 8 | pub mod exam_attempt; | 9 | pub mod exam_attempt; |
| 9 | pub mod field_update; | 10 | pub mod field_update; |
| 10 | pub mod note; | 11 | pub mod note; |
src/domain/course_session.rsmodified+11 -159
| @@ -1,15 +1,11 @@ | |||
| 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 1 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 2 | 2 | ||
| 3 | -use crate::constant::{COURSE_SESSION_TABLE, ENROLLMENT_COUNT_FIELD, MAX_SESSION_TOPIC_LEN}; | 3 | +use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; |
| 4 | -use crate::database::{Database, transaction_with_retry}; | ||
| 5 | -use crate::db::cap; | ||
| 6 | use crate::domain::course::CourseId; | 4 | use crate::domain::course::CourseId; |
| 7 | -use crate::db::field_update::FieldUpdate; | ||
| 8 | use crate::domain::monotonic_id::next_ulid; | 5 | use crate::domain::monotonic_id::next_ulid; |
| 9 | -use crate::db::page::PagedList; | 6 | +use crate::domain::timestamp::Timestamp; |
| 10 | -use crate::domain::timestamp::{Timestamp, range_error}; | ||
| 11 | use crate::domain::user::UserId; | 7 | use crate::domain::user::UserId; |
| 12 | -use crate::error::{AppError, ValidationError}; | 8 | +use crate::error::ValidationError; |
| 13 | use crate::validate::validate_optional; | 9 | use crate::validate::validate_optional; |
| 14 | 10 | ||
| 15 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] | 11 | #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] |
| @@ -59,14 +55,15 @@ impl SessionTopic { | |||
| 59 | /// so its roster is the course's enrollment plus the assigned teacher. | 55 | /// so its roster is the course's enrollment plus the assigned teacher. |
| 60 | #[derive(Debug, Clone, SurrealValue)] | 56 | #[derive(Debug, Clone, SurrealValue)] |
| 61 | pub struct CourseSession { | 57 | pub struct CourseSession { |
| 62 | - id: CourseSessionId, | 58 | + pub(crate) id: CourseSessionId, |
| 63 | - course: CourseId, | 59 | + pub(crate) course: CourseId, |
| 64 | /// Who teaches this session. Must hold the `teacher` role or higher — | 60 | /// Who teaches this session. Must hold the `teacher` role or higher — |
| 65 | - /// enforced at the web layer, where the target user row is at hand. | 61 | + /// enforced by [`crate::service::course_session::resolve_session_teacher`], |
| 66 | - teacher: UserId, | 62 | + /// where the target user row is at hand. |
| 67 | - topic: SessionTopic, | 63 | + pub(crate) teacher: UserId, |
| 68 | - starts_at: Timestamp, | 64 | + pub(crate) topic: SessionTopic, |
| 69 | - ends_at: Option<Timestamp>, | 65 | + pub(crate) starts_at: Timestamp, |
| 66 | + pub(crate) ends_at: Option<Timestamp>, | ||
| 70 | } | 67 | } |
| 71 | 68 | ||
| 72 | impl CourseSession { | 69 | impl CourseSession { |
| @@ -97,157 +94,12 @@ impl CourseSession { | |||
| 97 | pub fn is_teacher(&self, user: &UserId) -> bool { | 94 | pub fn is_teacher(&self, user: &UserId) -> bool { |
| 98 | &self.teacher == user | 95 | &self.teacher == user |
| 99 | } | 96 | } |
| 100 | - | ||
| 101 | - pub async fn create( | ||
| 102 | - course: &CourseId, | ||
| 103 | - teacher: &UserId, | ||
| 104 | - topic: SessionTopic, | ||
| 105 | - starts_at: Timestamp, | ||
| 106 | - ends_at: Option<Timestamp>, | ||
| 107 | - db: &Database, | ||
| 108 | - ) -> Result<CourseSession, AppError> { | ||
| 109 | - let session = CourseSession { | ||
| 110 | - id: CourseSessionId::generate(), | ||
| 111 | - course: course.clone(), | ||
| 112 | - teacher: teacher.clone(), | ||
| 113 | - topic, | ||
| 114 | - starts_at, | ||
| 115 | - ends_at, | ||
| 116 | - }; | ||
| 117 | - // The course row is *written* (bumped and put back), not read, so this | ||
| 118 | - // collides with `Course::delete`'s cascade: a lesson that outlives its | ||
| 119 | - // course 404s through `session_with_course` forever — unreadable, | ||
| 120 | - // unpatchable, undeletable. See [`cap::touch_and_create`]. | ||
| 121 | - cap::touch_and_create( | ||
| 122 | - &course.record(), | ||
| 123 | - ENROLLMENT_COUNT_FIELD, | ||
| 124 | - &session.id.record(), | ||
| 125 | - &session, | ||
| 126 | - db, | ||
| 127 | - ) | ||
| 128 | - .await? | ||
| 129 | - .ok_or(AppError::NotFound) | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - pub async fn read( | ||
| 133 | - id: &CourseSessionId, | ||
| 134 | - db: &Database, | ||
| 135 | - ) -> Result<Option<CourseSession>, AppError> { | ||
| 136 | - Ok(db.select(id.record()).await?) | ||
| 137 | - } | ||
| 138 | - | ||
| 139 | - /// A course's sessions, most recent lesson first. Ordered by `starts_at` | ||
| 140 | - /// (not id): a timetable is read by when the lesson happens, not by when | ||
| 141 | - /// the row was created. | ||
| 142 | - pub async fn list_for_course( | ||
| 143 | - course: &CourseId, | ||
| 144 | - limit: Option<i64>, | ||
| 145 | - offset: i64, | ||
| 146 | - db: &Database, | ||
| 147 | - ) -> Result<(Vec<CourseSession>, i64), AppError> { | ||
| 148 | - PagedList::new( | ||
| 149 | - "course_session WHERE course = $course", | ||
| 150 | - "ORDER BY starts_at DESC, id DESC", | ||
| 151 | - ) | ||
| 152 | - .bind("course", course.record()) | ||
| 153 | - .run(limit, offset, db) | ||
| 154 | - .await | ||
| 155 | - } | ||
| 156 | - | ||
| 157 | - /// Request-scoped: the handler holds nothing across its read and this | ||
| 158 | - /// write — the range check rides in the `WHERE` — so a field the request | ||
| 159 | - /// omitted (`None`) is not written at all. Re-sending the snapshot's value | ||
| 160 | - /// instead would revert a concurrent PATCH of that field — scoping the | ||
| 161 | - /// `SET` alone does not stop that, the values have to come from the | ||
| 162 | - /// request. `ends_at` is nullable, so it takes the outer/inner | ||
| 163 | - /// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear. | ||
| 164 | - pub async fn update( | ||
| 165 | - self, | ||
| 166 | - teacher: Option<UserId>, | ||
| 167 | - topic: Option<SessionTopic>, | ||
| 168 | - starts_at: Option<Timestamp>, | ||
| 169 | - ends_at: Option<Option<Timestamp>>, | ||
| 170 | - db: &Database, | ||
| 171 | - ) -> Result<CourseSession, AppError> { | ||
| 172 | - FieldUpdate::new(self.id.record()) | ||
| 173 | - .set("teacher", teacher.map(|teacher| teacher.record())) | ||
| 174 | - .set("topic", topic) | ||
| 175 | - .set("starts_at", starts_at) | ||
| 176 | - .set("ends_at", ends_at) | ||
| 177 | - .ordered("starts_at", "ends_at", range_error()) | ||
| 178 | - .run::<CourseSession>(db) | ||
| 179 | - .await | ||
| 180 | - } | ||
| 181 | - | ||
| 182 | - /// Delete the session and cascade-remove its roll-call rows, in one | ||
| 183 | - /// transaction: as two unbatched queries a failure between them stranded | ||
| 184 | - /// roll-call rows on a session that was already gone. The other half of | ||
| 185 | - /// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], | ||
| 186 | - /// which proves the session still exists inside its own write — a | ||
| 187 | - /// transaction here cannot stop a mark that commits *after* this one. | ||
| 188 | - pub async fn delete(self, db: &Database) -> Result<CourseSession, AppError> { | ||
| 189 | - let (mut result, mut errors) = transaction_with_retry( | ||
| 190 | - db, | ||
| 191 | - "BEGIN TRANSACTION; | ||
| 192 | - DELETE session_attendance WHERE session = $s; | ||
| 193 | - LET $before = (DELETE $s RETURN BEFORE); | ||
| 194 | - RETURN $before; | ||
| 195 | - COMMIT TRANSACTION;", | ||
| 196 | - &[("s".into(), self.id.record().into_value())], | ||
| 197 | - // No THROW of its own — an unconditional cascade, so the only | ||
| 198 | - // error worth telling apart is a lost round (see | ||
| 199 | - // [`crate::domain::exam::Exam::delete`]). | ||
| 200 | - &[], | ||
| 201 | - ) | ||
| 202 | - .await?; | ||
| 203 | - if let Some(error) = errors.drain().map(|(_, error)| error).next() { | ||
| 204 | - return Err(error.into()); | ||
| 205 | - } | ||
| 206 | - // Read through the trailing `RETURN`, never a hand-counted slot. | ||
| 207 | - let slot = result.num_statements().saturating_sub(2); | ||
| 208 | - let deleted: Option<CourseSession> = | ||
| 209 | - result.take::<Vec<CourseSession>>(slot)?.into_iter().next(); | ||
| 210 | - deleted.ok_or(AppError::NotFound) | ||
| 211 | - } | ||
| 212 | } | 97 | } |
| 213 | 98 | ||
| 214 | #[cfg(test)] | 99 | #[cfg(test)] |
| 215 | mod tests { | 100 | mod tests { |
| 216 | use super::*; | 101 | use super::*; |
| 217 | 102 | ||
| 218 | - /// A lesson must not outlive the course it is a lesson of: an orphan 404s | ||
| 219 | - /// forever through `session_with_course` — unreadable, unpatchable, | ||
| 220 | - /// undeletable. | ||
| 221 | - /// | ||
| 222 | - /// [`CourseSession::create`] therefore *writes* the course row rather than | ||
| 223 | - /// reading it ([`cap::touch_and_create`]); the harness and the window it | ||
| 224 | - /// races in are documented on | ||
| 225 | - /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. | ||
| 226 | - /// Mutation-tested: with the bare `db.create` this shipped with, all four | ||
| 227 | - /// rounds orphan. | ||
| 228 | - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] | ||
| 229 | - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] | ||
| 230 | - async fn a_session_never_outlives_its_course() { | ||
| 231 | - fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle<Result<(), AppError>> { | ||
| 232 | - tokio::spawn(async move { | ||
| 233 | - CourseSession::create( | ||
| 234 | - &course, | ||
| 235 | - &UserId::generate(), | ||
| 236 | - SessionTopic::try_new("limits").unwrap(), | ||
| 237 | - Timestamp::from_millis(1), | ||
| 238 | - None, | ||
| 239 | - &db, | ||
| 240 | - ) | ||
| 241 | - .await | ||
| 242 | - .map(|_| ()) | ||
| 243 | - }) | ||
| 244 | - } | ||
| 245 | - crate::db::course::assert_no_child_outlives_a_course_delete("session_orphan_race", | ||
| 246 | - COURSE_SESSION_TABLE, | ||
| 247 | - make,) | ||
| 248 | - .await; | ||
| 249 | - } | ||
| 250 | - | ||
| 251 | #[tokio::test] | 103 | #[tokio::test] |
| 252 | async fn topic_is_optional_but_bounded() { | 104 | async fn topic_is_optional_but_bounded() { |
| 253 | assert!(SessionTopic::try_new("").is_ok()); | 105 | assert!(SessionTopic::try_new("").is_ok()); |
src/domain/event.rsmodified+2 -2
| @@ -4,11 +4,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; | |||
| 4 | 4 | ||
| 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; | 5 | use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; |
| 6 | use crate::database::{Database, transaction_with_retry}; | 6 | use crate::database::{Database, transaction_with_retry}; |
| 7 | +use crate::db::field_update::FieldUpdate; | ||
| 7 | use crate::domain::class_group::ClassGroupId; | 8 | use crate::domain::class_group::ClassGroupId; |
| 8 | use crate::domain::class_member::{ClassMember, ClassMemberId}; | 9 | use crate::domain::class_member::{ClassMember, ClassMemberId}; |
| 9 | use crate::domain::course::CourseId; | 10 | use crate::domain::course::CourseId; |
| 10 | use crate::domain::enrollment::Enrollment; | 11 | use crate::domain::enrollment::Enrollment; |
| 11 | -use crate::db::field_update::FieldUpdate; | ||
| 12 | use crate::domain::monotonic_id::next_ulid; | 12 | use crate::domain::monotonic_id::next_ulid; |
| 13 | use crate::domain::registration::Registration; | 13 | use crate::domain::registration::Registration; |
| 14 | use crate::domain::role::Role; | 14 | use crate::domain::role::Role; |
| @@ -317,7 +317,7 @@ impl Event { | |||
| 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. |
| 318 | /// | 318 | /// |
| 319 | /// Re-sent while the store answers "conflict, retry", the way | 319 | /// Re-sent while the store answers "conflict, retry", the way |
| 320 | - /// [`crate::domain::course_session::CourseSession::delete`] is: now that | 320 | + /// [`crate::db::course_session::delete`] is: now that |
| 321 | /// [`crate::domain::attendance::Attendance::mark`] writes the event row to | 321 | /// [`crate::domain::attendance::Attendance::mark`] writes the event row to |
| 322 | /// prove it exists, a mark landing in this window really does contend for | 322 | /// prove it exists, a mark landing in this window really does contend for |
| 323 | /// it — and without the retry the *delete* is the side that loses, turning | 323 | /// it — and without the retry the *delete* is the side that loses, turning |
src/domain/session_attendance.rsmodified+19 -11
| @@ -5,10 +5,10 @@ use crate::constant::{ | |||
| 5 | SESSION_ATTENDANCE_TABLE, | 5 | SESSION_ATTENDANCE_TABLE, |
| 6 | }; | 6 | }; |
| 7 | use crate::database::{Database, transaction_with_retry}; | 7 | use crate::database::{Database, transaction_with_retry}; |
| 8 | +use crate::db::page::PagedList; | ||
| 8 | use crate::domain::attendance::AttendanceStatus; | 9 | use crate::domain::attendance::AttendanceStatus; |
| 9 | use crate::domain::course::CourseId; | 10 | use crate::domain::course::CourseId; |
| 10 | use crate::domain::course_session::{CourseSession, CourseSessionId}; | 11 | use crate::domain::course_session::{CourseSession, CourseSessionId}; |
| 11 | -use crate::db::page::PagedList; | ||
| 12 | use crate::domain::timestamp::Timestamp; | 12 | use crate::domain::timestamp::Timestamp; |
| 13 | use crate::domain::user::UserId; | 13 | use crate::domain::user::UserId; |
| 14 | use crate::error::AppError; | 14 | use crate::error::AppError; |
| @@ -99,7 +99,7 @@ impl SessionAttendance { | |||
| 99 | /// single atomic UPSERT — concurrent marks converge on the one row. | 99 | /// single atomic UPSERT — concurrent marks converge on the one row. |
| 100 | /// | 100 | /// |
| 101 | /// The "session still exists" gate rides in the same transaction as the | 101 | /// The "session still exists" gate rides in the same transaction as the |
| 102 | - /// mark, the mirror of the cascade in [`CourseSession::delete`]: the | 102 | + /// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the |
| 103 | /// caller's pre-flight read sits four round trips in front of this write, | 103 | /// caller's pre-flight read sits four round trips in front of this write, |
| 104 | /// so a delete landing in that gap used to leave a roll-call row on a | 104 | /// so a delete landing in that gap used to leave a roll-call row on a |
| 105 | /// session that was gone — and that row was *unremovable*, its only delete | 105 | /// session that was gone — and that row was *unremovable*, its only delete |
| @@ -151,7 +151,7 @@ impl SessionAttendance { | |||
| 151 | /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees | 151 | /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees |
| 152 | /// the stamp and credits nothing. It counts lessons that actually | 152 | /// the stamp and credits nothing. It counts lessons that actually |
| 153 | /// happened — scheduling one and cancelling it earns nothing, which is | 153 | /// happened — scheduling one and cancelling it earns nothing, which is |
| 154 | - /// why the credit does not live in `CourseSession::create`. Two | 154 | + /// why the credit does not live in `crate::db::course_session::create`. Two |
| 155 | /// simultaneous first marks both write the lesson row, so the store's own | 155 | /// simultaneous first marks both write the lesson row, so the store's own |
| 156 | /// conflict detection (and `transaction_with_retry` behind it) is what | 156 | /// conflict detection (and `transaction_with_retry` behind it) is what |
| 157 | /// keeps the stamp from being set twice. | 157 | /// keeps the stamp from being set twice. |
| @@ -295,7 +295,7 @@ impl SessionAttendance { | |||
| 295 | /// delete's own transaction — the other direction of the delta in | 295 | /// delete's own transaction — the other direction of the delta in |
| 296 | /// [`SessionAttendance::mark`], so a row that never existed and a row that | 296 | /// [`SessionAttendance::mark`], so a row that never existed and a row that |
| 297 | /// was withdrawn leave the same number behind. Only *this* route decrements: | 297 | /// was withdrawn leave the same number behind. Only *this* route decrements: |
| 298 | - /// [`CourseSession::delete`]'s cascade sweeps the rows with a `DELETE` of | 298 | + /// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of |
| 299 | /// its own and never comes through here, which is the ruling | 299 | /// its own and never comes through here, which is the ruling |
| 300 | /// `exam_sat_total` already carries — deleting the lesson does not un-attend | 300 | /// `exam_sat_total` already carries — deleting the lesson does not un-attend |
| 301 | /// it. `lessons_held_total` is never given back either: the lesson was | 301 | /// it. `lessons_held_total` is never given back either: the lesson was |
| @@ -384,13 +384,13 @@ mod tests { | |||
| 384 | } | 384 | } |
| 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 | + crate::db::course_session::create( |
| 388 | + db, | ||
| 388 | &crate::db::course::a_test_course(db).await, | 389 | &crate::db::course::a_test_course(db).await, |
| 389 | teacher, | 390 | teacher, |
| 390 | SessionTopic::try_new("limits").unwrap(), | 391 | SessionTopic::try_new("limits").unwrap(), |
| 391 | Timestamp::from_millis(starts_at), | 392 | Timestamp::from_millis(starts_at), |
| 392 | None, | 393 | None, |
| 393 | - db, | ||
| 394 | ) | 394 | ) |
| 395 | .await | 395 | .await |
| 396 | .unwrap() | 396 | .unwrap() |
| @@ -664,7 +664,9 @@ mod tests { | |||
| 664 | .await | 664 | .await |
| 665 | .unwrap(); | 665 | .unwrap(); |
| 666 | 666 | ||
| 667 | - session.delete(&db).await.unwrap(); | 667 | + crate::db::course_session::delete(&db, session) |
| 668 | + .await | ||
| 669 | + .unwrap(); | ||
| 668 | assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); | 670 | assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); |
| 669 | assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); | 671 | assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); |
| 670 | } | 672 | } |
| @@ -678,7 +680,9 @@ mod tests { | |||
| 678 | let student = a_student("s", &db).await; | 680 | let student = a_student("s", &db).await; |
| 679 | let session = a_session(&teacher, &db).await; | 681 | let session = a_session(&teacher, &db).await; |
| 680 | let ghost = session.clone(); | 682 | let ghost = session.clone(); |
| 681 | - session.delete(&db).await.unwrap(); | 683 | + crate::db::course_session::delete(&db, session) |
| 684 | + .await | ||
| 685 | + .unwrap(); | ||
| 682 | 686 | ||
| 683 | assert!(matches!( | 687 | assert!(matches!( |
| 684 | SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await, | 688 | SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await, |
| @@ -690,7 +694,7 @@ mod tests { | |||
| 690 | 694 | ||
| 691 | /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` | 695 | /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` |
| 692 | /// on `course_session` fires inside the delete's own transaction, and | 696 | /// on `course_session` fires inside the delete's own transaction, and |
| 693 | - /// [`CourseSession::delete`] sweeps its children before removing the row, | 697 | + /// [`crate::db::course_session::delete`] sweeps its children before removing the row, |
| 694 | /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is | 698 | /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is |
| 695 | /// written after the sweep has run, and used to commit straight past it. | 699 | /// written after the sweep has run, and used to commit straight past it. |
| 696 | /// | 700 | /// |
| @@ -735,7 +739,7 @@ mod tests { | |||
| 735 | let ghost = session.clone(); | 739 | let ghost = session.clone(); |
| 736 | let drop_it = { | 740 | let drop_it = { |
| 737 | let db = db.clone(); | 741 | let db = db.clone(); |
| 738 | - tokio::spawn(async move { session.delete(&db).await }) | 742 | + tokio::spawn(async move { crate::db::course_session::delete(&db, session).await }) |
| 739 | }; | 743 | }; |
| 740 | // The mark starts inside the held window: the sweep has run and the | 744 | // The mark starts inside the held window: the sweep has run and the |
| 741 | // session row is gone but uncommitted — which is exactly what a | 745 | // session row is gone but uncommitted — which is exactly what a |
| @@ -756,7 +760,11 @@ mod tests { | |||
| 756 | ); | 760 | ); |
| 757 | 761 | ||
| 758 | // Stored state is the whole verdict; a return value is not evidence. | 762 | // Stored state is the whole verdict; a return value is not evidence. |
| 759 | - if CourseSession::read(&id, &db).await.unwrap().is_none() { | 763 | + if crate::db::course_session::read(&db, &id) |
| 764 | + .await | ||
| 765 | + .unwrap() | ||
| 766 | + .is_none() | ||
| 767 | + { | ||
| 760 | swept += 1; | 768 | swept += 1; |
| 761 | orphans += SessionAttendance::list_for_session(&id, None, 0, &db) | 769 | orphans += SessionAttendance::list_for_session(&id, None, 0, &db) |
| 762 | .await | 770 | .await |
src/service/course_session.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +//! Course-session workflows: who may teach a lesson (the teacher-resolution | ||
| 2 | +//! gate), and the doors the web layer takes for every session read and | ||
| 3 | +//! write. The queries live in [`crate::db::course_session`]; the | ||
| 4 | +//! timetable's wire shaping and the course-rights checks stay in the web | ||
| 5 | +//! layer. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::course_session; | ||
| 9 | +use crate::domain::course::CourseId; | ||
| 10 | +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; | ||
| 11 | +use crate::domain::role::Role; | ||
| 12 | +use crate::domain::timestamp::Timestamp; | ||
| 13 | +use crate::domain::user::{User, UserId}; | ||
| 14 | +use crate::error::{AppError, ValidationError}; | ||
| 15 | + | ||
| 16 | +/// Resolve who a session's teacher should be: the caller when `teacher_id` is | ||
| 17 | +/// omitted (or names them), otherwise the referenced user — who must exist and | ||
| 18 | +/// hold the `teacher` role or higher (a student cannot teach a lesson). | ||
| 19 | +/// | ||
| 20 | +/// Scheduling hands the named person the session's teaching seat, so the | ||
| 21 | +/// floor is checked on the *live* role here rather than at the web layer: | ||
| 22 | +/// every future roll-call right derives from this column, and a stale | ||
| 23 | +/// `teacher_id` in a request body must fail with the same 400 no matter | ||
| 24 | +/// which route named it. | ||
| 25 | +pub async fn resolve_session_teacher( | ||
| 26 | + teacher_id: Option<&str>, | ||
| 27 | + caller: &User, | ||
| 28 | + db: &Database, | ||
| 29 | +) -> Result<User, AppError> { | ||
| 30 | + let target = match teacher_id { | ||
| 31 | + None => return Ok(caller.clone()), | ||
| 32 | + Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), | ||
| 33 | + Some(key) => UserId::from_key(key), | ||
| 34 | + }; | ||
| 35 | + let Some(user) = User::read(&target, db).await? else { | ||
| 36 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 37 | + field: "teacher_id", | ||
| 38 | + reason: "session teacher does not exist", | ||
| 39 | + })); | ||
| 40 | + }; | ||
| 41 | + if !user.get_role().at_least(Role::Teacher) { | ||
| 42 | + return Err(AppError::Validation(ValidationError::Invalid { | ||
| 43 | + field: "teacher_id", | ||
| 44 | + reason: "session teacher must hold the teacher role or higher", | ||
| 45 | + })); | ||
| 46 | + } | ||
| 47 | + Ok(user) | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Schedule a lesson on `course`. The write bumps the course row in the same | ||
| 51 | +/// transaction (`cap::touch_and_create`), so a lesson can never outlive its | ||
| 52 | +/// course — a create racing the course delete refuses instead of orphaning. | ||
| 53 | +pub async fn create( | ||
| 54 | + db: &Database, | ||
| 55 | + course: &CourseId, | ||
| 56 | + teacher: &UserId, | ||
| 57 | + topic: SessionTopic, | ||
| 58 | + starts_at: Timestamp, | ||
| 59 | + ends_at: Option<Timestamp>, | ||
| 60 | +) -> Result<CourseSession, AppError> { | ||
| 61 | + course_session::create(db, course, teacher, topic, starts_at, ends_at).await | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +pub async fn read(db: &Database, id: &CourseSessionId) -> Result<Option<CourseSession>, AppError> { | ||
| 65 | + course_session::read(db, id).await | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// A course's sessions, most recent lesson first — the timetable read. | ||
| 69 | +pub async fn list_for_course( | ||
| 70 | + db: &Database, | ||
| 71 | + course: &CourseId, | ||
| 72 | + limit: Option<i64>, | ||
| 73 | + offset: i64, | ||
| 74 | +) -> Result<(Vec<CourseSession>, i64), AppError> { | ||
| 75 | + course_session::list_for_course(db, course, limit, offset).await | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Only what the request carried is written: an omitted field (`None`) is | ||
| 79 | +/// not stored at all, so a concurrent PATCH of that field survives. The | ||
| 80 | +/// range consistency re-check rides in the UPDATE's own `WHERE`, so the | ||
| 81 | +/// caller holds nothing across its read and this write. | ||
| 82 | +pub async fn update( | ||
| 83 | + db: &Database, | ||
| 84 | + session: CourseSession, | ||
| 85 | + teacher: Option<UserId>, | ||
| 86 | + topic: Option<SessionTopic>, | ||
| 87 | + starts_at: Option<Timestamp>, | ||
| 88 | + ends_at: Option<Option<Timestamp>>, | ||
| 89 | +) -> Result<CourseSession, AppError> { | ||
| 90 | + course_session::update(db, session, teacher, topic, starts_at, ends_at).await | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +/// Delete the session and sweep its roll-call rows in one transaction. | ||
| 94 | +pub async fn delete(db: &Database, session: CourseSession) -> Result<CourseSession, AppError> { | ||
| 95 | + course_session::delete(db, session).await | ||
| 96 | +} | ||
src/service/mod.rsmodified+1 -0
| @@ -5,6 +5,7 @@ pub mod appointment; | |||
| 5 | pub mod appointment_slot; | 5 | pub mod appointment_slot; |
| 6 | pub mod class_blueprint; | 6 | pub mod class_blueprint; |
| 7 | pub mod course; | 7 | pub mod course; |
| 8 | +pub mod course_session; | ||
| 8 | pub mod exam_attempt; | 9 | pub mod exam_attempt; |
| 9 | pub mod note; | 10 | pub mod note; |
| 10 | pub mod payment_ledger; | 11 | pub mod payment_ledger; |
src/web/courses.rsmodified+17 -15
| @@ -11,7 +11,7 @@ use utoipa_axum::routes; | |||
| 11 | 11 | ||
| 12 | use crate::database::Database; | 12 | use crate::database::Database; |
| 13 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; | 13 | use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 14 | -use crate::domain::course_session::{CourseSession, SessionTopic}; | 14 | +use crate::domain::course_session::SessionTopic; |
| 15 | use crate::domain::enrollment::Enrollment; | 15 | use crate::domain::enrollment::Enrollment; |
| 16 | use crate::domain::exam::{ | 16 | use crate::domain::exam::{ |
| 17 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, | 17 | Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, |
| @@ -27,7 +27,6 @@ use crate::service; | |||
| 27 | use crate::state::AppState; | 27 | use crate::state::AppState; |
| 28 | 28 | ||
| 29 | use super::homework::{description_or_none, resolve_assigned}; | 29 | use super::homework::{description_or_none, resolve_assigned}; |
| 30 | -use super::sessions::resolve_session_teacher; | ||
| 31 | use super::subjects::subject_in_course; | 30 | use super::subjects::subject_in_course; |
| 32 | use super::terms::resolve_term; | 31 | use super::terms::resolve_term; |
| 33 | use super::{ | 32 | use super::{ |
| @@ -265,7 +264,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co | |||
| 265 | } else { | 264 | } else { |
| 266 | Vec::new() | 265 | Vec::new() |
| 267 | }; | 266 | }; |
| 268 | - for course in service::course::list_enrolled(db, user.get_id(), None, 0).await?.0 { | 267 | + for course in service::course::list_enrolled(db, user.get_id(), None, 0) |
| 268 | + .await? | ||
| 269 | + .0 | ||
| 270 | + { | ||
| 269 | if !courses | 271 | if !courses |
| 270 | .iter() | 272 | .iter() |
| 271 | .any(|known| known.get_id() == course.get_id()) | 273 | .any(|known| known.get_id() == course.get_id()) |
| @@ -401,7 +403,8 @@ async fn my_courses( | |||
| 401 | Query(page): Query<PageParams>, | 403 | Query(page): Query<PageParams>, |
| 402 | ) -> Result<Json<Page<CourseResponse>>, AppError> { | 404 | ) -> Result<Json<Page<CourseResponse>>, AppError> { |
| 403 | let (limit, offset) = page.resolve()?; | 405 | let (limit, offset) = page.resolve()?; |
| 404 | - let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; | 406 | + let (courses, total) = |
| 407 | + service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; | ||
| 405 | let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; | 408 | let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; |
| 406 | let items = courses | 409 | let items = courses |
| 407 | .iter() | 410 | .iter() |
| @@ -1227,20 +1230,22 @@ async fn create_session_in_course( | |||
| 1227 | service::course::require_open(&st.db, &course).await?; | 1230 | service::course::require_open(&st.db, &course).await?; |
| 1228 | 1231 | ||
| 1229 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; | 1232 | let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; |
| 1230 | - let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; | 1233 | + let teacher = |
| 1234 | + service::course_session::resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db) | ||
| 1235 | + .await?; | ||
| 1231 | let starts_at = Timestamp::from_millis(req.starts_at); | 1236 | let starts_at = Timestamp::from_millis(req.starts_at); |
| 1232 | let ends_at = req.ends_at.map(Timestamp::from_millis); | 1237 | let ends_at = req.ends_at.map(Timestamp::from_millis); |
| 1233 | check_not_past("starts_at", Some(starts_at))?; | 1238 | check_not_past("starts_at", Some(starts_at))?; |
| 1234 | check_not_past("ends_at", ends_at)?; | 1239 | check_not_past("ends_at", ends_at)?; |
| 1235 | check_time_range(Some(starts_at), ends_at)?; | 1240 | check_time_range(Some(starts_at), ends_at)?; |
| 1236 | 1241 | ||
| 1237 | - let session = CourseSession::create( | 1242 | + let session = service::course_session::create( |
| 1243 | + &st.db, | ||
| 1238 | course.get_id(), | 1244 | course.get_id(), |
| 1239 | teacher.get_id(), | 1245 | teacher.get_id(), |
| 1240 | topic, | 1246 | topic, |
| 1241 | starts_at, | 1247 | starts_at, |
| 1242 | ends_at, | 1248 | ends_at, |
| 1243 | - &st.db, | ||
| 1244 | ) | 1249 | ) |
| 1245 | .await?; | 1250 | .await?; |
| 1246 | let people = PersonRef::map_of(&[&teacher]); | 1251 | let people = PersonRef::map_of(&[&teacher]); |
| @@ -1285,7 +1290,7 @@ async fn list_course_sessions( | |||
| 1285 | )); | 1290 | )); |
| 1286 | } | 1291 | } |
| 1287 | let (rows, total) = | 1292 | let (rows, total) = |
| 1288 | - CourseSession::list_for_course(course.get_id(), limit, offset, &st.db).await?; | 1293 | + service::course_session::list_for_course(&st.db, course.get_id(), limit, offset).await?; |
| 1289 | // Join teachers onto the page alone — the lookup shrinks with the window. | 1294 | // Join teachers onto the page alone — the lookup shrinks with the window. |
| 1290 | let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?; | 1295 | let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?; |
| 1291 | let items = rows | 1296 | let items = rows |
| @@ -1359,13 +1364,10 @@ mod tests { | |||
| 1359 | let db = init_mem().await.unwrap(); | 1364 | let db = init_mem().await.unwrap(); |
| 1360 | let creator = user("creator", Role::Teacher, &db).await; | 1365 | let creator = user("creator", Role::Teacher, &db).await; |
| 1361 | let assigned = user("assigned", Role::Teacher, &db).await; | 1366 | let assigned = user("assigned", Role::Teacher, &db).await; |
| 1362 | - let course = service::course::assign_teacher( | 1367 | + let course = |
| 1363 | - &db, | 1368 | + service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id()) |
| 1364 | - &course(&creator, &db).await, | 1369 | + .await |
| 1365 | - assigned.get_id(), | 1370 | + .unwrap(); |
| 1366 | - ) | ||
| 1367 | - .await | ||
| 1368 | - .unwrap(); | ||
| 1369 | // Still teacher+: untouched by the floor. | 1371 | // Still teacher+: untouched by the floor. |
| 1370 | assert!(can_manage_course(&course, &assigned)); | 1372 | assert!(can_manage_course(&course, &assigned)); |
| 1371 | // ...but never an owner, assigned or not. | 1373 | // ...but never an owner, assigned or not. |
src/web/sessions.rsmodified+7 -35
| @@ -88,38 +88,10 @@ impl SessionAttendanceResponse { | |||
| 88 | } | 88 | } |
| 89 | } | 89 | } |
| 90 | 90 | ||
| 91 | -/// Resolve who a session's teacher should be: the caller when `teacher_id` is | ||
| 92 | -/// omitted (or names them), otherwise the referenced user — who must exist and | ||
| 93 | -/// hold the `teacher` role or higher (a student cannot teach a lesson). | ||
| 94 | -pub(crate) async fn resolve_session_teacher( | ||
| 95 | - teacher_id: Option<&str>, | ||
| 96 | - caller: &User, | ||
| 97 | - db: &Database, | ||
| 98 | -) -> Result<User, AppError> { | ||
| 99 | - let target = match teacher_id { | ||
| 100 | - None => return Ok(caller.clone()), | ||
| 101 | - Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), | ||
| 102 | - Some(key) => UserId::from_key(key), | ||
| 103 | - }; | ||
| 104 | - let Some(user) = User::read(&target, db).await? else { | ||
| 105 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 106 | - field: "teacher_id", | ||
| 107 | - reason: "session teacher does not exist", | ||
| 108 | - })); | ||
| 109 | - }; | ||
| 110 | - if !user.get_role().at_least(Role::Teacher) { | ||
| 111 | - return Err(AppError::Validation(ValidationError::Invalid { | ||
| 112 | - field: "teacher_id", | ||
| 113 | - reason: "session teacher must hold the teacher role or higher", | ||
| 114 | - })); | ||
| 115 | - } | ||
| 116 | - Ok(user) | ||
| 117 | -} | ||
| 118 | - | ||
| 119 | /// Load a session and its course together; a session whose course is gone | 91 | /// Load a session and its course together; a session whose course is gone |
| 120 | /// cannot happen given the delete cascade, so both misses are plain 404s. | 92 | /// cannot happen given the delete cascade, so both misses are plain 404s. |
| 121 | async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, Course), AppError> { | 93 | async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, Course), AppError> { |
| 122 | - let session = CourseSession::read(&CourseSessionId::from_key(id), db) | 94 | + let session = service::course_session::read(db, &CourseSessionId::from_key(id)) |
| 123 | .await? | 95 | .await? |
| 124 | .ok_or(AppError::NotFound)?; | 96 | .ok_or(AppError::NotFound)?; |
| 125 | let course = crate::service::course::read(db, session.get_course()) | 97 | let course = crate::service::course::read(db, session.get_course()) |
| @@ -228,7 +200,7 @@ async fn update_session( | |||
| 228 | .transpose()?; | 200 | .transpose()?; |
| 229 | let teacher = match req.teacher_id { | 201 | let teacher = match req.teacher_id { |
| 230 | Some(ref key) => Some( | 202 | Some(ref key) => Some( |
| 231 | - resolve_session_teacher(Some(key), &user, &st.db) | 203 | + service::course_session::resolve_session_teacher(Some(key), &user, &st.db) |
| 232 | .await? | 204 | .await? |
| 233 | .get_id() | 205 | .get_id() |
| 234 | .clone(), | 206 | .clone(), |
| @@ -237,15 +209,15 @@ async fn update_session( | |||
| 237 | }; | 209 | }; |
| 238 | // The end this request left out is only *read* for the range check — it is | 210 | // The end this request left out is only *read* for the range check — it is |
| 239 | // never written back, so a concurrent move of it survives. Pre-flight only: | 211 | // never written back, so a concurrent move of it survives. Pre-flight only: |
| 240 | - // `CourseSession::update` re-makes this check in the UPDATE's `WHERE`. | 212 | + // the write's own `WHERE` re-makes this check (the db layer's `update`). |
| 241 | check_time_range( | 213 | check_time_range( |
| 242 | Some(starts_at.unwrap_or_else(|| session.get_starts_at())), | 214 | Some(starts_at.unwrap_or_else(|| session.get_starts_at())), |
| 243 | ends_at.unwrap_or_else(|| session.get_ends_at()), | 215 | ends_at.unwrap_or_else(|| session.get_ends_at()), |
| 244 | )?; | 216 | )?; |
| 245 | 217 | ||
| 246 | - let updated = session | 218 | + let updated = |
| 247 | - .update(teacher, topic, starts_at, ends_at, &st.db) | 219 | + service::course_session::update(&st.db, session, teacher, topic, starts_at, ends_at) |
| 248 | - .await?; | 220 | + .await?; |
| 249 | let people = person_map([updated.get_teacher().clone()], &st.db).await?; | 221 | let people = person_map([updated.get_teacher().clone()], &st.db).await?; |
| 250 | Ok(Json(SessionResponse::new(&updated, &people))) | 222 | Ok(Json(SessionResponse::new(&updated, &people))) |
| 251 | } | 223 | } |
| @@ -278,7 +250,7 @@ async fn delete_session( | |||
| 278 | )); | 250 | )); |
| 279 | } | 251 | } |
| 280 | crate::service::course::require_open(&st.db, &course).await?; | 252 | crate::service::course::require_open(&st.db, &course).await?; |
| 281 | - session.delete(&st.db).await?; | 253 | + service::course_session::delete(&st.db, session).await?; |
| 282 | Ok(StatusCode::NO_CONTENT) | 254 | Ok(StatusCode::NO_CONTENT) |
| 283 | } | 255 | } |
| 284 | 256 | ||
tests/regress_attendance.rsmodified+3 -2
| @@ -13,9 +13,10 @@ mod common; | |||
| 13 | use axum::http::StatusCode; | 13 | use axum::http::StatusCode; |
| 14 | use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; | 14 | use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; |
| 15 | use hezarfen_backend::database::Database; | 15 | use hezarfen_backend::database::Database; |
| 16 | +use hezarfen_backend::db::course_session; | ||
| 16 | use hezarfen_backend::db::settings; | 17 | use hezarfen_backend::db::settings; |
| 17 | use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; | 18 | use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; |
| 18 | -use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; | 19 | +use hezarfen_backend::domain::course_session::CourseSessionId; |
| 19 | use hezarfen_backend::domain::event::EventId; | 20 | use hezarfen_backend::domain::event::EventId; |
| 20 | use hezarfen_backend::domain::session_attendance::SessionAttendance; | 21 | use hezarfen_backend::domain::session_attendance::SessionAttendance; |
| 21 | use hezarfen_backend::domain::timestamp::Timestamp; | 22 | use hezarfen_backend::domain::timestamp::Timestamp; |
| @@ -199,7 +200,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { | |||
| 199 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); | 200 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 200 | 201 | ||
| 201 | // The snapshot the racing request is holding, taken while the session lives. | 202 | // The snapshot the racing request is holding, taken while the session lives. |
| 202 | - let snapshot = CourseSession::read(&CourseSessionId::from_key(&session), &db) | 203 | + let snapshot = course_session::read(&db, &CourseSessionId::from_key(&session)) |
| 203 | .await | 204 | .await |
| 204 | .unwrap() | 205 | .unwrap() |
| 205 | .expect("session exists"); | 206 | .expect("session exists"); |
tests/regress_course_child_orphans.rsmodified+8 -13
| @@ -32,7 +32,7 @@ | |||
| 32 | //! The **race** half drives the real interleaving and lives in-crate, one pin | 32 | //! The **race** half drives the real interleaving and lives in-crate, one pin |
| 33 | //! per child beside the create it pins — | 33 | //! per child beside the create it pins — |
| 34 | //! `domain::exam::tests::an_exam_never_outlives_its_course`, | 34 | //! `domain::exam::tests::an_exam_never_outlives_its_course`, |
| 35 | -//! `domain::course_session::tests::a_session_never_outlives_its_course`, | 35 | +//! `db::course_session::tests::a_session_never_outlives_its_course`, |
| 36 | //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the | 36 | //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the |
| 37 | //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`. | 37 | //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`. |
| 38 | //! It is `#[ignore]`d and needs a real server, because the subject there *is* | 38 | //! It is `#[ignore]`d and needs a real server, because the subject there *is* |
| @@ -49,10 +49,11 @@ 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::db::course; | 51 | use hezarfen_backend::db::course; |
| 52 | +use hezarfen_backend::db::course_session as db_course_session; | ||
| 52 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; | 53 | use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; |
| 53 | use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; | 54 | use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; |
| 54 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; | 55 | use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; |
| 55 | -use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; | 56 | +use hezarfen_backend::domain::course_session::SessionTopic; |
| 56 | use hezarfen_backend::domain::exam::{ | 57 | use hezarfen_backend::domain::exam::{ |
| 57 | Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, | 58 | Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, |
| 58 | }; | 59 | }; |
| @@ -122,13 +123,13 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> | |||
| 122 | 123 | ||
| 123 | fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> { | 124 | fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> { |
| 124 | tokio::spawn(async move { | 125 | tokio::spawn(async move { |
| 125 | - CourseSession::create( | 126 | + db_course_session::create( |
| 127 | + &db, | ||
| 126 | &course, | 128 | &course, |
| 127 | &teacher(), | 129 | &teacher(), |
| 128 | SessionTopic::try_new("limits").unwrap(), | 130 | SessionTopic::try_new("limits").unwrap(), |
| 129 | Timestamp::from_millis(1), | 131 | Timestamp::from_millis(1), |
| 130 | None, | 132 | None, |
| 131 | - &db, | ||
| 132 | ) | 133 | ) |
| 133 | .await | 134 | .await |
| 134 | .map(|_| ()) | 135 | .map(|_| ()) |
| @@ -325,15 +326,9 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { | |||
| 325 | .await | 326 | .await |
| 326 | .unwrap(); | 327 | .unwrap(); |
| 327 | assert!( | 328 | assert!( |
| 328 | - course::delete( | 329 | + course::delete(&db, course::read(&db, &course).await.unwrap().unwrap()) |
| 329 | - &db, | 330 | + .await |
| 330 | - course::read(&db, &course) | 331 | + .unwrap(), |
| 331 | - .await | ||
| 332 | - .unwrap() | ||
| 333 | - .unwrap() | ||
| 334 | - ) | ||
| 335 | - .await | ||
| 336 | - .unwrap(), | ||
| 337 | "the course, and its note with it, goes" | 332 | "the course, and its note with it, goes" |
| 338 | ); | 333 | ); |
| 339 | 334 | ||