forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'layer-split/comms'

Browse files at this commit

4ab90d96b46eeb07b55ec02bff76229262389cd8Ahmet Kaan GümüşParent: 47eb006f820c36
# Conflicts:
#	src/db/mod.rs
#	src/domain/event.rs
#	src/domain/registration.rs
#	src/service/mod.rs
#	src/web/pomodoro.rs
src/db/meal_booking.rsmodified+1 -1
@@ -46,7 +46,7 @@ pub async fn list_for_menu(
4646 /// parent whose link was revoked (by an unlink or by the student-side role
4747 /// sweep) would otherwise keep a live view of the child's seat, watching
4848 /// cancellations made long after the link died — exactly what
49-/// [`ensure_can_observe`](crate::web::ensure_can_observe) refuses. The
49+/// [`ensure_can_observe`](crate::service::parent_link::ensure_can_observe) refuses. The
5050 /// caller re-derives the list from the links on every read, so the view
5151 /// dies with the link.
5252 pub async fn list_for_students(
src/db/message.rsadded+230 -0
@@ -0,0 +1,230 @@
1+//! The `message` table: the send-side create, the folder listings, the
2+//! party-scoped read, and the field-scoped writes each party makes to its own
3+//! copy. The folder arithmetic on a row's values lives in
4+//! [`crate::domain::message`].
5+
6+use crate::database::Database;
7+use crate::db::page::PagedList;
8+use crate::domain::message::{
9+ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
10+};
11+use crate::domain::timestamp::Timestamp;
12+use crate::domain::user::UserId;
13+use crate::error::AppError;
14+
15+pub async fn send(
16+ db: &Database,
17+ sender: &UserId,
18+ recipient: &UserId,
19+ subject: MessageSubject,
20+ body: MessageBody,
21+ label: Option<MessageLabel>,
22+) -> Result<Message, AppError> {
23+ let message = Message {
24+ id: MessageId::generate(),
25+ sender: sender.clone(),
26+ recipient: recipient.clone(),
27+ subject,
28+ body,
29+ label,
30+ sent_at: Timestamp::now(),
31+ read: false,
32+ sender_folder: Folder::Sent,
33+ recipient_folder: Folder::Inbox,
34+ sender_origin: None,
35+ recipient_origin: None,
36+ };
37+ let created: Option<Message> = db.create(message.id.record()).content(message).await?;
38+ created.ok_or_else(|| AppError::Internal("failed to create message".into()))
39+}
40+
41+/// One folder view for `user`, newest first. `inbox` is recipient-side,
42+/// `sent` is sender-side, and `archive`/`trash` are each the union of both
43+/// sides' filed copies (either party may archive or trash their own copy).
44+/// `read` narrows to that flag state (`false` on the inbox is the unread
45+/// view; on `sent`, receipts pending) — the folder condition is
46+/// parenthesized because `archive`'s and `trash`'s are ORs.
47+pub async fn list_folder(
48+ db: &Database,
49+ user: &UserId,
50+ folder: Folder,
51+ read: Option<bool>,
52+ limit: Option<i64>,
53+ offset: i64,
54+) -> Result<(Vec<Message>, i64), AppError> {
55+ let condition = match folder {
56+ Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
57+ Folder::Archive => {
58+ "(recipient = $usr AND recipient_folder = 'archive') \
59+ OR (sender = $usr AND sender_folder = 'archive')"
60+ }
61+ Folder::Trash => {
62+ "(recipient = $usr AND recipient_folder = 'trash') \
63+ OR (sender = $usr AND sender_folder = 'trash')"
64+ }
65+ _ => "recipient = $usr AND recipient_folder = $folder",
66+ };
67+ let read_clause = if read.is_some() {
68+ " AND read = $read"
69+ } else {
70+ ""
71+ };
72+ PagedList::new(
73+ format!("message WHERE ({condition}){read_clause}"),
74+ "ORDER BY id DESC",
75+ )
76+ .bind("usr", user.record())
77+ .bind("folder", folder.as_str().to_string())
78+ .bind("read", read.unwrap_or_default())
79+ .run(limit, offset, db)
80+ .await
81+}
82+
83+/// Read a message only if `user` is its sender or recipient and their
84+/// side hasn't been permanently deleted.
85+pub async fn read_for(
86+ db: &Database,
87+ id: &MessageId,
88+ user: &UserId,
89+) -> Result<Option<Message>, AppError> {
90+ let message: Option<Message> = db.select(id.record()).await?;
91+ Ok(message.filter(|message| {
92+ (&message.sender == user || &message.recipient == user)
93+ && message.folder_of(user) != Folder::Deleted
94+ }))
95+}
96+
97+/// Flip the recipient's read flag. Field-scoped write: the sender may be
98+/// filing their side concurrently, and a whole-row save would clobber it.
99+pub async fn set_read(db: &Database, message: Message, read: bool) -> Result<Message, AppError> {
100+ let mut result = db
101+ .query("UPDATE $id SET read = $read RETURN AFTER")
102+ .bind(("id", message.id.record()))
103+ .bind(("read", read))
104+ .await?
105+ .check()?;
106+ result
107+ .take::<Vec<Message>>(0)?
108+ .into_iter()
109+ .next()
110+ .ok_or(AppError::NotFound)
111+}
112+
113+/// File `user`'s side into `folder` (already validated against that
114+/// side's allowed set), stamping where the copy came from so it can be
115+/// restored. Only the caller's two fields are written — field-scoped for
116+/// the same race reason as [`set_read`].
117+///
118+/// Filing away remembers the folder being left, so `inbox → archive →
119+/// trash` restores to `archive` and that back to `inbox`. Two folders are
120+/// never stamped: the trash (`trash → archive` would leave the copy
121+/// pointing back at the discard pile — it falls back to the home folder)
122+/// and the target itself (a no-op move keeps the memory it had). Moving
123+/// back to a home folder clears it.
124+pub async fn move_to(
125+ db: &Database,
126+ message: Message,
127+ user: &UserId,
128+ folder: Folder,
129+) -> Result<Message, AppError> {
130+ let current = message.folder_of(user);
131+ let (field, origin_field) = if message.is_sender(user) {
132+ ("sender_folder", "sender_origin")
133+ } else {
134+ ("recipient_folder", "recipient_origin")
135+ };
136+ let origin = match folder {
137+ _ if !folder.is_filed() => None,
138+ _ if current == folder => message.origin_of(user),
139+ _ if current.is_restore_target() => Some(current),
140+ _ => None,
141+ };
142+ let mut result = db
143+ .query(format!(
144+ "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"
145+ ))
146+ .bind(("id", message.id.record()))
147+ .bind(("folder", folder.as_str().to_string()))
148+ .bind(("origin", origin.map(|origin| origin.as_str().to_string())))
149+ .await?
150+ .check()?;
151+ result
152+ .take::<Vec<Message>>(0)?
153+ .into_iter()
154+ .next()
155+ .ok_or(AppError::NotFound)
156+}
157+
158+/// Permanently drop `user`'s side — only if that side currently sits in
159+/// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent
160+/// move back to the inbox can't slip past a check-then-act window. The
161+/// row itself is removed once both sides are gone — judged on the
162+/// post-write row, so two concurrent deletes can't leak an all-deleted
163+/// row.
164+pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> {
165+ let (field, origin_field) = if message.is_sender(user) {
166+ ("sender_folder", "sender_origin")
167+ } else {
168+ ("recipient_folder", "recipient_origin")
169+ };
170+ let mut result = db
171+ .query(format!(
172+ "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \
173+ WHERE {field} = $trash RETURN AFTER"
174+ ))
175+ .bind(("id", message.id.record()))
176+ .bind(("deleted", Folder::Deleted.as_str().to_string()))
177+ .bind(("trash", Folder::Trash.as_str().to_string()))
178+ .await?
179+ .check()?;
180+ let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {
181+ return Err(AppError::Conflict(
182+ "only messages in the trash can be permanently deleted",
183+ ));
184+ };
185+ if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
186+ let _: Option<Message> = db.delete(after.id.record()).await?;
187+ }
188+ Ok(())
189+}
190+
191+#[cfg(test)]
192+mod tests {
193+ use super::*;
194+
195+ /// The `next_ulid` hazard: an inbox is documented newest-first and sorts
196+ /// `id DESC`, so messages sent inside one millisecond must come back in
197+ /// exact reverse write order, not at random (src/domain/monotonic_id.rs).
198+ /// Asserts the *stored* order, not the mint order.
199+ #[tokio::test]
200+ async fn inbox_is_newest_first_within_a_millisecond() {
201+ let db = crate::database::init_mem().await.unwrap();
202+ let sender = UserId::from_key("a");
203+ let recipient = UserId::from_key("b");
204+ let mut sent = Vec::new();
205+ for i in 0..25 {
206+ let message = send(
207+ &db,
208+ &sender,
209+ &recipient,
210+ MessageSubject::try_new(&format!("s{i}")).unwrap(),
211+ MessageBody::try_new("").unwrap(),
212+ None,
213+ )
214+ .await
215+ .unwrap();
216+ sent.push(message.get_id().key().to_string());
217+ }
218+
219+ let (listed, total) = list_folder(&db, &recipient, Folder::Inbox, None, None, 0)
220+ .await
221+ .unwrap();
222+ assert_eq!(total, 25);
223+ sent.reverse();
224+ let read_back: Vec<String> = listed
225+ .iter()
226+ .map(|row| row.get_id().key().to_string())
227+ .collect();
228+ assert_eq!(read_back, sent);
229+ }
230+}
src/db/mod.rsmodified+3 -0
@@ -13,10 +13,13 @@ pub mod exam_attempt;
1313 pub mod exam_question;
1414 pub mod field_update;
1515 pub mod meal_booking;
16+pub mod message;
1617 pub mod note;
1718 pub mod page;
19+pub mod parent_link;
1820 pub mod payment_ledger;
1921 pub mod pomodoro;
22+pub mod registration;
2023 pub mod session;
2124 pub mod settings;
2225 pub mod user;
src/db/parent_link.rsadded+59 -0
@@ -0,0 +1,59 @@
1+//! The `parent_link` table: the composite-id upsert, the existence probe,
2+//! the per-parent listing, and the delete. The *decisions* over these rows
3+//! — who may be tied, and which reads a live link grants — live in
4+//! [`crate::service::parent_link`].
5+
6+use crate::database::Database;
7+use crate::domain::parent_link::{ParentLink, ParentLinkId};
8+use crate::domain::user::UserId;
9+use crate::error::AppError;
10+
11+pub async fn link(
12+ db: &Database,
13+ parent: &UserId,
14+ student: &UserId,
15+ linked_by: &UserId,
16+) -> Result<ParentLink, AppError> {
17+ let link = ParentLink {
18+ id: ParentLinkId::composite(parent, student),
19+ parent: parent.clone(),
20+ student: student.clone(),
21+ linked_by: linked_by.clone(),
22+ };
23+ let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;
24+ saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))
25+}
26+
27+/// True iff a link row exists for the (parent, student) pair — the storage
28+/// half of the grant. The live half (the student side still holding the
29+/// role) is [`crate::service::parent_link::links_live`].
30+pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> {
31+ let found: Option<ParentLink> = db
32+ .select(ParentLinkId::composite(parent, student).record())
33+ .await?;
34+ Ok(found.is_some())
35+}
36+
37+/// Every student `parent` observes, newest link first.
38+pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
39+ let mut result = db
40+ .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")
41+ .bind(("parent", parent.record()))
42+ .await?
43+ .check()?;
44+ Ok(result.take::<Vec<ParentLink>>(0)?)
45+}
46+
47+pub async fn remove(
48+ db: &Database,
49+ parent: &UserId,
50+ student: &UserId,
51+) -> Result<Option<ParentLink>, AppError> {
52+ let mut result = db
53+ .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")
54+ .bind(("parent", parent.record()))
55+ .bind(("student", student.record()))
56+ .await?
57+ .check()?;
58+ Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())
59+}
src/db/registration.rsadded+55 -0
@@ -0,0 +1,55 @@
1+//! The `registration` table: the seat reads, the per-event listing, and
2+//! the delete that returns the seat in the same transaction. The register
3+//! workflow itself (the cap claim and its conflict mapping) lives in
4+//! [`crate::service::registration`].
5+
6+use crate::database::Database;
7+use crate::domain::event::EventId;
8+use crate::domain::registration::Registration;
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+/// Some(_) iff `user` holds a seat on `event` — the audience point check.
13+pub async fn read_for_user(
14+ db: &Database,
15+ event: &EventId,
16+ user: &UserId,
17+) -> Result<Option<Registration>, AppError> {
18+ let mut result = db
19+ .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")
20+ .bind(("ev", event.record()))
21+ .bind(("usr", user.record()))
22+ .await?
23+ .check()?;
24+ Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
25+}
26+
27+pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Registration>, AppError> {
28+ let mut result = db
29+ .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")
30+ .bind(("ev", event.record()))
31+ .await?
32+ .check()?;
33+ Ok(result.take::<Vec<Registration>>(0)?)
34+}
35+
36+pub async fn remove(
37+ db: &Database,
38+ event: &EventId,
39+ user: &UserId,
40+) -> Result<Option<Registration>, AppError> {
41+ // The seat comes back in the same transaction as the row that held it.
42+ let mut result = db
43+ .query(
44+ "BEGIN TRANSACTION;
45+ LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);
46+ UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);
47+ RETURN $gone;
48+ COMMIT TRANSACTION;",
49+ )
50+ .bind(("ev", event.record()))
51+ .bind(("usr", user.record()))
52+ .await?
53+ .check()?;
54+ Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())
55+}
src/domain/message.rsmodified+18 -231
@@ -12,12 +12,10 @@ use crate::constant::{
1212 MAX_MESSAGE_BODY_LEN, MAX_MESSAGE_LABEL_LEN, MAX_MESSAGE_SUBJECT_LEN, MESSAGE_TABLE,
1313 RECIPIENT_FOLDERS, SENDER_FOLDERS,
1414 };
15-use crate::database::Database;
1615 use crate::domain::monotonic_id::next_ulid;
17-use crate::db::page::PagedList;
1816 use crate::domain::timestamp::Timestamp;
1917 use crate::domain::user::UserId;
20-use crate::error::{AppError, ValidationError};
18+use crate::error::ValidationError;
2119 use crate::validate::{validate_optional, validate_required};
2220
2321 /// The mailbox folders a copy can sit in — the single source of folder names
@@ -36,7 +34,7 @@ pub enum Folder {
3634 Archive,
3735 Trash,
3836 /// The hidden "my copy is gone" folder; never a valid move or list
39- /// target — reached only through [`Message::delete_for`].
37+ /// target — reached only through [`crate::db::message::delete_for`].
4038 Deleted,
4139 }
4240
@@ -86,14 +84,14 @@ impl Folder {
8684 }
8785
8886 /// A filed-away copy — one that has somewhere to be restored to.
89- fn is_filed(self) -> bool {
87+ pub(crate) fn is_filed(self) -> bool {
9088 matches!(self, Folder::Archive | Folder::Trash)
9189 }
9290
9391 /// Whether this folder is worth remembering as a restore target. The
9492 /// trash is not: pulling a copy out of the trash and into the archive
9593 /// must not leave it pointing back at the trash.
96- fn is_restore_target(self) -> bool {
94+ pub(crate) fn is_restore_target(self) -> bool {
9795 matches!(self, Folder::Inbox | Folder::Sent | Folder::Archive)
9896 }
9997 }
@@ -103,7 +101,8 @@ pub struct MessageId(RecordId);
103101
104102 impl MessageId {
105103 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
106- /// the folder listings sort `id DESC` (newest first, [`Message::list_folder`]),
104+ /// the folder listings sort `id DESC` (newest first,
105+ /// [`crate::db::message::list_folder`]),
107106 /// and a random low half scrambles rows minted in the same millisecond.
108107 pub fn generate() -> Self {
109108 Self(RecordId::new(MESSAGE_TABLE, next_ulid().to_string()))
@@ -171,20 +170,20 @@ impl MessageLabel {
171170
172171 #[derive(Debug, Clone, SurrealValue)]
173172 pub struct Message {
174- id: MessageId,
175- sender: UserId,
176- recipient: UserId,
177- subject: MessageSubject,
178- body: MessageBody,
179- label: Option<MessageLabel>,
180- sent_at: Timestamp,
181- read: bool,
182- sender_folder: Folder,
183- recipient_folder: Folder,
173+ pub(crate) id: MessageId,
174+ pub(crate) sender: UserId,
175+ pub(crate) recipient: UserId,
176+ pub(crate) subject: MessageSubject,
177+ pub(crate) body: MessageBody,
178+ pub(crate) label: Option<MessageLabel>,
179+ pub(crate) sent_at: Timestamp,
180+ pub(crate) read: bool,
181+ pub(crate) sender_folder: Folder,
182+ pub(crate) recipient_folder: Folder,
184183 /// Where each side's copy sat before it was filed into archive/trash —
185184 /// the restore target. `None` while the copy sits in its home folder.
186- sender_origin: Option<Folder>,
187- recipient_origin: Option<Folder>,
185+ pub(crate) sender_origin: Option<Folder>,
186+ pub(crate) recipient_origin: Option<Folder>,
188187 }
189188
190189 impl Message {
@@ -243,182 +242,6 @@ impl Message {
243242 self.recipient_origin
244243 }
245244 }
246-
247- pub async fn send(
248- sender: &UserId,
249- recipient: &UserId,
250- subject: MessageSubject,
251- body: MessageBody,
252- label: Option<MessageLabel>,
253- db: &Database,
254- ) -> Result<Message, AppError> {
255- let message = Message {
256- id: MessageId::generate(),
257- sender: sender.clone(),
258- recipient: recipient.clone(),
259- subject,
260- body,
261- label,
262- sent_at: Timestamp::now(),
263- read: false,
264- sender_folder: Folder::Sent,
265- recipient_folder: Folder::Inbox,
266- sender_origin: None,
267- recipient_origin: None,
268- };
269- let created: Option<Message> = db.create(message.id.record()).content(message).await?;
270- created.ok_or_else(|| AppError::Internal("failed to create message".into()))
271- }
272-
273- /// One folder view for `user`, newest first. `inbox` is recipient-side,
274- /// `sent` is sender-side, and `archive`/`trash` are each the union of both
275- /// sides' filed copies (either party may archive or trash their own copy).
276- /// `read` narrows to that flag state (`false` on the inbox is the unread
277- /// view; on `sent`, receipts pending) — the folder condition is
278- /// parenthesized because `archive`'s and `trash`'s are ORs.
279- pub async fn list_folder(
280- user: &UserId,
281- folder: Folder,
282- read: Option<bool>,
283- limit: Option<i64>,
284- offset: i64,
285- db: &Database,
286- ) -> Result<(Vec<Message>, i64), AppError> {
287- let condition = match folder {
288- Folder::Sent => "sender = $usr AND sender_folder = 'sent'",
289- Folder::Archive => {
290- "(recipient = $usr AND recipient_folder = 'archive') \
291- OR (sender = $usr AND sender_folder = 'archive')"
292- }
293- Folder::Trash => {
294- "(recipient = $usr AND recipient_folder = 'trash') \
295- OR (sender = $usr AND sender_folder = 'trash')"
296- }
297- _ => "recipient = $usr AND recipient_folder = $folder",
298- };
299- let read_clause = if read.is_some() {
300- " AND read = $read"
301- } else {
302- ""
303- };
304- PagedList::new(
305- format!("message WHERE ({condition}){read_clause}"),
306- "ORDER BY id DESC",
307- )
308- .bind("usr", user.record())
309- .bind("folder", folder.as_str().to_string())
310- .bind("read", read.unwrap_or_default())
311- .run(limit, offset, db)
312- .await
313- }
314-
315- /// Read a message only if `user` is its sender or recipient and their
316- /// side hasn't been permanently deleted.
317- pub async fn read_for(
318- id: &MessageId,
319- user: &UserId,
320- db: &Database,
321- ) -> Result<Option<Message>, AppError> {
322- let message: Option<Message> = db.select(id.record()).await?;
323- Ok(message.filter(|message| {
324- (&message.sender == user || &message.recipient == user)
325- && message.folder_of(user) != Folder::Deleted
326- }))
327- }
328-
329- /// Flip the recipient's read flag. Field-scoped write: the sender may be
330- /// filing their side concurrently, and a whole-row save would clobber it.
331- pub async fn set_read(self, read: bool, db: &Database) -> Result<Message, AppError> {
332- let mut result = db
333- .query("UPDATE $id SET read = $read RETURN AFTER")
334- .bind(("id", self.id.record()))
335- .bind(("read", read))
336- .await?
337- .check()?;
338- result
339- .take::<Vec<Message>>(0)?
340- .into_iter()
341- .next()
342- .ok_or(AppError::NotFound)
343- }
344-
345- /// File `user`'s side into `folder` (already validated against that
346- /// side's allowed set), stamping where the copy came from so it can be
347- /// restored. Only the caller's two fields are written — field-scoped for
348- /// the same race reason as [`Message::set_read`].
349- ///
350- /// Filing away remembers the folder being left, so `inbox → archive →
351- /// trash` restores to `archive` and that back to `inbox`. Two folders are
352- /// never stamped: the trash (`trash → archive` would leave the copy
353- /// pointing back at the discard pile — it falls back to the home folder)
354- /// and the target itself (a no-op move keeps the memory it had). Moving
355- /// back to a home folder clears it.
356- pub async fn move_to(
357- self,
358- user: &UserId,
359- folder: Folder,
360- db: &Database,
361- ) -> Result<Message, AppError> {
362- let current = self.folder_of(user);
363- let (field, origin_field) = if self.is_sender(user) {
364- ("sender_folder", "sender_origin")
365- } else {
366- ("recipient_folder", "recipient_origin")
367- };
368- let origin = match folder {
369- _ if !folder.is_filed() => None,
370- _ if current == folder => self.origin_of(user),
371- _ if current.is_restore_target() => Some(current),
372- _ => None,
373- };
374- let mut result = db
375- .query(format!(
376- "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"
377- ))
378- .bind(("id", self.id.record()))
379- .bind(("folder", folder.as_str().to_string()))
380- .bind(("origin", origin.map(|origin| origin.as_str().to_string())))
381- .await?
382- .check()?;
383- result
384- .take::<Vec<Message>>(0)?
385- .into_iter()
386- .next()
387- .ok_or(AppError::NotFound)
388- }
389-
390- /// Permanently drop `user`'s side — only if that side currently sits in
391- /// the trash; the gate rides in the `UPDATE`'s `WHERE` so a concurrent
392- /// move back to the inbox can't slip past a check-then-act window. The
393- /// row itself is removed once both sides are gone — judged on the
394- /// post-write row, so two concurrent deletes can't leak an all-deleted
395- /// row.
396- pub async fn delete_for(self, user: &UserId, db: &Database) -> Result<(), AppError> {
397- let (field, origin_field) = if self.is_sender(user) {
398- ("sender_folder", "sender_origin")
399- } else {
400- ("recipient_folder", "recipient_origin")
401- };
402- let mut result = db
403- .query(format!(
404- "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \
405- WHERE {field} = $trash RETURN AFTER"
406- ))
407- .bind(("id", self.id.record()))
408- .bind(("deleted", Folder::Deleted.as_str().to_string()))
409- .bind(("trash", Folder::Trash.as_str().to_string()))
410- .await?
411- .check()?;
412- let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {
413- return Err(AppError::Conflict(
414- "only messages in the trash can be permanently deleted",
415- ));
416- };
417- if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
418- let _: Option<Message> = db.delete(after.id.record()).await?;
419- }
420- Ok(())
421- }
422245 }
423246
424247 #[cfg(test)]
@@ -432,42 +255,6 @@ mod tests {
432255 assert_eq!(MessageBody::try_new("").unwrap().as_str(), "");
433256 }
434257
435- /// The `next_ulid` hazard: an inbox is documented newest-first and sorts
436- /// `id DESC`, so messages sent inside one millisecond must come back in
437- /// exact reverse write order, not at random (src/domain/monotonic_id.rs).
438- /// Asserts the *stored* order, not the mint order.
439- #[tokio::test]
440- async fn inbox_is_newest_first_within_a_millisecond() {
441- let db = crate::database::init_mem().await.unwrap();
442- let sender = UserId::from_key("a");
443- let recipient = UserId::from_key("b");
444- let mut sent = Vec::new();
445- for i in 0..25 {
446- let message = Message::send(
447- &sender,
448- &recipient,
449- MessageSubject::try_new(&format!("s{i}")).unwrap(),
450- MessageBody::try_new("").unwrap(),
451- None,
452- &db,
453- )
454- .await
455- .unwrap();
456- sent.push(message.get_id().key().to_string());
457- }
458-
459- let (listed, total) = Message::list_folder(&recipient, Folder::Inbox, None, None, 0, &db)
460- .await
461- .unwrap();
462- assert_eq!(total, 25);
463- sent.reverse();
464- let read_back: Vec<String> = listed
465- .iter()
466- .map(|row| row.get_id().key().to_string())
467- .collect();
468- assert_eq!(read_back, sent);
469- }
470-
471258 #[tokio::test]
472259 async fn folder_sides_resolve_by_membership() {
473260 let sender = UserId::from_key("a");
src/domain/parent_link.rsmodified+4 -64
@@ -1,9 +1,7 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
33 use crate::constant::PARENT_LINK_TABLE;
4-use crate::database::Database;
54 use crate::domain::user::UserId;
6-use crate::error::AppError;
75
86 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
97 pub struct ParentLinkId(RecordId);
@@ -39,10 +37,10 @@ impl ParentLinkId {
3937 /// is a parent's job and a small child cannot do it themselves.
4038 #[derive(Debug, Clone, SurrealValue)]
4139 pub struct ParentLink {
42- id: ParentLinkId,
43- parent: UserId,
44- student: UserId,
45- linked_by: UserId,
40+ pub(crate) id: ParentLinkId,
41+ pub(crate) parent: UserId,
42+ pub(crate) student: UserId,
43+ pub(crate) linked_by: UserId,
4644 }
4745
4846 impl ParentLink {
@@ -62,64 +60,6 @@ impl ParentLink {
6260 &self.linked_by
6361 }
6462
65- /// Tie (idempotently) `student` to `parent`. One row per pair, keyed by the
66- /// deterministic composite id, so concurrent links converge on one row. The
67- /// caller validates the roles — this only stores the pair.
68- pub async fn link(
69- parent: &UserId,
70- student: &UserId,
71- linked_by: &UserId,
72- db: &Database,
73- ) -> Result<ParentLink, AppError> {
74- let link = ParentLink {
75- id: ParentLinkId::composite(parent, student),
76- parent: parent.clone(),
77- student: student.clone(),
78- linked_by: linked_by.clone(),
79- };
80- let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;
81- saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))
82- }
83-
84- /// True iff `parent` holds a link to `student` — the observation gate.
85- pub async fn exists(
86- parent: &UserId,
87- student: &UserId,
88- db: &Database,
89- ) -> Result<bool, AppError> {
90- let found: Option<ParentLink> = db
91- .select(ParentLinkId::composite(parent, student).record())
92- .await?;
93- Ok(found.is_some())
94- }
95-
96- /// Every student `parent` observes, newest link first.
97- pub async fn list_for_parent(
98- parent: &UserId,
99- db: &Database,
100- ) -> Result<Vec<ParentLink>, AppError> {
101- let mut result = db
102- .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")
103- .bind(("parent", parent.record()))
104- .await?
105- .check()?;
106- Ok(result.take::<Vec<ParentLink>>(0)?)
107- }
108-
109- pub async fn remove(
110- parent: &UserId,
111- student: &UserId,
112- db: &Database,
113- ) -> Result<Option<ParentLink>, AppError> {
114- let mut result = db
115- .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")
116- .bind(("parent", parent.record()))
117- .bind(("student", student.record()))
118- .await?
119- .check()?;
120- Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())
121- }
122-
12363 // Both role-change sweeps (the observed student leaving `student`, the
12464 // observing parent leaving `parent`) live in
12565 // [`crate::service::user::set_role`]: they commit with the role write
src/domain/registration.rsmodified+9 -140
@@ -1,12 +1,8 @@
11 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
22
3-use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};
4-use crate::database::Database;
5-use crate::db::cap;
3+use crate::constant::REGISTRATION_TABLE;
64 use crate::domain::event::EventId;
7-use crate::domain::role::Role;
85 use crate::domain::user::UserId;
9-use crate::error::AppError;
106
117 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
128 pub struct RegistrationId(RecordId);
@@ -41,10 +37,10 @@ impl RegistrationId {
4137 /// away from the registration kind hides them without deleting them.
4238 #[derive(Debug, Clone, SurrealValue)]
4339 pub struct Registration {
44- id: RegistrationId,
45- event: EventId,
46- user: UserId,
47- registered_by: UserId,
40+ pub(crate) id: RegistrationId,
41+ pub(crate) event: EventId,
42+ pub(crate) user: UserId,
43+ pub(crate) registered_by: UserId,
4844 }
4945
5046 impl Registration {
@@ -64,139 +60,12 @@ impl Registration {
6460 &self.registered_by
6561 }
6662
67- /// Register (idempotently) `user` onto `event`, refusing when a capacity
68- /// cap is set and every seat is taken. Someone already listed gets their
69- /// existing row back untouched — a true no-op that never counts against
70- /// the cap and never rewrites who placed them. The seat is taken by
71- /// [`cap::claim_live_and_create`] on the event row — an atomic single-record
72- /// conditional write that reads `audience.capacity` off that same row as it
73- /// decides, so neither a racing registration nor a concurrent PATCH
74- /// *lowering* the capacity can over-admit. Bound as a number instead, the
75- /// snapshot below would admit every request already in flight when the
76- /// lower cap landed.
77- ///
78- /// The seat is claimed on the event row, so the same statement says nothing
79- /// about the *user* it is for — and a fall to `parent` is the one demotion
80- /// whose sweep ([`crate::service::user::set_role`]) can miss a seat and
81- /// leave it unfreeable: `unregister` refuses a non-student target and a
82- /// parent cannot reach the route at all. So the transaction also claims the
83- /// holder's own record ([`cap::role_claim`]), which is the key that
84- /// demotion writes: either the sweep sees this seat, or this write sees the
85- /// parent and takes it back.
86- pub async fn register(
87- event: &EventId,
88- user: &UserId,
89- registered_by: &UserId,
90- db: &Database,
91- ) -> Result<Registration, AppError> {
92- if let Some(existing) = Self::read_for_user(event, user, db).await? {
93- return Ok(existing);
94- }
95- // Read for its refusals only — the audience kind and the closing time.
96- // The seat count itself is re-read by the claim.
97- crate::db::event::read(db, event)
98- .await?
99- .ok_or(AppError::NotFound)?
100- .registration_capacity()?;
101- let registration = Registration {
102- id: RegistrationId::composite(event, user),
103- event: event.clone(),
104- user: user.clone(),
105- registered_by: registered_by.clone(),
106- };
107- match cap::claim_live_and_create(
108- &event.record(),
109- REGISTRATION_COUNT_FIELD,
110- // An uncapped registration list stores no `capacity` key at all
111- // (SurrealDB drops a `NONE`-valued object key), so the coalesce is
112- // what "unlimited" reads as.
113- "audience.capacity ?? $num",
114- cap::UNLIMITED,
115- // Staff hold their own seats, so the bar is not "still a student"
116- // but "still someone who can be taken off the list".
117- Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))),
118- (&registration.id.record(), &registration),
119- db,
120- )
121- .await?
122- {
123- cap::Claimed::Made(created) => Ok(created),
124- // A concurrent placement of the same pair got there first: hand its
125- // row over, the same no-op the early return above would have made,
126- // and with no seat spent either way.
127- cap::Claimed::Duplicate => Self::read_for_user(event, user, db)
128- .await?
129- .ok_or_else(|| AppError::Internal("failed to register user".into())),
130- // Full, the event was deleted between the read and the claim, or
131- // the holder fell to parent while this ran — the conditional writes
132- // match nothing (or throw) either way, and only this path pays for
133- // the reads that tell them apart.
134- cap::Claimed::Full => match crate::db::event::read(db, event).await? {
135- None => Err(AppError::NotFound),
136- Some(_) => match crate::db::user::read(db, user).await? {
137- Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
138- "that account was demoted to parent while this request ran — \
139- only students can be registered for",
140- )),
141- _ => Err(AppError::Conflict("the event is full")),
142- },
143- },
144- }
145- }
146-
147- /// Some(_) iff `user` holds a seat on `event` — the audience point check.
148- pub async fn read_for_user(
149- event: &EventId,
150- user: &UserId,
151- db: &Database,
152- ) -> Result<Option<Registration>, AppError> {
153- let mut result = db
154- .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")
155- .bind(("ev", event.record()))
156- .bind(("usr", user.record()))
157- .await?
158- .check()?;
159- Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())
160- }
161-
162- pub async fn list_for_event(
163- event: &EventId,
164- db: &Database,
165- ) -> Result<Vec<Registration>, AppError> {
166- let mut result = db
167- .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")
168- .bind(("ev", event.record()))
169- .await?
170- .check()?;
171- Ok(result.take::<Vec<Registration>>(0)?)
172- }
173-
174- pub async fn remove(
175- event: &EventId,
176- user: &UserId,
177- db: &Database,
178- ) -> Result<Option<Registration>, AppError> {
179- // The seat comes back in the same transaction as the row that held it.
180- let mut result = db
181- .query(
182- "BEGIN TRANSACTION;
183- LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);
184- UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);
185- RETURN $gone;
186- COMMIT TRANSACTION;",
187- )
188- .bind(("ev", event.record()))
189- .bind(("usr", user.record()))
190- .await?
191- .check()?;
192- Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())
193- }
194-
19563 // The demotion sweep — freeing every seat a fall to `parent` would strand,
19664 // and leaving a list that has already frozen exactly as it stands — is an
19765 // arm of [`crate::service::user::set_role`], so the seat comes back in
19866 // the same transaction as the role that invalidated it. The freeze it obeys
199- // is [`Event::registration_capacity`]'s `Conflict` arm, re-spelled for
200- // SurrealQL as [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it
201- // by `event::tests::the_sql_freeze_guard_matches_the_rust_one`.
67+ // is [`crate::domain::event::Event::registration_capacity`]'s `Conflict`
68+ // arm, re-spelled for SurrealQL as
69+ // [`crate::constant::REGISTRATION_FROZEN_GUARD`] and held to it by
70+ // `event::tests::the_sql_freeze_guard_matches_the_rust_one`.
20271 }
src/service/message.rsadded+69 -0
@@ -0,0 +1,69 @@
1+//! Message workflows. Every persistence step here is a single atomic
2+//! record write ([`crate::db::message`]) whose rule rides in its own
3+//! `WHERE` clause, so there is no multi-call lock to hold and no policy of
4+//! its own — the handler validates the DTO, gates on the row it just read,
5+//! and sequences these calls. They live in the service so the web layer
6+//! never names the db layer.
7+
8+use crate::database::Database;
9+use crate::db::message;
10+use crate::domain::message::{
11+ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
12+};
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+pub async fn send(
17+ db: &Database,
18+ sender: &UserId,
19+ recipient: &UserId,
20+ subject: MessageSubject,
21+ body: MessageBody,
22+ label: Option<MessageLabel>,
23+) -> Result<Message, AppError> {
24+ message::send(db, sender, recipient, subject, body, label).await
25+}
26+
27+pub async fn list_folder(
28+ db: &Database,
29+ user: &UserId,
30+ folder: Folder,
31+ read: Option<bool>,
32+ limit: Option<i64>,
33+ offset: i64,
34+) -> Result<(Vec<Message>, i64), AppError> {
35+ message::list_folder(db, user, folder, read, limit, offset).await
36+}
37+
38+pub async fn read_for(
39+ db: &Database,
40+ id: &MessageId,
41+ user: &UserId,
42+) -> Result<Option<Message>, AppError> {
43+ message::read_for(db, id, user).await
44+}
45+
46+pub async fn set_read(
47+ db: &Database,
48+ message_row: Message,
49+ read: bool,
50+) -> Result<Message, AppError> {
51+ message::set_read(db, message_row, read).await
52+}
53+
54+pub async fn move_to(
55+ db: &Database,
56+ message_row: Message,
57+ user: &UserId,
58+ folder: Folder,
59+) -> Result<Message, AppError> {
60+ message::move_to(db, message_row, user, folder).await
61+}
62+
63+pub async fn delete_for(
64+ db: &Database,
65+ message_row: Message,
66+ user: &UserId,
67+) -> Result<(), AppError> {
68+ message::delete_for(db, message_row, user).await
69+}
src/service/mod.rsmodified+3 -0
@@ -12,9 +12,12 @@ pub mod exam;
1212 pub mod exam_attempt;
1313 pub mod exam_question;
1414 pub mod meal_booking;
15+pub mod message;
1516 pub mod note;
17+pub mod parent_link;
1618 pub mod payment_ledger;
1719 pub mod pomodoro;
20+pub mod registration;
1821 pub mod session;
1922 pub mod settings;
2023 pub mod user;
src/service/parent_link.rsadded+107 -0
@@ -0,0 +1,107 @@
1+//! Parent-link decisions: who may be tied to whom (the admin's `link`),
2+//! and what a link grants. A link row alone is never the grant — every
3+//! parent-side permission re-derives it against the student's *live* role
4+//! through [`links_live`], because the demotion sweeps in
5+//! [`crate::service::user::set_role`] run once over the rows that exist at
6+//! that moment and a sweep can lose a race with `link`. The row-storage
7+//! itself is [`crate::db::parent_link`].
8+
9+use crate::database::Database;
10+use crate::db::parent_link;
11+use crate::domain::parent_link::ParentLink;
12+use crate::domain::role::Role;
13+use crate::domain::user::{User, UserId};
14+use crate::error::{AppError, ValidationError};
15+
16+/// Tie (idempotently) `student` to `parent`. The gate is the school-office
17+/// rule: `{id}` must hold the `parent` role and `user_id` the `student`
18+/// role. A stale-link race cannot start here — a target demoted between
19+/// this check and the upsert fails the role gate again on the next call,
20+/// and the sweeps treat the fresh row like any other.
21+///
22+/// Returns the tie plus the two accounts it was judged on, so the caller
23+/// can render the response without re-reading either.
24+pub async fn link(
25+ db: &Database,
26+ parent: &UserId,
27+ student: &UserId,
28+ linked_by: &UserId,
29+) -> Result<(ParentLink, User, User), AppError> {
30+ let parent = crate::service::user::read(db, parent)
31+ .await?
32+ .ok_or(AppError::NotFound)?;
33+ if parent.get_role() != Role::Parent {
34+ return Err(AppError::Validation(ValidationError::Invalid {
35+ field: "id",
36+ reason: "students can only be tied to a parent account",
37+ }));
38+ }
39+ let Some(student) = crate::service::user::read(db, student).await? else {
40+ return Err(AppError::Validation(ValidationError::Invalid {
41+ field: "user_id",
42+ reason: "target user does not exist",
43+ }));
44+ };
45+ if student.get_role() != Role::Student {
46+ return Err(AppError::Validation(ValidationError::Invalid {
47+ field: "user_id",
48+ reason: "only students can be tied to a parent",
49+ }));
50+ }
51+ let link = parent_link::link(db, parent.get_id(), student.get_id(), linked_by).await?;
52+ Ok((link, parent, student))
53+}
54+
55+/// True iff `parent` holds a *live* link to `student`: the row exists AND
56+/// the student side still holds the student role. The link row alone is
57+/// not the grant — like a stale enrollment, a link whose student side
58+/// changed role must be inert, so the target's live role is re-read here.
59+/// A missing or non-student target reads as `false`, so a parent never
60+/// gets an existence oracle.
61+pub async fn links_live(
62+ db: &Database,
63+ parent: &UserId,
64+ student: &UserId,
65+) -> Result<bool, AppError> {
66+ Ok(parent_link::exists(db, parent, student).await?
67+ && crate::service::user::read(db, student)
68+ .await?
69+ .is_some_and(|student| student.get_role() == Role::Student))
70+}
71+
72+/// May `caller` read `target`'s per-student reports (marks, attendance,
73+/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
74+/// business); a parent may exactly when a `parent_link` row ties them to the
75+/// target *and* the target still holds the student role. Everyone else —
76+/// students included — gets a 403 (self-reads go through the `/me` endpoints).
77+pub async fn ensure_can_observe(
78+ caller: &User,
79+ target: &UserId,
80+ db: &Database,
81+) -> Result<(), AppError> {
82+ if caller.get_role().at_least(Role::Teacher) {
83+ return Ok(());
84+ }
85+ if caller.get_role() == Role::Parent && links_live(db, caller.get_id(), target).await? {
86+ return Ok(());
87+ }
88+ Err(AppError::Forbidden(
89+ "requires teacher role or higher, or a parent link to this student",
90+ ))
91+}
92+
93+/// Every student `parent` observes, newest link first. Rows, not a live
94+/// filter — callers re-derive each student's live role themselves when the
95+/// grant matters (the inert-row filter lives with each reader).
96+pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
97+ parent_link::list_for_parent(db, parent).await
98+}
99+
100+/// Untie a student from a parent — `Some` iff a tie existed.
101+pub async fn remove(
102+ db: &Database,
103+ parent: &UserId,
104+ student: &UserId,
105+) -> Result<Option<ParentLink>, AppError> {
106+ parent_link::remove(db, parent, student).await
107+}
src/service/registration.rsadded+103 -0
@@ -0,0 +1,103 @@
1+//! The registration workflow: taking a seat on a registration-audience
2+//! event. The reads and the seat-returning delete are
3+//! [`crate::db::registration`]; the seat itself is [`cap`]'s
4+//! claim-on-the-event-row.
5+
6+use crate::constant::REGISTRATION_COUNT_FIELD;
7+use crate::database::Database;
8+use crate::db::cap;
9+use crate::db::registration;
10+use crate::domain::event::{Event, EventId};
11+use crate::domain::registration::{Registration, RegistrationId};
12+use crate::domain::role::Role;
13+use crate::domain::user::UserId;
14+use crate::error::AppError;
15+
16+/// Register (idempotently) `user` onto `event`, refusing when a capacity
17+/// cap is set and every seat is taken. Someone already listed gets their
18+/// existing row back untouched — a true no-op that never counts against
19+/// the cap and never rewrites who placed them. The seat is taken by
20+/// [`cap::claim_live_and_create`] on the event row — an atomic single-record
21+/// conditional write that reads `audience.capacity` off that same row as it
22+/// decides, so neither a racing registration nor a concurrent PATCH
23+/// *lowering* the capacity can over-admit. Bound as a number instead, the
24+/// snapshot below would admit every request already in flight when the
25+/// lower cap landed.
26+///
27+/// The seat is claimed on the event row, so the same statement says nothing
28+/// about the *user* it is for — and a fall to `parent` is the one demotion
29+/// whose sweep ([`crate::service::user::set_role`]) can miss a seat and
30+/// leave it unfreeable: `unregister` refuses a non-student target and a
31+/// parent cannot reach the route at all. So the transaction also claims the
32+/// holder's own record ([`cap::role_claim`]), which is the key that
33+/// demotion writes: either the sweep sees this seat, or this write sees the
34+/// parent and takes it back.
35+pub async fn register(
36+ db: &Database,
37+ event: &EventId,
38+ user: &UserId,
39+ registered_by: &UserId,
40+) -> Result<Registration, AppError> {
41+ if let Some(existing) = registration::read_for_user(db, event, user).await? {
42+ return Ok(existing);
43+ }
44+ // Read for its refusals only — the audience kind and the closing time.
45+ // The seat count itself is re-read by the claim.
46+ Event::read(event, db)
47+ .await?
48+ .ok_or(AppError::NotFound)?
49+ .registration_capacity()?;
50+ let registration_row = Registration {
51+ id: RegistrationId::composite(event, user),
52+ event: event.clone(),
53+ user: user.clone(),
54+ registered_by: registered_by.clone(),
55+ };
56+ match cap::claim_live_and_create(
57+ &event.record(),
58+ REGISTRATION_COUNT_FIELD,
59+ // An uncapped registration list stores no `capacity` key at all
60+ // (SurrealDB drops a `NONE`-valued object key), so the coalesce is
61+ // what "unlimited" reads as.
62+ "audience.capacity ?? $num",
63+ cap::UNLIMITED,
64+ // Staff hold their own seats, so the bar is not "still a student"
65+ // but "still someone who can be taken off the list".
66+ Some((&user.record(), &format!("= '{}'", Role::Parent.as_str()))),
67+ (&registration_row.id.record(), &registration_row),
68+ db,
69+ )
70+ .await?
71+ {
72+ cap::Claimed::Made(created) => Ok(created),
73+ // A concurrent placement of the same pair got there first: hand its
74+ // row over, the same no-op the early return above would have made,
75+ // and with no seat spent either way.
76+ cap::Claimed::Duplicate => registration::read_for_user(db, event, user)
77+ .await?
78+ .ok_or_else(|| AppError::Internal("failed to register user".into())),
79+ // Full, the event was deleted between the read and the claim, or
80+ // the holder fell to parent while this ran — the conditional writes
81+ // match nothing (or throw) either way, and only this path pays for
82+ // the reads that tell them apart.
83+ cap::Claimed::Full => match Event::read(event, db).await? {
84+ None => Err(AppError::NotFound),
85+ Some(_) => match crate::db::user::read(db, user).await? {
86+ Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
87+ "that account was demoted to parent while this request ran — \
88+ only students can be registered for",
89+ )),
90+ _ => Err(AppError::Conflict("the event is full")),
91+ },
92+ },
93+ }
94+}
95+
96+/// Take a user off the list; `Some` iff they held a seat.
97+pub async fn remove(
98+ db: &Database,
99+ event: &EventId,
100+ user: &UserId,
101+) -> Result<Option<Registration>, AppError> {
102+ registration::remove(db, event, user).await
103+}
src/web/attendance.rsmodified+2 -1
@@ -15,10 +15,11 @@ use crate::domain::role::Role;
1515 use crate::domain::session_attendance::SessionAttendance;
1616 use crate::domain::user::{User, UserId};
1717 use crate::error::{AppError, ErrorResponse};
18+use crate::service::parent_link::ensure_can_observe;
1819 use crate::state::AppState;
1920
2021 use super::courses::can_manage_course;
21-use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};
22+use super::{CourseResponse, CurrentUser, course_people, person_map};
2223
2324 pub fn routes() -> OpenApiRouter<AppState> {
2425 OpenApiRouter::new()
src/web/classes.rsmodified+3 -2
@@ -26,13 +26,14 @@ use crate::domain::role::Role;
2626 use crate::domain::user::{User, UserId};
2727 use crate::error::{AppError, ErrorResponse, ValidationError};
2828 use crate::service::class_blueprint;
29+use crate::service::parent_link::ensure_can_observe;
2930 use crate::state::AppState;
3031
3132 use super::courses::can_manage_course;
3233 use super::terms::resolve_term;
3334 use super::{
34- CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, ensure_can_observe,
35- person_map, set_or_clear, undo_if_demoted,
35+ CurrentUser, Page, PageParams, PersonRef, RequireManager, RequireTeacher, person_map,
36+ set_or_clear, undo_if_demoted,
3637 };
3738
3839 pub fn routes() -> OpenApiRouter<AppState> {
src/web/events.rsmodified+5 -5
@@ -14,7 +14,6 @@ use crate::domain::attendance::{Attendance, AttendanceStatus};
1414 use crate::domain::class_group::{ClassGroup, ClassGroupId};
1515 use crate::domain::course::CourseId;
1616 use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
17-use crate::domain::registration::Registration;
1817 use crate::domain::role::Role;
1918 use crate::domain::timestamp::Timestamp;
2019 use crate::domain::user::{User, UserId};
@@ -756,7 +755,7 @@ async fn register(
756755 .await?
757756 .ok_or(AppError::NotFound)?;
758757 // Fast-fail gate; the authoritative re-check runs inside
759- // `Registration::register` under its lock.
758+ // `service::registration::register` under its lock.
760759 event.registration_capacity()?;
761760
762761 let target = match req.user_id {
@@ -776,7 +775,8 @@ async fn register(
776775 ));
777776 }
778777
779- let registration = Registration::register(&event_id, &target, user.get_id(), &st.db).await?;
778+ let registration =
779+ crate::service::registration::register(&st.db, &event_id, &target, user.get_id()).await?;
780780 // Resolve from the row, not the request: a re-register returns the
781781 // existing seat, whose registered_by is the *original* placer — someone
782782 // the {target, caller} pair may not contain.
@@ -836,7 +836,7 @@ async fn unregister(
836836 // staff member's seat is theirs alone. The bar is *staff*, not "a student":
837837 // a parent holds no seat any route can reach — they cannot get past
838838 // `RequireTeacher` to free their own — so a seat under that role is
839- // stranded, and a volume written before `Registration::register` claimed
839+ // stranded, and a volume written before `service::registration::register` claimed
840840 // the holder's row already carries some.
841841 if &target != user.get_id()
842842 && let Some(target_user) = crate::service::user::read(&st.db, &target).await?
@@ -847,7 +847,7 @@ async fn unregister(
847847 ));
848848 }
849849
850- if Registration::remove(&event_id, &target, &st.db)
850+ if crate::service::registration::remove(&st.db, &event_id, &target)
851851 .await?
852852 .is_none()
853853 {
src/web/homework.rsmodified+2 -1
@@ -34,6 +34,7 @@ use crate::domain::timestamp::Timestamp;
3434 use crate::domain::user::{User, UserId};
3535 use crate::error::{AppError, ErrorResponse, ValidationError};
3636 use crate::service;
37+use crate::service::parent_link::ensure_can_observe;
3738 use crate::state::AppState;
3839
3940 use super::courses::{can_manage_course, can_view_course, visible_courses};
@@ -41,7 +42,7 @@ use super::notes::content_disposition;
4142 use super::subjects::subject_in_course;
4243 use super::{
4344 CurrentUser, HomeworkResponse, Page, PageParams, RequireTeacher, UploadFileForm, blob_path,
44- check_not_past, ensure_can_observe, paginate, read_upload, remove_blob, set_or_clear,
45+ check_not_past, paginate, read_upload, remove_blob, set_or_clear,
4546 };
4647
4748 /// Serializes the homework subsystem's cross-record check-then-writes, which
src/web/marks.rsmodified+2 -1
@@ -16,10 +16,11 @@ use crate::domain::role::Role;
1616 use crate::domain::user::{User, UserId};
1717 use crate::error::{AppError, ErrorResponse};
1818 use crate::service;
19+use crate::service::parent_link::ensure_can_observe;
1920 use crate::state::AppState;
2021
2122 use super::courses::can_manage_course;
22-use super::{CourseResponse, CurrentUser, course_people, ensure_can_observe, person_map};
23+use super::{CourseResponse, CurrentUser, course_people, person_map};
2324
2425 pub fn routes() -> OpenApiRouter<AppState> {
2526 OpenApiRouter::new()
src/web/meals.rsmodified+10 -14
@@ -28,7 +28,6 @@ use crate::domain::menu::{MENU_LOCK, Menu, MenuDate, MenuId, MenuSlot, validate_
2828 use crate::domain::menu_dish::{
2929 DishDescription, DishName, DishPrice, DishTags, MenuDish, MenuDishId,
3030 };
31-use crate::domain::parent_link::ParentLink;
3231 // The same idempotence key `/payments/credits` takes — one grammar, one type.
3332 use crate::domain::payment_ledger::PaymentRequestKey;
3433 use crate::domain::role::Role;
@@ -802,11 +801,7 @@ async fn booking_target(
802801 reason: "a parent must name the student the seat is for",
803802 },
804803 ))?);
805- if ParentLink::exists(caller.get_id(), &target, db).await?
806- && crate::service::user::read(db, &target)
807- .await?
808- .is_some_and(|target| target.get_role() == Role::Student)
809- {
804+ if crate::service::parent_link::links_live(db, caller.get_id(), &target).await? {
810805 return Ok(target);
811806 }
812807 Err(AppError::Forbidden(
@@ -903,7 +898,7 @@ async fn my_bookings(
903898 let mut students = vec![user.get_id().clone()];
904899 if user.get_role() == Role::Parent {
905900 students.extend(
906- ParentLink::list_for_parent(user.get_id(), &st.db)
901+ crate::service::parent_link::list_for_parent(&st.db, user.get_id())
907902 .await?
908903 .iter()
909904 .map(|link| link.get_student().clone()),
@@ -1146,7 +1141,10 @@ async fn mark_attendance(
11461141 let student = UserId::from_key(&req.student_id);
11471142 // The target must exist; no booking is required, since a walk-in was still
11481143 // served and the record is operationally true.
1149- if crate::service::user::read(&st.db, &student).await?.is_none() {
1144+ if crate::service::user::read(&st.db, &student)
1145+ .await?
1146+ .is_none()
1147+ {
11501148 return Err(AppError::Validation(ValidationError::Invalid {
11511149 field: "student_id",
11521150 reason: "target user does not exist",
@@ -1318,7 +1316,8 @@ async fn balance_response(
13181316 /// Reading someone else's meal record — money, attendance, dietary profile:
13191317 /// teacher+, or a parent linked to the student. Reading your *own* is always
13201318 /// allowed, since every `{user}` route here accepts the caller's own id; that
1321-/// is the one way this gate differs from [`super::ensure_can_observe`], which
1319+/// is the one way this gate differs from
1320+/// [`crate::service::parent_link::ensure_can_observe`], which
13221321 /// 403s a self-read because its subjects have their own `/me` routes.
13231322 async fn ensure_can_read_student(
13241323 caller: &User,
@@ -1328,7 +1327,7 @@ async fn ensure_can_read_student(
13281327 if caller.get_id() == target {
13291328 return Ok(());
13301329 }
1331- super::ensure_can_observe(caller, target, db).await
1330+ crate::service::parent_link::ensure_can_observe(caller, target, db).await
13321331 }
13331332
13341333 /// May `caller` read `target`'s meal *money* — balance and ledger? Own always;
@@ -1351,10 +1350,7 @@ async fn ensure_can_read_money(
13511350 // role must be inert, so the target's live role is re-read. A missing or
13521351 // non-student target falls through to the same 403 — a parent never gets an
13531352 if caller.get_role() == Role::Parent
1354- && ParentLink::exists(caller.get_id(), target, db).await?
1355- && crate::service::user::read(db, target)
1356- .await?
1357- .is_some_and(|target| target.get_role() == Role::Student)
1353+ && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
13581354 {
13591355 return Ok(());
13601356 }
src/web/messages.rsmodified+9 -8
@@ -15,6 +15,7 @@ use crate::domain::message::{
1515 };
1616 use crate::domain::user::{User, UserId};
1717 use crate::error::{AppError, ErrorResponse, ValidationError};
18+use crate::service::message;
1819 use crate::state::AppState;
1920
2021 use super::dto::Role;
@@ -206,13 +207,13 @@ async fn send_message(
206207 ));
207208 }
208209
209- let message = Message::send(
210+ let message = message::send(
211+ &st.db,
210212 user.get_id(),
211213 recipient.get_id(),
212214 subject,
213215 body,
214216 label,
215- &st.db,
216217 )
217218 .await?;
218219 let people = people_of([&user, &recipient]);
@@ -250,7 +251,7 @@ async fn list(
250251 };
251252
252253 let (messages, total) =
253- Message::list_folder(user.get_id(), folder, filter.read, limit, offset, &st.db).await?;
254+ message::list_folder(&st.db, user.get_id(), folder, filter.read, limit, offset).await?;
254255 let people = load_people(&messages, &st.db).await?;
255256 let items = messages
256257 .iter()
@@ -288,7 +289,7 @@ async fn update_message(
288289 Path(id): Path<String>,
289290 Json(req): Json<UpdateMessage>,
290291 ) -> Result<Json<MessageResponse>, AppError> {
291- let mut message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db)
292+ let mut message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id())
292293 .await?
293294 .ok_or(AppError::NotFound)?;
294295
@@ -313,10 +314,10 @@ async fn update_message(
313314 None => None,
314315 };
315316 if let Some(read) = req.read {
316- message = message.set_read(read, &st.db).await?;
317+ message = message::set_read(&st.db, message, read).await?;
317318 }
318319 if let Some(folder) = folder {
319- message = message.move_to(user.get_id(), folder, &st.db).await?;
320+ message = message::move_to(&st.db, message, user.get_id(), folder).await?;
320321 }
321322
322323 let people = load_people(std::slice::from_ref(&message), &st.db).await?;
@@ -344,9 +345,9 @@ async fn delete_message(
344345 CurrentUser(user): CurrentUser,
345346 Path(id): Path<String>,
346347 ) -> Result<StatusCode, AppError> {
347- let message = Message::read_for(&MessageId::from_key(&id), user.get_id(), &st.db)
348+ let message = message::read_for(&st.db, &MessageId::from_key(&id), user.get_id())
348349 .await?
349350 .ok_or(AppError::NotFound)?;
350- message.delete_for(user.get_id(), &st.db).await?;
351+ message::delete_for(&st.db, message, user.get_id()).await?;
351352 Ok(StatusCode::NO_CONTENT)
352353 }
src/web/mod.rsmodified+1 -33
@@ -72,43 +72,11 @@ use crate::constant::{QUESTION_IMAGE_CONTENT_TYPES, SCHEDULE_PAST_GRACE_MS};
7272 use crate::database::Database;
7373 use crate::domain::exam_question::{Choice, ChoiceInput};
7474 use crate::domain::note_file::FileContentType;
75-use crate::domain::parent_link::ParentLink;
7675 use crate::domain::role::Role;
7776 use crate::domain::timestamp::Timestamp;
78-use crate::domain::user::{User, UserId};
77+use crate::domain::user::UserId;
7978 use crate::error::{AppError, ValidationError};
8079
81-/// May `caller` read `target`'s per-student reports (marks, attendance,
82-/// pomodoro)? Teacher+ always may (per-endpoint narrowing is the caller's
83-/// business); a parent may exactly when a `parent_link` row ties them to the
84-/// target *and* the target still holds the student role. Everyone else —
85-/// students included — gets a 403 (self-reads go through the `/me` endpoints).
86-pub(crate) async fn ensure_can_observe(
87- caller: &User,
88- target: &UserId,
89- db: &Database,
90-) -> Result<(), AppError> {
91- if caller.get_role().at_least(Role::Teacher) {
92- return Ok(());
93- }
94- // The link row alone is not the grant: like stale enrollments, a link
95- // whose student side changed role (a sweep lost a race with link_student)
96- // must be inert, so the target's live role is re-read here. Missing or
97- // non-student targets fall through to the same 403 — a parent never gets
98- // an existence oracle.
99- if caller.get_role() == Role::Parent
100- && ParentLink::exists(caller.get_id(), target, db).await?
101- && crate::service::user::read(db, target)
102- .await?
103- .is_some_and(|target| target.get_role() == Role::Student)
104- {
105- return Ok(());
106- }
107- Err(AppError::Forbidden(
108- "requires teacher role or higher, or a parent link to this student",
109- ))
110-}
111-
11280 /// Close the window between "this account is teacher+" and the write that
11381 /// records a teacher-only assignment (a class's homeroom teacher, a course's
11482 /// teacher list). Call it *after* the write, with the account it named.
src/web/payments.rsmodified+5 -7
@@ -3,7 +3,8 @@
33 //!
44 //! Every write here is manager+ — money is school administration, and a teacher
55 //! has no business in it. The read gate is deliberately *narrower* than the
6-//! per-student reports elsewhere ([`super::ensure_can_observe`]): a student sees
6+//! per-student reports elsewhere
7+//! ([`crate::service::parent_link::ensure_can_observe`]): a student sees
78 //! their own record, a parent a linked student's, manager+ everyone's, and a
89 //! teacher nothing at all.
910 //!
@@ -26,7 +27,6 @@ use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES};
2627 use crate::database::Database;
2728 use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};
2829 use crate::domain::fee_plan_assignment::FeePlanAssignment;
29-use crate::domain::parent_link::ParentLink;
3030 use crate::domain::payment_ledger::{
3131 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
3232 PaymentRequestKey,
@@ -775,7 +775,8 @@ async fn record_reversal(
775775 /// May `caller` read `target`'s payment record? Own always; a parent only for a
776776 /// student they hold a live link to; manager+ for anyone.
777777 ///
778-/// Deliberately narrower than [`super::ensure_can_observe`]: **a teacher sees no
778+/// Deliberately narrower than
779+/// [`crate::service::parent_link::ensure_can_observe`]: **a teacher sees no
779780 /// money**. What a family owes the school is not classroom information.
780781 async fn ensure_can_read_payments(
781782 caller: &User,
@@ -790,10 +791,7 @@ async fn ensure_can_read_payments(
790791 // non-student target falls through to the same 403 — a parent never gets an
791792 // existence oracle.
792793 if caller.get_role() == Role::Parent
793- && ParentLink::exists(caller.get_id(), target, db).await?
794- && crate::service::user::read(db, target)
795- .await?
796- .is_some_and(|target| target.get_role() == Role::Student)
794+ && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
797795 {
798796 return Ok(());
799797 }
src/web/pomodoro.rsmodified+2 -1
@@ -11,10 +11,11 @@ use crate::domain::pomodoro::PomodoroSession;
1111 use crate::domain::role::Role;
1212 use crate::domain::user::{User, UserId};
1313 use crate::error::{AppError, ErrorResponse};
14+use crate::service::parent_link::ensure_can_observe;
1415 use crate::service::pomodoro;
1516 use crate::state::AppState;
1617
17-use super::{CurrentUser, PageParams, ensure_can_observe, paginate};
18+use super::{CurrentUser, PageParams, paginate};
1819
1920 pub fn routes() -> OpenApiRouter<AppState> {
2021 OpenApiRouter::new()
src/web/users.rsmodified+33 -41
@@ -17,20 +17,20 @@ use crate::domain::badge::{self, BadgeAward};
1717 use crate::domain::class_group::{ClassGroup, ClassGroupId};
1818 use crate::domain::class_member::ClassMember;
1919
20-use crate::domain::parent_link::ParentLink;
2120 use crate::domain::preferences::{Language, PaletteColor, Theme};
2221 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone, ProfileStats};
2322 use crate::domain::role::Role;
2423 use crate::domain::user::{User, UserId};
2524 use crate::error::{AppError, ErrorResponse, ValidationError};
25+use crate::service::parent_link::ensure_can_observe;
2626 use crate::state::AppState;
2727
2828 use super::courses::visible_courses;
2929 use super::dto::AssignableRole;
3030 use super::dto::Role as RoleSchema;
3131 use super::{
32- CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse,
33- ensure_can_observe, paginate, read_image_upload, remove_blob, serve_inline_blob, store_blob,
32+ CurrentUser, Page, PageParams, PersonRef, RequireAdmin, UploadFileForm, UserResponse, paginate,
33+ read_image_upload, remove_blob, serve_inline_blob, store_blob,
3434 };
3535
3636 pub fn routes() -> OpenApiRouter<AppState> {
@@ -174,14 +174,9 @@ async fn apply_preferences(
174174 let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?;
175175 let language = merge_field(req.language.as_deref(), Language::try_from_str)?;
176176 let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?;
177- let updated = crate::service::user::set_preferences(
178- db,
179- user.get_id(),
180- theme,
181- language,
182- palette_color,
183- )
184- .await?;
177+ let updated =
178+ crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color)
179+ .await?;
185180 Ok(UserResponse::new(&updated))
186181 }
187182
@@ -541,7 +536,7 @@ async fn students_page(
541536 db: &Database,
542537 ) -> Result<Page<PersonRef>, AppError> {
543538 let (limit, offset) = page.resolve()?;
544- let links = ParentLink::list_for_parent(parent, db).await?;
539+ let links = crate::service::parent_link::list_for_parent(db, parent).await?;
545540 let ids: Vec<UserId> = links
546541 .iter()
547542 .map(|link| link.get_student().clone())
@@ -593,30 +588,13 @@ async fn link_student(
593588 Path(id): Path<String>,
594589 Json(req): Json<LinkStudent>,
595590 ) -> Result<Json<ParentLinkResponse>, AppError> {
596- let parent = crate::service::user::read(&st.db, &UserId::from_key(&id))
597- .await?
598- .ok_or(AppError::NotFound)?;
599- if parent.get_role() != Role::Parent {
600- return Err(AppError::Validation(ValidationError::Invalid {
601- field: "id",
602- reason: "students can only be tied to a parent account",
603- }));
604- }
605- let Some(student) =
606- crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await?
607- else {
608- return Err(AppError::Validation(ValidationError::Invalid {
609- field: "user_id",
610- reason: "target user does not exist",
611- }));
612- };
613- if student.get_role() != Role::Student {
614- return Err(AppError::Validation(ValidationError::Invalid {
615- field: "user_id",
616- reason: "only students can be tied to a parent",
617- }));
618- }
619- let link = ParentLink::link(parent.get_id(), student.get_id(), admin.get_id(), &st.db).await?;
591+ let (link, parent, student) = crate::service::parent_link::link(
592+ &st.db,
593+ &UserId::from_key(&id),
594+ &UserId::from_key(&req.user_id),
595+ admin.get_id(),
596+ )
597+ .await?;
620598 let people = PersonRef::map_of(&[&parent, &student, &admin]);
621599 Ok(Json(ParentLinkResponse {
622600 parent: PersonRef::resolve(&people, link.get_parent()),
@@ -678,9 +656,13 @@ async fn unlink_student(
678656 _admin: RequireAdmin,
679657 Path((id, student)): Path<(String, String)>,
680658 ) -> Result<StatusCode, AppError> {
681- if ParentLink::remove(&UserId::from_key(&id), &UserId::from_key(&student), &st.db)
682- .await?
683- .is_none()
659+ if crate::service::parent_link::remove(
660+ &st.db,
661+ &UserId::from_key(&id),
662+ &UserId::from_key(&student),
663+ )
664+ .await?
665+ .is_none()
684666 {
685667 return Err(AppError::NotFound);
686668 }
@@ -1070,7 +1052,9 @@ async fn ensure_may_read_profile(
10701052 async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> {
10711053 let target = UserId::from_key(id);
10721054 ensure_may_read_profile(caller, &target, &st.db).await?;
1073- crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound)
1055+ crate::service::user::read(&st.db, &target)
1056+ .await?
1057+ .ok_or(AppError::NotFound)
10741058 }
10751059
10761060 /// The caller's own public profile — what everyone else sees of them.
@@ -1165,7 +1149,15 @@ async fn upload_my_avatar(
11651149
11661150 let file = ulid::Ulid::new().to_string();
11671151 store_blob(&st, &file, &upload.data, || async {
1168- match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? {
1152+ match crate::service::user::set_avatar(
1153+ &st.db,
1154+ user.get_id(),
1155+ &file,
1156+ &upload.content_type,
1157+ size,
1158+ )
1159+ .await?
1160+ {
11691161 // Row written; the picture this one replaced comes off disk.
11701162 Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))),
11711163 // The account went away mid-upload — the fresh blob is an orphan.
tests/regress_role_sweep.rsmodified+5 -5
@@ -26,10 +26,10 @@ use hezarfen_backend::domain::class_group::{ClassGroup, ClassGroupId, ClassName}
2626 use hezarfen_backend::domain::class_member::ClassMember;
2727 use hezarfen_backend::domain::course::CourseId;
2828 use hezarfen_backend::domain::event::EventId;
29-use hezarfen_backend::domain::registration::Registration;
3029 use hezarfen_backend::domain::role::Role;
3130 use hezarfen_backend::domain::timestamp::Timestamp;
3231 use hezarfen_backend::domain::user::UserId;
32+use hezarfen_backend::service::registration;
3333 use serde_json::json;
3434
3535 /// How many rows `sql` selects ids for.
@@ -165,7 +165,7 @@ async fn a_seat_is_refused_once_the_holder_is_a_parent() {
165165 let event = a_registration_event(&app, &teacher, 1).await;
166166 demote(&student, Role::Parent, &db).await;
167167
168- let refused = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await;
168+ let refused = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
169169 assert!(
170170 refused.is_err(),
171171 "a parent may not be given a seat: {refused:?}"
@@ -190,7 +190,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
190190 let event = a_registration_event(&app, &teacher, 1).await;
191191 // The bait: a seat the sweep will delete, which is what holds it open.
192192 let earlier = a_registration_event(&app, &teacher, 1).await;
193- Registration::register(&earlier, &student, &UserId::from_key("staff"), &db)
193+ registration::register(&db, &earlier, &student, &UserId::from_key("staff"))
194194 .await
195195 .unwrap();
196196 hold_the_sweep("registration", &db).await;
@@ -198,7 +198,7 @@ async fn a_seat_never_survives_the_demotion_it_raced() {
198198 // The seat is written inside the held window: past the sweep's snapshot,
199199 // before the commit.
200200 let demoting = demote_in_the_window(&student, Role::Parent, &db).await;
201- let seat = Registration::register(&event, &student, &UserId::from_key("staff"), &db).await;
201+ let seat = registration::register(&db, &event, &student, &UserId::from_key("staff")).await;
202202 still_running(&demoting);
203203 demoting.await.unwrap();
204204
@@ -226,7 +226,7 @@ async fn a_stranded_parent_seat_is_freeable_by_a_teacher() {
226226 let (app, db) = app_and_db().await;
227227 let (teacher, student) = a_school(&app, &db).await;
228228 let event = a_registration_event(&app, &teacher, 1).await;
229- Registration::register(&event, &student, &UserId::from_key("staff"), &db)
229+ registration::register(&db, &event, &student, &UserId::from_key("staff"))
230230 .await
231231 .unwrap();
232232 // The state the old race left: the seat stands, the account is a parent,