diff --git a/src/db/course_session.rs b/src/db/course_session.rs new file mode 100644 index 0000000..f91f138 --- /dev/null +++ b/src/db/course_session.rs @@ -0,0 +1,169 @@ +//! The `course_session` table: reads, a course's timetable listing, the +//! request-scoped field update, and the delete that sweeps roll-call rows in +//! one transaction. Creation writes the course row through +//! [`cap::touch_and_create`] so a lesson can never outlive its course; the +//! web-facing doors and the teacher-resolution rule live in +//! [`crate::service::course_session`]. + +use surrealdb::types::SurrealValue; + +use crate::constant::ENROLLMENT_COUNT_FIELD; +use crate::database::{Database, transaction_with_retry}; +use crate::db::cap; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::course::CourseId; +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; +use crate::domain::timestamp::{Timestamp, range_error}; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn create( + db: &Database, + course: &CourseId, + teacher: &UserId, + topic: SessionTopic, + starts_at: Timestamp, + ends_at: Option, +) -> Result { + let session = CourseSession { + id: CourseSessionId::generate(), + course: course.clone(), + teacher: teacher.clone(), + topic, + starts_at, + ends_at, + }; + // The course row is *written* (bumped and put back), not read, so this + // collides with `Course::delete`'s cascade: a lesson that outlives its + // course 404s through `session_with_course` forever — unreadable, + // unpatchable, undeletable. See [`cap::touch_and_create`]. + cap::touch_and_create( + &course.record(), + ENROLLMENT_COUNT_FIELD, + &session.id.record(), + &session, + db, + ) + .await? + .ok_or(AppError::NotFound) +} + +pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// A course's sessions, most recent lesson first. Ordered by `starts_at` +/// (not id): a timetable is read by when the lesson happens, not by when +/// the row was created. +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "course_session WHERE course = $course", + "ORDER BY starts_at DESC, id DESC", + ) + .bind("course", course.record()) + .run(limit, offset, db) + .await +} + +/// Request-scoped: the handler holds nothing across its read and this +/// write — the range check rides in the `WHERE` — so a field the request +/// omitted (`None`) is not written at all. Re-sending the snapshot's value +/// instead would revert a concurrent PATCH of that field — scoping the +/// `SET` alone does not stop that, the values have to come from the +/// request. `ends_at` is nullable, so it takes the outer/inner +/// `Option>`: `None` = omitted (keep), `Some(None)` = clear. +pub async fn update( + db: &Database, + session: CourseSession, + teacher: Option, + topic: Option, + starts_at: Option, + ends_at: Option>, +) -> Result { + FieldUpdate::new(session.id.record()) + .set("teacher", teacher.map(|teacher| teacher.record())) + .set("topic", topic) + .set("starts_at", starts_at) + .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) + .run::(db) + .await +} + +/// Delete the session and cascade-remove its roll-call rows, in one +/// transaction: as two unbatched queries a failure between them stranded +/// roll-call rows on a session that was already gone. The other half of +/// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], +/// which proves the session still exists inside its own write — a +/// transaction here cannot stop a mark that commits *after* this one. +pub async fn delete(db: &Database, session: CourseSession) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE session_attendance WHERE session = $s; + LET $before = (DELETE $s RETURN BEFORE); + RETURN $before; + COMMIT TRANSACTION;", + &[("s".into(), session.id.record().into_value())], + // No THROW of its own — an unconditional cascade, so the only + // error worth telling apart is a lost round (see + // [`crate::domain::exam::Exam::delete`]). + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Read through the trailing `RETURN`, never a hand-counted slot. + let slot = result.num_statements().saturating_sub(2); + let deleted: Option = + result.take::>(slot)?.into_iter().next(); + deleted.ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::COURSE_SESSION_TABLE; + + /// A lesson must not outlive the course it is a lesson of: an orphan 404s + /// forever through `session_with_course` — unreadable, unpatchable, + /// undeletable. + /// + /// [`create`] therefore *writes* the course row rather than + /// reading it ([`cap::touch_and_create`]); the harness and the window it + /// races in are documented on + /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. + /// Mutation-tested: with the bare `db.create` this shipped with, all four + /// rounds orphan. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn a_session_never_outlives_its_course() { + fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + create( + &db, + &course, + &UserId::generate(), + SessionTopic::try_new("limits").unwrap(), + Timestamp::from_millis(1), + None, + ) + .await + .map(|_| ()) + }) + } + crate::db::course::assert_no_child_outlives_a_course_delete( + "session_orphan_race", + COURSE_SESSION_TABLE, + make, + ) + .await; + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index 1ad9342..3354610 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod cap; pub mod course; +pub mod course_session; pub mod exam_attempt; pub mod field_update; pub mod note; diff --git a/src/domain/course_session.rs b/src/domain/course_session.rs index 813c6fc..ccc7e5f 100644 --- a/src/domain/course_session.rs +++ b/src/domain/course_session.rs @@ -1,15 +1,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{COURSE_SESSION_TABLE, ENROLLMENT_COUNT_FIELD, MAX_SESSION_TOPIC_LEN}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN}; use crate::domain::course::CourseId; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; -use crate::domain::timestamp::{Timestamp, range_error}; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::validate_optional; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] @@ -59,14 +55,15 @@ impl SessionTopic { /// so its roster is the course's enrollment plus the assigned teacher. #[derive(Debug, Clone, SurrealValue)] pub struct CourseSession { - id: CourseSessionId, - course: CourseId, + pub(crate) id: CourseSessionId, + pub(crate) course: CourseId, /// Who teaches this session. Must hold the `teacher` role or higher — - /// enforced at the web layer, where the target user row is at hand. - teacher: UserId, - topic: SessionTopic, - starts_at: Timestamp, - ends_at: Option, + /// enforced by [`crate::service::course_session::resolve_session_teacher`], + /// where the target user row is at hand. + pub(crate) teacher: UserId, + pub(crate) topic: SessionTopic, + pub(crate) starts_at: Timestamp, + pub(crate) ends_at: Option, } impl CourseSession { @@ -97,157 +94,12 @@ impl CourseSession { pub fn is_teacher(&self, user: &UserId) -> bool { &self.teacher == user } - - pub async fn create( - course: &CourseId, - teacher: &UserId, - topic: SessionTopic, - starts_at: Timestamp, - ends_at: Option, - db: &Database, - ) -> Result { - let session = CourseSession { - id: CourseSessionId::generate(), - course: course.clone(), - teacher: teacher.clone(), - topic, - starts_at, - ends_at, - }; - // The course row is *written* (bumped and put back), not read, so this - // collides with `Course::delete`'s cascade: a lesson that outlives its - // course 404s through `session_with_course` forever — unreadable, - // unpatchable, undeletable. See [`cap::touch_and_create`]. - cap::touch_and_create( - &course.record(), - ENROLLMENT_COUNT_FIELD, - &session.id.record(), - &session, - db, - ) - .await? - .ok_or(AppError::NotFound) - } - - pub async fn read( - id: &CourseSessionId, - db: &Database, - ) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// A course's sessions, most recent lesson first. Ordered by `starts_at` - /// (not id): a timetable is read by when the lesson happens, not by when - /// the row was created. - pub async fn list_for_course( - course: &CourseId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "course_session WHERE course = $course", - "ORDER BY starts_at DESC, id DESC", - ) - .bind("course", course.record()) - .run(limit, offset, db) - .await - } - - /// Request-scoped: the handler holds nothing across its read and this - /// write — the range check rides in the `WHERE` — so a field the request - /// omitted (`None`) is not written at all. Re-sending the snapshot's value - /// instead would revert a concurrent PATCH of that field — scoping the - /// `SET` alone does not stop that, the values have to come from the - /// request. `ends_at` is nullable, so it takes the outer/inner - /// `Option>`: `None` = omitted (keep), `Some(None)` = clear. - pub async fn update( - self, - teacher: Option, - topic: Option, - starts_at: Option, - ends_at: Option>, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("teacher", teacher.map(|teacher| teacher.record())) - .set("topic", topic) - .set("starts_at", starts_at) - .set("ends_at", ends_at) - .ordered("starts_at", "ends_at", range_error()) - .run::(db) - .await - } - - /// Delete the session and cascade-remove its roll-call rows, in one - /// transaction: as two unbatched queries a failure between them stranded - /// roll-call rows on a session that was already gone. The other half of - /// that invariant is [`crate::domain::session_attendance::SessionAttendance::mark`], - /// which proves the session still exists inside its own write — a - /// transaction here cannot stop a mark that commits *after* this one. - pub async fn delete(self, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE session_attendance WHERE session = $s; - LET $before = (DELETE $s RETURN BEFORE); - RETURN $before; - COMMIT TRANSACTION;", - &[("s".into(), self.id.record().into_value())], - // No THROW of its own — an unconditional cascade, so the only - // error worth telling apart is a lost round (see - // [`crate::domain::exam::Exam::delete`]). - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, never a hand-counted slot. - let slot = result.num_statements().saturating_sub(2); - let deleted: Option = - result.take::>(slot)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - /// A lesson must not outlive the course it is a lesson of: an orphan 404s - /// forever through `session_with_course` — unreadable, unpatchable, - /// undeletable. - /// - /// [`CourseSession::create`] therefore *writes* the course row rather than - /// reading it ([`cap::touch_and_create`]); the harness and the window it - /// races in are documented on - /// [`crate::db::course::assert_no_child_outlives_a_course_delete`]. - /// Mutation-tested: with the bare `db.create` this shipped with, all four - /// rounds orphan. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn a_session_never_outlives_its_course() { - fn make(course: CourseId, db: Database) -> tokio::task::JoinHandle> { - tokio::spawn(async move { - CourseSession::create( - &course, - &UserId::generate(), - SessionTopic::try_new("limits").unwrap(), - Timestamp::from_millis(1), - None, - &db, - ) - .await - .map(|_| ()) - }) - } - crate::db::course::assert_no_child_outlives_a_course_delete("session_orphan_race", - COURSE_SESSION_TABLE, - make,) - .await; - } - #[tokio::test] async fn topic_is_optional_but_bounded() { assert!(SessionTopic::try_new("").is_ok()); diff --git a/src/domain/event.rs b/src/domain/event.rs index 0648d4e..c33d45e 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -4,11 +4,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; use crate::database::{Database, transaction_with_retry}; +use crate::db::field_update::FieldUpdate; use crate::domain::class_group::ClassGroupId; use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; use crate::domain::enrollment::Enrollment; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; use crate::domain::registration::Registration; use crate::domain::role::Role; @@ -317,7 +317,7 @@ impl Event { /// since every one of them is keyed on the event that is now gone. /// /// Re-sent while the store answers "conflict, retry", the way - /// [`crate::domain::course_session::CourseSession::delete`] is: now that + /// [`crate::db::course_session::delete`] is: now that /// [`crate::domain::attendance::Attendance::mark`] writes the event row to /// prove it exists, a mark landing in this window really does contend for /// it — and without the retry the *delete* is the side that loses, turning diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 8518219..57ced1c 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -5,10 +5,10 @@ use crate::constant::{ SESSION_ATTENDANCE_TABLE, }; use crate::database::{Database, transaction_with_retry}; +use crate::db::page::PagedList; use crate::domain::attendance::AttendanceStatus; use crate::domain::course::CourseId; use crate::domain::course_session::{CourseSession, CourseSessionId}; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -99,7 +99,7 @@ impl SessionAttendance { /// single atomic UPSERT — concurrent marks converge on the one row. /// /// The "session still exists" gate rides in the same transaction as the - /// mark, the mirror of the cascade in [`CourseSession::delete`]: the + /// mark, the mirror of the cascade in [`crate::db::course_session::delete`]: the /// caller's pre-flight read sits four round trips in front of this write, /// so a delete landing in that gap used to leave a roll-call row on a /// session that was gone — and that row was *unremovable*, its only delete @@ -151,7 +151,7 @@ impl SessionAttendance { /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees /// the stamp and credits nothing. It counts lessons that actually /// happened — scheduling one and cancelling it earns nothing, which is - /// why the credit does not live in `CourseSession::create`. Two + /// why the credit does not live in `crate::db::course_session::create`. Two /// simultaneous first marks both write the lesson row, so the store's own /// conflict detection (and `transaction_with_retry` behind it) is what /// keeps the stamp from being set twice. @@ -295,7 +295,7 @@ impl SessionAttendance { /// delete's own transaction — the other direction of the delta in /// [`SessionAttendance::mark`], so a row that never existed and a row that /// was withdrawn leave the same number behind. Only *this* route decrements: - /// [`CourseSession::delete`]'s cascade sweeps the rows with a `DELETE` of + /// [`crate::db::course_session::delete`]'s cascade sweeps the rows with a `DELETE` of /// its own and never comes through here, which is the ruling /// `exam_sat_total` already carries — deleting the lesson does not un-attend /// it. `lessons_held_total` is never given back either: the lesson was @@ -384,13 +384,13 @@ mod tests { } async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession { - CourseSession::create( + crate::db::course_session::create( + db, &crate::db::course::a_test_course(db).await, teacher, SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(starts_at), None, - db, ) .await .unwrap() @@ -664,7 +664,9 @@ mod tests { .await .unwrap(); - session.delete(&db).await.unwrap(); + crate::db::course_session::delete(&db, session) + .await + .unwrap(); assert_eq!(attended(&student, &db).await, 1, "the cascade decremented"); assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented"); } @@ -678,7 +680,9 @@ mod tests { let student = a_student("s", &db).await; let session = a_session(&teacher, &db).await; let ghost = session.clone(); - session.delete(&db).await.unwrap(); + crate::db::course_session::delete(&db, session) + .await + .unwrap(); assert!(matches!( SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await, @@ -690,7 +694,7 @@ mod tests { /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT` /// on `course_session` fires inside the delete's own transaction, and - /// [`CourseSession::delete`] sweeps its children before removing the row, + /// [`crate::db::course_session::delete`] sweeps its children before removing the row, /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is /// written after the sweep has run, and used to commit straight past it. /// @@ -735,7 +739,7 @@ mod tests { let ghost = session.clone(); let drop_it = { let db = db.clone(); - tokio::spawn(async move { session.delete(&db).await }) + tokio::spawn(async move { crate::db::course_session::delete(&db, session).await }) }; // The mark starts inside the held window: the sweep has run and the // session row is gone but uncommitted — which is exactly what a @@ -756,7 +760,11 @@ mod tests { ); // Stored state is the whole verdict; a return value is not evidence. - if CourseSession::read(&id, &db).await.unwrap().is_none() { + if crate::db::course_session::read(&db, &id) + .await + .unwrap() + .is_none() + { swept += 1; orphans += SessionAttendance::list_for_session(&id, None, 0, &db) .await diff --git a/src/service/course_session.rs b/src/service/course_session.rs new file mode 100644 index 0000000..5403b17 --- /dev/null +++ b/src/service/course_session.rs @@ -0,0 +1,96 @@ +//! Course-session workflows: who may teach a lesson (the teacher-resolution +//! gate), and the doors the web layer takes for every session read and +//! write. The queries live in [`crate::db::course_session`]; the +//! timetable's wire shaping and the course-rights checks stay in the web +//! layer. + +use crate::database::Database; +use crate::db::course_session; +use crate::domain::course::CourseId; +use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; +use crate::domain::role::Role; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::{AppError, ValidationError}; + +/// Resolve who a session's teacher should be: the caller when `teacher_id` is +/// omitted (or names them), otherwise the referenced user — who must exist and +/// hold the `teacher` role or higher (a student cannot teach a lesson). +/// +/// Scheduling hands the named person the session's teaching seat, so the +/// floor is checked on the *live* role here rather than at the web layer: +/// every future roll-call right derives from this column, and a stale +/// `teacher_id` in a request body must fail with the same 400 no matter +/// which route named it. +pub async fn resolve_session_teacher( + teacher_id: Option<&str>, + caller: &User, + db: &Database, +) -> Result { + let target = match teacher_id { + None => return Ok(caller.clone()), + Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), + Some(key) => UserId::from_key(key), + }; + let Some(user) = User::read(&target, db).await? else { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "session teacher does not exist", + })); + }; + if !user.get_role().at_least(Role::Teacher) { + return Err(AppError::Validation(ValidationError::Invalid { + field: "teacher_id", + reason: "session teacher must hold the teacher role or higher", + })); + } + Ok(user) +} + +/// Schedule a lesson on `course`. The write bumps the course row in the same +/// transaction (`cap::touch_and_create`), so a lesson can never outlive its +/// course — a create racing the course delete refuses instead of orphaning. +pub async fn create( + db: &Database, + course: &CourseId, + teacher: &UserId, + topic: SessionTopic, + starts_at: Timestamp, + ends_at: Option, +) -> Result { + course_session::create(db, course, teacher, topic, starts_at, ends_at).await +} + +pub async fn read(db: &Database, id: &CourseSessionId) -> Result, AppError> { + course_session::read(db, id).await +} + +/// A course's sessions, most recent lesson first — the timetable read. +pub async fn list_for_course( + db: &Database, + course: &CourseId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + course_session::list_for_course(db, course, limit, offset).await +} + +/// Only what the request carried is written: an omitted field (`None`) is +/// not stored at all, so a concurrent PATCH of that field survives. The +/// range consistency re-check rides in the UPDATE's own `WHERE`, so the +/// caller holds nothing across its read and this write. +pub async fn update( + db: &Database, + session: CourseSession, + teacher: Option, + topic: Option, + starts_at: Option, + ends_at: Option>, +) -> Result { + course_session::update(db, session, teacher, topic, starts_at, ends_at).await +} + +/// Delete the session and sweep its roll-call rows in one transaction. +pub async fn delete(db: &Database, session: CourseSession) -> Result { + course_session::delete(db, session).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 892e3cd..2c0fc38 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,7 @@ pub mod appointment; pub mod course; +pub mod course_session; pub mod exam_attempt; pub mod note; pub mod payment_ledger; diff --git a/src/web/courses.rs b/src/web/courses.rs index 9a52348..a1ac276 100644 --- a/src/web/courses.rs +++ b/src/web/courses.rs @@ -11,7 +11,7 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle}; -use crate::domain::course_session::{CourseSession, SessionTopic}; +use crate::domain::course_session::SessionTopic; use crate::domain::enrollment::Enrollment; use crate::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule, @@ -27,7 +27,6 @@ use crate::service; use crate::state::AppState; use super::homework::{description_or_none, resolve_assigned}; -use super::sessions::resolve_session_teacher; use super::subjects::subject_in_course; use super::terms::resolve_term; use super::{ @@ -265,7 +264,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (courses, total) = service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; + let (courses, total) = + service::course::list_enrolled(&st.db, user.get_id(), limit, offset).await?; let people = person_map(courses.iter().flat_map(course_people), &st.db).await?; let items = courses .iter() @@ -1227,20 +1230,22 @@ async fn create_session_in_course( service::course::require_open(&st.db, &course).await?; let topic = SessionTopic::try_new(&req.topic.unwrap_or_default())?; - let teacher = resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db).await?; + let teacher = + service::course_session::resolve_session_teacher(req.teacher_id.as_deref(), &user, &st.db) + .await?; let starts_at = Timestamp::from_millis(req.starts_at); let ends_at = req.ends_at.map(Timestamp::from_millis); check_not_past("starts_at", Some(starts_at))?; check_not_past("ends_at", ends_at)?; check_time_range(Some(starts_at), ends_at)?; - let session = CourseSession::create( + let session = service::course_session::create( + &st.db, course.get_id(), teacher.get_id(), topic, starts_at, ends_at, - &st.db, ) .await?; let people = PersonRef::map_of(&[&teacher]); @@ -1285,7 +1290,7 @@ async fn list_course_sessions( )); } let (rows, total) = - CourseSession::list_for_course(course.get_id(), limit, offset, &st.db).await?; + service::course_session::list_for_course(&st.db, course.get_id(), limit, offset).await?; // Join teachers onto the page alone — the lookup shrinks with the window. let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?; let items = rows @@ -1359,13 +1364,10 @@ mod tests { let db = init_mem().await.unwrap(); let creator = user("creator", Role::Teacher, &db).await; let assigned = user("assigned", Role::Teacher, &db).await; - let course = service::course::assign_teacher( - &db, - &course(&creator, &db).await, - assigned.get_id(), - ) - .await - .unwrap(); + let course = + service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id()) + .await + .unwrap(); // Still teacher+: untouched by the floor. assert!(can_manage_course(&course, &assigned)); // ...but never an owner, assigned or not. diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 7d70fe1..3a8d50e 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -88,38 +88,10 @@ impl SessionAttendanceResponse { } } -/// Resolve who a session's teacher should be: the caller when `teacher_id` is -/// omitted (or names them), otherwise the referenced user — who must exist and -/// hold the `teacher` role or higher (a student cannot teach a lesson). -pub(crate) async fn resolve_session_teacher( - teacher_id: Option<&str>, - caller: &User, - db: &Database, -) -> Result { - let target = match teacher_id { - None => return Ok(caller.clone()), - Some(key) if key == caller.get_id().key() => return Ok(caller.clone()), - Some(key) => UserId::from_key(key), - }; - let Some(user) = User::read(&target, db).await? else { - return Err(AppError::Validation(ValidationError::Invalid { - field: "teacher_id", - reason: "session teacher does not exist", - })); - }; - if !user.get_role().at_least(Role::Teacher) { - return Err(AppError::Validation(ValidationError::Invalid { - field: "teacher_id", - reason: "session teacher must hold the teacher role or higher", - })); - } - Ok(user) -} - /// Load a session and its course together; a session whose course is gone /// cannot happen given the delete cascade, so both misses are plain 404s. async fn session_with_course(id: &str, db: &Database) -> Result<(CourseSession, Course), AppError> { - let session = CourseSession::read(&CourseSessionId::from_key(id), db) + let session = service::course_session::read(db, &CourseSessionId::from_key(id)) .await? .ok_or(AppError::NotFound)?; let course = crate::service::course::read(db, session.get_course()) @@ -228,7 +200,7 @@ async fn update_session( .transpose()?; let teacher = match req.teacher_id { Some(ref key) => Some( - resolve_session_teacher(Some(key), &user, &st.db) + service::course_session::resolve_session_teacher(Some(key), &user, &st.db) .await? .get_id() .clone(), @@ -237,15 +209,15 @@ async fn update_session( }; // The end this request left out is only *read* for the range check — it is // never written back, so a concurrent move of it survives. Pre-flight only: - // `CourseSession::update` re-makes this check in the UPDATE's `WHERE`. + // the write's own `WHERE` re-makes this check (the db layer's `update`). check_time_range( Some(starts_at.unwrap_or_else(|| session.get_starts_at())), ends_at.unwrap_or_else(|| session.get_ends_at()), )?; - let updated = session - .update(teacher, topic, starts_at, ends_at, &st.db) - .await?; + let updated = + service::course_session::update(&st.db, session, teacher, topic, starts_at, ends_at) + .await?; let people = person_map([updated.get_teacher().clone()], &st.db).await?; Ok(Json(SessionResponse::new(&updated, &people))) } @@ -278,7 +250,7 @@ async fn delete_session( )); } crate::service::course::require_open(&st.db, &course).await?; - session.delete(&st.db).await?; + service::course_session::delete(&st.db, session).await?; Ok(StatusCode::NO_CONTENT) } diff --git a/tests/regress_attendance.rs b/tests/regress_attendance.rs index 5aec836..6d203cc 100644 --- a/tests/regress_attendance.rs +++ b/tests/regress_attendance.rs @@ -13,9 +13,10 @@ mod common; use axum::http::StatusCode; use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send}; use hezarfen_backend::database::Database; +use hezarfen_backend::db::course_session; use hezarfen_backend::db::settings; use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus}; -use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId}; +use hezarfen_backend::domain::course_session::CourseSessionId; use hezarfen_backend::domain::event::EventId; use hezarfen_backend::domain::session_attendance::SessionAttendance; use hezarfen_backend::domain::timestamp::Timestamp; @@ -199,7 +200,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() { assert_eq!(res.status, StatusCode::OK, "{}", res.body); // The snapshot the racing request is holding, taken while the session lives. - let snapshot = CourseSession::read(&CourseSessionId::from_key(&session), &db) + let snapshot = course_session::read(&db, &CourseSessionId::from_key(&session)) .await .unwrap() .expect("session exists"); diff --git a/tests/regress_course_child_orphans.rs b/tests/regress_course_child_orphans.rs index a7fa258..98d4b73 100644 --- a/tests/regress_course_child_orphans.rs +++ b/tests/regress_course_child_orphans.rs @@ -32,7 +32,7 @@ //! The **race** half drives the real interleaving and lives in-crate, one pin //! per child beside the create it pins — //! `domain::exam::tests::an_exam_never_outlives_its_course`, -//! `domain::course_session::tests::a_session_never_outlives_its_course`, +//! `db::course_session::tests::a_session_never_outlives_its_course`, //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`. //! It is `#[ignore]`d and needs a real server, because the subject there *is* @@ -49,10 +49,11 @@ use axum::http::StatusCode; use common::{app_and_db, id_of, login_as, send, upload_course_note_file}; use hezarfen_backend::database::{self, Database}; use hezarfen_backend::db::course; +use hezarfen_backend::db::course_session as db_course_session; use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle}; use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle}; use hezarfen_backend::domain::course_note_file::{CourseNoteFile, FileContentType, FileName}; -use hezarfen_backend::domain::course_session::{CourseSession, SessionTopic}; +use hezarfen_backend::domain::course_session::SessionTopic; use hezarfen_backend::domain::exam::{ Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle, }; @@ -122,13 +123,13 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle> fn make_session(course: CourseId, db: Database) -> JoinHandle> { tokio::spawn(async move { - CourseSession::create( + db_course_session::create( + &db, &course, &teacher(), SessionTopic::try_new("limits").unwrap(), Timestamp::from_millis(1), None, - &db, ) .await .map(|_| ()) @@ -325,15 +326,9 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() { .await .unwrap(); assert!( - course::delete( - &db, - course::read(&db, &course) - .await - .unwrap() - .unwrap() - ) - .await - .unwrap(), + course::delete(&db, course::read(&db, &course).await.unwrap().unwrap()) + .await + .unwrap(), "the course, and its note with it, goes" );