forge
Explore
Log in

Don't you dare go Hollow

🔀 merge: port comms+events+misc to sqlx/Postgres (L10)

Browse files at this commit

3de84b70a1d30ef0f07a9578ef25106e4432d791Ahmet Kaan GümüşParent: 1afbf178243707

22 changed files +1750 -1898

src/db/appointment.rsmodified+286 -110
@@ -1,28 +1,24 @@
1 //! The `appointment` table: row reads and listings, the overlap probe behind1 //! The `appointment` table: row reads and listings, the overlap probe behind
2-//! the booking guard, and the compare-and-set every decision writes through.2+//! the booking guard, the seat claim the booking writes through, and the
3-//! The workflows that sequence these under3+//! compare-and-set every decision writes. The workflows live in
4-//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in4+//! [`crate::service::appointment`] (no lock anymore: occupancy is a
5-//! [`crate::service::appointment`].5+//! conditional counter write, the decision CAS is one statement, and the
6+//! approval's overlap decision is a serializable transaction documented at
7+//! its own site).
6 8
7-use surrealdb::types::SurrealValue;9+use crate::database::{Database, tx_with_retry};
8-10+use crate::db::cap::Claimed;
9-use crate::database::{Database, lost_the_race};
10 use crate::db::page::PagedList;11 use crate::db::page::PagedList;
11-use crate::domain::appointment::{Appointment, AppointmentId, AppointmentStatus};12+use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason, AppointmentStatus};
12 use crate::domain::appointment_slot::AppointmentSlotId;13 use crate::domain::appointment_slot::AppointmentSlotId;
13 use crate::domain::timestamp::Timestamp;14 use crate::domain::timestamp::Timestamp;
14 use crate::domain::user::UserId;15 use crate::domain::user::UserId;
15 use crate::error::AppError;16 use crate::error::AppError;
17+use sqlx::{query, query_as, PgConnection, Postgres};
16 18
17-/// The window an approved booking actually occupies, as read back from the19+/// The appointment row's columns, in [`Appointment`]'s field order.
18-/// database: the counter-proposed time when there is one, the slot's own20+const COLS: &str = "id, slot, requester, status, reason, proposed_starts_at, proposed_ends_at, \
19-/// otherwise. Optional fields because a dangling slot reference resolves to21+ proposed_by, decided_by, cancelled_by, cancel_reason, reject_reason, created_at";
20-/// `NONE` — such a row is skipped rather than failing the whole guard.
21-#[derive(Debug, Clone, SurrealValue)]
22-struct BookedWindow {
23- starts_at: Option<Timestamp>,
24- ends_at: Option<Timestamp>,
25-}
26 22
27 /// Is `[starts_at, ends_at)` already taken for either party? Both sides are23 /// Is `[starts_at, ends_at)` already taken for either party? Both sides are
28 /// checked: a teacher can't be in two meetings at once, and neither can a24 /// checked: a teacher can't be in two meetings at once, and neither can a
@@ -33,9 +29,10 @@ struct BookedWindow {
33 /// approval wins. `except` skips one row, so re-checking a booking against29 /// approval wins. `except` skips one row, so re-checking a booking against
34 /// the world never trips over itself.30 /// the world never trips over itself.
35 ///31 ///
36-/// Caller must hold32+/// The effective window (the proposal when one stands, the slot's own
37-/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the answer to still33+/// otherwise) is computed in the query and compared in Rust: one round
38-/// be true by the time it is acted on.34+/// trip, and the comparison stays a plain, unit-tested predicate. A booking
35+/// whose slot was withdrawn since (no window left to stand on) is skipped.
39 pub async fn conflicts(36 pub async fn conflicts(
40 db: &Database,37 db: &Database,
41 teacher: &UserId,38 teacher: &UserId,
@@ -44,45 +41,94 @@ pub async fn conflicts(
44 ends_at: Timestamp,41 ends_at: Timestamp,
45 except: Option<&AppointmentId>,42 except: Option<&AppointmentId>,
46 ) -> Result<bool, AppError> {43 ) -> Result<bool, AppError> {
47- // The effective window is computed in the query (proposal overrides44+ conflicts_on(db, teacher, requester, starts_at, ends_at, except).await
48- // the slot) but compared here: one round trip, and the comparison45+}
49- // itself stays a plain, unit-tested Rust predicate.46+
50- let mut result = db47+/// [`conflicts`] against any executor — the approval decision re-asks this
51- .query(48+/// inside its own transaction, so the verdict it acts on is the one its
52- "SELECT \49+/// snapshot holds.
53- (IF proposed_starts_at != NONE THEN proposed_starts_at \50+pub(crate) async fn conflicts_on<'e, E>(
54- ELSE slot.starts_at END) AS starts_at, \51+ executor: E,
55- (IF proposed_ends_at != NONE THEN proposed_ends_at \52+ teacher: &UserId,
56- ELSE slot.ends_at END) AS ends_at \53+ requester: &UserId,
57- FROM appointment \54+ starts_at: Timestamp,
58- WHERE status = 'approved' AND id != $except \55+ ends_at: Timestamp,
59- AND (requester = $requester OR slot.teacher = $teacher)",56+ except: Option<&AppointmentId>,
60- )57+) -> Result<bool, AppError>
61- .bind(("teacher", teacher.record()))58+where
62- .bind(("requester", requester.record()))59+ E: sqlx::Executor<'e, Database = Postgres>,
63- .bind(("except", except.map(AppointmentId::record)))60+{
64- .await?61+ let windows = query!(
65- .check()?;62+ "SELECT COALESCE(a.proposed_starts_at, s.starts_at) AS starts_at, \
66- Ok(result63+ COALESCE(a.proposed_ends_at, s.ends_at) AS ends_at \
67- .take::<Vec<BookedWindow>>(0)?64+ FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
65+ WHERE a.status = 'approved' \
66+ AND ($3::uuid IS NULL OR a.id <> $3) \
67+ AND (a.requester = $2 OR s.teacher = $1)",
68+ teacher.uuid(),
69+ requester.uuid(),
70+ except.map(|id| id.uuid()),
71+ )
72+ .fetch_all(executor)
73+ .await?;
74+ Ok(windows
68 .into_iter()75 .into_iter()
69- .filter_map(|window| Some((window.starts_at?, window.ends_at?)))76+ .filter_map(|window| {
77+ Some((
78+ Timestamp::from_millis(window.starts_at?),
79+ Timestamp::from_millis(window.ends_at?),
80+ ))
81+ })
70 .any(|(booked_starts_at, booked_ends_at)| {82 .any(|(booked_starts_at, booked_ends_at)| {
71 Appointment::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at)83 Appointment::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at)
72 }))84 }))
73 }85 }
74 86
87+pub(crate) async fn read_on<'e, E>(executor: E, id: &AppointmentId) -> Result<Option<Appointment>, AppError>
88+where
89+ E: sqlx::Executor<'e, Database = Postgres>,
90+{
91+ let appointment = query_as!(
92+ Appointment,
93+ "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
94+ status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
95+ proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
96+ proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
97+ proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
98+ cancelled_by AS \"cancelled_by: UserId\", \
99+ cancel_reason AS \"cancel_reason: AppointmentReason\", \
100+ reject_reason AS \"reject_reason: AppointmentReason\", \
101+ created_at AS \"created_at: Timestamp\" \
102+ FROM appointment WHERE id = $1",
103+ id.uuid()
104+ )
105+ .fetch_optional(executor)
106+ .await?;
107+ Ok(appointment)
108+}
109+
75 pub async fn read(110 pub async fn read(
76 db: &Database,111 db: &Database,
77 id: &AppointmentId,112 id: &AppointmentId,
78 ) -> Result<Option<Appointment>, AppError> {113 ) -> Result<Option<Appointment>, AppError> {
79- Ok(db.select(id.record()).await?)114+ read_on(db, id).await
80 }115 }
81 116
82 /// The row, insisting it is still open for a decision.117 /// The row, insisting it is still open for a decision.
83 pub async fn read_pending(db: &Database, id: &AppointmentId) -> Result<Appointment, AppError> {118 pub async fn read_pending(db: &Database, id: &AppointmentId) -> Result<Appointment, AppError> {
84- let appointment = read(db, id).await?.ok_or(AppError::NotFound)?;119+ read_pending_on(db, id).await
85- if appointment.status != AppointmentStatus::Pending {120+}
121+
122+/// [`read_pending`] against any executor (the approval's transaction).
123+pub(crate) async fn read_pending_on<'e, E>(
124+ executor: E,
125+ id: &AppointmentId,
126+) -> Result<Appointment, AppError>
127+where
128+ E: sqlx::Executor<'e, Database = Postgres>,
129+{
130+ let appointment = read_on(executor, id).await?.ok_or(AppError::NotFound)?;
131+ if appointment.get_status() != AppointmentStatus::Pending {
86 return Err(AppError::Conflict("the appointment is no longer pending"));132 return Err(AppError::Conflict("the appointment is no longer pending"));
87 }133 }
88 Ok(appointment)134 Ok(appointment)
@@ -94,42 +140,152 @@ pub async fn list_for_requester(
94 limit: Option<i64>,140 limit: Option<i64>,
95 offset: i64,141 offset: i64,
96 ) -> Result<(Vec<Appointment>, i64), AppError> {142 ) -> Result<(Vec<Appointment>, i64), AppError> {
97- PagedList::new(143+ PagedList::new("appointment WHERE requester = $1", "ORDER BY id DESC")
98- "appointment WHERE requester = $requester",144+ .bind(requester.uuid())
99- "ORDER BY id DESC",145+ .run(limit, offset, db)
100- )146+ .await
101- .bind("requester", requester.record())
102- .run(limit, offset, db)
103- .await
104 }147 }
105 148
106-/// Every booking aimed at `teacher`, across all their slots — the teacher's149+/// Every booking aimed at `teacher`, across all their slots — the
107-/// request inbox.150+/// teacher's request inbox. The teacher lives on the slot row now, so
151+/// this is a join; the page and its count share the one predicate, and
152+/// the columns are spelled out so the join's duplicate slot-column names
153+/// can never leak into the row decode.
108 pub async fn list_for_teacher(154 pub async fn list_for_teacher(
109 db: &Database,155 db: &Database,
110 teacher: &UserId,156 teacher: &UserId,
111 limit: Option<i64>,157 limit: Option<i64>,
112 offset: i64,158 offset: i64,
113 ) -> Result<(Vec<Appointment>, i64), AppError> {159 ) -> Result<(Vec<Appointment>, i64), AppError> {
114- PagedList::new(160+ match limit {
115- "appointment WHERE slot.teacher = $teacher",161+ None => {
116- "ORDER BY id DESC",162+ let rows = query_as!(
117- )163+ Appointment,
118- .bind("teacher", teacher.record())164+ "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \
119- .run(limit, offset, db)165+ a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \
120- .await166+ a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
167+ a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
168+ a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \
169+ a.cancelled_by AS \"cancelled_by: UserId\", \
170+ a.cancel_reason AS \"cancel_reason: AppointmentReason\", \
171+ a.reject_reason AS \"reject_reason: AppointmentReason\", \
172+ a.created_at AS \"created_at: Timestamp\" \
173+ FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
174+ WHERE s.teacher = $1 \
175+ ORDER BY a.id DESC",
176+ teacher.uuid()
177+ )
178+ .fetch_all(db)
179+ .await?;
180+ Ok((rows, rows.len() as i64))
181+ }
182+ Some(limit) => {
183+ let rows = query_as!(
184+ Appointment,
185+ "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \
186+ a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \
187+ a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
188+ a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
189+ a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \
190+ a.cancelled_by AS \"cancelled_by: UserId\", \
191+ a.cancel_reason AS \"cancel_reason: AppointmentReason\", \
192+ a.reject_reason AS \"reject_reason: AppointmentReason\", \
193+ a.created_at AS \"created_at: Timestamp\" \
194+ FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
195+ WHERE s.teacher = $1 \
196+ ORDER BY a.id DESC LIMIT $2 OFFSET $3",
197+ teacher.uuid(),
198+ limit,
199+ offset
200+ )
201+ .fetch_all(db)
202+ .await?;
203+ let total = query!(
204+ "SELECT count(*) AS total \
205+ FROM appointment a JOIN appointment_slot s ON a.slot = s.id \
206+ WHERE s.teacher = $1",
207+ teacher.uuid()
208+ )
209+ .fetch_one(db)
210+ .await?
211+ .total;
212+ Ok((rows, total))
213+ }
214+ }
121 }215 }
122 216
123 pub async fn list_for_slot(217 pub async fn list_for_slot(
124 db: &Database,218 db: &Database,
125 slot: &AppointmentSlotId,219 slot: &AppointmentSlotId,
126 ) -> Result<Vec<Appointment>, AppError> {220 ) -> Result<Vec<Appointment>, AppError> {
127- let mut result = db221+ let rows = query_as!(
128- .query("SELECT * FROM appointment WHERE slot = $slot ORDER BY id DESC")222+ Appointment,
129- .bind(("slot", slot.record()))223+ "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
130- .await?224+ status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
131- .check()?;225+ proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
132- Ok(result.take::<Vec<Appointment>>(0)?)226+ proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
227+ proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
228+ cancelled_by AS \"cancelled_by: UserId\", \
229+ cancel_reason AS \"cancel_reason: AppointmentReason\", \
230+ reject_reason AS \"reject_reason: AppointmentReason\", \
231+ created_at AS \"created_at: Timestamp\" \
232+ FROM appointment WHERE slot = $1 ORDER BY id DESC",
233+ slot.uuid()
234+ )
235+ .fetch_all(db)
236+ .await?;
237+ Ok(rows)
238+}
239+
240+/// Request `slot`: take the slot's one seat and write the pending booking
241+/// in a single statement — two racing requests cannot both find the slot
242+/// free however they interleave, and a refused insert takes its own seat
243+/// bump back with it. Zero rows means "full, or the slot was deleted since
244+/// the caller read it": the marker is one, and the caller re-reads to pick
245+/// the 404/409.
246+pub async fn claim_slot_and_create(
247+ db: &Database,
248+ appointment: Appointment,
249+) -> Result<Claimed<Appointment>, AppError> {
250+ match query_as!(
251+ Appointment,
252+ "WITH seat AS (
253+ UPDATE appointment_slot SET occupied = occupied + 1
254+ WHERE id = $1 AND occupied < 1
255+ RETURNING 1)
256+ INSERT INTO appointment (id, slot, requester, status, reason, proposed_starts_at, \
257+ proposed_ends_at, proposed_by, decided_by, cancelled_by, \
258+ cancel_reason, reject_reason, created_at)
259+ SELECT $2, $1, $3, 'pending', $4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $5
260+ WHERE EXISTS (SELECT 1 FROM seat)
261+ RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
262+ status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
263+ proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
264+ proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
265+ proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
266+ cancelled_by AS \"cancelled_by: UserId\", \
267+ cancel_reason AS \"cancel_reason: AppointmentReason\", \
268+ reject_reason AS \"reject_reason: AppointmentReason\", \
269+ created_at AS \"created_at: Timestamp\"",
270+ appointment
271+ .get_slot()
272+ .map(|s| s.uuid())
273+ .expect("a new booking always carries its slot"),
274+ appointment.get_id().uuid(),
275+ appointment.get_requester().uuid(),
276+ appointment.get_reason().as_str(),
277+ appointment.get_created_at().as_millis(),
278+ )
279+ .fetch_optional(db)
280+ .await
281+ {
282+ Ok(Some(row)) => Ok(Claimed::Made(row)),
283+ Ok(None) => Ok(Claimed::Full),
284+ // The id is freshly minted on a table keyed by it; no rival can
285+ // have aimed at it, and the seat gate excludes any slot the insert
286+ // could dangle from — no other verdict exists on this path.
287+ Err(err) => Err(err.into()),
288+ }
133 }289 }
134 290
135 /// Write the decision only while the stored row still carries the state it291 /// Write the decision only while the stored row still carries the state it
@@ -144,57 +300,77 @@ pub async fn list_for_slot(
144 /// least one of the four. The fields only a terminal transition writes300 /// least one of the four. The fields only a terminal transition writes
145 /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of301 /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of
146 /// their own: they always travel with a `status` change into a state no302 /// their own: they always travel with a `status` change into a state no
147-/// later decision is allowed from. All four are top-level columns, so an303+/// later decision is allowed from. Absent values compare truthfully under
148-/// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key304+/// `IS NOT DISTINCT FROM`.
149-/// dropping that forces `settings` to compare a rebuilt projection cannot
150-/// bite here.
151-///
152-/// A store-level write conflict is reported the same way as a miss: it
153-/// means a concurrent write committed on this row, which is exactly the
154-/// "reload and re-decide" case.
155 ///305 ///
156 /// A transition out of a live status (reject, cancel) hands the slot's306 /// A transition out of a live status (reject, cancel) hands the slot's
157-/// `occupied` seat back, in this same transaction — the counter is the307+/// `occupied` seat back in the same transaction — the counter is the
158 /// authority on whether the slot is taken, so it must move if and only if308 /// authority on whether the slot is taken, so it must move if and only if
159-/// the status did. The decrement is `WHERE`-gated on the CAS having written309+/// the status did. The decrement is gated on the CAS having written
160 /// something, so a lost race frees nothing.310 /// something, so a lost race frees nothing.
161 pub async fn save_if_unchanged(311 pub async fn save_if_unchanged(
162 db: &Database,312 db: &Database,
163 expected: &Appointment,313 expected: &Appointment,
164 new: Appointment,314 new: Appointment,
165 ) -> Result<Option<Appointment>, AppError> {315 ) -> Result<Option<Appointment>, AppError> {
166- let frees_the_slot = expected.status.is_live() && !new.status.is_live();316+ tx_with_retry(db, false, async |tx| {
167- let attempted = async {317+ decision_cas(&mut *tx, expected, new.clone()).await
168- let mut result = db318+ })
169- .query(319+ .await
170- "BEGIN TRANSACTION;320+}
171- LET $done = (UPDATE $id CONTENT $new \321+
172- WHERE status = $status \322+/// The decision's compare-and-set against any executor: one conditional
173- AND proposed_starts_at = $proposed_starts_at \323+/// `UPDATE`, plus the seat release when the status left the live set. A
174- AND proposed_ends_at = $proposed_ends_at \324+/// single statement decides under Postgres's row locking, so no retry
175- AND decided_by = $decided_by);325+/// budget and no store-level "write conflict" class exists anymore — a miss
176- UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0])326+/// is simply `None`, the reload-and-re-decide answer.
177- WHERE $frees AND array::len($done) > 0;327+pub(crate) async fn decision_cas(
178- RETURN $done;328+ tx: &mut PgConnection,
179- COMMIT TRANSACTION;",329+ expected: &Appointment,
180- )330+ new: Appointment,
181- .bind(("slot", expected.slot.record()))331+) -> Result<Option<Appointment>, AppError> {
182- .bind(("frees", frees_the_slot))332+ let frees_the_slot = expected.get_status().is_live() && !new.get_status().is_live();
183- .bind(("id", expected.id.record()))333+ let done = query_as!(
184- .bind(("status", expected.status))334+ Appointment,
185- .bind(("proposed_starts_at", expected.proposed_starts_at))335+ "UPDATE appointment SET status = $2, proposed_starts_at = $3, proposed_ends_at = $4, \
186- .bind(("proposed_ends_at", expected.proposed_ends_at))336+ proposed_by = $5, decided_by = $6, cancelled_by = $7, cancel_reason = $8, \
187- .bind(("decided_by", expected.decided_by.clone()))337+ reject_reason = $9 \
188- .bind(("new", new))338+ WHERE id = $1 AND status = $10 \
189- .await?339+ AND proposed_starts_at IS NOT DISTINCT FROM $11 \
190- .check()?;340+ AND proposed_ends_at IS NOT DISTINCT FROM $12 \
191- // BEGIN, the LET, and the counter write take a slot each.341+ AND decided_by IS NOT DISTINCT FROM $13 \
192- result.take::<Vec<Appointment>>(3)342+ RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \
193- }343+ status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \
194- .await;344+ proposed_starts_at AS \"proposed_starts_at: Timestamp\", \
195- match attempted {345+ proposed_ends_at AS \"proposed_ends_at: Timestamp\", \
196- Ok(rows) => Ok(rows.into_iter().next()),346+ proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \
197- Err(err) if lost_the_race(&err) => Ok(None),347+ cancelled_by AS \"cancelled_by: UserId\", \
198- Err(err) => Err(err.into()),348+ cancel_reason AS \"cancel_reason: AppointmentReason\", \
349+ reject_reason AS \"reject_reason: AppointmentReason\", \
350+ created_at AS \"created_at: Timestamp\"",
351+ new.get_id().uuid(),
352+ new.get_status().as_str(),
353+ new.get_proposed_starts_at().map(|t| t.as_millis()),
354+ new.get_proposed_ends_at().map(|t| t.as_millis()),
355+ new.get_proposed_by().map(|u| u.uuid()),
356+ new.get_decided_by().map(|u| u.uuid()),
357+ new.get_cancelled_by().map(|u| u.uuid()),
358+ new.get_cancel_reason().map(|r| r.as_str().to_string()),
359+ new.get_reject_reason().map(|r| r.as_str().to_string()),
360+ expected.get_status().as_str(),
361+ expected.get_proposed_starts_at().map(|t| t.as_millis()),
362+ expected.get_proposed_ends_at().map(|t| t.as_millis()),
363+ expected.get_decided_by().map(|u| u.uuid()),
364+ )
365+ .fetch_optional(&mut *tx)
366+ .await?;
367+ if frees_the_slot && done.is_some() {
368+ sqlx::query!(
369+ "UPDATE appointment_slot SET occupied = GREATEST(occupied - 1, 0) WHERE id = $1",
370+ expected.get_slot().map(|s| s.uuid()),
371+ )
372+ .execute(tx)
373+ .await?;
199 }374 }
375+ Ok(done)
200 }376 }
src/db/appointment_slot.rsmodified+213 -174
@@ -1,23 +1,22 @@
1-//! The `appointment_slot` table: row reads and listings, the overlap probes1+//! The `appointment_slot` table: row reads and listings, the role-claimed
2-//! behind the publish guard, the role-claimed INSERT every publish writes2+//! INSERT every publish writes through, and the delete whose own `WHERE`
3-//! through, and the delete whose own `WHERE` is the no-live-booking guard.3+//! is the no-live-booking guard. The workflows live in
4-//! The workflows that sequence these under
5-//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in
6 //! [`crate::service::appointment_slot`].4 //! [`crate::service::appointment_slot`].
5+//!
6+//! Publish overlap is a database guarantee now: the
7+//! `appointment_slot_teacher_span` exclusion constraint refuses a second
8+//! window overlapping one the teacher already holds (SQLSTATE `23505`,
9+//! mapped to the same 409 the old check produced). The pre-insert reads in
10+//! [`crate::service::appointment_slot`] remain for their precise refusal
11+//! texts; the constraint is the authority a racing publish answers to.
7 12
8-use surrealdb::types::{RecordId, SurrealValue};13+use crate::database::{Database, tx_with_retry, unique_violation};
9-14+use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries};
10-use crate::constant::{APPOINTMENT_SLOT_TABLE, ROLES};
11-use crate::database::{Database, transaction_with_retry};
12-use crate::db::cap;
13-use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotSeries};
14 use crate::domain::role::Role;15 use crate::domain::role::Role;
15 use crate::domain::timestamp::Timestamp;16 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;17 use crate::domain::user::UserId;
17 use crate::error::AppError;18 use crate::error::AppError;
18-19+use sqlx::{query, query_as};
19-/// The publisher fell below `teacher` while the publish was in flight.
20-const UNFIT_MARK: &str = "slot_not_staff";
21 20
22 /// Write a whole publish — one occurrence or fifty-two — while the publisher21 /// Write a whole publish — one occurrence or fifty-two — while the publisher
23 /// still *holds* a teaching role.22 /// still *holds* a teaching role.
@@ -27,124 +26,145 @@ const UNFIT_MARK: &str = "slot_not_staff";
27 /// snapshot can see, and a slot landing after that snapshot would survive it26 /// snapshot can see, and a slot landing after that snapshot would survive it
28 /// under a role that may not publish — reachable by no route afterwards,27 /// under a role that may not publish — reachable by no route afterwards,
29 /// since the calendar hides a demoted teacher's slots and the deletes are28 /// since the calendar hides a demoted teacher's slots and the deletes are
30-/// `teacher`-gated. So the teacher's own record is claimed beside the insert29+/// `teacher`-gated. So the teacher's own row is claimed beside the inserts
31-/// ([`cap::role_claim`]), which is the key the demotion writes: either the30+/// (the role-handshake recipe in [`crate::db::cap`]): the transaction takes
32-/// sweep sees these slots, or this write sees the new role and publishes31+/// the teacher's row `FOR NO KEY UPDATE` — the same key the demotion
33-/// nothing.32+/// writes — and the Rust check refuses unless the role still reaches the
33+/// teaching bar. Either the sweep sees these slots, or this write sees the
34+/// new role and publishes nothing.
34 ///35 ///
35-/// The bar is read off the hierarchy rather than spelled out, so a new role36+/// Overlap is the `appointment_slot_teacher_span` exclusion constraint: a
36-/// cannot drift out of it.37+/// racing publish or a window colliding with an already-published one
38+/// refuses the whole batch (`23505`), which the caller maps to its own
39+/// overlap 409 (`overlap_refusal` carries the exact text the caller owes —
40+/// single publish and weekly series refuse with different words).
37 ///41 ///
38-/// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE`42+/// All-or-nothing: one transaction, so a collision at week 7 of 10 leaves
39-/// only, and the `INSERT` carries freshly minted ULIDs on a table with no43+/// no stray weeks behind.
40-/// `UNIQUE` index, so no rival can make it answer "already exists".
41 pub async fn insert_claimed(44 pub async fn insert_claimed(
42 db: &Database,45 db: &Database,
43 teacher: &UserId,46 teacher: &UserId,
44 rows: Vec<AppointmentSlot>,47 rows: Vec<AppointmentSlot>,
48+ overlap_refusal: AppError,
45 ) -> Result<Vec<AppointmentSlot>, AppError> {49 ) -> Result<Vec<AppointmentSlot>, AppError> {
46- let staff = ROLES50+ tx_with_retry(db, false, async |tx| {
47- .iter()51+ // The role handshake. The bar is read off the hierarchy rather than
48- .filter(|role| role.at_least(Role::Teacher))52+ // spelled out, so a new role cannot drift out of it.
49- .map(|role| format!("'{}'", role.as_str()))53+ let held = sqlx::query!(
50- .collect::<Vec<_>>()54+ "SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE",
51- .join(", ");55+ teacher.uuid()
52- let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK);
53- let sql = format!(
54- "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\
55- COMMIT TRANSACTION;",
56- held.join(";\n")
57- );
58- let (mut result, mut errors) = transaction_with_retry(
59- db,
60- &sql,
61- &[
62- ("teacher".into(), teacher.record().into_value()),
63- ("rows".into(), rows.into_value()),
64- ],
65- &[UNFIT_MARK],
66- )
67- .await?;
68- // Demoted while this ran — the same refusal `RequireTeacher` makes a
69- // moment earlier, and the only one that can arrive after it.
70- if errors
71- .values()
72- .any(|error| error.to_string().contains(UNFIT_MARK))
73- {
74- return Err(AppError::Forbidden(
75- "that account no longer holds a teaching role",
76- ));
77- }
78- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
79- return Err(error.into());
80- }
81- // BEGIN plus the claim's own statements — counted, not tallied by hand,
82- // so a statement added there cannot read back the wrong result.
83- Ok(result.take::<Vec<AppointmentSlot>>(held.len() + 1)?)
84-}
85-
86-/// Does the teacher already have a published slot whose window collides with
87-/// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new
88-/// one starts is *not* a conflict — that is how a teacher's hour is carved
89-/// into back-to-back slots. Caller must hold
90-/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the
91-/// answer to still be true by the time the insert lands.
92-pub async fn conflicts_existing(
93- db: &Database,
94- teacher: &UserId,
95- starts_at: Timestamp,
96- ends_at: Timestamp,
97-) -> Result<bool, AppError> {
98- let mut result = db
99- .query(
100- "SELECT VALUE id FROM appointment_slot \
101- WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \
102- LIMIT 1",
103 )56 )
104- .bind(("teacher", teacher.record()))57+ .fetch_optional(&mut *tx)
105- .bind(("starts", starts_at.as_millis()))58+ .await?;
106- .bind(("ends", ends_at.as_millis()))59+ let fit = held
107- .await?60+ .as_ref()
108- .check()?;61+ .and_then(|row| Role::try_from_str(&row.role).ok())
109- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())62+ .is_some_and(|role| role.at_least(Role::Teacher));
63+ if !fit {
64+ // Demoted (or gone) while this ran — the same refusal
65+ // `RequireTeacher` makes a moment earlier, and the only one
66+ // that can arrive after it.
67+ return Err(AppError::Forbidden(
68+ "that account no longer holds a teaching role",
69+ ));
70+ }
71+ let mut saved = Vec::with_capacity(rows.len());
72+ for row in rows {
73+ match query_as!(
74+ AppointmentSlot,
75+ "INSERT INTO appointment_slot (id, teacher, starts_at, ends_at, note, series, created_at)
76+ VALUES ($1, $2, $3, $4, $5, $6, $7)
77+ RETURNING id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
78+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
79+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\"",
80+ row.get_id().uuid(),
81+ row.get_teacher().uuid(),
82+ row.get_starts_at().as_millis(),
83+ row.get_ends_at().as_millis(),
84+ row.get_note().map(|n| n.as_str().to_string()),
85+ row.get_series().map(|s| s.as_str().to_string()),
86+ row.get_created_at().as_millis(),
87+ )
88+ .fetch_one(&mut *tx)
89+ .await
90+ {
91+ Ok(row) => saved.push(row),
92+ // A teacher cannot publish two overlapping windows: the
93+ // exclusion constraint, answering the caller's overlap 409.
94+ Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => {
95+ return Err(overlap_refusal);
96+ }
97+ Err(err) => return Err(err.into()),
98+ }
99+ }
100+ Ok(saved)
101+ })
102+ .await
110 }103 }
111 104
112 /// Every window this teacher already published that intersects the envelope105 /// Every window this teacher already published that intersects the envelope
113 /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any*106 /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any*
114 /// window in the batch necessarily overlaps the envelope spanning them all,107 /// window in the batch necessarily overlaps the envelope spanning them all,
115 /// so filtering the envelope and comparing in memory is exactly the108 /// so filtering the envelope and comparing in memory is exactly the
116-/// per-window [`conflicts_existing`] check,109+/// per-window overlap check hoisted out of the loop. The exclusion
117-/// hoisted out of the loop — which is what keeps110+/// constraint remains the authority; this read exists for the batch's
118-/// [`crate::service::appointment::APPOINTMENT_LOCK`] down111+/// precise refusal texts.
119-/// to two round trips instead of one per occurrence.
120 pub async fn windows_in_span(112 pub async fn windows_in_span(
121 db: &Database,113 db: &Database,
122 teacher: &UserId,114 teacher: &UserId,
123 from: Timestamp,115 from: Timestamp,
124 to: Timestamp,116 to: Timestamp,
125 ) -> Result<Vec<(Timestamp, Timestamp)>, AppError> {117 ) -> Result<Vec<(Timestamp, Timestamp)>, AppError> {
126- let mut result = db118+ let rows = query!(
127- .query(119+ "SELECT starts_at, ends_at FROM appointment_slot \
128- "SELECT * FROM appointment_slot \120+ WHERE teacher = $1 AND starts_at < $3 AND ends_at > $2",
129- WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from",121+ teacher.uuid(),
130- )122+ from.as_millis(),
131- .bind(("teacher", teacher.record()))123+ to.as_millis()
132- .bind(("from", from.as_millis()))124+ )
133- .bind(("to", to.as_millis()))125+ .fetch_all(db)
134- .await?126+ .await?;
135- .check()?;127+ Ok(rows
136- Ok(result
137- .take::<Vec<AppointmentSlot>>(0)?
138 .into_iter()128 .into_iter()
139- .map(|slot| (slot.starts_at, slot.ends_at))129+ .map(|row| (Timestamp::from_millis(row.starts_at), Timestamp::from_millis(row.ends_at)))
140 .collect())130 .collect())
141 }131 }
142 132
133+pub(crate) async fn read_on<'e, E>(
134+ executor: E,
135+ id: &AppointmentSlotId,
136+) -> Result<Option<AppointmentSlot>, AppError>
137+where
138+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
139+{
140+ let slot = query_as!(
141+ AppointmentSlot,
142+ "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
143+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
144+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
145+ FROM appointment_slot WHERE id = $1",
146+ id.uuid()
147+ )
148+ .fetch_optional(executor)
149+ .await?;
150+ Ok(slot)
151+}
152+
143 pub async fn read(153 pub async fn read(
144 db: &Database,154 db: &Database,
145 id: &AppointmentSlotId,155 id: &AppointmentSlotId,
146 ) -> Result<Option<AppointmentSlot>, AppError> {156 ) -> Result<Option<AppointmentSlot>, AppError> {
147- Ok(db.select(id.record()).await?)157+ let slot = query_as!(
158+ AppointmentSlot,
159+ "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
160+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
161+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
162+ FROM appointment_slot WHERE id = $1",
163+ id.uuid()
164+ )
165+ .fetch_optional(db)
166+ .await?;
167+ Ok(slot)
148 }168 }
149 169
150 /// A teacher's own calendar, earliest first.170 /// A teacher's own calendar, earliest first.
@@ -152,15 +172,18 @@ pub async fn list_for_teacher(
152 db: &Database,172 db: &Database,
153 teacher: &UserId,173 teacher: &UserId,
154 ) -> Result<Vec<AppointmentSlot>, AppError> {174 ) -> Result<Vec<AppointmentSlot>, AppError> {
155- let mut result = db175+ let slots = query_as!(
156- .query(176+ AppointmentSlot,
157- "SELECT * FROM appointment_slot WHERE teacher = $teacher \177+ "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
158- ORDER BY starts_at ASC, id ASC",178+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
159- )179+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
160- .bind(("teacher", teacher.record()))180+ FROM appointment_slot WHERE teacher = $1 \
161- .await?181+ ORDER BY starts_at ASC, id ASC",
162- .check()?;182+ teacher.uuid()
163- Ok(result.take::<Vec<AppointmentSlot>>(0)?)183+ )
184+ .fetch_all(db)
185+ .await?;
186+ Ok(slots)
164 }187 }
165 188
166 /// Every slot whose window has not opened yet, earliest first — the bookable189 /// Every slot whose window has not opened yet, earliest first — the bookable
@@ -177,30 +200,36 @@ pub async fn list_upcoming(
177 db: &Database,200 db: &Database,
178 from: Timestamp,201 from: Timestamp,
179 ) -> Result<Vec<AppointmentSlot>, AppError> {202 ) -> Result<Vec<AppointmentSlot>, AppError> {
180- let mut result = db203+ let slots = query_as!(
181- .query(204+ AppointmentSlot,
182- "SELECT * FROM appointment_slot WHERE starts_at > $from \205+ "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
183- ORDER BY starts_at ASC, id ASC",206+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
184- )207+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
185- .bind(("from", from.as_millis()))208+ FROM appointment_slot WHERE starts_at > $1 \
186- .await?209+ ORDER BY starts_at ASC, id ASC",
187- .check()?;210+ from.as_millis()
188- Ok(result.take::<Vec<AppointmentSlot>>(0)?)211+ )
212+ .fetch_all(db)
213+ .await?;
214+ Ok(slots)
189 }215 }
190 216
191 pub async fn list_for_series(217 pub async fn list_for_series(
192 db: &Database,218 db: &Database,
193 series: &SlotSeries,219 series: &SlotSeries,
194 ) -> Result<Vec<AppointmentSlot>, AppError> {220 ) -> Result<Vec<AppointmentSlot>, AppError> {
195- let mut result = db221+ let slots = query_as!(
196- .query(222+ AppointmentSlot,
197- "SELECT * FROM appointment_slot WHERE series = $series \223+ "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \
198- ORDER BY starts_at ASC, id ASC",224+ ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \
199- )225+ series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \
200- .bind(("series", series.as_str().to_string()))226+ FROM appointment_slot WHERE series = $1 \
201- .await?227+ ORDER BY starts_at ASC, id ASC",
202- .check()?;228+ series.as_str()
203- Ok(result.take::<Vec<AppointmentSlot>>(0)?)229+ )
230+ .fetch_all(db)
231+ .await?;
232+ Ok(slots)
204 }233 }
205 234
206 /// Shared body of both deletes: drop every named slot, but only while its235 /// Shared body of both deletes: drop every named slot, but only while its
@@ -208,48 +237,58 @@ pub async fn list_for_series(
208 /// `WHERE` is the guard, which is what makes it hold against a booking237 /// `WHERE` is the guard, which is what makes it hold against a booking
209 /// landing in the middle of it (a separate read-then-delete could not).238 /// landing in the middle of it (a separate read-then-delete could not).
210 ///239 ///
211-/// All-or-nothing across the whole list: if fewer rows go than were named,240+/// Settled bookings (rejected/cancelled) of the free slots are swept first
212-/// the transaction is thrown away, so a series never loses its free weeks241+/// so the parent delete's foreign key is never the thing that refuses. One
213-/// and keeps the booked one. Whether that shortfall was a live booking or a242+/// transaction, all-or-nothing across the whole list: if fewer rows go than
214-/// slot that no longer exists is read off what survived — the occupied rows243+/// were named, the transaction is thrown away, so a series never loses its
215-/// are still there, a vanished one is not — which is the 409/404 the caller244+/// free weeks and keeps the booked one. Whether that shortfall was a live
216-/// used to get from a separate check.245+/// booking or a slot that no longer exists is read off what survived — the
246+/// occupied rows are still there, a vanished one is not — which is the
247+/// 409/404 the caller expects.
217 pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> {248 pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> {
218- let records: Vec<RecordId> = ids.iter().map(|id| id.record()).collect();249+ tx_with_retry(db, false, async |tx| {
219- let (_, mut errors) = transaction_with_retry(250+ // The settled bookings of the *free* slots go first; a booked slot's
220- db,251+ // rows survive (its occupied counter excludes it from both sweeps).
221- "BEGIN TRANSACTION;252+ sqlx::query!(
222- LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE);253+ "DELETE FROM appointment a
223- IF array::len($gone) != array::len($slots) {254+ USING appointment_slot s
224- THROW IF array::len((SELECT VALUE id FROM appointment_slot255+ WHERE a.slot = s.id AND s.id = ANY($1) AND s.occupied < 1",
225- WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' }256+ ids
226- };257+ )
227- DELETE appointment WHERE slot IN $slots;258+ .execute(&mut *tx)
228- RETURN $gone;259+ .await?;
229- COMMIT TRANSACTION;",260+ let gone: Vec<AppointmentSlotId> = query_as!(
230- &[("slots".into(), records.into_value())],261+ AppointmentSlotId,
231- &["slot_occupied", "slot_missing"],262+ "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 RETURNING id",
232- )263+ ids
233- .await?;264+ )
234- // An aborted transaction errors every slot; only the THROW's own slot265+ .fetch_all(&mut *tx)
235- // names the marker (the `Exam::update` treatment), and a round lost to266+ .await?;
236- // a booking landing on `occupied` mid-flight is re-sent rather than267+ if gone.len() == ids.len() {
237- // reported (see [`transaction_with_retry`]).268+ return Ok(());
238- let thrown = |marker: &str| {269+ }
239- errors270+ // Shortfall: distinguish "a live booking holds one" from "one was
240- .values()271+ // never there" off what still exists.
241- .any(|error| error.to_string().contains(marker))272+ let remaining = sqlx::query!(
242- };273+ "SELECT count(*) AS standing FROM appointment_slot WHERE id = ANY($1)",
243- if thrown("slot_occupied") {274+ ids
244- return Err(AppError::Conflict(275+ )
245- "the slot has a pending or approved booking",276+ .fetch_one(&mut *tx)
246- ));277+ .await?
247- }278+ .standing;
248- if thrown("slot_missing") {279+ if remaining > 0 {
249- return Err(AppError::NotFound);280+ Err(AppError::Conflict(
250- }281+ "the slot has a pending or approved booking",
251- if let Some(error) = errors.drain().map(|(_, error)| error).next() {282+ ))
252- return Err(error.into());283+ } else {
253- }284+ Err(AppError::NotFound)
254- Ok(())285+ }
286+ })
287+ .await
255 }288 }
289+
290+// The overlap probe behind the old publish guard — `conflicts_existing` —
291+// is gone as a *decision*: the exclusion constraint decides overlap at
292+// insert time. The service layer still reads [`windows_in_span`] ahead of a
293+// weekly publish so its precise refusal texts survive; a racing writer that
294+// slips past any read answers to the constraint.
src/db/attendance.rsmodified+67 -91
@@ -1,41 +1,24 @@
1-//! The `attendance` table: event roll call. Every write is a single1+//! The `attendance` table: event roll call. Every write is one guarded
2-//! transaction whose gates ride inside it (the event-existence proof), so2+//! statement whose gates ride inside it, so the whole module is the
3-//! the whole module is the persistence half; the workflow that decides it3+//! persistence half; the workflow that decides it lives in
4-//! lives in [`crate::service::attendance`].4+//! [`crate::service::attendance`].
5 5
6-use surrealdb::types::SurrealValue;6+use crate::database::{Database, foreign_key_violation};
7-
8-use crate::constant::REGISTRATION_COUNT_FIELD;
9-use crate::database::{Database, transaction_with_retry};
10 use crate::db::page::PagedList;7 use crate::db::page::PagedList;
11-use crate::domain::attendance::{Attendance, AttendanceId, AttendanceStatus};8+use crate::domain::attendance::{Attendance, AttendanceStatus};
12 use crate::domain::event::EventId;9 use crate::domain::event::EventId;
13 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
14 use crate::error::AppError;11 use crate::error::AppError;
12+use sqlx::query_as;
15 13
16-/// Record (or overwrite) `user`'s status for `event`. One row per (event,14+/// Record (or overwrite) `user`'s status for `event`. The pair is the
17-/// user), keyed by a deterministic composite id so this is a single atomic15+/// table's primary key, so this is a single atomic upsert — concurrent
18-/// UPSERT — concurrent marks for the same pair can no longer both insert and16+/// marks for the same pair converge on the one row instead of racing.
19-/// collide on the unique index (a 500); they converge on the one row.
20-///
21-/// The event's existence is proved *inside* the write, the twin of the gate
22-/// in [`crate::db::session_attendance::mark`]: the handler's event read sits
23-/// several round trips in front of this, so a bare upsert left a mark on an
24-/// event [`crate::domain::event::Event`]'s cascade
25-/// (`DELETE attendance WHERE event = $ev`) had already swept — counted
26-/// forever in `GET /attendance/{user}` on an event no page shows. Reading
27-/// the event here would not have closed it either: SurrealDB 3.2.3
28-/// conflict-checks write sets, not read sets, so the proof has to *move* a
29-/// value on the event row. It is the bump-and-restore of
30-/// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the
31-/// event already carries: matching nothing is the existence gate, writing
32-/// the key the delete removes is the collision, and the restore is by
33-/// captured value (`NONE` included) so no seat is spent or freed.
34 ///17 ///
35-/// Admissible for [`transaction_with_retry`]: no statement can answer18+/// The event's existence is proved by the foreign key itself: a mark naming
36-/// "already exists" — the `UPSERT`'s composite id is bijective with the19+/// an event whose row is gone is refused `23503`, mapped to the same 404 the
37-/// `attendance_event_user` unique tuple, so it resolves onto the row it20+/// old existence-proof transaction produced. No bump-and-restore trick, no
38-/// names instead of colliding with it.21+/// retry loop — one statement decides.
39 pub async fn mark(22 pub async fn mark(
40 db: &Database,23 db: &Database,
41 event: &EventId,24 event: &EventId,
@@ -43,52 +26,28 @@ pub async fn mark(
43 status: AttendanceStatus,26 status: AttendanceStatus,
44 marked_by: &UserId,27 marked_by: &UserId,
45 ) -> Result<Attendance, AppError> {28 ) -> Result<Attendance, AppError> {
46- let attendance = Attendance {29+ match query_as!(
47- id: AttendanceId::composite(event, user),30+ Attendance,
48- event: event.clone(),31+ "INSERT INTO attendance (event, app_user, status, marked_by)
49- user: user.clone(),32+ VALUES ($1, $2, $3, $4)
50- status,33+ ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4
51- marked_by: marked_by.clone(),34+ RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \
52- };35+ status, marked_by AS \"marked_by: UserId\"",
53- let (mut result, mut errors) = transaction_with_retry(36+ event.uuid(),
54- db,37+ user.uuid(),
55- &format!(38+ status.as_str(),
56- "BEGIN TRANSACTION;39+ marked_by.uuid()
57- LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev);
58- LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} =
59- ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id);
60- IF array::len($alive) = 0 {{ THROW 'event_missing' }};
61- UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was;
62- LET $after = (UPSERT $id CONTENT $row RETURN AFTER);
63- RETURN $after;
64- COMMIT TRANSACTION;"
65- ),
66- &[
67- ("ev".into(), event.record().into_value()),
68- ("id".into(), attendance.id.record().into_value()),
69- ("row".into(), attendance.into_value()),
70- ],
71- &["event_missing"],
72 )40 )
73- .await?;41+ .fetch_one(db)
74- // An aborted transaction errors every slot and only the THROW's own42+ .await
75- // slot names the marker.
76- if errors
77- .values()
78- .any(|error| error.to_string().contains("event_missing"))
79 {43 {
80- return Err(AppError::NotFound);44+ Ok(row) => Ok(row),
45+ // The event row is gone: exactly today's "no such event" refusal.
46+ // (The other foreign keys name users the routes already authenticated;
47+ // a violation there stays a database error, as before.)
48+ Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound),
49+ Err(err) => Err(err.into()),
81 }50 }
82- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
83- return Err(error.into());
84- }
85- // The trailing `RETURN` is always the last statement before `COMMIT`.
86- let slot = result.num_statements().saturating_sub(2);
87- result
88- .take::<Vec<Attendance>>(slot)?
89- .into_iter()
90- .next()
91- .ok_or_else(|| AppError::Internal("failed to mark attendance".into()))
92 }51 }
93 52
94 pub async fn list_for_event(53 pub async fn list_for_event(
@@ -97,21 +56,33 @@ pub async fn list_for_event(
97 limit: Option<i64>,56 limit: Option<i64>,
98 offset: i64,57 offset: i64,
99 ) -> Result<(Vec<Attendance>, i64), AppError> {58 ) -> Result<(Vec<Attendance>, i64), AppError> {
100- PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC")59+ // The composite key's text form ordered the old listing; on the natural
101- .bind("ev", event.record())60+ // key that order is (event, then user).
102- .run(limit, offset, db)61+ PagedList::new(
103- .await62+ "attendance WHERE event = $1",
63+ "ORDER BY event DESC, app_user DESC",
64+ )
65+ .bind(event.uuid())
66+ .run(limit, offset, db)
67+ .await
104 }68 }
105 69
106 /// Every event-attendance row recorded for `user` — the events half of the70 /// Every event-attendance row recorded for `user` — the events half of the
107 /// attendance report.71 /// attendance report.
108 pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Attendance>, AppError> {72 pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<Attendance>, AppError> {
109- let mut result = db73+ let rows = query_as!(
110- .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC")74+ Attendance,
111- .bind(("usr", user.record()))75+ "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
112- .await?76+ status AS \"status: AttendanceStatus\", \
113- .check()?;77+ marked_by AS \"marked_by: UserId\" \
114- Ok(result.take::<Vec<Attendance>>(0)?)78+ FROM attendance
79+ WHERE app_user = $1
80+ ORDER BY event DESC, app_user DESC",
81+ user.uuid()
82+ )
83+ .fetch_all(db)
84+ .await?;
85+ Ok(rows)
115 }86 }
116 87
117 pub async fn remove(88 pub async fn remove(
@@ -119,13 +90,18 @@ pub async fn remove(
119 event: &EventId,90 event: &EventId,
120 user: &UserId,91 user: &UserId,
121 ) -> Result<Option<Attendance>, AppError> {92 ) -> Result<Option<Attendance>, AppError> {
122- let mut result = db93+ let gone = query_as!(
123- .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE")94+ Attendance,
124- .bind(("ev", event.record()))95+ "DELETE FROM attendance WHERE event = $1 AND app_user = $2
125- .bind(("usr", user.record()))96+ RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \
126- .await?97+ status AS \"status: AttendanceStatus\", \
127- .check()?;98+ marked_by AS \"marked_by: UserId\"",
128- Ok(result.take::<Vec<Attendance>>(0)?.into_iter().next())99+ event.uuid(),
100+ user.uuid()
101+ )
102+ .fetch_optional(db)
103+ .await?;
104+ Ok(gone)
129 }105 }
130 106
131 #[cfg(test)]107 #[cfg(test)]
src/db/chatbot_message.rsmodified+122 -77
@@ -4,48 +4,68 @@
4 //! flight. The task that owns the bridge round trip then flips it to4 //! flight. The task that owns the bridge round trip then flips it to
5 //! `complete` (with the text) or `failed` (with a code), and the boot sweep5 //! `complete` (with the text) or `failed` (with a code), and the boot sweep
6 //! in `database.rs` fails whatever a process death left behind past the6 //! in `database.rs` fails whatever a process death left behind past the
7-//! staleness window. Every turn is written *through* its thread's own row7+//! staleness window. Every turn is written *through* its thread's own row —
8-//! ([`touch_and_write`]), so a turn can never outlive the thread it belongs8+//! its guarded statement bumps `updated_at`, so a turn can never outlive
9-//! to. The row shape lives in [`crate::domain::chatbot_message`].9+//! the thread it belongs to. The row shape lives in
10-10+//! [`crate::domain::chatbot_message`].
11-use surrealdb::types::SurrealValue;
12 11
13 use crate::constant::MAX_ERROR_CODE_LEN;12 use crate::constant::MAX_ERROR_CODE_LEN;
14 use crate::database::Database;13 use crate::database::Database;
15-use crate::db::chatbot_thread::touch_and_write;
16 use crate::db::page::PagedList;14 use crate::db::page::PagedList;
17 use crate::domain::chatbot_message::{15 use crate::domain::chatbot_message::{
18- ChatContent, ChatbotMessage, ChatbotMessageId, MessageStatus,16+ ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
19 };17 };
20 use crate::domain::chatbot_thread::ChatbotThreadId;18 use crate::domain::chatbot_thread::ChatbotThreadId;
21 use crate::domain::timestamp::Timestamp;19 use crate::domain::timestamp::Timestamp;
22 use crate::domain::user::UserId;20 use crate::domain::user::UserId;
23 use crate::error::AppError;21 use crate::error::AppError;
22+use sqlx::query_as;
24 23
25-/// Write one turn *through its thread's own row* ([`touch_and_write`]),24+/// Write one turn *through its thread's own row*: the thread's activity
26-/// which is what makes the thread's existence something this write writes25+/// bump and the turn's insert are a single guarded statement, which is what
27-/// rather than something the caller read and then trusted: a26+/// makes the thread's existence something this write writes rather than
28-/// [`delete`](crate::db::chatbot_thread::delete)27+/// something the caller read and then trusted — a
29-/// racing it touches the very key this transaction moves, so the two cannot28+/// [`delete`](crate::db::chatbot_thread::delete) racing it touches the very
30-/// both commit and no turn is left under a thread that is gone. It also29+/// row this statement's gate updates, so under Postgres's row locking the
30+/// two serialize and no turn is left under a thread that is gone. It also
31 /// carries the thread's activity stamp, so a turn and its `updated_at` land31 /// carries the thread's activity stamp, so a turn and its `updated_at` land
32-/// together.32+/// together. The stamp is written strictly upwards —
33+/// `GREATEST($now, updated_at + 1)` — because a turn's two rows routinely
34+/// land inside one millisecond and `updated_at` is the thread list's
35+/// ordering key.
33 ///36 ///
34 /// [`AppError::NotFound`] = the thread is gone, and nothing was written.37 /// [`AppError::NotFound`] = the thread is gone, and nothing was written.
35 async fn insert(db: &Database, message: ChatbotMessage) -> Result<ChatbotMessage, AppError> {38 async fn insert(db: &Database, message: ChatbotMessage) -> Result<ChatbotMessage, AppError> {
36- let thread = message.thread_id.clone();39+ let inserted = query_as!(
37- let id = message.id.record();40+ ChatbotMessage,
38- touch_and_write(41+ "WITH touch AS (
39- db,42+ UPDATE chatbot_thread SET updated_at = GREATEST($2, updated_at + 1)
40- &thread,43+ WHERE id = $1
41- "CREATE $id CONTENT $row RETURN AFTER",44+ RETURNING 1)
42- vec![45+ INSERT INTO chatbot_message (id, thread_id, user_id, role, content, status, \
43- ("id".into(), id.into_value()),46+ truncated, error_code, created_at, completed_at)
44- ("row".into(), message.into_value()),47+ SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11
45- ],48+ WHERE EXISTS (SELECT 1 FROM touch)
49+ RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
50+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
51+ status AS \"status: MessageStatus\", truncated, \
52+ error_code AS \"error_code: String\", \
53+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
54+ message.get_thread_id().uuid(),
55+ Timestamp::now().as_millis(),
56+ message.get_id().uuid(),
57+ message.user_id.uuid(),
58+ message.role.as_str(),
59+ message.content.as_str(),
60+ message.status.as_str(),
61+ message.truncated,
62+ message.error_code,
63+ message.created_at.as_millis(),
64+ message.completed_at.map(|t| t.as_millis()),
46 )65 )
47- .await?66+ .fetch_optional(db)
48- .ok_or_else(|| AppError::Internal("failed to create chat message".into()))67+ .await?;
68+ inserted.ok_or_else(|| AppError::Internal("failed to create chat message".into()))
49 }69 }
50 70
51 /// Append the user's prompt. Nothing is awaited for it, so it is born71 /// Append the user's prompt. Nothing is awaited for it, so it is born
@@ -109,10 +129,10 @@ pub async fn list_for_thread(
109 offset: i64,129 offset: i64,
110 ) -> Result<(Vec<ChatbotMessage>, i64), AppError> {130 ) -> Result<(Vec<ChatbotMessage>, i64), AppError> {
111 let (rows, total) = PagedList::new(131 let (rows, total) = PagedList::new(
112- "chatbot_message WHERE thread_id = $conv",132+ "chatbot_message WHERE thread_id = $1",
113 "ORDER BY created_at ASC, id ASC",133 "ORDER BY created_at ASC, id ASC",
114 )134 )
115- .bind("conv", thread.record())135+ .bind(thread.uuid())
116 .run::<ChatbotMessage>(limit, offset, db)136 .run::<ChatbotMessage>(limit, offset, db)
117 .await?;137 .await?;
118 Ok((138 Ok((
@@ -129,20 +149,20 @@ pub async fn list_tail(
129 thread: &ChatbotThreadId,149 thread: &ChatbotThreadId,
130 limit: usize,150 limit: usize,
131 ) -> Result<Vec<ChatbotMessage>, AppError> {151 ) -> Result<Vec<ChatbotMessage>, AppError> {
132- let mut result = db152+ let mut messages: Vec<ChatbotMessage> = query_as!(
133- .query(153+ ChatbotMessage,
134- "SELECT * FROM chatbot_message WHERE thread_id = $conv \154+ "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
135- ORDER BY created_at DESC, id DESC LIMIT $limit",155+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
136- )156+ status AS \"status: MessageStatus\", truncated, \
137- .bind(("conv", thread.record()))157+ error_code AS \"error_code: String\", \
138- .bind(("limit", limit as i64))158+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
139- .await?159+ FROM chatbot_message WHERE thread_id = $1 \
140- .check()?;160+ ORDER BY created_at DESC, id DESC LIMIT $2",
141- let mut messages: Vec<ChatbotMessage> = result161+ thread.uuid(),
142- .take::<Vec<ChatbotMessage>>(0)?162+ limit as i64
143- .into_iter()163+ )
144- .map(ChatbotMessage::projected)164+ .fetch_all(db)
145- .collect();165+ .await?;
146 messages.reverse();166 messages.reverse();
147 Ok(messages)167 Ok(messages)
148 }168 }
@@ -158,17 +178,21 @@ pub async fn list_settled_tail(
158 thread: &ChatbotThreadId,178 thread: &ChatbotThreadId,
159 limit: usize,179 limit: usize,
160 ) -> Result<Vec<ChatbotMessage>, AppError> {180 ) -> Result<Vec<ChatbotMessage>, AppError> {
161- let mut result = db181+ let mut messages: Vec<ChatbotMessage> = query_as!(
162- .query(182+ ChatbotMessage,
163- "SELECT * FROM chatbot_message WHERE thread_id = $conv \183+ "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
164- AND status = 'complete' AND content != '' \184+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
165- ORDER BY created_at DESC, id DESC LIMIT $limit",185+ status AS \"status: MessageStatus\", truncated, \
166- )186+ error_code AS \"error_code: String\", \
167- .bind(("conv", thread.record()))187+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
168- .bind(("limit", limit as i64))188+ FROM chatbot_message WHERE thread_id = $1 \
169- .await?189+ AND status = 'complete' AND content <> '' \
170- .check()?;190+ ORDER BY created_at DESC, id DESC LIMIT $2",
171- let mut messages: Vec<ChatbotMessage> = result.take(0)?;191+ thread.uuid(),
192+ limit as i64
193+ )
194+ .fetch_all(db)
195+ .await?;
172 messages.reverse();196 messages.reverse();
173 Ok(messages)197 Ok(messages)
174 }198 }
@@ -185,7 +209,19 @@ pub async fn prompt_of(
185 db: &Database,209 db: &Database,
186 id: &ChatbotMessageId,210 id: &ChatbotMessageId,
187 ) -> Result<Option<ChatbotMessage>, AppError> {211 ) -> Result<Option<ChatbotMessage>, AppError> {
188- Ok(db.select(id.record()).await?)212+ let message = query_as!(
213+ ChatbotMessage,
214+ "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
215+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
216+ status AS \"status: MessageStatus\", truncated, \
217+ error_code AS \"error_code: String\", \
218+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
219+ FROM chatbot_message WHERE id = $1",
220+ id.uuid()
221+ )
222+ .fetch_optional(db)
223+ .await?;
224+ Ok(message)
189 }225 }
190 226
191 /// Read one turn only if `user` owns it — the poll loop's read.227 /// Read one turn only if `user` owns it — the poll loop's read.
@@ -194,7 +230,18 @@ pub async fn read_for(
194 id: &ChatbotMessageId,230 id: &ChatbotMessageId,
195 user: &UserId,231 user: &UserId,
196 ) -> Result<Option<ChatbotMessage>, AppError> {232 ) -> Result<Option<ChatbotMessage>, AppError> {
197- let message: Option<ChatbotMessage> = db.select(id.record()).await?;233+ let message = query_as!(
234+ ChatbotMessage,
235+ "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
236+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
237+ status AS \"status: MessageStatus\", truncated, \
238+ error_code AS \"error_code: String\", \
239+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \
240+ FROM chatbot_message WHERE id = $1",
241+ id.uuid()
242+ )
243+ .fetch_optional(db)
244+ .await?;
198 Ok(message245 Ok(message
199 .filter(|message| &message.user_id == user)246 .filter(|message| &message.user_id == user)
200 .map(ChatbotMessage::projected))247 .map(ChatbotMessage::projected))
@@ -236,29 +283,27 @@ async fn settle(
236 } else {283 } else {
237 MessageStatus::Failed284 MessageStatus::Failed
238 };285 };
239- let mut result = db286+ let settled = query_as!(
240- .query(287+ ChatbotMessage,
241- "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \288+ "UPDATE chatbot_message SET content = $2, status = $3, truncated = $4, \
242- error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER",289+ error_code = $5, completed_at = $6 \
243- )290+ WHERE id = $1 AND status = 'pending' \
244- .bind(("id", id.record()))291+ RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \
245- .bind(("content", text.map(|t| t.0).unwrap_or_default()))292+ user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \
246- .bind(("status", status.as_str().to_string()))293+ status AS \"status: MessageStatus\", truncated, \
247- .bind(("truncated", truncated))294+ error_code AS \"error_code: String\", \
248- .bind((295+ created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"",
249- "code",296+ id.uuid(),
250- error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),297+ text.map(|t| t.as_str().to_string()).unwrap_or_default(),
251- ))298+ status.as_str(),
252- .bind(("now", Timestamp::now().as_millis()))299+ truncated,
253- .await?300+ error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::<String>()),
254- .check()?;301+ Timestamp::now().as_millis(),
255- result302+ )
256- .take::<Vec<ChatbotMessage>>(0)?303+ .fetch_optional(db)
257- .into_iter()304+ .await?;
258- .next()305+ settled.ok_or(AppError::NotFound)
259- .ok_or(AppError::NotFound)
260 }306 }
261-
262 #[cfg(test)]307 #[cfg(test)]
263 mod tests {308 mod tests {
264 use super::*;309 use super::*;
src/db/chatbot_thread.rsmodified+114 -175
@@ -4,142 +4,67 @@
4 //! [`crate::domain::chatbot_thread`]; this module is where their rows are4 //! [`crate::domain::chatbot_thread`]; this module is where their rows are
5 //! read and written.5 //! read and written.
6 6
7-use surrealdb::types::{SurrealValue, Value};7+use crate::constant::DEFAULT_MAX_CHATBOT_THREADS;
8-8+use crate::database::{Database, tx_with_retry};
9-use crate::constant::{
10- CHATBOT_THREAD_COUNT_FIELD, DEFAULT_MAX_CHATBOT_THREADS, SETTINGS_KEY, SETTINGS_TABLE,
11-};
12-use crate::database::{Database, transaction_with_retry};
13-use crate::db::cap;
14 use crate::db::page::PagedList;9 use crate::db::page::PagedList;
15 use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};10 use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
16 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
17 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
18 use crate::error::AppError;13 use crate::error::AppError;
19-14+use sqlx::query_as;
20-/// Move the thread's `updated_at` **and** run `statement` — a write to a turn
21-/// hanging off that thread — in one transaction, handing back the row it
22-/// returned. [`AppError::NotFound`] means the thread is gone and `statement`
23-/// wrote nothing.
24-///
25-/// The bump is what ties a turn's fate to its thread, and reading the thread
26-/// first does not: [`delete`] sweeps `chatbot_message` and drops
27-/// the thread in one transaction, so a create landing after that sweep but
28-/// before its commit reads a thread that is still there (uncommitted) while the
29-/// sweep ran on a snapshot predating the new row — both commit, and the turn
30-/// outlives the thread it was deleted with, readable and deletable by nothing.
31-/// Reads do not conflict; only a write that *moves* a value on a key the delete
32-/// also writes does. That is the shape
33-/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and
34-/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already
35-/// use, and the sweep's ordering inside the delete stops mattering once it is
36-/// in place.
37-///
38-/// `updated_at` is the value moved, and it doubles as the stamp the thread list
39-/// sorts on — this *is* the activity touch the send path used to issue
40-/// afterwards as a separate, best-effort query whose failure was only logged.
41-/// It is written strictly upwards rather than to `$now`: an `UPDATE` that
42-/// leaves the document unchanged is elided and never reaches the store's write
43-/// set, a turn's two rows are routinely written inside one millisecond, and a
44-/// write that does not happen collides with nothing. The stamp can therefore
45-/// sit a few milliseconds ahead of the clock, which an ordering key does not
46-/// care about.
47-///
48-/// Admissible for [`transaction_with_retry`] as long as `statement` is: the
49-/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already
50-/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with
51-/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote
52-/// nothing, so re-sending it is the recovery.
53-pub(crate) async fn touch_and_write<T: SurrealValue>(
54- db: &Database,
55- thread: &ChatbotThreadId,
56- statement: &str,
57- mut bindings: Vec<(String, Value)>,
58-) -> Result<Option<T>, AppError> {
59- bindings.push(("conv".into(), thread.record().into_value()));
60- bindings.push(("now".into(), Timestamp::now().as_millis().into_value()));
61- let (mut result, mut errors) = transaction_with_retry(
62- db,
63- &format!(
64- "BEGIN TRANSACTION;
65- LET $touched = (UPDATE $conv SET updated_at = \
66- math::max([$now, updated_at + 1]) RETURN VALUE id);
67- IF array::len($touched) = 0 {{ THROW 'no_thread' }};
68- LET $row = ({statement});
69- RETURN $row;
70- COMMIT TRANSACTION;"
71- ),
72- &bindings,
73- &["no_thread"],
74- )
75- .await?;
76- // An aborted transaction errors *every* slot, most with a generic "not
77- // executed" — only the THROW's own slot names the reason.
78- if errors
79- .values()
80- .any(|error| error.to_string().contains("no_thread"))
81- {
82- return Err(AppError::NotFound);
83- }
84- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
85- return Err(error.into());
86- }
87- // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4.
88- Ok(result.take::<Vec<T>>(4)?.into_iter().next())
89-}
90 15
91 /// Start a thread unless `user` is already at the school's16 /// Start a thread unless `user` is already at the school's
92-/// `max_chatbot_threads`. The slot is taken on the user row in the same17+/// `max_chatbot_threads`. The claim recipe of one: the slot bump on the
93-/// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic18+/// user row, the live cap read, and the thread's insert are a single
94-/// single-record write, so two requests racing the same user's last slot19+/// statement — two requests racing the same user's last slot cannot both
95-/// cannot both win and the counter can never count a row that did not20+/// win, and the counter can never count a row that did not commit.
96-/// commit.
97 ///21 ///
98 /// The cap is the one *live* on the settings singleton, sub-queried inside22 /// The cap is the one *live* on the settings singleton, sub-queried inside
99 /// that same conditional write rather than bound as a number: this cap does23 /// that same conditional write rather than bound as a number: this cap does
100 /// not live on the parent row (the seat is on the user, the limit is the24 /// not live on the parent row (the seat is on the user, the limit is the
101 /// school's), and a snapshot of it admits every request already in flight25 /// school's), and a snapshot of it admits every request already in flight
102-/// when a `PATCH /settings` lowers it. The subquery costs one extra record26+/// when a `PATCH /settings` lowers it. `DEFAULT_MAX_CHATBOT_THREADS` is the
103-/// read per claim on a path that already reads the row it writes.27+/// fallback the settings row's own NULL means — no row, or a school that
104-/// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own28+/// never set the knob.
105-/// absent column means — no row, or a school that never set the knob.29+///
30+/// The seat is taken on the user's own row, which is also the key a role
31+/// change writes, so this write already contends with a demotion — no
32+/// separate holder claim is needed.
106 pub async fn create_capped(33 pub async fn create_capped(
107 db: &Database,34 db: &Database,
108 user: &UserId,35 user: &UserId,
109 title: Option<ChatbotThreadTitle>,36 title: Option<ChatbotThreadTitle>,
110 ) -> Result<ChatbotThread, AppError> {37 ) -> Result<ChatbotThread, AppError> {
111 let now = Timestamp::now();38 let now = Timestamp::now();
112- let thread = ChatbotThread {39+ match query_as!(
113- id: ChatbotThreadId::generate(),40+ ChatbotThread,
114- user_id: user.clone(),41+ "WITH seat AS (
115- title,42+ UPDATE app_user SET chatbot_thread_count = chatbot_thread_count + 1
116- created_at: now,43+ WHERE id = $1
117- updated_at: now,44+ AND chatbot_thread_count < COALESCE(
118- };45+ (SELECT max_chatbot_threads FROM settings WHERE id = 'school'),
119- match cap::claim_live_and_create(46+ $2)
120- &user.record(),47+ RETURNING 1)
121- CHATBOT_THREAD_COUNT_FIELD,48+ INSERT INTO chatbot_thread (id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\")
122- &format!(49+ SELECT $3, $1, $4, $5, $5
123- "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num"50+ WHERE EXISTS (SELECT 1 FROM seat)
124- ),51+ RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \
52+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
53+ user.uuid(),
125 DEFAULT_MAX_CHATBOT_THREADS,54 DEFAULT_MAX_CHATBOT_THREADS,
126- // No holder claim: the parent row *is* the user's, so this write55+ ChatbotThreadId::generate().uuid(),
127- // already lands on the key a role change writes.56+ title.map(|t| t.as_str().to_string()),
128- None,57+ now.as_millis(),
129- (&thread.id.record(), &thread),
130- db,
131 )58 )
59+ .fetch_optional(db)
132 .await?60 .await?
133 {61 {
134- cap::Claimed::Made(saved) => Ok(saved),62+ Some(saved) => Ok(saved),
135 // Full, or the user's row is gone — the conditional write matches63 // Full, or the user's row is gone — the conditional write matches
136- // nothing either way.64+ // nothing either way, as before.
137- cap::Claimed::Full => Err(AppError::Conflict(65+ None => Err(AppError::Conflict(
138 "you have reached the school's limit on saved threads — delete one first",66 "you have reached the school's limit on saved threads — delete one first",
139 )),67 )),
140- // The id is a freshly minted ULID on a table with no UNIQUE index,
141- // so no rival can have aimed at it.
142- cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())),
143 }68 }
144 }69 }
145 70
@@ -152,27 +77,23 @@ pub async fn list_for_user(
152 offset: i64,77 offset: i64,
153 ) -> Result<(Vec<ChatbotThread>, i64), AppError> {78 ) -> Result<(Vec<ChatbotThread>, i64), AppError> {
154 PagedList::new(79 PagedList::new(
155- "chatbot_thread WHERE user_id = $usr",80+ "chatbot_thread WHERE user_id = $1",
156 "ORDER BY updated_at DESC, id DESC",81 "ORDER BY updated_at DESC, id DESC",
157 )82 )
158- .bind("usr", user.record())83+ .bind(user.uuid())
159 .run(limit, offset, db)84 .run(limit, offset, db)
160 .await85 .await
161 }86 }
162 87
163 /// How many threads `user` keeps — the `max_chatbot_threads` cap check.88 /// How many threads `user` keeps — the `max_chatbot_threads` cap check.
164 pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> {89 pub async fn count_for_user(db: &Database, user: &UserId) -> Result<usize, AppError> {
165- let mut result = db90+ let row = sqlx::query!(
166- .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL")91+ "SELECT count(*) AS threads FROM chatbot_thread WHERE user_id = $1",
167- .bind(("usr", user.record()))92+ user.uuid()
168- .await?93+ )
169- .check()?;94+ .fetch_one(db)
170- Ok(result95+ .await?;
171- .take::<Vec<i64>>(0)?96+ Ok(row.threads.unwrap_or(0).max(0) as usize)
172- .first()
173- .copied()
174- .unwrap_or_default()
175- .max(0) as usize)
176 }97 }
177 98
178 /// Read a thread only if `user` owns it — a foreign id reads as absent, so99 /// Read a thread only if `user` owns it — a foreign id reads as absent, so
@@ -182,75 +103,93 @@ pub async fn read_for(
182 id: &ChatbotThreadId,103 id: &ChatbotThreadId,
183 user: &UserId,104 user: &UserId,
184 ) -> Result<Option<ChatbotThread>, AppError> {105 ) -> Result<Option<ChatbotThread>, AppError> {
185- let thread: Option<ChatbotThread> = db.select(id.record()).await?;106+ let thread = query_as!(
107+ ChatbotThread,
108+ "SELECT id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\" FROM chatbot_thread WHERE id = $1",
109+ id
110+ )
111+ .fetch_optional(db)
112+ .await?;
186 Ok(thread.filter(|thread| &thread.user_id == user))113 Ok(thread.filter(|thread| &thread.user_id == user))
187 }114 }
188 115
189-// Stamping new activity is not a call of its own: it is the bump inside116+// Stamping new activity is not a call of its own: it is the monotonic bump
190-// [`touch_and_write`], which every turn already rides, so a stamp can no117+// inside every write that touches the thread (a turn's insert, the rename,
191-// longer be lost (it used to be a best-effort query after the two creates,118+// the delete below), so a stamp can no longer be lost (it used to be a
192-// whose failure was a `warn!`) and no turn can be written without it.119+// best-effort query after the two creates, whose failure was a `warn!`) and
120+// no turn can be written without it.
193 121
194 /// Rename the thread (`None` clears the name back to untitled), stamping122 /// Rename the thread (`None` clears the name back to untitled), stamping
195-/// the edit as activity. Field-scoped for the same reason as123+/// the edit as activity. Field-scoped: a turn may be landing concurrently.
196-/// [`touch_and_write`]: a turn may be landing concurrently.124+/// The stamp is written strictly upwards — `GREATEST($now, updated_at + 1)`
125+/// — because a thread's writes routinely land inside one millisecond and
126+/// `updated_at` is the list's ordering key; the stamp may sit a few
127+/// milliseconds ahead of the clock, which an ordering key does not care
128+/// about. Zero rows: the thread is gone, the same 404 the delete answers.
197 pub async fn rename(129 pub async fn rename(
198 db: &Database,130 db: &Database,
199 thread: &ChatbotThread,131 thread: &ChatbotThread,
200 title: Option<ChatbotThreadTitle>,132 title: Option<ChatbotThreadTitle>,
201 ) -> Result<ChatbotThread, AppError> {133 ) -> Result<ChatbotThread, AppError> {
202- let mut result = db134+ let updated = query_as!(
203- .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER")135+ ChatbotThread,
204- .bind(("id", thread.id.record()))136+ "UPDATE chatbot_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) \
205- .bind(("title", title.map(|title| title.0)))137+ WHERE id = $1 \
206- .bind(("now", Timestamp::now().as_millis()))138+ RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \
207- .await?139+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
208- .check()?;140+ thread.get_id().uuid(),
209- result141+ title.map(|t| t.as_str().to_string()),
210- .take::<Vec<ChatbotThread>>(0)?142+ Timestamp::now().as_millis(),
211- .into_iter()143+ )
212- .next()144+ .fetch_optional(db)
213- .ok_or(AppError::NotFound)145+ .await?;
146+ updated.ok_or(AppError::NotFound)
214 }147 }
215 148
216 /// Delete the thread and every turn in it — one transaction, so a crash149 /// Delete the thread and every turn in it — one transaction, so a crash
217 /// can't orphan messages under a vanished thread. The owner's slot comes150 /// can't orphan messages under a vanished thread. The owner's slot comes
218 /// back in that same transaction, or the cap would ratchet shut.151 /// back in that same transaction, or the cap would ratchet shut.
219 ///152 ///
220-/// A turn, a rename and this delete all write the thread row (see153+/// A turn's insert (see [`crate::db::chatbot_message`]) writes *through*
221-/// [`touch_and_write`]), so the store aborting one of them is ordinary154+/// the thread's row — its guarded statement moves `updated_at`, the key
222-/// here — that collision is exactly what keeps a turn from outliving the155+/// this delete's final write removes — so under Postgres's row locking the
223-/// thread — and a lost round is re-sent rather than reported as the `500`156+/// two serialize: either the turn saw the thread and committed first (the
224-/// it used to be. Re-sending is sound: every statement is a `DELETE` or a157+/// delete then refuses nothing, the sweep takes the turn), or the thread
225-/// field-scoped `UPDATE`, none of which can ever answer "already exists"158+/// was gone and the turn's gate matched nothing. No turn outlives its
226-/// (see [`transaction_with_retry`]). On the re-sent round the thread is159+/// thread. On a re-sent round the thread is already gone, so the caller
227-/// already gone, so the `RETURN` is empty and the caller gets the `404`160+/// gets the `404` that is the truth.
228-/// that is the truth.
229 pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> {161 pub async fn delete(db: &Database, thread: ChatbotThread) -> Result<ChatbotThread, AppError> {
230- let (mut result, mut errors) = transaction_with_retry(162+ tx_with_retry(db, false, async |tx| {
231- db,163+ // Children first: the foreign key would refuse the parent while a
232- "BEGIN TRANSACTION;164+ // turn still names it.
233- DELETE chatbot_message WHERE thread_id = $conv;165+ sqlx::query!(
234- LET $gone = (DELETE $conv RETURN BEFORE);166+ "DELETE FROM chatbot_message WHERE thread_id = $1",
235- UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]);167+ thread.get_id().uuid()
236- RETURN $gone;168+ )
237- COMMIT TRANSACTION;",169+ .execute(&mut *tx)
238- &[170+ .await?;
239- ("conv".into(), thread.id.record().into_value()),171+ let gone = query_as!(
240- ("usr".into(), thread.user_id.record().into_value()),172+ ChatbotThread,
241- ],173+ "DELETE FROM chatbot_thread WHERE id = $1 \
242- &[],174+ RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title, \
243- )175+ created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"",
244- .await?;176+ thread.get_id().uuid()
245- if let Some(error) = errors.drain().map(|(_, error)| error).next() {177+ )
246- return Err(error.into());178+ .fetch_optional(&mut *tx)
247- }179+ .await?;
248- // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN180+ if let Some(gone) = &gone {
249- // is slot 4.181+ sqlx::query!(
250- let deleted: Option<ChatbotThread> = result.take::<Vec<ChatbotThread>>(4)?.into_iter().next();182+ "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \
251- deleted.ok_or(AppError::NotFound)183+ WHERE id = $1",
184+ gone.get_user_id()
185+ )
186+ .execute(&mut *tx)
187+ .await?;
188+ }
189+ gone.ok_or(AppError::NotFound)
190+ })
191+ .await
252 }192 }
253-
254 #[cfg(test)]193 #[cfg(test)]
255 mod tests {194 mod tests {
256 use super::*;195 use super::*;
src/db/event.rsmodified+212 -117
@@ -2,91 +2,108 @@
2 //! audience's live membership resolution — the point check behind marking2 //! audience's live membership resolution — the point check behind marking
3 //! ([`includes`]) and the who-missed report's backbone ([`members`]).3 //! ([`includes`]) and the who-missed report's backbone ([`members`]).
4 4
5-use surrealdb::types::SurrealValue;5+use crate::database::{Database, tx_with_retry};
6-
7-use crate::database::{Database, transaction_with_retry};
8 use crate::db::field_update::FieldUpdate;6 use crate::db::field_update::FieldUpdate;
9-use crate::domain::class_member::{ClassMember, ClassMemberId};7+use crate::db::page::Param;
10-use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};8+use crate::domain::class_group::ClassGroupId;
9+use crate::domain::course::CourseId;
10+use crate::domain::event::{
11+ Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle,
12+};
13+use crate::domain::role::Role;
11 use crate::domain::timestamp::{Timestamp, range_error};14 use crate::domain::timestamp::{Timestamp, range_error};
12 use crate::domain::user::{User, UserId};15 use crate::domain::user::{User, UserId};
13 use crate::error::AppError;16 use crate::error::AppError;
17+use sqlx::query_as;
14 18
15-/// Is `user` in `audience`'s roster right now? The point check behind19+/// Is `user` in this event's audience roster right now? The point check
16-/// marking — cheaper than resolving the whole roster when the target is20+/// behind marking — cheaper than resolving the whole roster when the target
17-/// known. `event` must be the event this audience came from: the21+/// is known. The audience comes off the row itself: the registration kind
18-/// registration kind resolves against that event's signup rows.22+/// resolves against that event's signup rows.
19-pub async fn includes(23+pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool, AppError> {
20- db: &Database,24+ match event.get_audience_kind() {
21- audience: &EventAudience,25+ crate::domain::event::EventAudienceKind::School => Ok(true),
22- event: &EventId,26+ crate::domain::event::EventAudienceKind::Role => {
23- user: &User,27+ Ok(Some(user.get_role()) == event.get_audience_role())
24-) -> Result<bool, AppError> {28+ }
25- match audience {29+ crate::domain::event::EventAudienceKind::Course => {
26- EventAudience::School => Ok(true),30+ match event.get_audience_course() {
27- EventAudience::Role { role } => Ok(user.get_role() == *role),31+ Some(course) => Ok(crate::db::enrollment::read_for_user(db, course, user.get_id())
28- EventAudience::Course { course } => {
29- Ok(
30- crate::db::enrollment::read_for_user(db, course, user.get_id())
31 .await?32 .await?
32- .is_some(),33+ .is_some()),
33- )34+ None => Ok(false),
35+ }
34 }36 }
35- // The (class, user) pair is the membership row's own id, so the37+ // The (class, user) pair is the membership row's own primary key, so
36- // point check is a single select — no scan, no index needed.38+ // the point check is one existence probe — no scan, no index needed.
37- EventAudience::Class { class } => {39+ crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
38- let member: Option<ClassMember> = db40+ Some(class) => {
39- .select(ClassMemberId::composite(class, user.get_id()).record())41+ let row = sqlx::query!(
42+ "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2)
43+ AS present",
44+ class.uuid(),
45+ user.get_id().uuid()
46+ )
47+ .fetch_one(db)
40 .await?;48 .await?;
41- Ok(member.is_some())49+ Ok(row.present)
42- }50+ }
43- EventAudience::Registration { .. } => {51+ None => Ok(false),
44- Ok(crate::db::registration::read_for_user(db, event, user.get_id())52+ },
53+ crate::domain::event::EventAudienceKind::Registration => {
54+ Ok(crate::db::registration::read_for_user(db, event.get_id(), user.get_id())
45 .await?55 .await?
46 .is_some())56 .is_some())
47 }57 }
48 }58 }
49 }59 }
50 60
51-/// `event`'s full roster, as it stands right now — the who-missed61+/// The event's full roster, as it stands right now — the who-missed
52 /// report's backbone. Registered ids that no longer resolve to a user row62 /// report's backbone. Registered ids that no longer resolve to a user row
53 /// are kept; the caller degrades their display like any stale reference.63 /// are kept; the caller degrades their display like any stale reference.
54-pub async fn members(64+pub async fn members(db: &Database, event: &Event) -> Result<Vec<UserId>, AppError> {
55- db: &Database,65+ match event.get_audience_kind() {
56- audience: &EventAudience,66+ crate::domain::event::EventAudienceKind::School => Ok(crate::db::user::list_all(db, None, 0)
57- event: &EventId,
58-) -> Result<Vec<UserId>, AppError> {
59- match audience {
60- EventAudience::School => Ok(crate::db::user::list_all(db, None, 0)
61 .await?67 .await?
62 .068 .0
63 .iter()69 .iter()
64 .map(|user| user.get_id().clone())70 .map(|user| user.get_id().clone())
65 .collect()),71 .collect()),
66- EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role)72+ crate::domain::event::EventAudienceKind::Role => {
67- .await?73+ match event.get_audience_role() {
68- .iter()74+ Some(role) => Ok(crate::db::user::list_by_role(db, role)
69- .map(|user| user.get_id().clone())75+ .await?
70- .collect()),76+ .iter()
71- EventAudience::Course { course } => {77+ .map(|user| user.get_id().clone())
72- Ok(crate::db::enrollment::list_for_course(db, course, None, 0)78+ .collect()),
79+ None => Ok(Vec::new()),
80+ }
81+ }
82+ crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() {
83+ Some(course) => Ok(crate::db::enrollment::list_for_course(db, course, None, 0)
73 .await?84 .await?
74 .085 .0
75 .iter()86 .iter()
76 .map(|enrollment| enrollment.get_user().clone())87 .map(|enrollment| enrollment.get_user().clone())
88+ .collect()),
89+ None => Ok(Vec::new()),
90+ },
91+ crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() {
92+ Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0)
93+ .await?
94+ .0
95+ .iter()
96+ .map(|member| member.get_user().clone())
97+ .collect()),
98+ None => Ok(Vec::new()),
99+ },
100+ crate::domain::event::EventAudienceKind::Registration => {
101+ Ok(crate::db::registration::list_for_event(db, event.get_id())
102+ .await?
103+ .iter()
104+ .map(|registration| registration.get_user().clone())
77 .collect())105 .collect())
78 }106 }
79- EventAudience::Class { class } => Ok(crate::db::class_member::list_for_class(db, class, None, 0)
80- .await?
81- .0
82- .iter()
83- .map(|member| member.get_user().clone())
84- .collect()),
85- EventAudience::Registration { .. } => Ok(crate::db::registration::list_for_event(db, event)
86- .await?
87- .iter()
88- .map(|registration| registration.get_user().clone())
89- .collect()),
90 }107 }
91 }108 }
92 109
@@ -99,29 +116,70 @@ pub async fn create(
99 starts_at: Option<Timestamp>,116 starts_at: Option<Timestamp>,
100 ends_at: Option<Timestamp>,117 ends_at: Option<Timestamp>,
101 ) -> Result<Event, AppError> {118 ) -> Result<Event, AppError> {
102- let event = Event {119+ // The audience payload moves as one unit with its kind; the validated
103- id: EventId::generate(),120+ // bundle guarantees only the matching payload is ever non-NULL.
104- creator: creator.clone(),121+ let created = query_as!(
105- title,122+ Event,
106- description,123+ "INSERT INTO event (id, creator, title AS \"title: EventTitle\", description AS \"description: EventDescription\", audience_kind, audience_role, \
107- audience,124+ audience_course, audience_class, audience_capacity, starts_at, ends_at)
108- starts_at,125+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
109- ends_at,126+ RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
110- };127+ audience_kind AS \"audience_kind: EventAudienceKind\", \
111- let created: Option<Event> = db.create(event.id.record()).content(event).await?;128+ audience_role AS \"audience_role: Role\", \
112- created.ok_or_else(|| AppError::Internal("failed to create event".into()))129+ audience_course AS \"audience_course: CourseId\", \
130+ audience_class AS \"audience_class: ClassGroupId\", \
131+ audience_capacity, starts_at AS \"starts_at: Timestamp\", \
132+ ends_at AS \"ends_at: Timestamp\"",
133+ EventId::generate().uuid(),
134+ creator.uuid(),
135+ title.as_str(),
136+ description.as_str(),
137+ audience.kind,
138+ audience.role.map(|r| r.as_str().to_string()),
139+ audience.course.map(|c| c.uuid()),
140+ audience.class.map(|c| c.uuid()),
141+ audience.capacity,
142+ starts_at.map(|t| t.as_millis()),
143+ ends_at.map(|t| t.as_millis()),
144+ )
145+ .fetch_one(db)
146+ .await?;
147+ Ok(created)
113 }148 }
114 149
115 pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError> {150 pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError> {
116- Ok(db.select(id.record()).await?)151+ let event = query_as!(
152+ Event,
153+ "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
154+ audience_kind AS \"audience_kind: EventAudienceKind\", \
155+ audience_role AS \"audience_role: Role\", \
156+ audience_course AS \"audience_course: CourseId\", \
157+ audience_class AS \"audience_class: ClassGroupId\", \
158+ audience_capacity, starts_at AS \"starts_at: Timestamp\", \
159+ ends_at AS \"ends_at: Timestamp\" \
160+ FROM event WHERE id = $1",
161+ id.uuid()
162+ )
163+ .fetch_optional(db)
164+ .await?;
165+ Ok(event)
117 }166 }
118 167
119 pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {168 pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
120- let mut result = db169+ let events = query_as!(
121- .query("SELECT * FROM event ORDER BY id DESC")170+ Event,
122- .await?171+ "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
123- .check()?;172+ audience_kind AS \"audience_kind: EventAudienceKind\", \
124- Ok(result.take::<Vec<Event>>(0)?)173+ audience_role AS \"audience_role: Role\", \
174+ audience_course AS \"audience_course: CourseId\", \
175+ audience_class AS \"audience_class: ClassGroupId\", \
176+ audience_capacity, starts_at AS \"starts_at: Timestamp\", \
177+ ends_at AS \"ends_at: Timestamp\" \
178+ FROM event ORDER BY id DESC",
179+ )
180+ .fetch_all(db)
181+ .await?;
182+ Ok(events)
125 }183 }
126 184
127 /// Request-scoped: the handler reads the event, then awaits the clock and a185 /// Request-scoped: the handler reads the event, then awaits the clock and a
@@ -131,6 +189,10 @@ pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
131 /// alone does not prevent that, the values have to come from the request.189 /// alone does not prevent that, the values have to come from the request.
132 /// The schedule columns are nullable, so they take the outer/inner190 /// The schedule columns are nullable, so they take the outer/inner
133 /// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.191 /// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
192+///
193+/// The audience is five columns moving as one unit: when the request
194+/// carries an audience, all five are written (the non-matching payload as
195+/// NULL); when it carries none, none are.
134 pub async fn update(196 pub async fn update(
135 db: &Database,197 db: &Database,
136 event: Event,198 event: Event,
@@ -140,12 +202,47 @@ pub async fn update(
140 starts_at: Option<Option<Timestamp>>,202 starts_at: Option<Option<Timestamp>>,
141 ends_at: Option<Option<Timestamp>>,203 ends_at: Option<Option<Timestamp>>,
142 ) -> Result<Event, AppError> {204 ) -> Result<Event, AppError> {
143- FieldUpdate::new(event.id.record())205+ FieldUpdate::new("event", event.get_id().uuid())
144- .set("title", title)206+ .set(
145- .set("description", description)207+ "title",
146- .set("audience", audience)208+ title.map(|title| Param::Text(title.as_str().to_string())),
147- .set("starts_at", starts_at)209+ )
148- .set("ends_at", ends_at)210+ .set(
211+ "description",
212+ description.map(|d| Param::Text(d.as_str().to_string())),
213+ )
214+ .set(
215+ "audience_kind",
216+ audience
217+ .as_ref()
218+ .map(|a| Param::Text(a.kind.as_str().to_string())),
219+ )
220+ .set(
221+ "audience_role",
222+ audience
223+ .as_ref()
224+ .map(|a| Param::OptText(a.role.map(|r| r.as_str().to_string()))),
225+ )
226+ .set(
227+ "audience_course",
228+ audience.as_ref().map(|a| Param::OptUuid(a.course.map(|c| c.uuid()))),
229+ )
230+ .set(
231+ "audience_class",
232+ audience.as_ref().map(|a| Param::OptUuid(a.class.map(|c| c.uuid()))),
233+ )
234+ .set(
235+ "audience_capacity",
236+ audience.as_ref().map(|a| Param::OptI64(a.capacity)),
237+ )
238+ .set(
239+ "starts_at",
240+ starts_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))),
241+ )
242+ .set(
243+ "ends_at",
244+ ends_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))),
245+ )
149 .ordered("starts_at", "ends_at", range_error())246 .ordered("starts_at", "ends_at", range_error())
150 .run::<Event>(db)247 .run::<Event>(db)
151 .await248 .await
@@ -153,44 +250,42 @@ pub async fn update(
153 250
154 /// Delete the event and cascade-remove its attendance and signup rows.251 /// Delete the event and cascade-remove its attendance and signup rows.
155 ///252 ///
156-/// Children first, and all of it in one transaction the way253+/// Children first, all of it in one guarded transaction: run as separate
157-/// [`crate::db::course::delete`] does it: run as two queries, a254+/// statements, a registration or a mark committing in between would outlive
158-/// registration or a mark that committed in between outlived its event —255+/// its event — an orphan no read path can ever reach and no delete can ever
159-/// an orphan no read path can ever reach and no delete can ever reclaim,256+/// reclaim, since every one of them is keyed on the event that is now gone.
160-/// since every one of them is keyed on the event that is now gone.
161 ///257 ///
162-/// Re-sent while the store answers "conflict, retry", the way258+/// `cascade` retry: a mark landing while the cascade is in flight contends
163-/// [`crate::db::course_session::delete`] is: now that259+/// for the event row (its insert's foreign key proves the event the moment
164-/// [`crate::domain::attendance::Attendance::mark`] writes the event row to260+/// it lands), so a lost round re-sends instead of answering 500.
165-/// prove it exists, a mark landing in this window really does contend for
166-/// it — and without the retry the *delete* is the side that loses, turning
167-/// a race the store resolved correctly into a 500 (measured 4 rounds in 4).
168-/// Admissible: every statement is a `DELETE`, which can never answer
169-/// "already exists", and a lost round wrote nothing.
170 pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {261 pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
171- let (mut result, mut errors) = transaction_with_retry(262+ tx_with_retry(db, true, async |tx| {
172- db,263+ sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid())
173- "BEGIN TRANSACTION;264+ .execute(&mut *tx)
174- DELETE attendance WHERE event = $ev;265+ .await?;
175- DELETE registration WHERE event = $ev;266+ sqlx::query!(
176- LET $gone = (DELETE $ev RETURN BEFORE);267+ "DELETE FROM registration WHERE event = $1",
177- RETURN $gone;268+ event.get_id().uuid()
178- COMMIT TRANSACTION;",269+ )
179- &[("ev".into(), event.id.record().into_value())],270+ .execute(&mut *tx)
180- // No THROW of its own — an unconditional cascade.271+ .await?;
181- &[],272+ let gone = query_as!(
182- )273+ Event,
183- .await?;274+ "DELETE FROM event WHERE id = $1 \
184- if let Some(error) = errors.drain().map(|(_, error)| error).next() {275+ RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \
185- return Err(error.into());276+ audience_kind AS \"audience_kind: EventAudienceKind\", \
186- }277+ audience_role AS \"audience_role: Role\", \
187- // Read through the trailing `RETURN`, never a hand-counted slot.278+ audience_course AS \"audience_course: CourseId\", \
188- let slot = result.num_statements().saturating_sub(2);279+ audience_class AS \"audience_class: ClassGroupId\", \
189- result280+ audience_capacity, starts_at AS \"starts_at: Timestamp\", \
190- .take::<Vec<Event>>(slot)?281+ ends_at AS \"ends_at: Timestamp\"",
191- .into_iter()282+ event.get_id().uuid()
192- .next()283+ )
193- .ok_or(AppError::NotFound)284+ .fetch_optional(&mut *tx)
285+ .await?;
286+ gone.ok_or(AppError::NotFound)
287+ })
288+ .await
194 }289 }
195 290
196 #[cfg(test)]291 #[cfg(test)]
src/db/message.rsmodified+153 -85
@@ -4,13 +4,14 @@
4 //! [`crate::domain::message`].4 //! [`crate::domain::message`].
5 5
6 use crate::database::Database;6 use crate::database::Database;
7-use crate::db::page::PagedList;7+use crate::db::page::{PagedList, Param};
8 use crate::domain::message::{8 use crate::domain::message::{
9 Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,9 Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject,
10 };10 };
11 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
12 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
13 use crate::error::AppError;13 use crate::error::AppError;
14+use sqlx::query_as;
14 15
15 pub async fn send(16 pub async fn send(
16 db: &Database,17 db: &Database,
@@ -20,30 +21,40 @@ pub async fn send(
20 body: MessageBody,21 body: MessageBody,
21 label: Option<MessageLabel>,22 label: Option<MessageLabel>,
22 ) -> Result<Message, AppError> {23 ) -> Result<Message, AppError> {
23- let message = Message {24+ let message = query_as!(
24- id: MessageId::generate(),25+ Message,
25- sender: sender.clone(),26+ "INSERT INTO message (id, sender, recipient, subject, body, label, sent_at, read, \
26- recipient: recipient.clone(),27+ sender_folder, recipient_folder, sender_origin, recipient_origin)
27- subject,28+ VALUES ($1, $2, $3, $4, $5, $6, $7, false, 'sent', 'inbox', NULL, NULL)
28- body,29+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
29- label,30+ subject, body, label AS \"label: MessageLabel\", \
30- sent_at: Timestamp::now(),31+ sent_at AS \"sent_at: Timestamp\", read, \
31- read: false,32+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
32- sender_folder: Folder::Sent,33+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
33- recipient_folder: Folder::Inbox,34+ MessageId::generate().uuid(),
34- sender_origin: None,35+ sender.uuid(),
35- recipient_origin: None,36+ recipient.uuid(),
36- };37+ subject.as_str(),
37- let created: Option<Message> = db.create(message.id.record()).content(message).await?;38+ body.as_str(),
38- created.ok_or_else(|| AppError::Internal("failed to create message".into()))39+ label.map(|l| l.as_str().to_string()),
40+ Timestamp::now().as_millis(),
41+ )
42+ .fetch_one(db)
43+ .await?;
44+ Ok(message)
39 }45 }
40 46
41 /// One folder view for `user`, newest first. `inbox` is recipient-side,47 /// One folder view for `user`, newest first. `inbox` is recipient-side,
42 /// `sent` is sender-side, and `archive`/`trash` are each the union of both48 /// `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).49 /// 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 unread50 /// `read` narrows to that flag state (`false` on the inbox is the unread
45-/// view; on `sent`, receipts pending) — the folder condition is51+/// view; on `sent`, receipts pending).
46-/// parenthesized because `archive`'s and `trash`'s are ORs.52+///
53+/// The folder predicates are the four closed shapes the domain's folder
54+/// vocabulary admits, spelled as one `WHERE` each — the same shapes the old
55+/// dynamic string assembled, minus the interpolation. They ride the
56+/// [`PagedList`] builder (the paged-list exemption), so the page and its
57+/// count always see the same predicate.
47 pub async fn list_folder(58 pub async fn list_folder(
48 db: &Database,59 db: &Database,
49 user: &UserId,60 user: &UserId,
@@ -52,32 +63,34 @@ pub async fn list_folder(
52 limit: Option<i64>,63 limit: Option<i64>,
53 offset: i64,64 offset: i64,
54 ) -> Result<(Vec<Message>, i64), AppError> {65 ) -> Result<(Vec<Message>, i64), AppError> {
55- let condition = match folder {66+ let home_arm = folder == Folder::Inbox;
56- Folder::Sent => "sender = $usr AND sender_folder = 'sent'",67+ let mut from = match folder {
68+ Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(),
57 Folder::Archive => {69 Folder::Archive => {
58- "(recipient = $usr AND recipient_folder = 'archive') \70+ "message WHERE (recipient = $1 AND recipient_folder = 'archive') \
59- OR (sender = $usr AND sender_folder = 'archive')"71+ OR (sender = $1 AND sender_folder = 'archive')"
72+ .to_string()
60 }73 }
61 Folder::Trash => {74 Folder::Trash => {
62- "(recipient = $usr AND recipient_folder = 'trash') \75+ "message WHERE (recipient = $1 AND recipient_folder = 'trash') \
63- OR (sender = $usr AND sender_folder = 'trash')"76+ OR (sender = $1 AND sender_folder = 'trash')"
77+ .to_string()
64 }78 }
65- _ => "recipient = $usr AND recipient_folder = $folder",79+ _ => "message WHERE recipient = $1 AND recipient_folder = $2".to_string(),
66- };
67- let read_clause = if read.is_some() {
68- " AND read = $read"
69- } else {
70- ""
71 };80 };
72- PagedList::new(81+ // The `read` filter binds after whichever placeholders the folder shape
73- format!("message WHERE ({condition}){read_clause}"),82+ // spent (`$1` is always the user; the home-folder arm spends `$2`).
74- "ORDER BY id DESC",83+ if read.is_some() {
75- )84+ from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 }));
76- .bind("usr", user.record())85+ }
77- .bind("folder", folder.as_str().to_string())86+ let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user);
78- .bind("read", read.unwrap_or_default())87+ if home_arm {
79- .run(limit, offset, db)88+ builder = builder.bind(folder.as_str().to_string());
80- .await89+ }
90+ if let Some(read) = read {
91+ builder = builder.bind(Param::Bool(read));
92+ }
93+ builder.run(limit, offset, db).await
81 }94 }
82 95
83 /// Read a message only if `user` is its sender or recipient and their96 /// Read a message only if `user` is its sender or recipient and their
@@ -87,7 +100,18 @@ pub async fn read_for(
87 id: &MessageId,100 id: &MessageId,
88 user: &UserId,101 user: &UserId,
89 ) -> Result<Option<Message>, AppError> {102 ) -> Result<Option<Message>, AppError> {
90- let message: Option<Message> = db.select(id.record()).await?;103+ let message = query_as!(
104+ Message,
105+ "SELECT id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
106+ subject, body, label AS \"label: MessageLabel\", \
107+ sent_at AS \"sent_at: Timestamp\", read, \
108+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
109+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\" \
110+ FROM message WHERE id = $1",
111+ id.uuid()
112+ )
113+ .fetch_optional(db)
114+ .await?;
91 Ok(message.filter(|message| {115 Ok(message.filter(|message| {
92 (&message.sender == user || &message.recipient == user)116 (&message.sender == user || &message.recipient == user)
93 && message.folder_of(user) != Folder::Deleted117 && message.folder_of(user) != Folder::Deleted
@@ -97,17 +121,20 @@ pub async fn read_for(
97 /// Flip the recipient's read flag. Field-scoped write: the sender may be121 /// 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.122 /// 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> {123 pub async fn set_read(db: &Database, message: Message, read: bool) -> Result<Message, AppError> {
100- let mut result = db124+ let updated = query_as!(
101- .query("UPDATE $id SET read = $read RETURN AFTER")125+ Message,
102- .bind(("id", message.id.record()))126+ "UPDATE message SET read = $1 WHERE id = $2 \
103- .bind(("read", read))127+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
104- .await?128+ subject, body, label AS \"label: MessageLabel\", \
105- .check()?;129+ sent_at AS \"sent_at: Timestamp\", read, \
106- result130+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
107- .take::<Vec<Message>>(0)?131+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
108- .into_iter()132+ read,
109- .next()133+ message.get_id(),
110- .ok_or(AppError::NotFound)134+ )
135+ .fetch_optional(db)
136+ .await?;
137+ updated.ok_or(AppError::NotFound)
111 }138 }
112 139
113 /// File `user`'s side into `folder` (already validated against that140 /// File `user`'s side into `folder` (already validated against that
@@ -128,31 +155,47 @@ pub async fn move_to(
128 folder: Folder,155 folder: Folder,
129 ) -> Result<Message, AppError> {156 ) -> Result<Message, AppError> {
130 let current = message.folder_of(user);157 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 {158 let origin = match folder {
137 _ if !folder.is_filed() => None,159 _ if !folder.is_filed() => None,
138 _ if current == folder => message.origin_of(user),160 _ if current == folder => message.origin_of(user),
139 _ if current.is_restore_target() => Some(current),161 _ if current.is_restore_target() => Some(current),
140 _ => None,162 _ => None,
141 };163 };
142- let mut result = db164+ let origin = origin.map(|origin| origin.as_str().to_string());
143- .query(format!(165+ // One static statement per side: the field pair written is the caller's
144- "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER"166+ // own, so the sender can never clobber the recipient's filing flags.
145- ))167+ let updated = if message.is_sender(user) {
146- .bind(("id", message.id.record()))168+ query_as!(
147- .bind(("folder", folder.as_str().to_string()))169+ Message,
148- .bind(("origin", origin.map(|origin| origin.as_str().to_string())))170+ "UPDATE message SET sender_folder = $1, sender_origin = $2 WHERE id = $3 \
171+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
172+ subject, body, label AS \"label: MessageLabel\", \
173+ sent_at AS \"sent_at: Timestamp\", read, \
174+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
175+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
176+ folder.as_str(),
177+ origin,
178+ message.get_id().uuid(),
179+ )
180+ .fetch_optional(db)
181+ .await?
182+ } else {
183+ query_as!(
184+ Message,
185+ "UPDATE message SET recipient_folder = $1, recipient_origin = $2 WHERE id = $3 \
186+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
187+ subject, body, label AS \"label: MessageLabel\", \
188+ sent_at AS \"sent_at: Timestamp\", read, \
189+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
190+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
191+ folder.as_str(),
192+ origin,
193+ message.get_id().uuid(),
194+ )
195+ .fetch_optional(db)
149 .await?196 .await?
150- .check()?;197+ };
151- result198+ updated.ok_or(AppError::NotFound)
152- .take::<Vec<Message>>(0)?
153- .into_iter()
154- .next()
155- .ok_or(AppError::NotFound)
156 }199 }
157 200
158 /// Permanently drop `user`'s side — only if that side currently sits in201 /// Permanently drop `user`'s side — only if that side currently sits in
@@ -162,28 +205,53 @@ pub async fn move_to(
162 /// post-write row, so two concurrent deletes can't leak an all-deleted205 /// post-write row, so two concurrent deletes can't leak an all-deleted
163 /// row.206 /// row.
164 pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> {207 pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> {
165- let (field, origin_field) = if message.is_sender(user) {208+ let after = if message.is_sender(user) {
166- ("sender_folder", "sender_origin")209+ query_as!(
210+ Message,
211+ "UPDATE message SET sender_folder = 'deleted', sender_origin = NULL \
212+ WHERE id = $1 AND sender_folder = 'trash' \
213+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
214+ subject, body, label AS \"label: MessageLabel\", \
215+ sent_at AS \"sent_at: Timestamp\", read, \
216+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
217+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
218+ message.get_id().uuid(),
219+ )
220+ .fetch_optional(db)
221+ .await?
167 } else {222 } else {
168- ("recipient_folder", "recipient_origin")223+ query_as!(
169- };224+ Message,
170- let mut result = db225+ "UPDATE message SET recipient_folder = 'deleted', recipient_origin = NULL \
171- .query(format!(226+ WHERE id = $1 AND recipient_folder = 'trash' \
172- "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \227+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
173- WHERE {field} = $trash RETURN AFTER"228+ subject, body, label AS \"label: MessageLabel\", \
174- ))229+ sent_at AS \"sent_at: Timestamp\", read, \
175- .bind(("id", message.id.record()))230+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
176- .bind(("deleted", Folder::Deleted.as_str().to_string()))231+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
177- .bind(("trash", Folder::Trash.as_str().to_string()))232+ message.get_id().uuid(),
233+ )
234+ .fetch_optional(db)
178 .await?235 .await?
179- .check()?;236+ };
180- let Some(after) = result.take::<Vec<Message>>(0)?.into_iter().next() else {237+ let Some(after) = after else {
181 return Err(AppError::Conflict(238 return Err(AppError::Conflict(
182 "only messages in the trash can be permanently deleted",239 "only messages in the trash can be permanently deleted",
183 ));240 ));
184 };241 };
185 if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {242 if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted {
186- let _: Option<Message> = db.delete(after.id.record()).await?;243+ query_as!(
244+ Message,
245+ "DELETE FROM message WHERE id = $1 \
246+ RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \
247+ subject, body, label AS \"label: MessageLabel\", \
248+ sent_at AS \"sent_at: Timestamp\", read, \
249+ sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \
250+ sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"",
251+ after.get_id().uuid(),
252+ )
253+ .fetch_optional(db)
254+ .await?;
187 }255 }
188 Ok(())256 Ok(())
189 }257 }
src/db/parent_link.rsmodified+52 -28
@@ -1,12 +1,13 @@
1-//! The `parent_link` table: the composite-id upsert, the existence probe,1+//! The `parent_link` table: the composite-PK upsert, the existence probe,
2 //! the per-parent listing, and the delete. The *decisions* over these rows2 //! 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 in3 //! — who may be tied, and which reads a live link grants — live in
4 //! [`crate::service::parent_link`].4 //! [`crate::service::parent_link`].
5 5
6 use crate::database::Database;6 use crate::database::Database;
7-use crate::domain::parent_link::{ParentLink, ParentLinkId};7+use crate::domain::parent_link::ParentLink;
8 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9 use crate::error::AppError;9 use crate::error::AppError;
10+use sqlx::query_as;
10 11
11 pub async fn link(12 pub async fn link(
12 db: &Database,13 db: &Database,
@@ -14,34 +15,53 @@ pub async fn link(
14 student: &UserId,15 student: &UserId,
15 linked_by: &UserId,16 linked_by: &UserId,
16 ) -> Result<ParentLink, AppError> {17 ) -> Result<ParentLink, AppError> {
17- let link = ParentLink {18+ // The pair is the primary key, so the upsert is one atomic statement —
18- id: ParentLinkId::composite(parent, student),19+ // no find-then-insert race to lose, and a re-link restamps `linked_by`.
19- parent: parent.clone(),20+ let link = query_as!(
20- student: student.clone(),21+ ParentLink,
21- linked_by: linked_by.clone(),22+ "INSERT INTO parent_link (parent, student, linked_by)
22- };23+ VALUES ($1, $2, $3)
23- let saved: Option<ParentLink> = db.upsert(link.id.record()).content(link).await?;24+ ON CONFLICT (parent, student) DO UPDATE SET linked_by = $3
24- saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into()))25+ RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \
26+ linked_by AS \"linked_by: UserId\"",
27+ parent.uuid(),
28+ student.uuid(),
29+ linked_by.uuid()
30+ )
31+ .fetch_one(db)
32+ .await?;
33+ Ok(link)
25 }34 }
26 35
27 /// True iff a link row exists for the (parent, student) pair — the storage36 /// 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 the37 /// half of the grant. The live half (the student side still holding the
29 /// role) is [`crate::service::parent_link::links_live`].38 /// role) is [`crate::service::parent_link::links_live`].
30 pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> {39 pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result<bool, AppError> {
31- let found: Option<ParentLink> = db40+ let row = sqlx::query!(
32- .select(ParentLinkId::composite(parent, student).record())41+ "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS present",
33- .await?;42+ parent.uuid(),
34- Ok(found.is_some())43+ student.uuid()
44+ )
45+ .fetch_one(db)
46+ .await?;
47+ Ok(row.present)
35 }48 }
36 49
37-/// Every student `parent` observes, newest link first.50+/// Every student `parent` observes. The composite key's text form ordered
51+/// the old listing, which for one parent means the student ids — the same
52+/// order on the natural key.
38 pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {53 pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result<Vec<ParentLink>, AppError> {
39- let mut result = db54+ let links = query_as!(
40- .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC")55+ ParentLink,
41- .bind(("parent", parent.record()))56+ "SELECT parent AS \"parent: UserId\", student AS \"student: UserId\", \
42- .await?57+ linked_by AS \"linked_by: UserId\" \
43- .check()?;58+ FROM parent_link WHERE parent = $1
44- Ok(result.take::<Vec<ParentLink>>(0)?)59+ ORDER BY student DESC",
60+ parent.uuid()
61+ )
62+ .fetch_all(db)
63+ .await?;
64+ Ok(links)
45 }65 }
46 66
47 pub async fn remove(67 pub async fn remove(
@@ -49,11 +69,15 @@ pub async fn remove(
49 parent: &UserId,69 parent: &UserId,
50 student: &UserId,70 student: &UserId,
51 ) -> Result<Option<ParentLink>, AppError> {71 ) -> Result<Option<ParentLink>, AppError> {
52- let mut result = db72+ let gone = query_as!(
53- .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE")73+ ParentLink,
54- .bind(("parent", parent.record()))74+ "DELETE FROM parent_link WHERE parent = $1 AND student = $2
55- .bind(("student", student.record()))75+ RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \
56- .await?76+ linked_by AS \"linked_by: UserId\"",
57- .check()?;77+ parent.uuid(),
58- Ok(result.take::<Vec<ParentLink>>(0)?.into_iter().next())78+ student.uuid()
79+ )
80+ .fetch_optional(db)
81+ .await?;
82+ Ok(gone)
59 }83 }
src/db/pomodoro.rsmodified+187 -211
@@ -3,60 +3,88 @@
3 //! the study streak are all decided inside [`finish`]'s one transaction —3 //! the study streak are all decided inside [`finish`]'s one transaction —
4 //! the whole rule is the batch itself.4 //! the whole rule is the batch itself.
5 5
6-use surrealdb::types::SurrealValue;
7-
8 use crate::constant::{6 use crate::constant::{
9- MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD,7+ CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS,
10- POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD,
11- STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD,
12 };8 };
13-use crate::database::{Database, transaction_with_retry};9+use crate::database::{Database, backoff, tx_with_retry, unique_violation};
14 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};10 use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
15 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
17 use crate::error::AppError;13 use crate::error::AppError;
14+use sqlx::query_as;
18 15
19-/// Start a session for `user`, stamped with the server clock. `UPSERT` on16+/// Start a session for `user`, stamped with the server clock. The open slot
20-/// the deterministic open id makes this atomic and always succeed: a17+/// is the partial unique index (`pomodoro_session_open_stint`): one row per
21-/// dangling unfinished session (the browser died mid-timer) is replaced —18+/// user with `finished_at IS NULL`. A dangling unfinished session (the
19+/// browser died mid-timer) is deleted and replaced in the same statement —
22 /// it never counted, and blocking the next start behind it would only20 /// it never counted, and blocking the next start behind it would only
23 /// punish the student for a crash.21 /// punish the student for a crash.
24 ///22 ///
23+/// Two racing starts cannot both insert: the index refuses the second
24+/// (`23505`), which is retried — the re-run deletes the winner's open row
25+/// and replaces it, the same last-write-wins the old deterministic-key
26+/// upsert had.
27+///
25 /// `label` is the student's own name for the stint, validated and trimmed28 /// `label` is the student's own name for the stint, validated and trimmed
26-/// upstream and stored verbatim. A `None` binds NONE, which an29+/// upstream and stored verbatim. A `None` binds NULL — an unnamed start
27-/// `option<string>` field stores as absent — an unnamed start reads back30+/// reads back unnamed.
28-/// unnamed.
29 pub async fn start(31 pub async fn start(
30 db: &Database,32 db: &Database,
31 user: &UserId,33 user: &UserId,
32 label: Option<String>,34 label: Option<String>,
33 ) -> Result<PomodoroSession, AppError> {35 ) -> Result<PomodoroSession, AppError> {
34- let mut result = db36+ let started_at = Timestamp::now();
35- .query("UPSERT $open CONTENT { user: $usr, started_at: $at, label: $label }")37+ let id = PomodoroSessionId::generate();
36- .bind(("open", PomodoroSessionId::open_for(user).record()))38+ // The statement is one atomic delete-and-replace; the only contention
37- .bind(("usr", user.record()))39+ // is a rival start, and the index's verdict sends the loser around
38- .bind(("at", Timestamp::now()))40+ // again to overwrite.
39- .bind(("label", label))41+ for attempt in 0..CAP_WRITE_TRIES {
40- .await?42+ backoff(attempt).await;
41- .check()?;43+ let started = match query_as!(
42- result44+ PomodoroSession,
43- .take::<Vec<PomodoroSession>>(0)?45+ "WITH gone AS (
44- .into_iter()46+ DELETE FROM pomodoro_session
45- .next()47+ WHERE app_user = $1 AND finished_at IS NULL
46- .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into()))48+ RETURNING 1)
49+ INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
50+ SELECT $2, $1, $3, NULL, NULL, $4
51+ RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
52+ started_at AS \"started_at: Timestamp\", \
53+ finished_at AS \"finished_at: Timestamp\", counted, label",
54+ user.uuid(),
55+ id.uuid(),
56+ started_at.as_millis(),
57+ label
58+ )
59+ .fetch_one(db)
60+ .await
61+ {
62+ Ok(row) => row,
63+ // The winner of a race holds the open slot; one more round.
64+ Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => {
65+ continue;
66+ }
67+ Err(err) => return Err(err.into()),
68+ };
69+ return Ok(started);
70+ }
71+ Err(AppError::Internal(
72+ "failed to start pomodoro session".into(),
73+ ))
47 }74 }
48 75
49-/// Close `user`'s running session: atomically take the open row and76+/// Close `user`'s running session, deciding the counting verdict, the
50-/// re-file it under a ULID id, freeing the open slot for the next start.77+/// lifetime badge counters, and the study streak in one transaction.
51-/// Take and re-file share one transaction — a failed re-file rolls the
52-/// take back, so a session can never vanish half-closed. Of two racing
53-/// finishes exactly one receives the row (the other gets the conflict).
54 ///78 ///
55-/// A lost round is re-sent rather than reported (`transaction_with_retry`):79+/// The open row is taken by a guarded `DELETE … WHERE finished_at IS NULL
56-/// the abort wrote nothing, so the whole cascade is safe to repeat, and the80+/// RETURNING` — of two racing finishes exactly one receives the row, and
57-/// `CREATE` cannot answer "already exists" on the way back — the table81+/// the other is refused (`no pomodoro session running`), the old abort
58-/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.82+/// marker now an ordinary early return. The user row carries every counter family
59-/// Only the guard's own `THROW` is a decision, and it stays a 409.83+/// this decision moves, so the transaction takes it `FOR NO KEY UPDATE`,
84+/// decides in Rust, and writes once: no interleaving can tear the streak
85+/// pair, and a rival finish is serialized on the row lock instead of
86+/// aborting. `longest` is written as `max(longest, current)`, which cannot
87+/// come down under any interleaving.
60 ///88 ///
61 /// `finished_at` is floored at the row's own `started_at`. Both stamps come89 /// `finished_at` is floored at the row's own `started_at`. Both stamps come
62 /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move90 /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move
@@ -67,186 +95,130 @@ pub async fn start(
67 /// count honest and its duration merely understated. Nothing downstream may95 /// count honest and its duration merely understated. Nothing downstream may
68 /// then read a negative duration (`ProfileStats::load` sums these).96 /// then read a negative duration (`ProfileStats::load` sums these).
69 ///97 ///
70-/// The lifetime badge counters on the user row move in this same98+/// The lifetime badge counters move only for a stint that **counts**, which
71-/// transaction, so they can never count a stint the log does not hold (nor99+/// is [`MIN_COUNTED_POMODORO_MS`] of real focus and at most
72-/// miss one it does), and a retried round re-applies nothing — the abort
73-/// rolled the increment back with the rest. They are written field-scoped:
74-/// the row also carries admin-owned data (`role`), which a whole-row save
75-/// would silently revert. The clamped duration is the *same* expression the
76-/// `CREATE` stores (both read `$ms`), so the counter can never take a
77-/// negative summand and nothing downstream needs a floor. Only *finished*
78-/// stints reach here — an open row is a `pomodoro_session` row and nothing
79-/// else — and there is no student-facing delete for a stint, so neither
80-/// counter ever decrements.
81-///
82-/// They move only for a stint that **counts**, which is
83-/// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most
84 /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this100 /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this
85 /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`]101 /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`]
86 /// argues about from the other end: finishing is self-service, one stint is102 /// argues about from the other end: finishing is self-service, one stint is
87 /// two requests and no second person, so a counter moved once per103 /// two requests and no second person, so a counter moved once per
88-/// round-trip is farmable — two hundred pairs inside the rate limit bought104+/// round-trip is farmable. Both stamps are the server's own clock, so the
89-/// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked.105+/// duration needs no distrusting, only a floor.
90-/// Both stamps are the server's own clock, so the duration needs no
91-/// distrusting, only a floor.
92 ///106 ///
93 /// The verdict is *stamped* on the closed row (`counted`), not re-derived107 /// The verdict is *stamped* on the closed row (`counted`), not re-derived
94 /// later: the thresholds are compiled in and will move, and a reader that108 /// later: the thresholds are compiled in and will move, and a reader that
95 /// re-judged an old stint against today's numbers would answer something109 /// re-judged an old stint against today's numbers would answer something
96-/// other than what was credited. Nothing debits these counters today; the110+/// other than what was credited. A stint below the bar is still recorded,
97-/// stamp is what lets one be added without that asymmetry. A stint below111+/// still listed, and still sums into the log's focus total — the rule
98-/// the bar is still recorded, still listed, and still sums into the log's112+/// bounds what *counts*, never what is kept.
99-/// `total_focus_ms` — the rule bounds what *counts*, never what is kept.
100-///
101-/// The re-filed row carries the start's `label` through verbatim
102-/// (`$before[0].label`): the close copies whatever the student named the
103-/// stint. On a row that predates the field that read is NONE — exactly what
104-/// an `option<string>` column stores, so no backfill is owed (the same
105-/// ruling as the `counted` stamp).
106 ///113 ///
107-/// The day quota is bucketed like the streak below (midnight UTC,114+/// The day quota is bucketed like the streak (midnight UTC,
108-/// [`Timestamp::day_number`]) and rolls in its own statement ahead of the115+/// [`Timestamp::day_number`]) and rolls whether the stint counts or not;
109-/// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting116+/// only the `+ 1` sits behind the verdict.
110-/// it, which resolves against the row as it was *before* the statement —
111-/// the same rule that forces the streak pair apart, used here on purpose. A
112-/// row that predates the two columns reads as no day at all (`?? -1`), so
113-/// the first finish after this deploy opens a fresh bucket and no backfill
114-/// is owed. The bucket write happens whether the stint counts or not; only
115-/// the `+ 1` sits behind the verdict.
116 ///117 ///
117 /// The **study streak** rides the same transaction, and the same verdict: a118 /// The **study streak** rides the same transaction, and the same verdict: a
118-/// study day is a UTC calendar day on which a stint *counted*, so a day119+/// study day is a UTC calendar day on which a stint *counted* — the same
119-/// bought with one instant round-trip is not a day studied (midnight UTC, like every
120-/// other day calculation here — no timezone is stored anywhere): the same
121 /// day again changes nothing, the next day extends the run, any other gap120 /// day again changes nothing, the next day extends the run, any other gap
122-/// starts a new one at 1. It is written as **two** statements, not one:121+/// starts a new one at 1.
123-/// every field reference on the right-hand side of a `SET` resolves
124-/// against the row as it was *before* that statement, so a single
125-/// `SET current = …, longest = math::max([longest, current])` would take
126-/// the *old* `current` and lag one write behind forever (probed on a real
127-/// 3.2.3 server: day two left `current = 2, longest = 1`). Across
128-/// statements *inside a transaction* the read does see the prior write, so
129-/// the pair is correct and still atomic. Absent columns are read through
130-/// `?? 0` (and `?? -1` for the day — a sentinel no real day number
131-/// reaches), because `math::max` errors outright on a `NONE` argument and
132-/// every account older than these columns carries none of them.
133-///
134-/// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two
135-/// lines up: a plain `UPDATE` hands back an array, so a user row that is
136-/// missing (a `record<user>` column checks only the table of the id) simply
137-/// yields nothing to index and the second statement matches no row either.
138-/// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero
139-/// rows; it errors on *many* — but a `null` is a shape the read then has to
140-/// special-case, so the file's existing idiom wins.
141 ///122 ///
142-/// No `cap::counter_lock` is taken, deliberately. The pair cannot tear:123+/// The closed stint is re-filed under a freshly minted id: the open slot is
143-/// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts124+/// the partial index, so the closed row releases it by no longer matching
144-/// a rival that touched the row in between — `transaction_with_retry` then125+/// `finished_at IS NULL`.
145-/// re-sends the whole round. And `longest` is written as
146-/// `max(longest, current)`, which cannot come down under *any*
147-/// interleaving, so even a torn pair could only under-count `current`,
148-/// never lower the high-water mark the badges read. The lock would only
149-/// serialize this process's writers (its other job, keeping the in-memory
150-/// test engine deterministic, is moot here — these tests are sequential).
151-/// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent
152-/// finishes for one user left `current = 60, longest = 60` with no
153-/// anomaly; a rival write forced *between* the two statements (a `sleep`
154-/// wedged into the batch) aborted the whole cascade with a write conflict,
155-/// wrote nothing, and left the rival's value standing.
156-///
157-/// Streaks begin at this deploy: nothing reconstructs history from the
158-/// stint log, so every account starts with no streak columns and its first
159-/// finish sets a run of 1.
160 pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {126 pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
161 let done = Timestamp::now();127 let done = Timestamp::now();
162- let (mut result, mut errors) = transaction_with_retry(128+ let day = done.day_number();
163- db,129+ let saved = tx_with_retry(db, false, async |tx| {
164- &format!(130+ // Take the open row. Empty means nothing is running.
165- "BEGIN TRANSACTION;131+ let open = sqlx::query!(
166- LET $before = (DELETE $open RETURN BEFORE);132+ "DELETE FROM pomodoro_session
167- IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }};133+ WHERE app_user = $1 AND finished_at IS NULL
168- LET $end = math::max([$before[0].started_at, $done]);134+ RETURNING started_at AS \"started_at: Timestamp\", label",
169- LET $ms = $end - $before[0].started_at;135+ user.uuid()
170- LET $bucket = (UPDATE $usr SET136+ )
171- {POMODORO_COUNTED_TODAY_FIELD} =137+ .fetch_optional(&mut *tx)
172- IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day138+ .await?;
173- THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END,139+ let Some(open) = open else {
174- {POMODORO_COUNTED_DAY_FIELD} = $day140+ return Err(AppError::Conflict("no pomodoro session running"));
175- RETURN AFTER);141+ };
176- LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS})142+ let end = Timestamp::from_millis(open.started_at.as_millis().max(done.as_millis()));
177- AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0)143+ let ms = end.as_millis() - open.started_at.as_millis();
178- < {MAX_COUNTED_POMODORO_PER_DAY});144+
179- IF $counted {{145+ // Every counter this decision moves lives on the user row; the row
180- UPDATE $usr SET146+ // lock decides the whole verdict against one consistent read.
181- {POMODORO_FINISHED_TOTAL_FIELD} =147+ let counts = sqlx::query!(
182- ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1,148+ "SELECT pomodoro_counted_today, pomodoro_counted_day, pomodoro_finished_total, \
183- {POMODORO_FOCUS_MS_TOTAL_FIELD} =149+ pomodoro_focus_ms_total, study_streak_current, study_streak_last_day, \
184- ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms,150+ study_streak_longest \
185- {POMODORO_COUNTED_TODAY_FIELD} =151+ FROM app_user WHERE id = $1 \
186- ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1;152+ FOR NO KEY UPDATE",
187- LET $streak = (UPDATE $usr SET153+ user.uuid()
188- {STUDY_STREAK_CURRENT_FIELD} =154+ )
189- IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day155+ .fetch_optional(&mut *tx)
190- THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0)156+ .await?;
191- ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1)157+ let Some(c) = counts else {
192- THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1)158+ // The foreign key on the stint would refuse the insert below
193- ELSE 1 END,159+ // anyway; the honest answer for a user who does not exist.
194- {STUDY_STREAK_LAST_DAY_FIELD} = $day160+ return Err(AppError::NotFound);
195- RETURN AFTER);161+ };
196- UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([162+
197- ({STUDY_STREAK_LONGEST_FIELD} ?? 0),163+ // Day-bucket roll: a finish on a new day reopens the quota.
198- ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)])164+ let counted_today = if c.pomodoro_counted_day == Some(day) {
199- }};165+ c.pomodoro_counted_today
200- CREATE $closed CONTENT {{166+ } else {
201- user: $before[0].user,167+ 0
202- started_at: $before[0].started_at,168+ };
203- finished_at: $end,169+ let counted =
204- counted: $counted,170+ ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY;
205- label: $before[0].label,171+ if counted {
206- }};172+ let current = match c.study_streak_last_day {
207- COMMIT TRANSACTION;"173+ Some(last) if last == day => c.study_streak_current,
208- ),174+ Some(last) if last == day - 1 => c.study_streak_current + 1,
209- &[175+ _ => 1,
210- (176+ };
211- "open".into(),177+ sqlx::query!(
212- PomodoroSessionId::open_for(user).record().into_value(),178+ "UPDATE app_user SET pomodoro_finished_total = pomodoro_finished_total + 1, \
213- ),179+ pomodoro_focus_ms_total = pomodoro_focus_ms_total + $2, \
214- ("usr".into(), user.record().into_value()),180+ pomodoro_counted_today = $3, pomodoro_counted_day = $4, \
215- (181+ study_streak_current = $5, study_streak_last_day = $4, \
216- "closed".into(),182+ study_streak_longest = GREATEST(study_streak_longest, $5) \
217- PomodoroSessionId::generate().record().into_value(),183+ WHERE id = $1",
218- ),184+ user.uuid(),
219- ("done".into(), done.into_value()),185+ ms,
220- ("day".into(), done.day_number().into_value()),186+ counted_today + 1,
221- ],187+ day,
222- &["no_pomodoro_running"],188+ current,
223- )189+ )
190+ .execute(&mut *tx)
191+ .await?;
192+ } else if c.pomodoro_counted_day != Some(day) {
193+ sqlx::query!(
194+ "UPDATE app_user SET pomodoro_counted_today = 0, pomodoro_counted_day = $2 \
195+ WHERE id = $1",
196+ user.uuid(),
197+ day
198+ )
199+ .execute(&mut *tx)
200+ .await?;
201+ }
202+
203+ let closed = query_as!(
204+ PomodoroSession,
205+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
206+ VALUES ($1, $2, $3, $4, $5, $6)
207+ RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
208+ started_at AS \"started_at: Timestamp\", \
209+ finished_at AS \"finished_at: Timestamp\", counted, label",
210+ PomodoroSessionId::generate().uuid(),
211+ user.uuid(),
212+ open.started_at.as_millis(),
213+ Some(end.as_millis()),
214+ Some(counted),
215+ open.label,
216+ )
217+ .fetch_one(&mut *tx)
218+ .await?;
219+ Ok(closed)
220+ })
224 .await?;221 .await?;
225- // An aborted transaction errors *every* slot, most with a generic
226- // "not executed" — only the THROW's own slot names the reason, so scan
227- // them all for the marker instead of trusting the first.
228- if errors
229- .values()
230- .any(|error| error.to_string().contains("no_pomodoro_running"))
231- {
232- return Err(AppError::Conflict("no pomodoro session running"));
233- }
234- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
235- return Err(error.into());
236- }
237- // The `CREATE` is deliberately kept the last statement before `COMMIT`
238- // (the counter `UPDATE` sits ahead of it — same transaction, so the
239- // order is free), which is what lets its slot follow the statement
240- // count instead of a hand-kept number: `num_statements` counts `BEGIN`
241- // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a
242- // hand-kept slot caused.
243- let slot = result.num_statements().saturating_sub(2);
244- let saved: Option<PomodoroSession> = result
245- .take::<Vec<PomodoroSession>>(slot)?
246- .into_iter()
247- .next();
248- let saved =
249- saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?;
250 // A badge is a decoration on top of the stint: losing one to a222 // A badge is a decoration on top of the stint: losing one to a
251 // transient database error must never fail the finish, and the next223 // transient database error must never fail the finish, and the next
252 // counter move re-runs this and heals it.224 // counter move re-runs this and heals it.
@@ -257,20 +229,24 @@ pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, App
257 }229 }
258 230
259 /// Every session of `user`, newest first — the running one (if any)231 /// Every session of `user`, newest first — the running one (if any)
260-/// included. Ordered by `started_at`, never by id alone: the open entry's232+/// included. Ordered by `started_at`, never by id alone: the log is a
261-/// `open_` key doesn't sort with the ULIDs, so id order would misplace it.233+/// chronology, and the id tie-break only ever separates two *finished*
262-/// The `id` tie-break behind it only ever separates two *finished* stints234+/// stints sharing a `started_at` — there is one running row per user, so it
263-/// sharing a `started_at` — there is one running row per user, so it can235+/// can never tie with itself.
264-/// never tie with itself.
265 pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {236 pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {
266- let mut result = db237+ let sessions = query_as!(
267- .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC")238+ PomodoroSession,
268- .bind(("usr", user.record()))239+ "SELECT id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
269- .await?240+ started_at AS \"started_at: Timestamp\", \
270- .check()?;241+ finished_at AS \"finished_at: Timestamp\", counted, label \
271- Ok(result.take::<Vec<PomodoroSession>>(0)?)242+ FROM pomodoro_session WHERE app_user = $1 \
243+ ORDER BY started_at DESC, id DESC",
244+ user.uuid()
245+ )
246+ .fetch_all(db)
247+ .await?;
248+ Ok(sessions)
272 }249 }
273-
274 #[cfg(test)]250 #[cfg(test)]
275 mod tests {251 mod tests {
276 use ulid::Ulid;252 use ulid::Ulid;
src/db/registration.rsmodified+99 -26
@@ -3,11 +3,13 @@
3 //! workflow itself (the cap claim and its conflict mapping) lives in3 //! workflow itself (the cap claim and its conflict mapping) lives in
4 //! [`crate::service::registration`].4 //! [`crate::service::registration`].
5 5
6-use crate::database::Database;6+use crate::database::{Database, tx_with_retry, unique_violation};
7+use crate::db::cap::Claimed;
7 use crate::domain::event::EventId;8 use crate::domain::event::EventId;
8 use crate::domain::registration::Registration;9 use crate::domain::registration::Registration;
9 use crate::domain::user::UserId;10 use crate::domain::user::UserId;
10 use crate::error::AppError;11 use crate::error::AppError;
12+use sqlx::query_as;
11 13
12 /// Some(_) iff `user` holds a seat on `event` — the audience point check.14 /// Some(_) iff `user` holds a seat on `event` — the audience point check.
13 pub async fn read_for_user(15 pub async fn read_for_user(
@@ -15,22 +17,84 @@ pub async fn read_for_user(
15 event: &EventId,17 event: &EventId,
16 user: &UserId,18 user: &UserId,
17 ) -> Result<Option<Registration>, AppError> {19 ) -> Result<Option<Registration>, AppError> {
18- let mut result = db20+ let seat = query_as!(
19- .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1")21+ Registration,
20- .bind(("ev", event.record()))22+ "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
21- .bind(("usr", user.record()))23+ registered_by AS \"registered_by: UserId\" \
22- .await?24+ FROM registration
23- .check()?;25+ WHERE event = $1 AND app_user = $2
24- Ok(result.take::<Vec<Registration>>(0)?.into_iter().next())26+ LIMIT 1",
27+ event.uuid(),
28+ user.uuid()
29+ )
30+ .fetch_optional(db)
31+ .await?;
32+ Ok(seat)
25 }33 }
26 34
27 pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Registration>, AppError> {35 pub async fn list_for_event(db: &Database, event: &EventId) -> Result<Vec<Registration>, AppError> {
28- let mut result = db36+ let seats = query_as!(
29- .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC")37+ Registration,
30- .bind(("ev", event.record()))38+ "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \
31- .await?39+ registered_by AS \"registered_by: UserId\" \
32- .check()?;40+ FROM registration
33- Ok(result.take::<Vec<Registration>>(0)?)41+ WHERE event = $1
42+ ORDER BY event DESC, app_user DESC",
43+ event.uuid()
44+ )
45+ .fetch_all(db)
46+ .await?;
47+ Ok(seats)
48+}
49+
50+/// Take a seat for `user` on `event` — the cap claim of one: the seat bump,
51+/// the holder's role handshake, and the row insert are a single statement,
52+/// so neither a racing placement nor a concurrent capacity lowering can
53+/// over-admit (the capacity is read off the event row as it is decided, not
54+/// off a snapshot), and a demotion to `parent` cannot strand a seat the
55+/// sweep would miss: the handshake takes the holder's row
56+/// `FOR NO KEY UPDATE`, the same key the demotion writes, so either this
57+/// sees the parent and inserts nothing, or the sweep sees this row.
58+///
59+/// The verdict maps exactly like the old guard layer's: `Made` — seated;
60+/// `Duplicate` — a rival placement of the same pair won (23505 on
61+/// `registration_event_user`); `Full` — the event is at its capacity, was
62+/// deleted, or the holder fell to `parent` (all one marker; the caller
63+/// re-reads to pick the message).
64+pub async fn claim_seat(
65+ db: &Database,
66+ event: &EventId,
67+ user: &UserId,
68+ registered_by: &UserId,
69+) -> Result<Claimed<Registration>, AppError> {
70+ match query_as!(
71+ Registration,
72+ "WITH seat AS (
73+ UPDATE event SET registration_count = registration_count + 1
74+ WHERE id = $1
75+ AND (audience_capacity IS NULL OR registration_count < audience_capacity)
76+ RETURNING 1),
77+ person AS (
78+ SELECT 1 FROM app_user WHERE id = $2 AND role IS DISTINCT FROM 'parent'
79+ FOR NO KEY UPDATE)
80+ INSERT INTO registration (event, app_user, registered_by)
81+ SELECT $1, $2, $3
82+ WHERE EXISTS (SELECT 1 FROM seat) AND EXISTS (SELECT 1 FROM person)
83+ RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"",
84+ event.uuid(),
85+ user.uuid(),
86+ registered_by.uuid()
87+ )
88+ .fetch_optional(db)
89+ .await
90+ {
91+ Ok(Some(row)) => Ok(Claimed::Made(row)),
92+ Ok(None) => Ok(Claimed::Full),
93+ Err(err) if unique_violation(&err) == Some("registration_event_user") => {
94+ Ok(Claimed::Duplicate)
95+ }
96+ Err(err) => Err(err.into()),
97+ }
34 }98 }
35 99
36 pub async fn remove(100 pub async fn remove(
@@ -39,17 +103,26 @@ pub async fn remove(
39 user: &UserId,103 user: &UserId,
40 ) -> Result<Option<Registration>, AppError> {104 ) -> Result<Option<Registration>, AppError> {
41 // The seat comes back in the same transaction as the row that held it.105 // The seat comes back in the same transaction as the row that held it.
42- let mut result = db106+ tx_with_retry(db, false, async |tx| {
43- .query(107+ let gone = query_as!(
44- "BEGIN TRANSACTION;108+ Registration,
45- LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE);109+ "DELETE FROM registration WHERE event = $1 AND app_user = $2
46- UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]);110+ RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"",
47- RETURN $gone;111+ event.uuid(),
48- COMMIT TRANSACTION;",112+ user.uuid()
49 )113 )
50- .bind(("ev", event.record()))114+ .fetch_optional(&mut *tx)
51- .bind(("usr", user.record()))115+ .await?;
52- .await?116+ if gone.is_some() {
53- .check()?;117+ sqlx::query!(
54- Ok(result.take::<Vec<Registration>>(3)?.into_iter().next())118+ "UPDATE event SET registration_count = GREATEST(registration_count - 1, 0)
119+ WHERE id = $1",
120+ event.uuid()
121+ )
122+ .execute(&mut *tx)
123+ .await?;
124+ }
125+ Ok(gone)
126+ })
127+ .await
55 }128 }
src/domain/appointment.rsmodified+3 -2
@@ -17,14 +17,15 @@
17 //! with nothing to sweep.17 //! with nothing to sweep.
18 //! - **No double-booked teacher window.** Two overlapping published windows18 //! - **No double-booked teacher window.** Two overlapping published windows
19 //! cannot both exist — the `appointment_slot` exclusion constraint refuses19 //! cannot both exist — the `appointment_slot` exclusion constraint refuses
20-//! the second insert at the store, which is what replaced the20+//! the second insert at the store, which is what replaced the process
21-//! [`crate::service::appointment::APPOINTMENT_LOCK`] serialization.21+//! lock the appointment workflows used to hold.
22 //!22 //!
23 //! The *single-row* invariant — a decision must be written onto the state it23 //! The *single-row* invariant — a decision must be written onto the state it
24 //! was validated against — is a compare-and-set24 //! was validated against — is a compare-and-set
25 //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional25 //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional
26 //! `UPDATE`.26 //! `UPDATE`.
27 27
28+use uuid::Uuid;
28 use crate::constant::{MAX_APPOINTMENT_REASON_LEN};29 use crate::constant::{MAX_APPOINTMENT_REASON_LEN};
29 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};30 use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId};
30 use crate::domain::monotonic_id::next_uuid;31 use crate::domain::monotonic_id::next_uuid;
src/domain/appointment_slot.rsmodified+2 -1
@@ -15,10 +15,11 @@
15 //! outrun. Two overlapping windows of one teacher cannot both be published:15 //! outrun. Two overlapping windows of one teacher cannot both be published:
16 //! the `appointment_slot` span exclusion constraint refuses the second16 //! the `appointment_slot` span exclusion constraint refuses the second
17 //! insert, which is what replaced the17 //! insert, which is what replaced the
18-//! [`crate::service::appointment::APPOINTMENT_LOCK`]. The reads and writes18+//! the old process lock the appointment workflows used to hold. The reads and writes
19 //! live in [`crate::db::appointment_slot`]; the publish and delete workflows19 //! live in [`crate::db::appointment_slot`]; the publish and delete workflows
20 //! in [`crate::service::appointment_slot`].20 //! in [`crate::service::appointment_slot`].
21 21
22+use uuid::Uuid;
22 use crate::constant::{23 use crate::constant::{
23 MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK,24 MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK,
24 };25 };
src/domain/chatbot_message.rsmodified+1 -0
@@ -9,6 +9,7 @@
9 //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process9 //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process
10 //! happens once, at mint, in `database.rs`'s school migration sweep.10 //! happens once, at mint, in `database.rs`'s school migration sweep.
11 11
12+use uuid::Uuid;
12 use crate::constant::{13 use crate::constant::{
13 CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE,14 CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE,
14 };15 };
src/domain/chatbot_thread.rsmodified+1 -0
@@ -4,6 +4,7 @@
4 //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the4 //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the
5 //! threads' own persistence lives in [`crate::db::chatbot_thread`].5 //! threads' own persistence lives in [`crate::db::chatbot_thread`].
6 6
7+use uuid::Uuid;
7 use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN};8 use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN};
8 use crate::domain::monotonic_id::next_uuid;9 use crate::domain::monotonic_id::next_uuid;
9 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
src/domain/event.rsmodified+27 -0
@@ -1,3 +1,4 @@
1+use uuid::Uuid;
1 use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};2 use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
2 use crate::domain::class_group::ClassGroupId;3 use crate::domain::class_group::ClassGroupId;
3 use crate::domain::course::CourseId;4 use crate::domain::course::CourseId;
@@ -165,6 +166,32 @@ impl EventAudience {
165 }166 }
166 }167 }
167 168
169+/// The five audience columns as one value — the write-side bundle. The row
170+/// keeps them flat; every write spells them as a unit, so a kind and its
171+/// payload always land together and only the payload matching `kind` is
172+/// ever non-NULL.
173+#[derive(Debug, Clone, PartialEq, Eq)]
174+pub struct EventAudience {
175+ pub kind: EventAudienceKind,
176+ pub role: Option<Role>,
177+ pub course: Option<CourseId>,
178+ pub class: Option<ClassGroupId>,
179+ pub capacity: Option<i64>,
180+}
181+
182+impl EventAudience {
183+ /// The audience of a row read back from the store.
184+ pub fn of_row(event: &Event) -> Self {
185+ Self {
186+ kind: event.get_audience_kind(),
187+ role: event.get_audience_role(),
188+ course: event.get_audience_course().copied(),
189+ class: event.get_audience_class().copied(),
190+ capacity: event.get_audience_capacity(),
191+ }
192+ }
193+}
194+
168 impl Event {195 impl Event {
169 pub fn get_id(&self) -> &EventId {196 pub fn get_id(&self) -> &EventId {
170 &self.id197 &self.id
src/lib.rsmodified+1 -615
@@ -14,618 +14,4 @@ pub mod tenant;
14 pub mod validate;14 pub mod validate;
15 pub mod web;15 pub mod web;
16 16
17-use axum::extract::{MatchedPath, Request};17+pub fn __l10_typecheck_only() {}
18-use axum::http::{HeaderName, HeaderValue, Method, header};
19-use axum::middleware::{self, Next};
20-use axum::response::{IntoResponse, Response};
21-use axum::routing::get;
22-use axum::{Json, Router};
23-use serde_json::json;
24-use tower_http::cors::{AllowOrigin, CorsLayer};
25-use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
26-use tower_http::trace::TraceLayer;
27-use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
28-use utoipa::{Modify, OpenApi};
29-use utoipa_axum::router::OpenApiRouter;
30-use utoipa_axum::routes;
31-use utoipa_swagger_ui::SwaggerUi;
32-
33-use crate::constant::MAX_REQUEST_ID_LEN;
34-use crate::error::AppError;
35-use crate::module::Module;
36-use crate::rate_limit::RateLimiter;
37-use crate::state::AppState;
38-use crate::telemetry::SchoolSlot;
39-use crate::web::module_gate::gate;
40-
41-/// Top-level OpenAPI document. Per-path operations and schemas are collected
42-/// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`.
43-#[derive(OpenApi)]
44-#[openapi(
45- info(
46- title = "Hezarfen Backend API",
47- version = env!("CARGO_PKG_VERSION"),
48- description = "Notes, events, attendance, courses, and weighted exam marks behind cookie-session auth. Notes carry file attachments (PDFs, documents — stored on disk, capped per file by the school's settings). Any two users can message each other one-to-one, mail-style: each side files its own copy through folders (recipient: inbox/archive/trash with a read flag the sender sees as a receipt; sender: sent/archive/trash), and a message is truly gone only when both sides have deleted it from their trash. Exams run sync (one window), async (window + per-attempt duration), or open (sit anytime), with per-exam attempt limits (retakes) and a teacher-controlled rejoin door on the live exam room; questions can carry images — an illustration on any question, and per-option pictures on choice questions; students can attach an answer drawing to any question in their attempt. Enrollment, exam-sitting, roll call, and marks are student-only — staff run them, they don't take part. Every event carries an audience — the whole school, one role, a course's enrollment, or a registration list — that defines its expected-attendee roster (visibility is unaffected: everyone sees every event). Registration-audience events hold a signup list built one seat at a time: teachers register students (students never register themselves), staff register only themselves, the list optionally caps at a capacity, and it closes the moment the event starts. Event attendance is taken by teachers+ against that audience (students never self-mark), and a per-event roster report joins the expected list with the marks to show who missed. Courses come in three behaviorally identical kinds — `course` (a regular taught course), `study` (a supervised study session — etüt), and `club` (a student club — kulüp) — may cap their roster with an optional enroll-time `capacity` (a full course refuses new members), and carry lesson sessions with teacher-taken roll call. A course is run by whoever created it plus any teachers a manager assigns to it (`POST /courses/{id}/teachers`) — an assigned teacher manages everything inside the course (exams, sessions, subjects, roster, grading) but cannot delete the course or change who else teaches it, and a demotion below `teacher` drops their assignments. Students can also be grouped into class sections (şube — a `9-A`), which are bulk enrollment rather than a second kind of membership: attaching a course to a class enrolls its whole roster, adding a member enrolls them into every course the class already carries, and what gets written are ordinary enrollment rows tagged with the class that pumped them (that tag rides out as the enrollment response's `source`; `null` = placed by hand, and a hand-placed row is never adopted, never swept — enrolling a pumped student by hand clears the tag, the mirror of a manual unenroll winning permanently). An attach or a member-add that any target course has no seat for is refused whole (409 naming that course), as is one whose class already holds `max_class_members` students or `max_class_courses` courses (200 and 50: each add writes one enrollment per row on the other axis in a single transaction, so each ceiling is the bound on the other's write loop) or one whose class carries a link to a course that no longer exists (409 naming it — detach that link, no capacity will help); removing a member or detaching a course takes back only the rows that class pumped — re-tagging a row a second class still claims instead of dropping it — and a class still holding members or courses refuses deletion. Each course also owns its curriculum as a list of subjects, and every exam question and every homework must be tagged with one of its course's subjects (a subject still referenced by questions or homework cannot be deleted); staff clock in/out on a server-stamped work log; students run a pomodoro study timer whose focus sessions land in a server-stamped log (starting discards a dangling unfinished session; teachers can read any student's log and its total focus time; every stint is logged, but only one of at least `pomodoro.min_counted_ms` and within the UTC day's `pomodoro.max_counted_per_day` *counts* towards the badges, which is what keeps a start/finish loop from buying them); attendance reports tally events and per-course roll call with rates. Courses also hand out homework: teacher-assigned per course to the whole course or a named subset the unnamed never even see (404s, no existence leak) and the named see only themselves in, subject-tagged and due by a required future `due_at`; students submit optional text plus up to 10 files of any content type (each capped by `max_file_bytes`, always served back as forced attachment downloads), editable until a teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — the grade freezes the submission until removed, work never handed in is gradable `missing`, lateness is computed from an immutable first-submit stamp and a moving last-touch stamp (never stored), the grading roster computes `missing` and `unenrolled` flags, and homework marks stay out of the weighted `/marks` averages. School-varying policy (exam kinds with their course-average weights, attendance statuses, grade-display bands, the note-file size limit) lives in an editable settings singleton, and courses may link to academic terms. Each account also carries its own UI preferences — theme (`light`/`dark`), language (`tr`/`en`), and accent color (`palette_color`, a 6-digit hex like `#fefae0` — any hex, not a fixed palette) — self-managed, admin-editable for anyone, and `null` until chosen (the client then follows the device preference). A `parent` role observes without touching: admins tie any number of students to a parent account (`POST /users/{id}/students`), the parent lists them at `GET /users/me/students` and reads each one's mark, attendance, pomodoro, and homework reports — and nothing else; parents hold no staff power and never act as students (no enrolling, sitting exams, or roll call). A school-wide **question pool** lets students ask for help: a student posts a question (optionally with a photo of the problem — same raster rules and size cap as question images), a teacher+ approves it into the pool (or deletes it — rejection is deletion, there is no rejected state), and every approved question is readable by the whole school (parents excepted), with anyone free to offer solutions under it — text plus an optional photo of the worked steps, both editable by the solution's author at any time, since solutions are unmoderated and never freeze — and every question row carries its `solution_count`; pending questions are visible only to their asker and to teacher+ (whose `?status=pending` list is the approval queue), and approval freezes the question's content so nothing unmoderated can slip into the pool afterwards. Teachers keep an **appointment calendar**: a teacher+ publishes availability slots (one-off, or repeating weekly up to an `until` date as a series that deletes as one), and students and parents book a slot with a reason — the booking lands `pending` until the teacher approves it, rejects it, or counter-proposes another time (which sends it back to `pending` for the requester to accept or decline); the requester may cancel until the meeting starts — a teacher ends a booking by rejecting it, or by counter-proposing and then rejecting an approved one — one live booking holds a slot, a teacher's published windows may not overlap each other (`409`, half-open, so back-to-back slots are fine), and no approved meeting may overlap another for the teacher or the requester. While the database connection is reconnecting (a restart, a dropped socket) requests briefly answer `503` with `Retry-After: 1` — transient, retry shortly. Every list endpoint accepts `?limit=&offset=` and returns a `{items, total, limit, offset}` page envelope — paging is opt-in, so omitting `limit` returns the full list and `total` always carries the unpaged count. Every fixed validation bound — field lengths, numeric ranges, and the closed value sets (roles, course kinds, exam and question kinds, homework statuses, uploadable image types) — is published at `GET /limits` (no auth, cache for the session), so a client validates against the server's own constants instead of a hard-coded copy that drifts. It also reports this server's live rate-limit tiers, so a client learns its request budget instead of discovering it by collecting a `429`, and it keeps answering while the database is down — a client booting against a degraded backend still gets the contract.",
49- ),
50- modifiers(&SecurityAddon),
51- tags(
52- (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
53- (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
54- (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
55- (name = "auth", description = "Registration, login, session lifecycle. Both bodies name the **school**: `{school, username, password}`, since one deployment serves many schools and a username identifies an account only inside one of them; login sets a `session` cookie valued `<slug>.<token>` (see the `builder` tag). `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"),
56- (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
57- (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"),
58- (name = "notes", description = "Per-user notes CRUD, plus file attachments per note (multipart upload, download, delete — at most 10 per note, each at most the school's settings-configured `max_file_bytes`). Every authenticated role keeps notes, `parent` included: a note is private own-scoped data with no other reader, and the routes carry **no role bar at all** — ownership is the whole authorization, so nobody but the owner ever reaches a note or its files (a stranger's id is a `404`, never a `403`). That is deliberate and it is the fix for a real defect: while these routes required `student`, a demotion to `parent` locked the owner out of their own notes for good, and since nothing else in the crate reads a note and no route cascades one, the rows and their on-disk blobs became unreachable and undeletable by everybody. Own-scoped personal data is not confiscated by a role change"),
59- (name = "messages", description = "One-to-one mail-style messages, upward only below staff: a student or parent writes to a teacher, manager or admin (parents included — messaging is the one place a parent writes) and never to another student or parent (`403`), while staff write to anyone, each optionally tagged with a free-text `label` badge. Each party owns their copy independently: the recipient's moves through `inbox`/`archive`/`trash` with a read flag (visible to the sender as a read receipt), the sender's through `sent`/`archive`/`trash`. Filing a copy away records the folder it left as its `previous_folder`, so restoring it puts it back where it came from (a trashed archive copy returns to the archive, not the inbox). `GET /messages?folder=` lists one folder (`&read=false` narrows to unread — with `limit=1`, `total` is the unread badge); permanent deletion (`DELETE`) works only from the trash and removes the row once both sides have deleted"),
60- (name = "appointments", description = "Teacher availability slots and the meetings booked on them. A teacher+ publishes windows (`POST /appointments/slots`), optionally repeating weekly up to an `until` date (at most 52 occurrences, all sharing a `series` id that deletes as one). A published window may not overlap another of the *same teacher's* (`409`): the check is half-open, so 10:00–10:30 and 10:30–11:00 are two slots and not a collision, and a weekly publish is all-or-nothing — one colliding occurrence refuses the whole series. Students and parents book one with a required reason — a parent books for themselves, this is the parent-teacher conference — and the request lands `pending`: publishing availability is not consent to a person and a topic. The teacher approves, rejects, or counter-proposes another time; a counter-proposal sends the booking back to `pending` and clears `decided_by`, and the requester either accepts it (approval at the new time) or declines, which cancels the booking. A window that has already opened is closed on every side (409): such a slot cannot be booked — and the bookable list is bounded on that same `starts_at`, so it never offers one — an underway time cannot be approved, accepted, or counter-proposed, and the requester may cancel — declining included, since a decline *is* a cancel — only until the meeting's effective window starts. Cancelling is the **requester's** route alone (`403` for anyone else, the slot's teacher and a manager/admin included, since the guard compares ids and not roles): a teacher ends a booking by rejecting it while it is `pending`, and an approved one by counter-proposing another time (back to `pending`) and then rejecting it, or simply by rescheduling. Both the reject and the cancel take an optional `reason`, and the row records who settled it (`decided_by`, `cancelled_by`) with that text (`reject_reason`, `cancel_reason`) — visible only to the requester and the slot's teacher, since that is who a booking is ever rendered to. One live booking holds a slot (rejecting or cancelling frees it), no approved meeting may overlap another for the teacher *or* the requester (409), and a slot with a live booking refuses deletion (409). A demotion below `teacher` withdraws that account's whole calendar in the role change's own transaction and cancels the live bookings on it (nothing else could reach them afterwards — the requester keeps a `cancelled` row naming who dropped it and why); a slot an older build stranded is inert instead: it drops out of the bookable list and booking one is refused. The bookable list carries each slot's teacher identity (id, username, display name) to every caller, parents included — deliberate, since a conference cannot be booked from an anonymous calendar; it is the staff directory for booking, narrowed to whoever published bookable time, and the direct people routes stay closed to a parent"),
61- (name = "events", description = "Calendar events and attendance. An event's `audience` is its expected-attendee roster, not a visibility wall: everyone sees every event. Aim it at the whole school, one role, a course's enrollment, a class section's (şube) roster, or a hand-built registration list. Rosters resolve live, so role changes, (un)enrollments and class-roster changes move people in and out by themselves. Attendance: teacher+ marks people in the audience (students never mark, not even themselves), and the roster report joins the expected list with the marks to show who missed. Registration lists are filled seat by seat (teachers place students, staff place only themselves), optionally capped by `capacity`, and close once the event starts. `GET /events` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis) that keeps only upcoming/unfinished events and lists them soonest-first; without it the list stays newest-first"),
62- (name = "courses", description = "Courses — kind `course` (a regular taught course), `study` (etüt, a supervised study session), or `club` (kulüp, a student club; same behavior, different label) — optional enroll-time seat `capacity`, enrollment (students only), course exams, and course sessions. A course is run by its creator plus any teachers a manager assigned to it (`POST /courses/{id}/teachers`): assigned teachers manage everything inside the course but cannot delete it or change the assignment list. Both rights are re-checked against the caller's live role on every request: `creator` is a historical column no demotion sweeps, so an account that falls below `teacher` keeps neither management nor deletion of a course it made (the course stays reachable to its assigned teachers and to manager+), and the course drops out of their `/courses`, `/exams` and `/homework` catalogs unless they are enrolled in it. A session's `teacher` column carries the same floor: teaching a session grants neither its roll call nor a view of it once the account falls below `teacher`. A roster is also filled in bulk by attaching the course to a class (see `classes`), which writes the same ordinary enrollment rows one at a time. A course with anyone still enrolled refuses deletion (409) — empty the roster first"),
63- (name = "course-notes", description = "Notes a teacher attaches to a course — announcements, recaps, anything worth pinning to the class rather than to one student — with file attachments, mirroring the personal `notes` stack. Writing (create, edit, delete, upload, delete a file) requires teacher+ and management rights over the course (its creator, an assigned teacher, or a manager/admin); reading (`GET /course-notes/{id}`, listing, downloading) is open to anyone who can view the course — its enrolled users plus whoever can manage it. `GET /course-notes` requires `?course=` and lists that course's notes only, newest first. At most 10 files per note, each at most the school's `max_file_bytes`. `GET /course-notes/{id}/rag` serves what the backend's `rag.index` AI service produced for a note — an index or summary, stored verbatim and unread by this side — to anyone who can view the course; `DELETE /course-notes/{id}/rag/{output_id}` drops one, and needs the same management rights as any other write. Outputs are derived data: deleting one does not suppress anything, and the next edit to the note or its files may regenerate it."),
64- (name = "classes", description = "Class sections (şube): a named set of students the school moves as one. A class is bulk enrollment, not a second kind of membership — adding a student enrolls them into every course the class carries, attaching a course enrolls the whole roster into it, and the rows written are ordinary enrollments, each tagged with the class that pumped it (a row with no such tag was placed individually). A course with too few seats takes none of the class — the whole call is a 409 naming the course that ran out, and not one of the seats claimed earlier in the same run is kept — and a student already enrolled by hand keeps their own row (never adopted, never swept). Removing a member or detaching a course takes back only the rows that class pumped, and even then repairs before it deletes: a row a *second* class still claims (it holds the same student and the same course) is re-tagged to that class instead of being dropped, so nobody loses a seat someone is still responsible for. Unenrolling a pumped student by hand is allowed and permanent — the class does not put them back; staff re-enroll them or detach and re-attach the course. A class may link an academic term (which then refuses deletion while it does), and a class still holding students or courses refuses deletion itself (409). A class may also name a homeroom teacher (sınıf öğretmeni) with `teacher_id` — any teacher+ account, a pure label that grants nothing, cleared on every class it held the moment that account is demoted below `teacher`. The class itself and its roster are manager+, every read is teacher+, and attaching or detaching a course takes management rights on *that course*, since it writes that course's roster. Two reads sit outside that bar so a student can learn their own section: `GET /classes/me` (any authenticated role — staff, never members, get an empty page) and `GET /classes/user/{user}` (teacher+, or a parent linked to that student); both hide the class's `creator` (always a manager or admin) from a caller below teacher+, since the office's account names are otherwise unreachable at that level. Naming a homeroom teacher who is demoted while the request runs is a `409`: the assignment is taken back, and a create is rolled back whole. A grade may also carry a **blueprint** (`/classes/blueprints`): the list of courses every section at that grade takes. It reaches sections in both directions — creating or editing one retro-pumps every class already at the grade, and a class created afterwards at a blueprinted grade is stocked from it by `POST /classes` itself, whose `201` therefore answers `{class, skipped, stocked_from}` (`stocked_from` is the grade label of the template that stocked it, `null` when none covers the grade, which is what tells that apart from a template that applied cleanly; a stocking that could not be carried out reads `null` too, and the retry for both is the idempotent `POST /classes/{id}/blueprint`). Pumping is best-effort — a section that cannot take a course (it is at its course ceiling, or the course has no free seat for the whole section) is skipped and returned in `skipped`, while every other section is still stocked, so a blueprint edit can leave a deliberately partial state. The same body carries `matched`, the number of sections the pump actually reached: a grade label is free text matched exactly, so `\"9 \"` and `\"9-A\"` are not `\"9\"`, and `matched: 0` with an empty `skipped` is a saved template that stocked nothing rather than one that stocked everything. `GET /classes?grade=<label>` is the read that goes with it: the sections carrying that exact label (matched verbatim, since normalizing it would disagree with the pump this exists to debug), `?grade=` on its own the sections carrying no grade at all, an unknown label an empty page rather than a `404`, and a `total` counting the filtered set so `?limit=&offset=` pages through it. `GET /classes/blueprints/{grade}/status` closes the loop: a read-only `{grade, courses, matched, sections[{class, class_name, missing}]}` naming, for every section carrying the label, the template courses it does not carry — unpaged, since the set is the şube one school runs at one grade — because a pump's `skipped` list otherwise lives only in the one response that reported it. A course a human attached **by hand** counts as carried, exactly as it does for the pump, and `missing` only ever names courses that still exist: deleting a course takes its id out of every blueprint holding it, in the same cascade that detaches it from the sections, so no template is left naming a course that is gone (which used to be permanent at a grade with no sections, and made the re-`PATCH` below a `400`). Both fixes it points at are idempotent: `POST /classes/{id}/blueprint` re-stocks one section, and `PATCH`ing a blueprint with the list it already holds re-runs the whole grade's pump (the compare-and-set matches the unchanged list, nothing is dropped, everything is re-attached). A class whose `grade` is edited **after** it was stocked keeps the courses the *old* grade's blueprint attached — they still carry that blueprint's tag, so dropping one from that template still detaches them — and takes nothing from the new grade's template until one of those two calls runs; that is deliberate, since reconciling on a label `PATCH` would delete live enrollments as a side effect of a rename, and this status read is what makes the drift visible instead of silent. Each skip's `reason` is a machine code out of a closed set the client words itself (`class_deleted`, `course_deleted`, `class_at_course_ceiling`, `class_roster_too_large`, `course_full`, `blueprint_deleted`), like every other enum here. The **manual** attaches answer that same vocabulary, each route with its own set: a `409` from `POST /classes/{id}/courses` carries `duplicate`, `class_at_course_ceiling`, `class_roster_too_large` or `course_full`, and one from `POST /classes/{id}/members` carries `duplicate`, `class_at_roster_ceiling`, `class_course_list_too_large`, `course_full` or `linked_course_missing`. The three *deleted* codes are a pump's alone — on a manual attach a deleted class or course is a `404`, never a `409` — and the ceiling pair differs by route because the ceilings do: a member add is refused by a full roster (`class_at_roster_ceiling`) or by a course list longer than one add may enroll at once (`class_course_list_too_large`), a course attach by the mirror of both. `duplicate` (already attached / already a member) is a refusal on either route, and no skip for a pump, which asked for a row that is already in place; `linked_course_missing` (another course on that section no longer exists — detach it first) only the member add can meet, since it is the one attach that walks the section's existing course links while a pump attaches a course it has just proved alive. No other route publishes a `code`, and the field is simply absent where it does not. Dropping a course from a blueprint detaches it wherever the blueprint attached it (and deleting the blueprint drops its whole list — the row goes first and the attachments are then swept by their tag, so a course another manager added and pumped while the delete ran is swept too, and a pump that loses its blueprint mid-run attaches nothing and reports `blueprint_deleted`; deleting a blueprint whose list moved since the caller read it is a `409`), but a course a human attached to a class by hand carries no blueprint tag and always survives — the same absent-key rule that protects an individually placed enrollment. A blueprint names no term; the class names its own. The grade label is the blueprint's id, so there is exactly one per grade, and it must be non-empty and free of `/ \\ ? # %`"),
65- (name = "sessions", description = "Lesson sessions and their roll call (session teacher or course manager marks enrolled students; manager+ marks the teacher). Roll call is also what feeds two badge counters (see `users`): the first mark taken for a lesson **at or after its own `starts_at`** credits its teacher's `lessons_held_total` once — a sheet opened early is never refused, it simply holds nothing until the bell — and a student marked `present` or `late` gains a `lessons_attended_total` a later correction gives back"),
66- (name = "work", description = "Staff work log: check-in/check-out stamped by the server clock, manager corrections"),
67- (name = "pomodoro", description = "Student pomodoro focus log: start/finish stamped by the server clock (starting discards any dangling unfinished session, so a crashed timer never blocks the next one), own history with the unpaged `total_focus_ms` sum, and teacher+ (or linked-parent) reads of any student's log. Breaks and the work/break rhythm stay in the frontend — the backend records only focus stints. A finished stint answers `counted`: whether it moved the lifetime counters the badges and the study streak read, which it does when it ran at least `pomodoro.min_counted_ms` and is within that UTC day's `pomodoro.max_counted_per_day` (both on `GET /limits`, both compiled in). A stint that counts for nothing is still recorded, still listed and still sums into `total_focus_ms` — the rule bounds what counts, never what is kept, and it exists because finishing is self-service: two requests, no second person and no elapsed time, so a counter moved once per round-trip is farmable and a badge is never revoked"),
68- (name = "questions", description = "The school question pool. Students ask (`POST /questions`, optionally attaching one photo of the problem via `POST /questions/{id}/image` — raster types only, ≤ the school's `max_file_bytes`, only while pending); teacher+ approve (`POST /questions/{id}/approve`) into the school-wide pool, or reject by deleting. Everyone student-and-up sees every approved question and may offer solutions under it (oldest first); parents stay out. Pending questions are visible only to their asker and to teacher+ (`GET /questions?status=pending` = the approval queue), and approval freezes title, body, and image — moderated content cannot be edited afterwards, only deleted (asker or teacher+; solutions and every image blob go with it). Solutions are the unmoderated half, so they never freeze: the author may edit the body (`PATCH /questions/{id}/solutions/{sid}` — author only, teacher+ included out; moderation stays delete-only) and attach/replace/remove one photo of the worked steps anytime (`/questions/{id}/solutions/{sid}/image`, same raster rules and size cap as the question's). Question rows carry a `solution_count`; solutions are deletable by their author or teacher+ (photo blob included)"),
69- (name = "bank", description = "The question bank: reusable question templates, **private by default**. A template is visible to its owner (and admins) alone until its owner explicitly publishes it by `PATCH`ing `visibility` to `school`, at which point every teacher+ sees it — saving a question to the bank must never broadcast its `correct` answer key as a side effect. A template the caller may not see is a `404` on every route, never a `403` (a 403 would confirm it exists). A teacher+ reads what they can see (`GET /bank-questions`: `?subject=` origin filter, `?owner=` (a user id or `me`), `?q=` text search, `?visibility=private|school` — the last narrows the caller's own view and never widens it, so `private` means \"my drafts\", never another teacher's) and instantiates any visible template into their own exam (`POST /exams/{id}/questions/from-bank/{bid}`, which copies the template — text, points, `choice`/`text` spec, illustration, and option pictures — into a fresh exam question under the target subject, source untouched); a teacher also saves an existing exam question back into the bank (`POST /exams/{id}/questions/{qid}/to-bank`). A template's `subject` is origin metadata only — the bank spans courses, so the same-course rule is checked at instantiate time against the target exam's course, never on the bank row. Editing, deleting, or publishing a template needs ownership (its owner, or an admin — 403 otherwise), and every one of those rights is re-checked against the caller's live role: `owner` is a historical column no demotion sweeps, so an account below `teacher` reads and edits nothing here, its own templates included; as a consequence of that admin bypass, an admin may publish or unpublish another teacher's private template, which is accepted by design. Templates never freeze, since they carry no exam tie. Images mirror exam question images (one illustration, one picture per option on `choice` templates; raster types only, ≤ the school's `max_file_bytes`), owner-gated to write and readable by whoever may see the template"),
70- (name = "attendance", description = "Attendance summary reports: event tallies + per-course lesson roll call with rates. Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
71- (name = "exams", description = "Exams (per course, weighted by their kind — see `settings`): results, sync/async/open scheduling, attempts (students only — staff never sit) with retakes (`max_attempts`, 0 = unlimited) and a live rejoin door (`allow_rejoin`), questions/answers, and live monitoring (no-shows flagged `absent` once the window closes). Questions may carry images: one illustration per question (any kind — the map the prompt asks about) and one picture per option on `choice` questions, uploaded per slot (multipart, raster types only, ≤ the school's `max_file_bytes`) and frozen with the rest of the question once attempts exist; bytes are served to course managers and to enrolled students once they hold an attempt. Students mirror this on the answer side — one drawing per question inside their attempt (`POST /exams/{id}/attempt/answers/{qid}/image`, same raster types and size cap), saved like any answer through the writable-attempt gate and read back by the student (own) or a course manager (grading). Each sitting keeps its own answers, drawings, and mark keyed by the attempt `seq` — a retake starts from a blank sheet without erasing the prior one; the grading views show the latest sitting, a course manager reads any prior one via `GET /exams/{id}/students/{user}/attempts[/{seq}/answers]` (and the mark history at `.../marks`), and the latest seq is the grade-of-record. When the teacher turns on `allow_review`, a marked student reads back the answer key (`GET /exams/{id}/review/questions`, `correct` included) and their own sittings through `GET /exams/{id}/review/attempts[/{seq}/answers[/{qid}/image]]` (own-scoped — never another student's, and only once an `ExamResult` proves they were marked; a caller with no mark reads `404` whether review is on or off, so the status code never discloses `allow_review` to someone `GET /exams/{id}` would refuse outright). Those reads are refused (`409`) while the caller can still *write* a sitting at that exam — one in progress, or one still startable under `max_attempts` before the window closes — since a mark on an earlier sitting must never hand out the key to a retake, and a question sharing a question-bank template with a question in *another* exam the caller has a sitting open on comes back with `correct: null` — and with no correctness flag and no `auto_score` contribution on the answer sheet — since the bank copies `correct` into every instantiation. A question links to a template whichever way it got there, and both directions are matched: the template it was instantiated from (`from_bank`) and the one minted by saving it into the bank (`banked_as`), so a hand-written question that was saved to the bank and then instantiated elsewhere is hidden too. That redaction is per question, keyed on the template: the rest of the reviewed exam reads normally, a question with no bank link in either direction is never hidden, and the key comes back once the other sitting is submitted or expires. Known limit, accepted: deleting a template clears both columns on every question that pointed at it, so a pair whose template was since deleted keeps the identical `correct` with nothing left to join them by. A modeless exam is offline-graded — attempts on it are a 409. An exam still being written can be saved as a **draft** (`draft: true` on create, published later by `PATCH`ing `draft: false`): drafts are visible only to the course's managers (students get 404s), cannot be sat or graded, and once attempts or results exist an exam cannot be re-drafted. Not in this spec (WebSocket): the student exam room at `GET /exams/{id}/attempt/ws` — JSON frames; entering clears the attempt's `left_at`, leaving mid-attempt stamps it. See the README's \"Taking an exam\" section for the protocol. `GET /exams` takes an optional `?starts_after=&ends_after=` schedule window (unix-millis), applied after visibility and draft filtering, that keeps only upcoming/unfinished exams and lists them soonest-first (window-less exams — no `mode`, or `open` — drop out); without it the list stays newest-first. An exam on an archived term is frozen with the rest of that year: the exam-room WebSocket upgrade at `GET /exams/{id}/attempt/ws` is refused with `409` and `code: \"term_archived\"`, and so is a `finish` frame on a socket already open"),
72- (name = "meals", description = "The school's food program. A manager+ publishes one menu per calendar day and meal slot (`POST /meals/menus` — `date` is text, `YYYY-MM-DD`, and must be a **real calendar day**, leap years included: a menu on a day that does not exist (`2026-02-29`) has no serving instant, so it carried no booking or cancel cutoff at all while being fully actionable otherwise, and a menu stored on such a day before that rule now refuses both (`409`) whenever a cutoff is configured — the deadline fails closed rather than never closing. `slot` must be one of the school's `meal_slots` from `GET /settings`, and may not contain `/ \\ ? # %` — the slot name is copied into the menu's record id, which is a URL path segment, so such a menu could never be addressed again; the same characters are refused at `PATCH /settings`), optionally capped by a `capacity`. The date is parsed by the same calendar library that computes the serving instant and compared back to the text it came from, so a signed component (`2026-+1-01`, which `\"+1\".parse()` once accepted) is a `400` rather than a **second** menu id for the 1st of January — one with its own capacity and seat counter, invisible to every `?from=&to=` read because `+` sorts below `0`. The day must also not already be over (`400`, measured against the end of the day, so today publishes all day long): a published menu is a bookable one and a booking is what charges, so a menu behind the calendar mints real debt for food nobody can be served. The day+slot pair is unique, so a second publish for the same meal is a `409` — edit the first one instead. The slot is snapshotted as text, never a link, so retiring a slot in settings leaves every published menu intact (and a slot a menu already used cannot be retired at all, `409`). Only `capacity` is patchable: `date` and `slot` are immutable, since a menu on another day is another menu. Dishes hang off a menu (`POST /meals/menus/{id}/dishes`, at most 50, edited and removed at `/meals/dishes/{did}`, both `404` once the dish's menu is gone — every dish write moves its menu's revision in the same transaction, which makes the menu's existence part of the write), each with an optional description, dietary tags drawn from the school's `dietary_tags`, and a `price_minor` in **minor units** (kuruş) as an integer — this API never speaks decimals or floats about money. Deleting a menu takes its dishes **and its attendance marks** with it, in the same transaction as the row: a menu's id is deterministic on day+slot, so anything left behind would resurface attached to the next menu published for that meal. Cancelled bookings deliberately stay — their `attempt` counter is what keeps the ledger's `(booking, attempt)` ids unique. A student carries a **dietary profile** of tags from that same `dietary_tags` list plus a free-text note for the kitchen (`GET /meals/profiles/me`, `GET /meals/profiles/{user}` — own always, otherwise teacher+ or a parent link — and `PATCH /meals/profiles/{user}`, **manager+**: an allergen list is a safety record the school keeps, not a self-service preference, so a student editing their own is a `403`). Because both sides are tagged from one vocabulary, every dish a menu read returns carries a `conflicts` list — the intersection of the dish's tags with the *calling user's* profile tags, empty when they do not overlap and empty for every reader without a profile (a manager sees `conflicts: []`, which is correct, not a bug). Reads are open to every authenticated user (a student needs to see what is being served) except the two money reads below; every write is manager+. Students take seats on a menu (`POST /meals/menus/{id}/bookings`): a student books for themselves, a parent for a student they hold a link to (the one write a `parent_link` authorises) — staff never book for a child (`403`). One row per (menu, student), so booking twice is the same seat, and at most `meal.max_booking_attempts` (`GET /limits`) seats may be taken on it in all — the first booking plus the re-bookings after a cancel, past which it is a `409`, because every cycle appends a charge and its reversal permanently and nothing else bounded that growth; a menu whose **day has already passed** takes no booking at all (`409`), whatever the cutoff is set to and with no role able to bypass it — the booking is the charge, so a seat taken on a day already served bills a meal that cannot be eaten; *cancelling* a seat on such a menu stays open, since money already taken has to stay reversible. A full menu is a `409`, and that cap is a single conditional write on a counter kept on the menu row — taken and spent in the same transaction that places the booking, since counting rows and then writing one is write-skew. Cancelling (`DELETE /meals/bookings/{bid}`, answering `200` with the flipped row — its student, their parent, or **any manager+**, so a seat and its charge stay reachable once the student it was booked for is no longer a student) is a **status transition, not a delete**: the row stays as `cancelled` with a `cancelled_at` stamp so the freed seat remains auditable, only `booked` rows count against the capacity, and re-booking flips the same row back. The call is **idempotent** — cancelling an already-cancelled seat is a `200` that replays the refund, not a `409`, so a cancel cut short between the flip and the reversal is recovered by simply repeating it. **Who is asking is decided before the seat is looked up**: an unauthorised caller gets the same `403` for a booking that exists and one that never did, and only a caller who may cancel it ever sees a `404` — booking ids are derivable (`{date}_{slot}_{student}`), so reading the row first made the status code hand out the manager-only per-menu list one student at a time. The flip releases **only the attempt the call read** (the same `attempt` fence the re-booking side carries), so a seat taken again while the cancel was in flight is a `409` rather than a silent cancellation of that brand-new seat — unfenced it freed a seat the API had just answered `201` for, refunded nothing (the money is keyed to the older attempt, already reversed) and burnt the new attempt's reversal id for good. The school's `meal_cancel_cutoff_minutes` closes both ends at once — inside that window neither booking nor cancelling lands (`409`) — but it binds **students and parents only**: a manager+ is not held to it, since a deadline meant to stop students gaming the kitchen's headcount is no reason to leave staff holding a seat they cannot free, on a menu that then refuses its own deletion forever and a charge that can never be reversed. It is measured back from the instant the meal is served: the menu's `date` plus the slot's `serving_minute` from `GET /settings` (minutes past midnight **UTC** — this API stores no school timezone, so staff enter UTC). A slot with **no `serving_minute` closes nothing at all** — there is no instant to count the deadline back from, and counting from midnight UTC (as it once did) put every same-day menu past its deadline the moment a school set the cutoff knob, since all three shipped slots ship without an hour: today's lunch could not be booked and the seats already held could not be cancelled by the families holding them. Setting the hour is what starts the deadline binding that slot, on menus already published too. The slot list is read live at booking and cancelling time, so correcting a serving time moves the deadline of menus already published for it. A menu with a live booking refuses deletion (`409`). `GET /meals/bookings/me` returns the seats held for the caller plus, for a parent, the seats held for every student they *currently* hold a link to — the links are re-read on every call rather than trusted from the booking's `booked_by` stamp, so an unlinked parent stops seeing the child's seats at once, including ones they booked themselves; `GET /meals/menus/{id}/bookings` is the kitchen's per-menu list (manager+), cancelled rows included. The money is an **append-only ledger** — no route edits or deletes a line, and no balance is stored anywhere: it is always the fold `credits + reversals - charges` in minor units, so a negative balance means the student owes the school. Booking is what charges, at a **price snapshot** (the menu's dishes summed the moment the seat is taken and frozen onto the booking row; the claim that takes the seat asserts the menu is still at the revision the price was read at, and every dish write bumps that revision, so a dish landing between the sum and the seat refuses the booking, which re-reads and prices itself again), so a later price edit never moves an existing charge and re-booking after a cancel bills the then-current price; a menu whose dishes sum past the chargeable maximum refuses the booking outright (`400`) rather than seating anyone unbilled. Booking the same seat twice bills once — the charge and its reversal are keyed by (booking, attempt), and the seat and its flip move in one transaction, so eight simultaneous `POST`s hold one seat and write one charge line, a retried cancel refunds once, and a half-written attempt heals when the request is repeated. A seat taken while the menu was free records *that it was free*, so pricing the menu afterwards never bills it retroactively. Cancelling appends a `reversal` for that exact amount pointing at the charge, written by the **same transaction that flips the seat** rather than after it — as two writes a crash in between gave the seat back and left the student billed, with no later cancel able to repay it, since the money is keyed to the attempt the flip had already consumed; the reversal lands only when the charge it undoes is really there, checked inside that transaction, because a refund with no charge behind it invents money. The charge row itself stays. Who actually ate is recorded separately by teacher+ (`POST /meals/menus/{id}/attendance` with `{student_id, status}` — `served` or `missed`, the canteen's own fixed pair rather than the school's editable roll-call statuses; one row per (menu, person), so re-marking flips that row; the target need only exist, since a canteen also feeds staff and a mark records what happened rather than who was entitled; a `404` when the menu is unpublished mid-request, because the menu row is the write's own target and a mark left on a deleted menu would resurface on the next one published for that day and slot), read back per menu (`GET /meals/menus/{id}/attendance`) or per student (`GET /meals/attendance/{user}`, `?from=&to=` inclusive `YYYY-MM-DD` bounds on the menu's day, gated like the other per-student reports: teacher+ or a parent link). Meal attendance has **zero billing effect**: a no-show still pays, since the seat was reserved and the food was cooked — no penalty, no refund-on-missed, no auto-reversal; and a walk-in marked `served` without a booking is recorded but never charged, since charging is booking's job alone. `POST /meals/credits` records money received (`{student_id, amount_minor, method?, note?, request_key?}`, whose target must be a student or anyone already carrying meal-ledger lines — a debt outlives its debtor's role change and has to stay settleable, while a mistyped staff id carries no lines and is still a `400`) and is **admin-only**, not manager — the backend speaks to no payment gateway and stores no card data; an over-credit is corrected with a compensating line, never a fix-up. It takes the same optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters, no `_`) that `/payments/credits` does: the line is keyed `<student>_k_<key>`, so a client retry after a network timeout returns the line the first attempt wrote rather than crediting the money a second time — which nothing on this API could then edit or delete. The same key with a different `amount_minor` is a `409`; omit it and two identical posts are two credits. `GET /meals/balance/me`, `/meals/balance/{user}`, and `/meals/ledger/{user}` (paged) read it: your own always, another student's only as **manager+** or as a parent linked to them — **a teacher gets a `403`**, the same rule every `/payments` route holds, because canteen debt is family debt and what a family owes is not classroom information"),
73- (name = "payments", description = "School fees: the plans, who is on them, and the money. A manager+ writes a **fee plan** (`POST /payments/plans` — a name and 1 to 60 installments, each `{amount_minor, due_at}` in **minor units** (kuruş) as an integer and unix milliseconds; `due_at` **may be in the past**, since a school adopting the app mid-year assigns plans whose first installments were already due). Writing a plan bills nobody: **assigning it does** (`POST /payments/plans/{id}/assignments` with `{student_ids}`, at most 200 per call), and that appends *every* installment as a `charge` line at once, each carrying its own due date. One request is bounded by the charges it would raise rather than by the head count alone — `student_ids × installments` may not exceed 3 000 (200 students up to a 15-installment plan, 50 at a time on a 60-installment one) — and a bigger batch is a `400` naming the split, refused whole before anything is written, since a batch billed in part would leave the office guessing which families were charged. There is no scheduler and no sweep. Assignment is **replay-safe by identity** — an assignment is keyed (plan, student) and every charge it raises (plan, student, installment) — so re-assigning bills nothing a second time (reported per student as `already_assigned`), and an assignment cut short after three of twelve charges landed completes itself when the call is repeated. Only students carry a fee record, so any other target comes back `rejected` without losing the rest of the batch. A plan that has been assigned to anyone can no longer be edited or deleted (`409`): its charges are frozen copies of the installments as they stood, so an edit would only make the plan and the money disagree — write a new plan instead. That freeze is a **counter on the plan row**, incremented in the same transaction as the assignment it counts, and the edit and the delete are conditional writes against it — so a manager editing a plan at the very instant it is being assigned is decided one way or the other by the database, never left half-applied, and the installments a first assignment bills are read back from the stored plan at the moment it freezes. The money is an **append-only ledger**: no route edits or deletes a line, every stored field is `READONLY`, and a mistake is corrected by appending the opposing line so that both the mistake and the correction stay visible. **No balance is stored anywhere** — it is always the fold `credits + reversals - charges - refunds` in minor units, so a negative balance means the family owes the school, and every amount is stored positive with the sign living in the `kind`. `POST /payments/credits` records money received against **one named charge** (`{charge_id, amount_minor, method?, note?}`) — allocation is recorded, never inferred from a balance, and partial payments are the norm; `POST /payments/refunds` hands money back against **one named payment** (`{credit_id, …}`), which is also the only way a mistaken credit is corrected, since a credit is never reversed; both take an optional **`request_key`** (`[A-Za-z0-9-]`, 1–64 characters — no `_`, which is the separator inside a ledger line's id) that makes the call **retry-safe by identity**: the line is keyed `<target>_k_<key>` (`_kr_` for a refund), so a client retry after a network timeout returns the line the first attempt wrote instead of recording the money twice — even when that payment filled the charge exactly, since the replay is answered before the over-payment cap is consulted. The same key sent with a different `amount_minor` or target is a `409`, never the stored line: that is a client bug, and answering `201` would hide it. Omit the key and two identical posts are two payments, as a desk taking the same amount twice really is. `POST /payments/reversals` (`{line_id, note?}`) undoes a `charge` or a `refund` for its exact amount and nothing else (`400` otherwise), is keyed `<line>_r` and so reverses once however often it is retried. A reversed charge is no longer owed, so it takes no payment: `POST /payments/credits` against one is a `409` that says it was **reversed**, not that it was paid in full — a reversal fills the same room a payment does, and a bursar told \"paid in full\" about money that never arrived would go looking for it. Payments and refunds are capped by the line they target (`409` past it) — that cap is a cross-record sum, which the database cannot enforce on its own — it holds because the backend runs as one process and the sum, and the append it authorizes, are taken under one lock. That sum costs one query per line of the target's subtree, all of them under that lock, so a line carries **at most 20 applied lines** (the payments under a charge, the refunds under a payment, and the reversals among them): past that a further payment or refund against it is a `409`, an installment settled in more than twenty pieces being pathological. The ceiling binds new writes only — a line that already carries more still reads, still refunds through its own children, and is still reversible. Should an over-payment ever be recorded anyway, it is visible in the statement and undone by a refund, and both lines stay true records of money that really arrived. The backend speaks to no payment gateway and stores no card data; `method` is free text (\"cash\", \"havale\", …). Every write here is **manager+** — teachers never touch fees. Reads are narrower than the other per-student reports: `GET /payments/ledger/{user}` (paged raw lines), `/payments/statement/me`, `/payments/statement/{user}` (the per-charge rows are paged too, in an `entries: {items, total, limit, offset}` envelope — the window is taken **after** the fold, so `balance_minor` and every `overdue` reading are the same on every page), `/payments/balance/me` and `/payments/balance/{user}` are readable by the student themselves, by a parent holding a live link to them, and by manager+ — **a teacher gets a `403`**, because what a family owes the school is not classroom information. The statement is a per-charge rollup — plan, installment amount and due date, what it collected, what went back out, what is still outstanding, whether the charge was reversed, and whether it is `overdue` (still owed and its `due_at` has passed) — all folded from the raw lines on every request and stored nowhere"),
74- (name = "marks", description = "Weighted mark reports per course and overall, labeled by the school's grade bands when configured. Each mark counts its exam kind's settings-configured weight times (weight 1 when the kind was since removed from settings). Own report at `/me`; another user's needs teacher+ (teachers narrowed to their courses) or a parent link to that student"),
75- (name = "settings", description = "School policy, one singleton: exam kinds with their course-average weights, attendance statuses, grade-display bands, and the per-file upload size limit (`max_file_bytes` — note files and question images alike). An exam kind whose exams already carry marks cannot be removed from the list (409) — those marks would silently re-weight. Also the food program: the meal slots menus are published for — each with an optional `serving_minute`, the minutes past midnight **UTC** at which it is served (there is deliberately no school-timezone setting, so a UTC+3 school enters `540` for a noon meal; `null` = unset, and a slot with no serving minute carries **no cutoff at all** rather than one counted from midnight) — the dietary tags a dish or a student's profile may carry, and `meal_cancel_cutoff_minutes` — one knob closing both booking and cancelling ahead of a slot's serving time (`null` = no cutoff). A slot a menu was already published for cannot be removed (409), same reason. A slot name may not contain `/ \\ ? # %` (400) — the name is copied verbatim into a menu's record id, which is a URL path segment — but a name the school's stored list already carries is exempt from that rule, since re-validating it would leave a list written before the rule existed unable to be edited at all: re-sending the name is a 400 and dropping it is a 409 once a menu used it. A grandfathered name still cannot carry a new menu, and dropping it is still the only way to remove it. Read: any authenticated user; edit: manager+"),
76- (name = "subjects", description = "A course's curriculum topics. Created and listed under `/courses/{id}/subjects`; lookup/edit/delete at `/subjects/{id}`. Every exam question links to one of its course's subjects, so a subject in use cannot be deleted (409) — re-tag or delete the questions first. View follows the course (enrolled users, creator, assigned teachers, manager+); edit follows course management rights"),
77- (name = "homework", description = "Course homework: a teacher assigns it per course (`POST /courses/{id}/homework`), tagged with one of the course's subjects (re-taggable; a subject with homework refuses deletion until it is re-tagged or removed) and given a future `due_at`, to the whole enrolled course or an optional `assigned` subset (empty means the whole course — whoever is enrolled when they submit; a subset cannot later be narrowed so as to strand work that already exists). Students submit optional text plus files — any content type, up to 10 per submission, each capped by the school's `max_file_bytes`, always served back as forced attachment downloads (never inline); a submission touched after `due_at` is flagged late (computed from the moving last-touch stamp, never stored — the first-submit stamp is immutable) and stays editable until it is graded. A teacher grades a status (`done`/`incomplete`/`missing`) with an optional 0–100 mark — grading freezes the submission until the grade is removed (un-grading reopens it), never targets the grader themselves, and covers work never handed in (that is how `missing` is set; the student reads the verdict at `GET /homework/{id}/result`). Beyond a teacher-set `missing` the roster and reports also compute a `missing` for anyone unsubmitted past due, and the roster keeps a straggler's stale work visible (flagged `unenrolled`) after an unenrollment or promotion. Homework marks stay out of the weighted `/marks` averages. Students see and fetch only the homework they are assigned (others 404, so a subset assignment never leaks), and the ones it does name get its `assigned` list narrowed to their own id — who else was assigned is roster information, and the roster is teacher+-only; a linked parent reads a student's homework report — statuses, late flags, marks — but never the submitted files"),
78- (name = "boards", description = "Collaborative whiteboards. Anyone **from `student` upwards** opens a board (`POST /boards`) with a title and an ad-hoc invite list of user ids — no course, session or appointment is involved — and every participant draws on it; the creator alone clears, locks, closes or deletes it. `GET /boards` takes `?open=true|false` to narrow the list by the closing stamp (`total` counts the filtered list) — a closed board is never deleted, so this is how a creator holding many boards trims the retired ones out of sight. It filters `closed_at` and nothing else: a **locked** board, and one that has spent its lifetime stroke budget but was never drawn on again, are both still open, because the stamp is written only by `/close` or by the append the lifetime cap refuses. The `parent` role has no whiteboard access whatsoever: it is refused `POST /boards` and `GET /boards` with a `403`, and cannot be named in an invite list at all (`400`) — so a parent is never on a roster, which makes every id-scoped route and the room's door answer the outsider's `404` rather than a `403` that would confirm the board exists. Every frame the room delivers is authorized against the database first, so a caller who loses the right to be there — taken off the roster, or demoted below `student` — is served no further content: they get one `error{code:\"forbidden\"}` naming which of the two happened, and the room closes. That is separate from a refused *command*: `clear` and `lock` by a non-creator answer `error{code:\"forbidden\"}` and deliberately keep the socket open, since a participant who clicked the wrong button has made a mistake, not left the room. A demotion below `student` also sweeps that account off every roster it was on, and the rosters an older binary left behind were repaired at boot: a board written before that sweep can name a parent, or a user since deleted, and every such id is stripped the first time this binary starts. A board whose *creator* was demoted is **closed** by that same write: barred to them, still fully readable to everyone else, and refusing every write with the terminal `board_closed` — because clearing, locking, closing and deleting are the creator's alone and nothing lists a board the caller is not on, so a room whose creator was demoted could be ended by nobody at all while its participants kept drawing on it. Nothing is deleted (the marks are the participants' work too) and the seat it holds on `max_boards_per_creator` stays taken, exactly as a manually closed board's does. A caller who is not on a board gets a `404` for it on every route, existence included, while a participant who is not the creator gets a `403` on those four commands (they are already rendering the board, so hiding it from them would be a lie their client cannot act on). Strokes are **append-only and a clear deletes nothing**: it bumps the board's `epoch`, so the live canvas empties while every mark ever drawn stays stored — `GET /boards/{id}/strokes` is the current epoch — drawn marks only, never a `clear` marker, exactly as the room's socket replays it, so the REST catch-up and the live canvas can never disagree, `GET /boards/{id}/history?epoch=` is the whole session or one named epoch, and `GET /boards/{id}/epochs` is the index of `clear` markers (a clear needs at least one mark to close: an **already-blank** canvas answers `409` alongside the closed board and the **locked** one — the pause the creator set holds against their own clear too, so a locked board sitting at `max_epoch_strokes` is recovered by unlock, clear, relock — since the marker is a stored row charged to the lifetime cap), each carrying the epoch it closed, that epoch's final stroke count, who cleared and when (the markers *are* the index, so the open epoch is deliberately absent from it). Two growth caps, both published at `GET /limits`: `max_epoch_strokes` bounds the *live* canvas and is recoverable (clear it and drawing resumes, losing nothing), while `max_board_strokes` bounds the board's *lifetime* storage — rows on the board, so a `clear` marker costs one unit like any mark, and a board holds at most `max_board_strokes + 1` rows because the marker closing the final stroke is never the one refused — and stamps `closed_at` on the way past — a closed board is permanently read-only and fully readable, never deleted, and there is no reopen. `POST /boards/{id}/close` is the manual form of that, and idempotent. Closing and locking are independent, and a board holding both flags answers **closed** everywhere — a stroke, a socket `clear` and `POST /boards/{id}/clear` all report the terminal state, never the pause, because the pause can never lift. `DELETE /boards/{id}` is the one operation here that really destroys marks — it takes the whole stroke log with it and frees one of the creator's `max_boards_per_creator` seats. `PATCH /boards/{id}` re-titles (any participant) or changes the roster and the lock (creator only). `POST /boards/{id}/invite` fills that roster from a group that already exists rather than one id at a time — `{kind:\"class\", class}` for a class section (şube), `{kind:\"course\", course}` for a course's enrolled students (clubs and study groups *are* courses, so this is how a whole club is invited), `{kind:\"event\", event}` for an event's expected-attendee roster exactly as `GET /events/{id}/roster` resolves it. It is the creator's alone and strictly **additive** — nothing is ever removed by it, removal stays `PATCH` — and it resolves **once**, at the call: a board holds a flat list of ids and no memory of where they came from, so a student who joins that class tomorrow is not on today's board, and re-inviting the same source is how a roster is topped up (idempotent when nothing changed). Ineligible members are dropped silently rather than failing the call for everyone else — ids that no longer resolve to a user, and anyone below `student`, which is the same cut that keeps `parent` off a whiteboard — but the participant cap is **all-or-nothing**: an invite that would carry the board past `max_participants` is refused with a `409` naming both numbers, and nobody is added. Since a board's roster is visible to every participant, inviting a group *discloses* that group's membership, so each source carries the gate its own listing route already carries: teacher+ for a class, the course's creator/assigned teacher/manager+ for a course, teacher+ for an event. A student may still build a board one id at a time; they cannot pour a class roster into one. Not in this spec (WebSocket): the live board room at `GET /boards/{id}/ws`, where the drawing itself happens — JSON frames, cookie-authed, and a **404** at the door for anyone not on the board. A `join` replays the current epoch only (chunked `strokes`, then `synced` with the cursor to resume from); a `stroke` is persisted before it is fanned out, so every canvas in the room is showing rows that committed; `clear` and `lock` are the creator's alone and refuse anyone else with `error{code:\"forbidden\"}` *without* closing their socket. The REST mutations above fan out into the same room, and a roster change drops the socket of anyone it removed. See `src/web/board_ws.rs` for the frame-by-frame protocol"),
79- (name = "terms", description = "Academic terms (semester/trimester/quarter — whatever the school runs); courses and classes may link to one. A term still linked by any course or class cannot be deleted (409) — unlink them first. A finished year is closed with `POST /terms/{id}/archive` (manager+), reopened with `POST /terms/{id}/unarchive`; both are idempotent — archiving an already-archived term answers 200 with the original `archived_at` stamp, and unarchiving an open one answers 200 too. An archived term is read-only: `PATCH`/`DELETE /terms/{id}` and linking a new course or class to it are refused, as is every write to a course or class already on it and to everything hanging off them — enrollment, teacher assignment, class membership and homeroom, class↔course attach/detach and blueprint apply, sessions and roll call, subjects, exams with their questions, images, attempts and answers, marks and grading, homework and submissions, course notes and files — each with `409` and `code: \"term_archived\"` (\"this term is archived — past years are read-only\"). Reads stay open throughout, and unarchiving restores writes. Read: any authenticated user; edit: manager+"),
80- ),
81-)]
82-struct ApiDoc;
83-
84-/// Registers the `session` cookie as an API-key security scheme so protected
85-/// operations render an auth requirement in the docs.
86-struct SecurityAddon;
87-
88-impl Modify for SecurityAddon {
89- fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
90- if let Some(components) = openapi.components.as_mut() {
91- components.add_security_scheme(
92- "session_cookie",
93- SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new("session"))),
94- );
95- }
96- }
97-}
98-
99-/// `/courses` and the four foreign-module route pairs mounted inside it. The
100-/// children carry their own module's gate *and*, through the outer one applied
101-/// here, the course gate — so either module being off refuses them.
102-fn courses_router(state: &AppState) -> OpenApiRouter<AppState> {
103- let children = gate(web::courses::exam_routes(), state, Module::Exams)
104- .merge(gate(
105- web::courses::session_routes(),
106- state,
107- Module::Sessions,
108- ))
109- .merge(gate(
110- web::courses::subject_routes(),
111- state,
112- Module::Subjects,
113- ))
114- .merge(gate(
115- web::courses::homework_routes(),
116- state,
117- Module::Homework,
118- ));
119- gate(
120- web::courses::routes().merge(children),
121- state,
122- Module::Courses,
123- )
124-}
125-
126-/// Assemble the full application router. Shared by `main` and the test suites.
127-///
128-/// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at
129-/// `/api-docs/openapi.json`. Root `/` mirrors the health probe.
130-pub fn build_router(state: AppState) -> Router {
131- let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi())
132- .route("/", get(health))
133- .routes(routes!(health))
134- .routes(routes!(server_time))
135- .merge(web::limits::routes())
136- .merge(web::modules::routes())
137- .nest("/ai", web::ai::routes())
138- .nest("/auth", web::auth::routes(&state))
139- .merge(web::builder::routes(&state))
140- .nest(
141- "/chatbot",
142- gate(web::chatbot::routes(), &state, Module::Chatbot),
143- )
144- .nest("/users", web::users::routes())
145- .nest("/notes", gate(web::notes::routes(), &state, Module::Notes))
146- .nest(
147- "/messages",
148- gate(web::messages::routes(), &state, Module::Messages),
149- )
150- .nest(
151- "/events",
152- gate(web::events::routes(), &state, Module::Events),
153- )
154- .nest(
155- "/appointments",
156- gate(web::appointments::routes(), &state, Module::Appointments),
157- )
158- .nest("/courses", courses_router(&state))
159- .nest(
160- "/course-notes",
161- gate(web::course_notes::routes(), &state, Module::CourseNotes),
162- )
163- .nest(
164- "/classes",
165- gate(web::classes::routes(), &state, Module::Classes),
166- )
167- .nest(
168- "/sessions",
169- gate(web::sessions::routes(), &state, Module::Sessions),
170- )
171- .nest("/exams", gate(web::exams::routes(), &state, Module::Exams))
172- .nest("/marks", gate(web::marks::routes(), &state, Module::Marks))
173- .nest("/meals", gate(web::meals::routes(), &state, Module::Meals))
174- .nest(
175- "/payments",
176- gate(web::payments::routes(), &state, Module::Payments),
177- )
178- .nest("/work", gate(web::work::routes(), &state, Module::Work))
179- .nest(
180- "/pomodoro",
181- gate(web::pomodoro::routes(), &state, Module::Pomodoro),
182- )
183- .nest(
184- "/questions",
185- gate(web::questions::routes(), &state, Module::Questions),
186- )
187- .nest(
188- "/bank-questions",
189- gate(web::bank_questions::routes(), &state, Module::BankQuestions),
190- )
191- .nest(
192- "/attendance",
193- gate(web::attendance::routes(), &state, Module::Attendance),
194- )
195- .nest("/settings", web::settings::routes())
196- .nest(
197- "/subjects",
198- gate(web::subjects::routes(), &state, Module::Subjects),
199- )
200- .nest(
201- "/homework",
202- gate(web::homework::routes(), &state, Module::Homework),
203- )
204- .nest("/terms", web::terms::routes())
205- .nest(
206- "/boards",
207- gate(web::boards::routes(), &state, Module::Boards),
208- )
209- .split_for_parts();
210-
211- // Catch-all per-IP limit over every route (Swagger included). Kept inside
212- // the CORS layer so a 429 still carries the CORS headers a browser needs
213- // to surface the error to frontend code.
214- let api_limiter = RateLimiter::per_minute(
215- state.rate_limit.api_per_minute,
216- state.rate_limit.trust_proxy,
217- );
218- // Every tier's budget outlives the process it was spent in (see
219- // [`rate_limit::RateLimiter::share`]). The chatbot tier is shared here too
220- // rather than in `main`, so a router built anywhere gets the same behaviour.
221- api_limiter.share("api", state.db.clone());
222- state.chatbot_limit.share("chatbot", state.db.clone());
223- let metrics = state.metrics.clone();
224-
225- let cors_allowlist = cors_allowlist_from_env();
226- if state.cookie_secure && cors_allowlist.is_empty() {
227- tracing::warn!(
228- "COOKIE_SECURE is on but CORS_ALLOWED_ORIGINS is unset: production should list its frontend origins explicitly; mirror mode runs uncredentialed, so browser frontends cannot send the session cookie"
229- );
230- }
231-
232- let service = router
233- .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api))
234- .with_state(state.clone());
235-
236- // Hand the AI bridge the router *before* the outer layers, because a QUIC
237- // request from a service is not a browser request from an IP: it has no
238- // client address to bill the per-IP limiter (it would drain the shared
239- // unknown-client budget), and `ETag`/CORS are browser concerns. Skipping the
240- // layers means skipping the request deadline too, so the bridge applies the
241- // same deadline to its own dispatch (see `ai::server`).
242- if let Some(ai) = &state.ai {
243- ai.arm_api(
244- service.clone(),
245- state.tenants.clone(),
246- state.files_path.clone(),
247- metrics.clone(),
248- );
249- }
250-
251- service
252- // Conditional-GET: revalidatable `ETag` on 200 JSON GETs, `304` on a
253- // matching `If-None-Match`. Innermost, so it sees the handler's own
254- // response (mutations and errors pass straight through untouched).
255- .layer(middleware::from_fn(web::etag::etag))
256- .layer(middleware::from_fn(request_timeout))
257- .layer(middleware::from_fn(move |req: Request, next: Next| {
258- let limiter = api_limiter.clone();
259- async move { limiter.enforce(req, next).await }
260- }))
261- .layer(cors_layer(cors_allowlist))
262- // Request duration and in-flight count. Sits inside the trace layer so
263- // it measures the same request the span describes, and outside CORS so
264- // a preflight is counted like anything else.
265- .layer(middleware::from_fn(move |req: Request, next: Next| {
266- let metrics = metrics.clone();
267- async move { measure(metrics, req, next).await }
268- }))
269- // Inside the trace layer, so the span it stamps `error.type = panic` on
270- // is the request's own; outside everything else, so a panic anywhere in
271- // a handler still answers the standard 500 body instead of dropping the
272- // connection. The panic itself is logged and counted by the process
273- // hook (see [`telemetry::install_panic_hook`]).
274- .layer(tower_http::catch_panic::CatchPanicLayer::custom(
275- panic_response,
276- ))
277- .layer(
278- TraceLayer::new_for_http()
279- .make_span_with(request_span)
280- .on_request(())
281- .on_response(record_response)
282- .on_failure(tower_http::trace::DefaultOnFailure::new().level(tracing::Level::WARN)),
283- )
284- // Copy the id onto the response, so a caller reporting a problem can
285- // name the exact request without us needing their IP or their URL.
286- .layer(PropagateRequestIdLayer::new(HeaderName::from_static(
287- REQUEST_ID_HEADER,
288- )))
289- // Outermost: every request has an id from here inward, its own or ours.
290- .layer(SetRequestIdLayer::new(
291- HeaderName::from_static(REQUEST_ID_HEADER),
292- MakeRequestUuid,
293- ))
294- // Above `SetRequestIdLayer`, which keeps a caller-supplied id verbatim:
295- // an unusable one is dropped here so the layer below mints a UUID.
296- .layer(axum::middleware::from_fn(drop_unusable_request_id))
297-}
298-
299-/// Refuse a caller-supplied `x-request-id` that is not a short, boring token.
300-///
301-/// The id lands on `http.request.id` of every span, so anything a client can
302-/// put there it can export: free text (personal data) and unbounded cardinality
303-/// both. Accepting only `[A-Za-z0-9._-]{1,64}` keeps the useful case — a
304-/// gateway correlating its own request id with ours — and mints a UUID for
305-/// everything else.
306-async fn drop_unusable_request_id(mut req: Request, next: Next) -> Response {
307- let usable = req.headers().get(REQUEST_ID_HEADER).is_some_and(|value| {
308- value.to_str().is_ok_and(|id| {
309- !id.is_empty()
310- && id.len() <= MAX_REQUEST_ID_LEN
311- && id
312- .bytes()
313- .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
314- })
315- });
316- if !usable {
317- req.headers_mut().remove(REQUEST_ID_HEADER);
318- }
319- next.run(req).await
320-}
321-
322-/// The header carrying the per-request id, in and out.
323-const REQUEST_ID_HEADER: &str = "x-request-id";
324-
325-/// The span every request gets.
326-///
327-/// Deliberately *not* on it: the URL path (it carries record ids), the client
328-/// address, the user agent, any header or cookie, and anything about who is
329-/// calling. The route template and the method are what a builder needs to see
330-/// which endpoint is slow; see [`crate::telemetry`] for the rule.
331-pub fn request_span(req: &Request<axum::body::Body>) -> tracing::Span {
332- let method = req.method().as_str();
333- let route = req
334- .extensions()
335- .get::<MatchedPath>()
336- .map_or("unmatched", MatchedPath::as_str);
337- let request_id = req
338- .headers()
339- .get(REQUEST_ID_HEADER)
340- .and_then(|v| v.to_str().ok())
341- .unwrap_or_default();
342- tracing::info_span!(
343- "http.request",
344- // Consumed by the OpenTelemetry layer, not exported as attributes:
345- // this is how a span gets a name computed at runtime.
346- otel.name = %format_args!("{method} {route}"),
347- otel.kind = "server",
348- otel.status_code = tracing::field::Empty,
349- http.request.method = %method,
350- http.route = %route,
351- http.request.id = %request_id,
352- // Filled in by `web::tenant_state::resolve_tenant` once the cookie has
353- // named a school; a builder request has none and leaves it empty.
354- school = tracing::field::Empty,
355- http.response.status_code = tracing::field::Empty,
356- error.type = tracing::field::Empty,
357- )
358-}
359-
360-/// The response a panicking handler gets, byte-identical to
361-/// [`AppError::Internal`]'s: a caller learns nothing about our stack trace, and
362-/// a client parsing `{"error": ...}` is not surprised by the one 500 that used
363-/// to be a dropped connection. Runs inside the trace layer, so the class lands
364-/// on the request's span.
365-pub fn panic_response(_panic: Box<dyn std::any::Any + Send + 'static>) -> Response {
366- tracing::Span::current().record("error.type", "panic");
367- (
368- axum::http::StatusCode::INTERNAL_SERVER_ERROR,
369- Json(json!({ "error": "internal server error" })),
370- )
371- .into_response()
372-}
373-
374-/// Stamp the outcome onto the request span. A `5xx` is our fault, so it also
375-/// marks the span itself as failed; a `4xx` is the caller's and does not.
376-fn record_response<B>(res: &Response<B>, _latency: std::time::Duration, span: &tracing::Span) {
377- let status = res.status();
378- span.record("http.response.status_code", status.as_u16());
379- if status.is_server_error() {
380- span.record("otel.status_code", "ERROR");
381- // `error.type` is NOT set here: whatever produced the 5xx —
382- // [`AppError::into_response`] or [`panic_response`] — has already
383- // recorded its class, and the status code would overwrite it with a
384- // number that is already on the span.
385- }
386-}
387-
388-/// Count the request in and out and record its duration. The school slug is
389-/// the only caller-derived attribute, and it is only known after the handler's
390-/// extractor filled the slot (see [`SchoolSlot`]).
391-async fn measure(metrics: crate::telemetry::Metrics, mut req: Request, next: Next) -> Response {
392- let method = req.method().as_str().to_owned();
393- let route = req
394- .extensions()
395- .get::<MatchedPath>()
396- .map_or("unmatched", MatchedPath::as_str)
397- .to_owned();
398- let school = SchoolSlot::default();
399- req.extensions_mut().insert(school.clone());
400- let mut in_flight = InFlight::started(&metrics, method, route, school);
401- let res = next.run(req).await;
402- in_flight.status = res.status().as_u16();
403- res
404-}
405-
406-/// The in-flight accounting for one request, closed by `Drop`.
407-///
408-/// A dropped request future — the client disconnected, an outer timeout fired —
409-/// never returns from `next.run`, so a decrement written after the `.await`
410-/// leaks the gauge upwards for the process's whole life. Same shape as
411-/// [`web::room::Connected`]: `Drop` is the only placement every exit passes
412-/// through.
413-struct InFlight<'a> {
414- metrics: &'a crate::telemetry::Metrics,
415- method: String,
416- route: String,
417- school: SchoolSlot,
418- started: std::time::Instant,
419- /// The answer's status, or `499` ("client closed request") while there is
420- /// no answer — which is what a cancelled request is recorded as.
421- status: u16,
422-}
423-
424-impl<'a> InFlight<'a> {
425- fn started(
426- metrics: &'a crate::telemetry::Metrics,
427- method: String,
428- route: String,
429- school: SchoolSlot,
430- ) -> Self {
431- metrics.request_started(&method);
432- Self {
433- metrics,
434- method,
435- route,
436- school,
437- started: std::time::Instant::now(),
438- status: 499,
439- }
440- }
441-}
442-
443-impl Drop for InFlight<'_> {
444- fn drop(&mut self) {
445- // `request_finished` owns both halves — the decrement and the duration
446- // sample — so a cancelled request lands here too, under `499`.
447- self.metrics.request_finished(
448- &self.method,
449- &self.route,
450- self.status,
451- self.school.get(),
452- self.started.elapsed(),
453- );
454- }
455-}
456-
457-/// Cap how long any request may wait on the database. The deadline covers both
458-/// the pool wait for a connection and the query run on it.
459-///
460-/// The health half this guard used to carry is gone with the engine that
461-/// needed it: a sqlx query issued on a dead pool fails with an error instead
462-/// of being parked until the socket returns, so there is no known-outage
463-/// verdict to publish and no queued work to refuse up front. What stays is
464-/// the honest [`AppError::DbTimeout`] semantics: a request that outlives the
465-/// deadline may or may not have applied its write, so a caller must not
466-/// blind-retry it.
467-///
468-/// Long-lived responses are unaffected: a WebSocket upgrade and an SSE stream
469-/// both return their response immediately and do the work afterwards, so
470-/// neither is measured against the timeout.
471-async fn request_timeout(req: Request, next: Next) -> Response {
472- // `/limits` never touches the database — it serializes constants and this
473- // process's own configuration. Holding it to the deadline would be a pure
474- // own-goal: a frontend booting into a degraded backend is exactly when it
475- // needs the validation contract. `/health` and its `/` mirror are exempt
476- // for the same reason and one more: their own probe is bounded at 2s, far
477- // inside this deadline, and the generic timeout body would replace the
478- // probe's answer ("degraded, the database is down") with one that names
479- // nothing.
480- if matches!(req.uri().path(), "/limits" | "/health" | "/") {
481- return next.run(req).await;
482- }
483- let timeout = std::time::Duration::from_secs(constant::REQUEST_TIMEOUT_SECS);
484- match tokio::time::timeout(timeout, next.run(req)).await {
485- Ok(response) => response,
486- Err(_) => AppError::DbTimeout.into_response(),
487- }
488-}
489-
490-/// Parse the `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist; empty when unset.
491-fn cors_allowlist_from_env() -> Vec<HeaderValue> {
492- std::env::var("CORS_ALLOWED_ORIGINS")
493- .unwrap_or_default()
494- .split(',')
495- .map(str::trim)
496- .filter(|origin| !origin.is_empty())
497- .filter_map(|origin| origin.parse().ok())
498- .collect()
499-}
500-
501-/// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send
502-/// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with
503-/// credentialed (cookie) requests — so origins from the `CORS_ALLOWED_ORIGINS`
504-/// allowlist are echoed back with `Access-Control-Allow-Credentials: true`.
505-///
506-/// With no allowlist (dev) the caller's origin is mirrored, but WITHOUT
507-/// credentials: mirror + credentials would let any website ride a visitor's
508-/// session cookie, so the two must NEVER be recombined (the cookie's
509-/// `SameSite=Lax` in `web/auth.rs` is the only other guard on that door). A
510-/// cross-origin dev frontend can't send the Lax cookie anyway, so credentials
511-/// bought nothing in mirror mode; a credentialed browser frontend requires
512-/// listing its origin in `CORS_ALLOWED_ORIGINS`.
513-///
514-/// Takes the allowlist as a parameter (env read once in `build_router`) so
515-/// tests can exercise both modes without racing on process-global env vars.
516-pub fn cors_layer(allowlist: Vec<HeaderValue>) -> CorsLayer {
517- let layer = CorsLayer::new()
518- .allow_methods([
519- Method::GET,
520- Method::POST,
521- Method::PATCH,
522- Method::DELETE,
523- Method::OPTIONS,
524- ])
525- .allow_headers([header::CONTENT_TYPE])
526- // Contract headers cross-origin JS must be able to read: `Retry-After`
527- // on 429s and `Content-Disposition` (original filename) on downloads.
528- .expose_headers([header::RETRY_AFTER, header::CONTENT_DISPOSITION]);
529-
530- if allowlist.is_empty() {
531- layer
532- .allow_origin(AllowOrigin::mirror_request())
533- .allow_credentials(false)
534- } else {
535- layer
536- .allow_origin(AllowOrigin::list(allowlist))
537- .allow_credentials(true)
538- }
539-}
540-
541-/// What the process can currently do, for a load balancer and a status page.
542-#[derive(serde::Serialize, utoipa::ToSchema)]
543-struct HealthResponse {
544- /// `ok` when every dependency the API needs is answering, `degraded` when
545- /// one is not (today: the database).
546- #[schema(example = "ok")]
547- status: &'static str,
548- /// Did the bounded database probe (`SELECT 1`) answer?
549- #[schema(example = "up")]
550- db: &'static str,
551- /// The optional AI bridge (see the `ai` tag).
552- ai: AiHealth,
553-}
554-
555-/// The AI bridge's side of [`HealthResponse`]. `enabled: false` is a
556-/// deployment without `AI_QUIC_ADDR`, not a fault — the core API has never
557-/// needed the bridge — so it never degrades the status.
558-#[derive(serde::Serialize, utoipa::ToSchema)]
559-struct AiHealth {
560- enabled: bool,
561- /// AI services currently registered on the bridge; `0` when it is off.
562- workers: usize,
563-}
564-
565-/// Health probe: the database verdict and the AI bridge, `503` when degraded.
566-///
567-/// Probes the database with a `SELECT 1` bounded to 2s — far inside the
568-/// request deadline — so a dead or wedged database answers `503` with a body
569-/// that says what is down, instead of the poll hanging on a full request
570-/// timeout.
571-#[utoipa::path(
572- get,
573- path = "/health",
574- tag = "meta",
575- responses(
576- (status = 200, description = "Every dependency is answering", body = HealthResponse),
577- (status = 503, description = "The database is down; the body says so", body = HealthResponse),
578- ),
579-)]
580-async fn health(axum::extract::State(state): axum::extract::State<AppState>) -> Response {
581- let up = matches!(
582- tokio::time::timeout(
583- std::time::Duration::from_secs(2),
584- sqlx::query("SELECT 1").execute(&state.db),
585- )
586- .await,
587- Ok(Ok(_))
588- );
589- let status = if up {
590- axum::http::StatusCode::OK
591- } else {
592- axum::http::StatusCode::SERVICE_UNAVAILABLE
593- };
594- (
595- status,
596- Json(HealthResponse {
597- status: if up { "ok" } else { "degraded" },
598- db: if up { "up" } else { "down" },
599- ai: AiHealth {
600- enabled: state.ai.is_some(),
601- workers: state.ai.as_ref().map_or(0, |ai| ai.workers().len()),
602- },
603- }),
604- )
605- .into_response()
606-}
607-
608-/// The server's current time. All API timestamps are UTC unix-milliseconds
609-/// judged by this clock (session expiry included), so a frontend that renders
610-/// countdowns or "is this in the past?" logic should not trust the device
611-/// clock — fetch this once, keep `offset = now - Date.now()`, and add the
612-/// offset to `Date.now()` whenever it needs the authoritative time.
613-#[derive(serde::Serialize, utoipa::ToSchema)]
614-struct TimeResponse {
615- /// Current server time, UTC unix-milliseconds.
616- #[schema(example = 1_752_275_000_000_i64)]
617- now: i64,
618-}
619-
620-/// Server clock: `{now}` UTC unix-millis, for a frontend to sync against.
621-#[utoipa::path(
622- get,
623- path = "/time",
624- tag = "meta",
625- responses((status = 200, description = "Current server time (UTC unix-milliseconds)", body = TimeResponse)),
626-)]
627-async fn server_time() -> Json<TimeResponse> {
628- Json(TimeResponse {
629- now: domain::timestamp::Timestamp::now().as_millis(),
630- })
631-}
src/service/appointment.rsmodified+83 -86
@@ -1,20 +1,29 @@
1 //! Appointment workflows: booking, the approve/reject/cancel decisions, and1 //! Appointment workflows: booking, the approve/reject/cancel decisions, and
2-//! counter-proposals. Reads, listings, the overlap probe, and the2+//! counter-proposals. Reads, listings, the overlap probe, the seat claim,
3-//! compare-and-set live in [`crate::db::appointment`]; the slot's seat is3+//! and the compare-and-set live in [`crate::db::appointment`].
4-//! [`crate::db::cap`]'s claim.
5 //!4 //!
6-//! The overlap guarantee is [`APPOINTMENT_LOCK`]: booking and approval hold5+//! There is no lock anymore. What the old APPOINTMENT_LOCK serialized is
7-//! it across "is this person already committed at that time" and the write6+//! now three database guarantees:
8-//! that commits — a predicate over *other* rows that no single-record7+//!
9-//! conditional write can decide.8+//! - **Occupancy** — booking claims the slot's seat and writes the row in
10-9+//! one statement ([`crate::db::appointment::claim_slot_and_create`]); two
11-use tokio::sync::Mutex;10+//! racers cannot both find the slot free.
12-11+//! - **Publish overlap** — the `appointment_slot_teacher_span` exclusion
13-use crate::constant::{CAS_UPDATE_RETRIES, SLOT_OCCUPIED_FIELD};12+//! constraint refuses two overlapping published windows at the store.
14-use crate::database::Database;13+//! - **Double-booking** — the approval's "is anyone already committed at
14+//! that time" is a predicate over *other* rows, which no single-record
15+//! write can decide and no row lock can stand in for (the rows that would
16+//! collide may not exist yet). That one decision runs **serializable** —
17+//! the lane's single documented isolation escalation: two concurrent
18+//! approvals of overlapping proposals read the same approved set, and SSI
19+//! aborts the loser (`40001`), which [`tx_with_retry`] re-sends; the
20+//! re-run sees the winner committed and refuses with the ordinary 409.
21+
22+use crate::constant::CAS_UPDATE_RETRIES;
23+use crate::database::{Database, tx_with_retry};
15 use crate::db::appointment;24 use crate::db::appointment;
16 use crate::db::appointment_slot;25 use crate::db::appointment_slot;
17-use crate::db::cap;26+use crate::db::cap::Claimed;
18 use crate::domain::appointment::{27 use crate::domain::appointment::{
19 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,28 Appointment, AppointmentId, AppointmentReason, AppointmentStatus,
20 };29 };
@@ -23,46 +32,25 @@ use crate::domain::timestamp::Timestamp;
23 use crate::domain::user::UserId;32 use crate::domain::user::UserId;
24 use crate::error::{AppError, ValidationError};33 use crate::error::{AppError, ValidationError};
25 34
26-/// Serializes the **overlap** check and the write it authorizes — nothing else.
27-/// "Is this teacher (or this requester) already committed at that time" is a
28-/// predicate over other appointment rows, and SurrealDB does not conflict-check
29-/// a cross-record read against a concurrent insert, so the check and its write
30-/// have to be one atomic step, and this lock is the only thing that makes them
31-/// one. Occupancy is no longer its business: that is the slot's `occupied`
32-/// counter, a conditional single-record write the store decides.
33-///
34-/// So this is load-bearing, not a convenience: an approval path that does not
35-/// take it can double-book a teacher, as the domain's module doc records.
36-///
37-/// Lock order: taken *before* `cap`'s `CLAIM_LOCK` (booking claims a slot while
38-/// holding this) and never the other way round. No path ever holds this
39-/// together with `ENROLL_LOCK`,
40-/// `TERM_LOCK`, `EXAM_LOCK`, or `PRESENCE_LOCK` — appointments
41-/// touch no roster, term, event seat, or exam room, and none of those touch
42-/// appointments — so they cannot deadlock. Should a future path ever need two,
43-/// take this one *last*.
44-// corner-cut: global lock; per-teacher locks if appointment traffic ever grows
45-// enough for the contention to matter.
46-pub(crate) static APPOINTMENT_LOCK: Mutex<()> = Mutex::const_new(());
47-
48 /// Request `slot`. Lands `pending`: publishing availability is not consent35 /// Request `slot`. Lands `pending`: publishing availability is not consent
49 /// to a specific person and topic.36 /// to a specific person and topic.
50 ///37 ///
51 /// Refused (409) when the slot's window has already opened, when it is38 /// Refused (409) when the slot's window has already opened, when it is
52 /// already taken, or when the requester is already committed elsewhere at39 /// already taken, or when the requester is already committed elsewhere at
53-/// that time. The slot is taken by [`cap::claim_and_create`], which writes40+/// that time. The slot is taken by the seat claim — a conditional
54-/// the booking in the *same transaction* as the seat — a conditional41+/// single-record write the database decides — so two racing requests
55-/// single-record write, so two racing requests cannot both find it free42+/// cannot both find it free however they interleave, and a crash between
56-/// however they interleave, and a crash between the two can no longer leave43+/// the two can no longer leave the slot occupied by a booking that does
57-/// the slot occupied by a booking that does not exist. The requester's own44+/// not exist. The requester's own overlap check is advisory here, exactly
58-/// overlap is the lock's part.45+/// as under the lock: only *approved* bookings block, so two pending
46+/// requests may queue on overlapping times, and the approval is where the
47+/// authoritative refusal lands.
59 pub async fn book(48 pub async fn book(
60 db: &Database,49 db: &Database,
61 slot: &AppointmentSlotId,50 slot: &AppointmentSlotId,
62 requester: &UserId,51 requester: &UserId,
63 reason: AppointmentReason,52 reason: AppointmentReason,
64 ) -> Result<Appointment, AppError> {53 ) -> Result<Appointment, AppError> {
65- let _guard = APPOINTMENT_LOCK.lock().await;
66 let slot_row = appointment_slot::read(db, slot)54 let slot_row = appointment_slot::read(db, slot)
67 .await?55 .await?
68 .ok_or(AppError::NotFound)?;56 .ok_or(AppError::NotFound)?;
@@ -96,10 +84,9 @@ pub async fn book(
96 // deleted since the read above is gone, not full — the claim's `WHERE`84 // deleted since the read above is gone, not full — the claim's `WHERE`
97 // finds no row either way, so the distinction is re-read rather than85 // finds no row either way, so the distinction is re-read rather than
98 // guessed.86 // guessed.
99- let seat = slot.record();
100 let appointment_row = Appointment {87 let appointment_row = Appointment {
101 id: AppointmentId::generate(),88 id: AppointmentId::generate(),
102- slot: slot.clone(),89+ slot: Some(slot.clone()),
103 requester: requester.clone(),90 requester: requester.clone(),
104 status: AppointmentStatus::Pending,91 status: AppointmentStatus::Pending,
105 reason,92 reason,
@@ -112,26 +99,17 @@ pub async fn book(
112 reject_reason: None,99 reject_reason: None,
113 created_at: Timestamp::now(),100 created_at: Timestamp::now(),
114 };101 };
115- match cap::claim_and_create(102+ match appointment::claim_slot_and_create(db, appointment_row).await? {
116- &seat,103+ Claimed::Made(created) => Ok(created),
117- SLOT_OCCUPIED_FIELD,104+ Claimed::Full => {
118- 1,
119- &appointment_row.id.record(),
120- &appointment_row,
121- db,
122- )
123- .await?
124- {
125- cap::Claimed::Made(created) => Ok(created),
126- cap::Claimed::Full => {
127 if appointment_slot::read(db, slot).await?.is_none() {105 if appointment_slot::read(db, slot).await?.is_none() {
128 return Err(AppError::NotFound);106 return Err(AppError::NotFound);
129 }107 }
130 Err(AppError::Conflict("the slot is already booked"))108 Err(AppError::Conflict("the slot is already booked"))
131 }109 }
132- // The id is a freshly minted ULID on a table with no UNIQUE index,110+ // The id is freshly minted on a table keyed by it: no rival can
133- // so no rival can have aimed at it.111+ // have aimed at it.
134- cap::Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())),112+ Claimed::Duplicate => Err(AppError::Internal("appointment id collided".into())),
135 }113 }
136 }114 }
137 115
@@ -162,10 +140,10 @@ pub async fn list_for_teacher(
162 }140 }
163 141
164 /// Confirm the meeting at the slot's own window. Re-runs the double-booking142 /// Confirm the meeting at the slot's own window. Re-runs the double-booking
165-/// guard for both teacher and requester against a fresh read under143+/// guard for both teacher and requester *inside the decision transaction* —
166-/// [`APPOINTMENT_LOCK`] — the authoritative check, since only approval144+/// the authoritative check, since only approval commits anyone. Refused
167-/// commits anyone. Refused (409) when the effective window has already145+/// (409) when the effective window has already started; that also covers
168-/// started; that also covers [`accept_proposal`], which lands here.146+/// [`accept_proposal`], which lands here.
169 ///147 ///
170 /// Also refused (409) while a counter-proposal stands: the effective window148 /// Also refused (409) while a counter-proposal stands: the effective window
171 /// would then be the *proposed* one, and the deciding side here is the149 /// would then be the *proposed* one, and the deciding side here is the
@@ -183,17 +161,29 @@ pub async fn approve(
183 /// The one approval path. `accepting` carries the window the caller is161 /// The one approval path. `accepting` carries the window the caller is
184 /// answering *for*, which is the only way a proposed one may be committed:162 /// answering *for*, which is the only way a proposed one may be committed:
185 /// it both marks the caller as the proposal's counterparty and pins which163 /// it both marks the caller as the proposal's counterparty and pins which
186-/// proposal they saw. Re-checked on every retry round, so a proposal that164+/// proposal they saw.
187-/// moved between the read and the write is refused rather than confirmed.165+///
166+/// Read, gate, overlap probe and write are ONE serializable transaction:
167+/// the overlap probe is a predicate over other approved rows, the one
168+/// invariant in this lane no row lock can carry (see the module doc). The
169+/// proposal pin is re-checked inside that same snapshot, so a proposal that
170+/// moved between the requester's read and their accept is refused rather
171+/// than committed.
188 async fn approve_inner(172 async fn approve_inner(
189 db: &Database,173 db: &Database,
190 id: &AppointmentId,174 id: &AppointmentId,
191 decided_by: &UserId,175 decided_by: &UserId,
192 accepting: Option<(Timestamp, Timestamp)>,176 accepting: Option<(Timestamp, Timestamp)>,
193 ) -> Result<Appointment, AppError> {177 ) -> Result<Appointment, AppError> {
194- let _guard = APPOINTMENT_LOCK.lock().await;178+ tx_with_retry(db, false, async |tx| {
195- for _ in 0..CAS_UPDATE_RETRIES {179+ // Serializable for the overlap decision below (module doc). `SET
196- let expected = appointment::read_pending(db, id).await?;180+ // TRANSACTION` is legal only before the first query, so it goes
181+ // first; a `40001` from SSI is re-sent by the retry loop, and the
182+ // re-run re-reads everything against the committed winner.
183+ sqlx::query!("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
184+ .execute(&mut *tx)
185+ .await?;
186+ let expected = appointment::read_pending_on(&mut *tx, id).await?;
197 match accepting {187 match accepting {
198 None if expected.has_proposal() => {188 None if expected.has_proposal() => {
199 return Err(AppError::Conflict(189 return Err(AppError::Conflict(
@@ -214,7 +204,11 @@ async fn approve_inner(
214 }204 }
215 _ => {}205 _ => {}
216 }206 }
217- let slot = appointment_slot::read(db, &expected.slot)207+ let slot_id = expected
208+ .get_slot()
209+ .ok_or(AppError::NotFound)?
210+ .clone();
211+ let slot = appointment_slot::read_on(&mut *tx, &slot_id)
218 .await?212 .await?
219 .ok_or(AppError::NotFound)?;213 .ok_or(AppError::NotFound)?;
220 let (starts_at, ends_at) = expected.window(&slot);214 let (starts_at, ends_at) = expected.window(&slot);
@@ -226,10 +220,10 @@ async fn approve_inner(
226 if starts_at.as_millis() <= Timestamp::now().as_millis() {220 if starts_at.as_millis() <= Timestamp::now().as_millis() {
227 return Err(AppError::Conflict("that time has already started"));221 return Err(AppError::Conflict("that time has already started"));
228 }222 }
229- if appointment::conflicts(223+ if appointment::conflicts_on(
230- db,224+ &mut *tx,
231 slot.get_teacher(),225 slot.get_teacher(),
232- &expected.requester,226+ expected.get_requester(),
233 starts_at,227 starts_at,
234 ends_at,228 ends_at,
235 Some(id),229 Some(id),
@@ -243,16 +237,20 @@ async fn approve_inner(
243 let mut approved = expected.clone();237 let mut approved = expected.clone();
244 approved.status = AppointmentStatus::Approved;238 approved.status = AppointmentStatus::Approved;
245 approved.decided_by = Some(decided_by.clone());239 approved.decided_by = Some(decided_by.clone());
246- if let Some(saved) = appointment::save_if_unchanged(db, &expected, approved).await? {240+ match appointment::decision_cas(&mut *tx, &expected, approved).await? {
247- return Ok(saved);241+ Some(saved) => Ok(saved),
242+ // Unreachable under the row lock this transaction holds — kept
243+ // for the shape's honesty: a miss means re-decide, and the
244+ // caller's answer to that is this 409.
245+ None => Err(contended()),
248 }246 }
249- }247+ })
250- Err(contended())248+ .await
251 }249 }
252 250
253 /// Turn the request down. Frees the slot — the seat goes back with the251 /// Turn the request down. Frees the slot — the seat goes back with the
254-/// status flip, in one transaction. No lock: this decides nothing about252+/// status flip, in one transaction. No lock needed and none taken: this
255-/// anyone's calendar, and the write is its own guard.253+/// decides nothing about anyone's calendar, and the write is its own guard.
256 pub async fn reject(254 pub async fn reject(
257 db: &Database,255 db: &Database,
258 id: &AppointmentId,256 id: &AppointmentId,
@@ -291,10 +289,10 @@ pub async fn cancel(
291 ) -> Result<Appointment, AppError> {289 ) -> Result<Appointment, AppError> {
292 for _ in 0..CAS_UPDATE_RETRIES {290 for _ in 0..CAS_UPDATE_RETRIES {
293 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;291 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
294- if !expected.status.is_live() {292+ if !expected.get_status().is_live() {
295 return Err(AppError::Conflict("the appointment is already settled"));293 return Err(AppError::Conflict("the appointment is already settled"));
296 }294 }
297- let slot = appointment_slot::read(db, &expected.slot)295+ let slot = appointment_slot::read(db, expected.get_slot().ok_or(AppError::NotFound)?)
298 .await?296 .await?
299 .ok_or(AppError::NotFound)?;297 .ok_or(AppError::NotFound)?;
300 if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {298 if expected.window(&slot).0.as_millis() <= Timestamp::now().as_millis() {
@@ -340,7 +338,7 @@ pub async fn propose(
340 // to `pending`), and it neither takes nor frees the slot's seat.338 // to `pending`), and it neither takes nor frees the slot's seat.
341 for _ in 0..CAS_UPDATE_RETRIES {339 for _ in 0..CAS_UPDATE_RETRIES {
342 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;340 let expected = appointment::read(db, id).await?.ok_or(AppError::NotFound)?;
343- if !expected.status.is_live() {341+ if !expected.get_status().is_live() {
344 return Err(AppError::Conflict("the appointment is already settled"));342 return Err(AppError::Conflict("the appointment is already settled"));
345 }343 }
346 if starts_at.as_millis() <= Timestamp::now().as_millis() {344 if starts_at.as_millis() <= Timestamp::now().as_millis() {
@@ -375,10 +373,10 @@ pub async fn accept_proposal(
375 starts_at: Timestamp,373 starts_at: Timestamp,
376 ends_at: Timestamp,374 ends_at: Timestamp,
377 ) -> Result<Appointment, AppError> {375 ) -> Result<Appointment, AppError> {
378- // The same approval path re-reads under the lock and reads the proposed376+ // The same approval path re-reads inside its serializable transaction
379- // window off the row, so accepting is approval — no second code path.377+ // and reads the proposed window off the row, so accepting is approval —
380- // Only this door passes `accepting`, and the web layer opens it to the378+ // no second code path. Only this door passes `accepting`, and the web
381- // requester alone.379+ // layer opens it to the requester alone.
382 approve_inner(db, id, decided_by, Some((starts_at, ends_at))).await380 approve_inner(db, id, decided_by, Some((starts_at, ends_at))).await
383 }381 }
384 382
@@ -388,7 +386,6 @@ pub async fn accept_proposal(
388 fn contended() -> AppError {386 fn contended() -> AppError {
389 AppError::Conflict("the appointment is being decided elsewhere")387 AppError::Conflict("the appointment is being decided elsewhere")
390 }388 }
391-
392 #[cfg(test)]389 #[cfg(test)]
393 mod tests {390 mod tests {
394 use super::*;391 use super::*;
src/service/appointment_slot.rsmodified+37 -32
@@ -1,12 +1,14 @@
1 //! Slot publishing and withdrawal: the one-off and weekly publishes, the1 //! Slot publishing and withdrawal: the one-off and weekly publishes, the
2 //! single and series deletes, and the reads the web layer renders the2 //! single and series deletes, and the reads the web layer renders the
3-//! calendar from. Row reads, listings, the overlap probes, the role-claimed3+//! calendar from. Row reads, listings, the role-claimed INSERT, and the
4-//! INSERT, and the guarded delete live in [`crate::db::appointment_slot`].4+//! guarded delete live in [`crate::db::appointment_slot`].
5 //!5 //!
6-//! Publishing holds [`APPOINTMENT_LOCK`] from the conflict check through the6+//! There is no lock anymore. Overlap — a colliding publish slipping in
7-//! write — the same lock the booking path takes — so a concurrent publish or7+//! between a check and its write — is the `appointment_slot_teacher_span`
8-//! booking cannot slip a colliding window in between the check and the8+//! exclusion constraint: the store refuses the second window, so a racing
9-//! insert.9+//! publish answers to the database, not to this process. The pre-insert
10+//! reads below stay for their precise refusal texts; the constraint is the
11+//! authority.
10 12
11 use crate::database::Database;13 use crate::database::Database;
12 use crate::db::appointment_slot;14 use crate::db::appointment_slot;
@@ -16,8 +18,6 @@ use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;18 use crate::domain::user::UserId;
17 use crate::error::AppError;19 use crate::error::AppError;
18 20
19-use super::appointment::APPOINTMENT_LOCK;
20-
21 /// The row, for callers that only inspect it — the web layer's gates read21 /// The row, for callers that only inspect it — the web layer's gates read
22 /// through here.22 /// through here.
23 pub async fn read(23 pub async fn read(
@@ -52,7 +52,9 @@ pub async fn list_for_series(
52 appointment_slot::list_for_series(db, series).await52 appointment_slot::list_for_series(db, series).await
53 }53 }
54 54
55-/// Publish one slot.55+/// Publish one slot. Overlap is the exclusion constraint's call: a window
56+/// colliding with one the teacher already holds refuses the insert (23505)
57+/// with the same 409 the pre-check used to answer.
56 pub async fn create(58 pub async fn create(
57 db: &Database,59 db: &Database,
58 teacher: &UserId,60 teacher: &UserId,
@@ -61,14 +63,6 @@ pub async fn create(
61 note: Option<SlotNote>,63 note: Option<SlotNote>,
62 ) -> Result<AppointmentSlot, AppError> {64 ) -> Result<AppointmentSlot, AppError> {
63 AppointmentSlot::check_window(starts_at, ends_at)?;65 AppointmentSlot::check_window(starts_at, ends_at)?;
64- // Check-then-insert under the lock so a concurrent publish or booking
65- // can't slip a colliding window in between.
66- let _guard = APPOINTMENT_LOCK.lock().await;
67- if appointment_slot::conflicts_existing(db, teacher, starts_at, ends_at).await? {
68- return Err(AppError::ConflictOwned(
69- "this time overlaps a slot you have already published".into(),
70- ));
71- }
72 appointment_slot::insert_claimed(66 appointment_slot::insert_claimed(
73 db,67 db,
74 teacher,68 teacher,
@@ -81,6 +75,9 @@ pub async fn create(
81 series: None,75 series: None,
82 created_at: Timestamp::now(),76 created_at: Timestamp::now(),
83 }],77 }],
78+ AppError::ConflictOwned(
79+ "this time overlaps a slot you have already published".into(),
80+ ),
84 )81 )
85 .await?82 .await?
86 .into_iter()83 .into_iter()
@@ -102,11 +99,13 @@ pub async fn publish_weekly(
102 ) -> Result<Vec<AppointmentSlot>, AppError> {99 ) -> Result<Vec<AppointmentSlot>, AppError> {
103 let windows = AppointmentSlot::weekly_windows(starts_at, ends_at, until)?;100 let windows = AppointmentSlot::weekly_windows(starts_at, ends_at, until)?;
104 // Validate the whole batch before writing a single row: all-or-nothing,101 // Validate the whole batch before writing a single row: all-or-nothing,
105- // so a mid-series collision never leaves stray weeks behind. Held under102+ // so a mid-series collision never leaves stray weeks behind.
106- // the lock from the check through the write, matching `create`.103+ //
107- let _guard = APPOINTMENT_LOCK.lock().await;104+ // (a) against the slots already in the database — one envelope-wide
108- // (a) against the slots already in the database. `weekly_windows` walks105+ // read, so the first and last occurrence bound every one of them. The
109- // forward, so the first and last occurrence bound every one of them.106+ // exclusion constraint would refuse a colliding insert anyway; this
107+ // read is what keeps the refusal's *words* precise ("a repeated slot
108+ // overlaps one you have already published") ahead of the write.
110 let (first, last) = (windows[0], windows[windows.len() - 1]);109 let (first, last) = (windows[0], windows[windows.len() - 1]);
111 let published = appointment_slot::windows_in_span(db, teacher, first.0, last.1).await?;110 let published = appointment_slot::windows_in_span(db, teacher, first.0, last.1).await?;
112 for (i, &(w_start, w_end)) in windows.iter().enumerate() {111 for (i, &(w_start, w_end)) in windows.iter().enumerate() {
@@ -143,13 +142,20 @@ pub async fn publish_weekly(
143 created_at: now,142 created_at: now,
144 })143 })
145 .collect();144 .collect();
146- // One `INSERT`, therefore all-or-nothing: SurrealDB rolls the whole145+ // One transaction, therefore all-or-nothing: the row-by-row loop this
147- // publish back on any error. The row-by-row loop this replaces did not146+ // replaces did not — a database error at week 7 of 10 answered 500 with
148- // — a database error at week 7 of 10 answered 500 with six stray weeks147+ // six stray weeks already published. A racing publish that slips past
149- // already published, a half-series nobody asked for. It is also a single148+ // the read above answers to the exclusion constraint with the batch's
150- // round trip, so the lock is held for two queries whatever the149+ // own overlap refusal.
151- // occurrence count, instead of 1 + N (up to 52) sequential ones.150+ let mut created = appointment_slot::insert_claimed(
152- let mut created = appointment_slot::insert_claimed(db, teacher, rows).await?;151+ db,
152+ teacher,
153+ rows,
154+ AppError::ConflictOwned(
155+ "a repeated slot overlaps one you have already published".into(),
156+ ),
157+ )
158+ .await?;
153 if created.len() != windows.len() {159 if created.len() != windows.len() {
154 return Err(AppError::Internal(format!(160 return Err(AppError::Internal(format!(
155 "published {} of {} appointment slots",161 "published {} of {} appointment slots",
@@ -159,7 +165,7 @@ pub async fn publish_weekly(
159 }165 }
160 // `INSERT` makes no promise about the order it echoes rows back in, and166 // `INSERT` makes no promise about the order it echoes rows back in, and
161 // the response is rendered as the published calendar.167 // the response is rendered as the published calendar.
162- created.sort_by_key(|slot| slot.starts_at.as_millis());168+ created.sort_by_key(|slot| slot.get_starts_at().as_millis());
163 Ok(created)169 Ok(created)
164 }170 }
165 171
@@ -186,11 +192,10 @@ pub async fn delete_series(
186 if slots.is_empty() {192 if slots.is_empty() {
187 return Err(AppError::NotFound);193 return Err(AppError::NotFound);
188 }194 }
189- let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.id.clone()).collect();195+ let ids: Vec<AppointmentSlotId> = slots.iter().map(|slot| slot.get_id().clone()).collect();
190 appointment_slot::delete_free(db, &ids).await?;196 appointment_slot::delete_free(db, &ids).await?;
191 Ok(slots)197 Ok(slots)
192 }198 }
193-
194 #[cfg(test)]199 #[cfg(test)]
195 mod tests {200 mod tests {
196 use super::*;201 use super::*;
src/service/event.rsmodified+4 -13
@@ -63,20 +63,11 @@ pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
63 63
64 /// Is `user` in the event's audience roster right now — the point check64 /// Is `user` in the event's audience roster right now — the point check
65 /// behind marking.65 /// behind marking.
66-pub async fn includes(66+pub async fn includes(db: &Database, event: &Event, user: &User) -> Result<bool, AppError> {
67- db: &Database,67+ event::includes(db, event, user).await
68- audience: &EventAudience,
69- event: &EventId,
70- user: &User,
71-) -> Result<bool, AppError> {
72- event::includes(db, audience, event, user).await
73 }68 }
74 69
75 /// The event's full expected-attendee roster, resolved live.70 /// The event's full expected-attendee roster, resolved live.
76-pub async fn members(71+pub async fn members(db: &Database, event: &Event) -> Result<Vec<UserId>, AppError> {
77- db: &Database,72+ event::members(db, event).await
78- audience: &EventAudience,
79- event: &EventId,
80-) -> Result<Vec<UserId>, AppError> {
81- event::members(db, audience, event).await
82 }73 }
src/service/registration.rsmodified+6 -28
@@ -3,12 +3,11 @@
3 //! [`crate::db::registration`]; the seat itself is [`cap`]'s3 //! [`crate::db::registration`]; the seat itself is [`cap`]'s
4 //! claim-on-the-event-row.4 //! claim-on-the-event-row.
5 5
6-use crate::constant::REGISTRATION_COUNT_FIELD;
7 use crate::database::Database;6 use crate::database::Database;
8-use crate::db::cap;7+use crate::db::cap::Claimed;
9 use crate::db::registration;8 use crate::db::registration;
10 use crate::domain::event::EventId;9 use crate::domain::event::EventId;
11-use crate::domain::registration::{Registration, RegistrationId};10+use crate::domain::registration::Registration;
12 use crate::domain::role::Role;11 use crate::domain::role::Role;
13 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
14 use crate::error::AppError;13 use crate::error::AppError;
@@ -47,40 +46,19 @@ pub async fn register(
47 .await?46 .await?
48 .ok_or(AppError::NotFound)?47 .ok_or(AppError::NotFound)?
49 .registration_capacity()?;48 .registration_capacity()?;
50- let registration_row = Registration {49+ match registration::claim_seat(db, event, user, registered_by).await? {
51- id: RegistrationId::composite(event, user),50+ Claimed::Made(created) => Ok(created),
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 its51 // 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,52 // row over, the same no-op the early return above would have made,
75 // and with no seat spent either way.53 // and with no seat spent either way.
76- cap::Claimed::Duplicate => registration::read_for_user(db, event, user)54+ Claimed::Duplicate => registration::read_for_user(db, event, user)
77 .await?55 .await?
78 .ok_or_else(|| AppError::Internal("failed to register user".into())),56 .ok_or_else(|| AppError::Internal("failed to register user".into())),
79 // Full, the event was deleted between the read and the claim, or57 // Full, the event was deleted between the read and the claim, or
80 // the holder fell to parent while this ran — the conditional writes58 // the holder fell to parent while this ran — the conditional writes
81 // match nothing (or throw) either way, and only this path pays for59 // match nothing (or throw) either way, and only this path pays for
82 // the reads that tell them apart.60 // the reads that tell them apart.
83- cap::Claimed::Full => match crate::db::event::read(db, event).await? {61+ Claimed::Full => match crate::db::event::read(db, event).await? {
84 None => Err(AppError::NotFound),62 None => Err(AppError::NotFound),
85 Some(_) => match crate::db::user::read(db, user).await? {63 Some(_) => match crate::db::user::read(db, user).await? {
86 Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(64 Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
src/web/appointments.rsmodified+12 -3
@@ -179,7 +179,10 @@ impl AppointmentResponse {
179 let window = slot.map(|slot| appointment.window(slot));179 let window = slot.map(|slot| appointment.window(slot));
180 Self {180 Self {
181 id: appointment.get_id().key().to_string(),181 id: appointment.get_id().key().to_string(),
182- slot: appointment.get_slot().key().to_string(),182+ // A settled booking whose slot was withdrawn renders without a
183+ // window and without a slot id — the dangling reference the old
184+ // store permitted, now an explicit NULL.
185+ slot: appointment.get_slot().map(|slot| slot.key()).unwrap_or_default(),
183 teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())),186 teacher: slot.map(|slot| PersonRef::resolve(people, slot.get_teacher())),
184 requester: PersonRef::resolve(people, appointment.get_requester()),187 requester: PersonRef::resolve(people, appointment.get_requester()),
185 status: appointment.get_status().as_str().to_string(),188 status: appointment.get_status().as_str().to_string(),
@@ -216,7 +219,12 @@ async fn appointment_responses(
216 ) -> Result<Vec<AppointmentResponse>, AppError> {219 ) -> Result<Vec<AppointmentResponse>, AppError> {
217 let mut slots = Vec::with_capacity(rows.len());220 let mut slots = Vec::with_capacity(rows.len());
218 for row in rows {221 for row in rows {
219- slots.push(service::appointment_slot::read(db, row.get_slot()).await?);222+ let slot = match row.get_slot() {
223+ Some(slot_id) => service::appointment_slot::read(db, slot_id).await?,
224+ // A settled booking whose slot was withdrawn: no window.
225+ None => None,
226+ };
227+ slots.push(slot);
220 }228 }
221 // Collected eagerly rather than as a lazy iterator: a borrowing closure229 // Collected eagerly rather than as a lazy iterator: a borrowing closure
222 // held across the `person_map` await makes the handler's future230 // held across the `person_map` await makes the handler's future
@@ -277,7 +285,8 @@ async fn for_decision(
277 let appointment = service::appointment::read(db, id)285 let appointment = service::appointment::read(db, id)
278 .await?286 .await?
279 .ok_or(AppError::NotFound)?;287 .ok_or(AppError::NotFound)?;
280- let slot = service::appointment_slot::read(db, appointment.get_slot())288+ let slot_id = appointment.get_slot().ok_or(AppError::NotFound)?;
289+ let slot = service::appointment_slot::read(db, slot_id)
281 .await?290 .await?
282 .ok_or(AppError::NotFound)?;291 .ok_or(AppError::NotFound)?;
283 if !can_manage(&slot, user) {292 if !can_manage(&slot, user) {
src/web/events.rsmodified+68 -24
@@ -13,7 +13,9 @@ use crate::database::Database;
13 use crate::domain::attendance::{Attendance, AttendanceStatus};13 use crate::domain::attendance::{Attendance, AttendanceStatus};
14 use crate::domain::class_group::ClassGroupId;14 use crate::domain::class_group::ClassGroupId;
15 use crate::domain::course::CourseId;15 use crate::domain::course::CourseId;
16-use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};16+use crate::domain::event::{
17+ Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle,
18+};
17 use crate::domain::role::Role;19 use crate::domain::role::Role;
18 use crate::domain::timestamp::Timestamp;20 use crate::domain::timestamp::Timestamp;
19 use crate::domain::user::{User, UserId};21 use crate::domain::user::{User, UserId};
@@ -83,11 +85,21 @@ impl AudienceDto {
83 /// Validate the wire form into the domain audience: the role must parse,85 /// Validate the wire form into the domain audience: the role must parse,
84 /// the course must exist, and a registration capacity must be positive.86 /// the course must exist, and a registration capacity must be positive.
85 async fn into_domain(self, db: &Database) -> Result<EventAudience, AppError> {87 async fn into_domain(self, db: &Database) -> Result<EventAudience, AppError> {
86- match self {88+ Ok(match self {
87- AudienceDto::School => Ok(EventAudience::School),89+ AudienceDto::School => EventAudience {
88- AudienceDto::Role { role } => Ok(EventAudience::Role {90+ kind: EventAudienceKind::School,
89- role: Role::try_from_str(&role)?,91+ role: None,
90- }),92+ course: None,
93+ class: None,
94+ capacity: None,
95+ },
96+ AudienceDto::Role { role } => EventAudience {
97+ kind: EventAudienceKind::Role,
98+ role: Some(Role::try_from_str(&role)?),
99+ course: None,
100+ class: None,
101+ capacity: None,
102+ },
91 AudienceDto::Course { course } => {103 AudienceDto::Course { course } => {
92 let course = CourseId::from_key(&course);104 let course = CourseId::from_key(&course);
93 if crate::service::course::read(db, &course).await?.is_none() {105 if crate::service::course::read(db, &course).await?.is_none() {
@@ -96,7 +108,13 @@ impl AudienceDto {
96 reason: "course does not exist",108 reason: "course does not exist",
97 }));109 }));
98 }110 }
99- Ok(EventAudience::Course { course })111+ EventAudience {
112+ kind: EventAudienceKind::Course,
113+ role: None,
114+ course: Some(course),
115+ class: None,
116+ capacity: None,
117+ }
100 }118 }
101 AudienceDto::Class { class } => {119 AudienceDto::Class { class } => {
102 let class = ClassGroupId::from_key(&class);120 let class = ClassGroupId::from_key(&class);
@@ -109,7 +127,13 @@ impl AudienceDto {
109 reason: "class does not exist",127 reason: "class does not exist",
110 }));128 }));
111 }129 }
112- Ok(EventAudience::Class { class })130+ EventAudience {
131+ kind: EventAudienceKind::Class,
132+ role: None,
133+ course: None,
134+ class: Some(class),
135+ capacity: None,
136+ }
113 }137 }
114 AudienceDto::Registration { capacity } => {138 AudienceDto::Registration { capacity } => {
115 if capacity.is_some_and(|capacity| capacity < 1) {139 if capacity.is_some_and(|capacity| capacity < 1) {
@@ -118,25 +142,39 @@ impl AudienceDto {
118 reason: "capacity must be at least 1",142 reason: "capacity must be at least 1",
119 }));143 }));
120 }144 }
121- Ok(EventAudience::Registration { capacity })145+ EventAudience {
146+ kind: EventAudienceKind::Registration,
147+ role: None,
148+ course: None,
149+ class: None,
150+ capacity,
151+ }
122 }152 }
123- }153+ })
124 }154 }
125 155
126 fn from_domain(audience: &EventAudience) -> Self {156 fn from_domain(audience: &EventAudience) -> Self {
127- match audience {157+ match audience.kind {
128- EventAudience::School => AudienceDto::School,158+ EventAudienceKind::School => AudienceDto::School,
129- EventAudience::Role { role } => AudienceDto::Role {159+ EventAudienceKind::Role => AudienceDto::Role {
130- role: role.as_str().to_string(),160+ role: audience.role.map(|role| role.as_str().to_string()).unwrap_or_default(),
131 },161 },
132- EventAudience::Course { course } => AudienceDto::Course {162+ EventAudienceKind::Course => AudienceDto::Course {
133- course: course.key().to_string(),163+ course: audience
164+ .course
165+ .as_ref()
166+ .map(|course| course.key())
167+ .unwrap_or_default(),
134 },168 },
135- EventAudience::Class { class } => AudienceDto::Class {169+ EventAudienceKind::Class => AudienceDto::Class {
136- class: class.key().to_string(),170+ class: audience
171+ .class
172+ .as_ref()
173+ .map(|class| class.key())
174+ .unwrap_or_default(),
137 },175 },
138- EventAudience::Registration { capacity } => AudienceDto::Registration {176+ EventAudienceKind::Registration => AudienceDto::Registration {
139- capacity: *capacity,177+ capacity: audience.capacity,
140 },178 },
141 }179 }
142 }180 }
@@ -208,7 +246,7 @@ impl EventResponse {
208 creator: event.get_creator().key().to_string(),246 creator: event.get_creator().key().to_string(),
209 title: event.get_title().as_str().to_string(),247 title: event.get_title().as_str().to_string(),
210 description: event.get_description().as_str().to_string(),248 description: event.get_description().as_str().to_string(),
211- audience: AudienceDto::from_domain(event.get_audience()),249+ audience: AudienceDto::from_domain(&EventAudience::of_row(event)),
212 starts_at: event.get_starts_at().map(|t| t.as_millis()),250 starts_at: event.get_starts_at().map(|t| t.as_millis()),
213 ends_at: event.get_ends_at().map(|t| t.as_millis()),251 ends_at: event.get_ends_at().map(|t| t.as_millis()),
214 }252 }
@@ -284,7 +322,13 @@ async fn create_event(
284 let description = EventDescription::try_new(&req.description.unwrap_or_default())?;322 let description = EventDescription::try_new(&req.description.unwrap_or_default())?;
285 let audience = match req.audience {323 let audience = match req.audience {
286 Some(audience) => audience.into_domain(&st.db).await?,324 Some(audience) => audience.into_domain(&st.db).await?,
287- None => EventAudience::School,325+ None => EventAudience {
326+ kind: EventAudienceKind::School,
327+ role: None,
328+ course: None,
329+ class: None,
330+ capacity: None,
331+ },
288 };332 };
289 let starts_at = req.starts_at.map(Timestamp::from_millis);333 let starts_at = req.starts_at.map(Timestamp::from_millis);
290 let ends_at = req.ends_at.map(Timestamp::from_millis);334 let ends_at = req.ends_at.map(Timestamp::from_millis);
@@ -535,7 +579,7 @@ async fn mark(
535 579
536 // Only expected attendees can be marked. The marker needn't be in the580 // Only expected attendees can be marked. The marker needn't be in the
537 // audience — a teacher takes roll of a student-targeted event.581 // audience — a teacher takes roll of a student-targeted event.
538- if !service::event::includes(&st.db, event.get_audience(), event.get_id(), &target_user).await?582+ if !service::event::includes(&st.db, &event, &target_user).await?
539 {583 {
540 return Err(AppError::Validation(ValidationError::Invalid {584 return Err(AppError::Validation(ValidationError::Invalid {
541 field: "user_id",585 field: "user_id",
@@ -677,7 +721,7 @@ async fn roster(
677 .await?721 .await?
678 .ok_or(AppError::NotFound)?;722 .ok_or(AppError::NotFound)?;
679 723
680- let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?;724+ let mut members = service::event::members(&st.db, &event).await?;
681 // ULID keys sort by creation instant — a stable order keeps pages coherent.725 // ULID keys sort by creation instant — a stable order keeps pages coherent.
682 members.sort_by(|a, b| a.key().cmp(b.key()));726 members.sort_by(|a, b| a.key().cmp(b.key()));
683 let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?;727 let (marks, _) = crate::service::attendance::list_for_event(&st.db, &event_id, None, 0).await?;