forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/course_session'

Browse files at this commit

10d1fef10674eadcb658e1c26308202eb1cb2bd4Ahmet Kaan GümüşParent: 38a619c0ddaa5d
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;
55 pub mod cap;
66 pub mod class_blueprint;
77 pub mod course;
8+pub mod course_session;
89 pub mod exam_attempt;
910 pub mod field_update;
1011 pub mod note;
src/domain/course_session.rsmodified+11 -159
@@ -1,15 +1,11 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
3-use crate::constant::{COURSE_SESSION_TABLE, ENROLLMENT_COUNT_FIELD, MAX_SESSION_TOPIC_LEN};
4-use crate::database::{Database, transaction_with_retry};
5-use crate::db::cap;
3+use crate::constant::{COURSE_SESSION_TABLE, MAX_SESSION_TOPIC_LEN};
64 use crate::domain::course::CourseId;
7-use crate::db::field_update::FieldUpdate;
85 use crate::domain::monotonic_id::next_ulid;
9-use crate::db::page::PagedList;
10-use crate::domain::timestamp::{Timestamp, range_error};
6+use crate::domain::timestamp::Timestamp;
117 use crate::domain::user::UserId;
12-use crate::error::{AppError, ValidationError};
8+use crate::error::ValidationError;
139 use crate::validate::validate_optional;
1410
1511 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
@@ -59,14 +55,15 @@ impl SessionTopic {
5955 /// so its roster is the course's enrollment plus the assigned teacher.
6056 #[derive(Debug, Clone, SurrealValue)]
6157 pub struct CourseSession {
62- id: CourseSessionId,
63- course: CourseId,
58+ pub(crate) id: CourseSessionId,
59+ pub(crate) course: CourseId,
6460 /// 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.
66- teacher: UserId,
67- topic: SessionTopic,
68- starts_at: Timestamp,
69- ends_at: Option<Timestamp>,
61+ /// enforced by [`crate::service::course_session::resolve_session_teacher`],
62+ /// where the target user row is at hand.
63+ pub(crate) teacher: UserId,
64+ pub(crate) topic: SessionTopic,
65+ pub(crate) starts_at: Timestamp,
66+ pub(crate) ends_at: Option<Timestamp>,
7067 }
7168
7269 impl CourseSession {
@@ -97,157 +94,12 @@ impl CourseSession {
9794 pub fn is_teacher(&self, user: &UserId) -> bool {
9895 &self.teacher == user
9996 }
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- }
21297 }
21398
21499 #[cfg(test)]
215100 mod tests {
216101 use super::*;
217102
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-
251103 #[tokio::test]
252104 async fn topic_is_optional_but_bounded() {
253105 assert!(SessionTopic::try_new("").is_ok());
src/domain/event.rsmodified+2 -2
@@ -4,11 +4,11 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
44
55 use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
66 use crate::database::{Database, transaction_with_retry};
7+use crate::db::field_update::FieldUpdate;
78 use crate::domain::class_group::ClassGroupId;
89 use crate::domain::class_member::{ClassMember, ClassMemberId};
910 use crate::domain::course::CourseId;
1011 use crate::domain::enrollment::Enrollment;
11-use crate::db::field_update::FieldUpdate;
1212 use crate::domain::monotonic_id::next_ulid;
1313 use crate::domain::registration::Registration;
1414 use crate::domain::role::Role;
@@ -317,7 +317,7 @@ impl Event {
317317 /// since every one of them is keyed on the event that is now gone.
318318 ///
319319 /// 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
321321 /// [`crate::domain::attendance::Attendance::mark`] writes the event row to
322322 /// prove it exists, a mark landing in this window really does contend for
323323 /// 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::{
55 SESSION_ATTENDANCE_TABLE,
66 };
77 use crate::database::{Database, transaction_with_retry};
8+use crate::db::page::PagedList;
89 use crate::domain::attendance::AttendanceStatus;
910 use crate::domain::course::CourseId;
1011 use crate::domain::course_session::{CourseSession, CourseSessionId};
11-use crate::db::page::PagedList;
1212 use crate::domain::timestamp::Timestamp;
1313 use crate::domain::user::UserId;
1414 use crate::error::AppError;
@@ -99,7 +99,7 @@ impl SessionAttendance {
9999 /// single atomic UPSERT — concurrent marks converge on the one row.
100100 ///
101101 /// 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
103103 /// caller's pre-flight read sits four round trips in front of this write,
104104 /// so a delete landing in that gap used to leave a roll-call row on a
105105 /// session that was gone — and that row was *unremovable*, its only delete
@@ -151,7 +151,7 @@ impl SessionAttendance {
151151 /// [`LESSON_COUNTED_AT_FIELD`] on the lesson and every later mark sees
152152 /// the stamp and credits nothing. It counts lessons that actually
153153 /// 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
155155 /// simultaneous first marks both write the lesson row, so the store's own
156156 /// conflict detection (and `transaction_with_retry` behind it) is what
157157 /// keeps the stamp from being set twice.
@@ -295,7 +295,7 @@ impl SessionAttendance {
295295 /// delete's own transaction — the other direction of the delta in
296296 /// [`SessionAttendance::mark`], so a row that never existed and a row that
297297 /// 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
299299 /// its own and never comes through here, which is the ruling
300300 /// `exam_sat_total` already carries — deleting the lesson does not un-attend
301301 /// it. `lessons_held_total` is never given back either: the lesson was
@@ -384,13 +384,13 @@ mod tests {
384384 }
385385
386386 async fn a_session_at(teacher: &UserId, starts_at: i64, db: &Database) -> CourseSession {
387- CourseSession::create(
387+ crate::db::course_session::create(
388+ db,
388389 &crate::db::course::a_test_course(db).await,
389390 teacher,
390391 SessionTopic::try_new("limits").unwrap(),
391392 Timestamp::from_millis(starts_at),
392393 None,
393- db,
394394 )
395395 .await
396396 .unwrap()
@@ -664,7 +664,9 @@ mod tests {
664664 .await
665665 .unwrap();
666666
667- session.delete(&db).await.unwrap();
667+ crate::db::course_session::delete(&db, session)
668+ .await
669+ .unwrap();
668670 assert_eq!(attended(&student, &db).await, 1, "the cascade decremented");
669671 assert_eq!(held(&teacher, &db).await, 1, "the cascade decremented");
670672 }
@@ -678,7 +680,9 @@ mod tests {
678680 let student = a_student("s", &db).await;
679681 let session = a_session(&teacher, &db).await;
680682 let ghost = session.clone();
681- session.delete(&db).await.unwrap();
683+ crate::db::course_session::delete(&db, session)
684+ .await
685+ .unwrap();
682686
683687 assert!(matches!(
684688 SessionAttendance::mark(&ghost, &student, status("present"), &teacher, &db).await,
@@ -690,7 +694,7 @@ mod tests {
690694
691695 /// The claim the existence gate cannot make by *reading*. A `DEFINE EVENT`
692696 /// 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,
694698 /// so the `SLEEP` opens exactly the window a mark has to lose: the sheet is
695699 /// written after the sweep has run, and used to commit straight past it.
696700 ///
@@ -735,7 +739,7 @@ mod tests {
735739 let ghost = session.clone();
736740 let drop_it = {
737741 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 })
739743 };
740744 // The mark starts inside the held window: the sweep has run and the
741745 // session row is gone but uncommitted — which is exactly what a
@@ -756,7 +760,11 @@ mod tests {
756760 );
757761
758762 // 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+ {
760768 swept += 1;
761769 orphans += SessionAttendance::list_for_session(&id, None, 0, &db)
762770 .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;
55 pub mod appointment_slot;
66 pub mod class_blueprint;
77 pub mod course;
8+pub mod course_session;
89 pub mod exam_attempt;
910 pub mod note;
1011 pub mod payment_ledger;
src/web/courses.rsmodified+17 -15
@@ -11,7 +11,7 @@ use utoipa_axum::routes;
1111
1212 use crate::database::Database;
1313 use crate::domain::course::{Course, CourseDescription, CourseId, CourseKind, CourseTitle};
14-use crate::domain::course_session::{CourseSession, SessionTopic};
14+use crate::domain::course_session::SessionTopic;
1515 use crate::domain::enrollment::Enrollment;
1616 use crate::domain::exam::{
1717 Exam, ExamAttemptLimit, ExamDescription, ExamDuration, ExamKind, ExamMode, ExamSchedule,
@@ -27,7 +27,6 @@ use crate::service;
2727 use crate::state::AppState;
2828
2929 use super::homework::{description_or_none, resolve_assigned};
30-use super::sessions::resolve_session_teacher;
3130 use super::subjects::subject_in_course;
3231 use super::terms::resolve_term;
3332 use super::{
@@ -265,7 +264,10 @@ pub(crate) async fn visible_courses(user: &User, db: &Database) -> Result<Vec<Co
265264 } else {
266265 Vec::new()
267266 };
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+ {
269271 if !courses
270272 .iter()
271273 .any(|known| known.get_id() == course.get_id())
@@ -401,7 +403,8 @@ async fn my_courses(
401403 Query(page): Query<PageParams>,
402404 ) -> Result<Json<Page<CourseResponse>>, AppError> {
403405 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?;
405408 let people = person_map(courses.iter().flat_map(course_people), &st.db).await?;
406409 let items = courses
407410 .iter()
@@ -1227,20 +1230,22 @@ async fn create_session_in_course(
12271230 service::course::require_open(&st.db, &course).await?;
12281231
12291232 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?;
12311236 let starts_at = Timestamp::from_millis(req.starts_at);
12321237 let ends_at = req.ends_at.map(Timestamp::from_millis);
12331238 check_not_past("starts_at", Some(starts_at))?;
12341239 check_not_past("ends_at", ends_at)?;
12351240 check_time_range(Some(starts_at), ends_at)?;
12361241
1237- let session = CourseSession::create(
1242+ let session = service::course_session::create(
1243+ &st.db,
12381244 course.get_id(),
12391245 teacher.get_id(),
12401246 topic,
12411247 starts_at,
12421248 ends_at,
1243- &st.db,
12441249 )
12451250 .await?;
12461251 let people = PersonRef::map_of(&[&teacher]);
@@ -1285,7 +1290,7 @@ async fn list_course_sessions(
12851290 ));
12861291 }
12871292 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?;
12891294 // Join teachers onto the page alone — the lookup shrinks with the window.
12901295 let people = person_map(rows.iter().map(|s| s.get_teacher().clone()), &st.db).await?;
12911296 let items = rows
@@ -1359,13 +1364,10 @@ mod tests {
13591364 let db = init_mem().await.unwrap();
13601365 let creator = user("creator", Role::Teacher, &db).await;
13611366 let assigned = user("assigned", Role::Teacher, &db).await;
1362- let course = service::course::assign_teacher(
1363- &db,
1364- &course(&creator, &db).await,
1365- assigned.get_id(),
1366- )
1367- .await
1368- .unwrap();
1367+ let course =
1368+ service::course::assign_teacher(&db, &course(&creator, &db).await, assigned.get_id())
1369+ .await
1370+ .unwrap();
13691371 // Still teacher+: untouched by the floor.
13701372 assert!(can_manage_course(&course, &assigned));
13711373 // ...but never an owner, assigned or not.
src/web/sessions.rsmodified+7 -35
@@ -88,38 +88,10 @@ impl SessionAttendanceResponse {
8888 }
8989 }
9090
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-
11991 /// Load a session and its course together; a session whose course is gone
12092 /// cannot happen given the delete cascade, so both misses are plain 404s.
12193 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))
12395 .await?
12496 .ok_or(AppError::NotFound)?;
12597 let course = crate::service::course::read(db, session.get_course())
@@ -228,7 +200,7 @@ async fn update_session(
228200 .transpose()?;
229201 let teacher = match req.teacher_id {
230202 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)
232204 .await?
233205 .get_id()
234206 .clone(),
@@ -237,15 +209,15 @@ async fn update_session(
237209 };
238210 // The end this request left out is only *read* for the range check — it is
239211 // 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`).
241213 check_time_range(
242214 Some(starts_at.unwrap_or_else(|| session.get_starts_at())),
243215 ends_at.unwrap_or_else(|| session.get_ends_at()),
244216 )?;
245217
246- let updated = session
247- .update(teacher, topic, starts_at, ends_at, &st.db)
248- .await?;
218+ let updated =
219+ service::course_session::update(&st.db, session, teacher, topic, starts_at, ends_at)
220+ .await?;
249221 let people = person_map([updated.get_teacher().clone()], &st.db).await?;
250222 Ok(Json(SessionResponse::new(&updated, &people)))
251223 }
@@ -278,7 +250,7 @@ async fn delete_session(
278250 ));
279251 }
280252 crate::service::course::require_open(&st.db, &course).await?;
281- session.delete(&st.db).await?;
253+ service::course_session::delete(&st.db, session).await?;
282254 Ok(StatusCode::NO_CONTENT)
283255 }
284256
tests/regress_attendance.rsmodified+3 -2
@@ -13,9 +13,10 @@ mod common;
1313 use axum::http::StatusCode;
1414 use common::{app_and_db, create_course, create_session, enroll, login, login_as, me_id, send};
1515 use hezarfen_backend::database::Database;
16+use hezarfen_backend::db::course_session;
1617 use hezarfen_backend::db::settings;
1718 use hezarfen_backend::domain::attendance::{Attendance, AttendanceStatus};
18-use hezarfen_backend::domain::course_session::{CourseSession, CourseSessionId};
19+use hezarfen_backend::domain::course_session::CourseSessionId;
1920 use hezarfen_backend::domain::event::EventId;
2021 use hezarfen_backend::domain::session_attendance::SessionAttendance;
2122 use hezarfen_backend::domain::timestamp::Timestamp;
@@ -199,7 +200,7 @@ async fn a_mark_against_a_deleted_session_is_refused_and_stores_nothing() {
199200 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
200201
201202 // 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))
203204 .await
204205 .unwrap()
205206 .expect("session exists");
tests/regress_course_child_orphans.rsmodified+8 -13
@@ -32,7 +32,7 @@
3232 //! The **race** half drives the real interleaving and lives in-crate, one pin
3333 //! per child beside the create it pins —
3434 //! `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`,
3636 //! `domain::subject::tests::a_subject_never_outlives_its_course` — over the
3737 //! shared harness `domain::course::assert_no_child_outlives_a_course_delete`.
3838 //! It is `#[ignore]`d and needs a real server, because the subject there *is*
@@ -49,10 +49,11 @@ use axum::http::StatusCode;
4949 use common::{app_and_db, id_of, login_as, send, upload_course_note_file};
5050 use hezarfen_backend::database::{self, Database};
5151 use hezarfen_backend::db::course;
52+use hezarfen_backend::db::course_session as db_course_session;
5253 use hezarfen_backend::domain::course::{CourseDescription, CourseId, CourseKind, CourseTitle};
5354 use hezarfen_backend::domain::course_note::{CourseNote, CourseNoteContent, CourseNoteTitle};
5455 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;
5657 use hezarfen_backend::domain::exam::{
5758 Exam, ExamAttemptLimit, ExamDescription, ExamKind, ExamSchedule, ExamTitle,
5859 };
@@ -122,13 +123,13 @@ fn make_exam(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>>
122123
123124 fn make_session(course: CourseId, db: Database) -> JoinHandle<Result<(), AppError>> {
124125 tokio::spawn(async move {
125- CourseSession::create(
126+ db_course_session::create(
127+ &db,
126128 &course,
127129 &teacher(),
128130 SessionTopic::try_new("limits").unwrap(),
129131 Timestamp::from_millis(1),
130132 None,
131- &db,
132133 )
133134 .await
134135 .map(|_| ())
@@ -325,15 +326,9 @@ async fn a_course_note_file_under_a_deleted_note_is_refused() {
325326 .await
326327 .unwrap();
327328 assert!(
328- course::delete(
329- &db,
330- course::read(&db, &course)
331- .await
332- .unwrap()
333- .unwrap()
334- )
335- .await
336- .unwrap(),
329+ course::delete(&db, course::read(&db, &course).await.unwrap().unwrap())
330+ .await
331+ .unwrap(),
337332 "the course, and its note with it, goes"
338333 );
339334