diff --git a/src/db/appointment.rs b/src/db/appointment.rs index 6d95bea..f78c047 100644 --- a/src/db/appointment.rs +++ b/src/db/appointment.rs @@ -1,28 +1,24 @@ //! The `appointment` table: row reads and listings, the overlap probe behind -//! the booking guard, and the compare-and-set every decision writes through. -//! The workflows that sequence these under -//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in -//! [`crate::service::appointment`]. +//! the booking guard, the seat claim the booking writes through, and the +//! compare-and-set every decision writes. The workflows live in +//! [`crate::service::appointment`] (no lock anymore: occupancy is a +//! conditional counter write, the decision CAS is one statement, and the +//! approval's overlap decision is a serializable transaction documented at +//! its own site). -use surrealdb::types::SurrealValue; - -use crate::database::{Database, lost_the_race}; +use crate::database::{Database, tx_with_retry}; +use crate::db::cap::Claimed; use crate::db::page::PagedList; -use crate::domain::appointment::{Appointment, AppointmentId, AppointmentStatus}; +use crate::domain::appointment::{Appointment, AppointmentId, AppointmentReason, AppointmentStatus}; use crate::domain::appointment_slot::AppointmentSlotId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::{query, query_as, PgConnection, Postgres}; -/// The window an approved booking actually occupies, as read back from the -/// database: the counter-proposed time when there is one, the slot's own -/// otherwise. Optional fields because a dangling slot reference resolves to -/// `NONE` — such a row is skipped rather than failing the whole guard. -#[derive(Debug, Clone, SurrealValue)] -struct BookedWindow { - starts_at: Option, - ends_at: Option, -} +/// The appointment row's columns, in [`Appointment`]'s field order. +const COLS: &str = "id, slot, requester, status, reason, proposed_starts_at, proposed_ends_at, \ + proposed_by, decided_by, cancelled_by, cancel_reason, reject_reason, created_at"; /// Is `[starts_at, ends_at)` already taken for either party? Both sides are /// checked: a teacher can't be in two meetings at once, and neither can a @@ -33,9 +29,10 @@ struct BookedWindow { /// approval wins. `except` skips one row, so re-checking a booking against /// the world never trips over itself. /// -/// Caller must hold -/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the answer to still -/// be true by the time it is acted on. +/// The effective window (the proposal when one stands, the slot's own +/// otherwise) is computed in the query and compared in Rust: one round +/// trip, and the comparison stays a plain, unit-tested predicate. A booking +/// whose slot was withdrawn since (no window left to stand on) is skipped. pub async fn conflicts( db: &Database, teacher: &UserId, @@ -44,45 +41,94 @@ pub async fn conflicts( ends_at: Timestamp, except: Option<&AppointmentId>, ) -> Result { - // The effective window is computed in the query (proposal overrides - // the slot) but compared here: one round trip, and the comparison - // itself stays a plain, unit-tested Rust predicate. - let mut result = db - .query( - "SELECT \ - (IF proposed_starts_at != NONE THEN proposed_starts_at \ - ELSE slot.starts_at END) AS starts_at, \ - (IF proposed_ends_at != NONE THEN proposed_ends_at \ - ELSE slot.ends_at END) AS ends_at \ - FROM appointment \ - WHERE status = 'approved' AND id != $except \ - AND (requester = $requester OR slot.teacher = $teacher)", - ) - .bind(("teacher", teacher.record())) - .bind(("requester", requester.record())) - .bind(("except", except.map(AppointmentId::record))) - .await? - .check()?; - Ok(result - .take::>(0)? + conflicts_on(db, teacher, requester, starts_at, ends_at, except).await +} + +/// [`conflicts`] against any executor — the approval decision re-asks this +/// inside its own transaction, so the verdict it acts on is the one its +/// snapshot holds. +pub(crate) async fn conflicts_on<'e, E>( + executor: E, + teacher: &UserId, + requester: &UserId, + starts_at: Timestamp, + ends_at: Timestamp, + except: Option<&AppointmentId>, +) -> Result +where + E: sqlx::Executor<'e, Database = Postgres>, +{ + let windows = query!( + "SELECT COALESCE(a.proposed_starts_at, s.starts_at) AS starts_at, \ + COALESCE(a.proposed_ends_at, s.ends_at) AS ends_at \ + FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ + WHERE a.status = 'approved' \ + AND ($3::uuid IS NULL OR a.id <> $3) \ + AND (a.requester = $2 OR s.teacher = $1)", + teacher.uuid(), + requester.uuid(), + except.map(|id| id.uuid()), + ) + .fetch_all(executor) + .await?; + Ok(windows .into_iter() - .filter_map(|window| Some((window.starts_at?, window.ends_at?))) + .filter_map(|window| { + Some(( + Timestamp::from_millis(window.starts_at?), + Timestamp::from_millis(window.ends_at?), + )) + }) .any(|(booked_starts_at, booked_ends_at)| { Appointment::overlaps(starts_at, ends_at, booked_starts_at, booked_ends_at) })) } +pub(crate) async fn read_on<'e, E>(executor: E, id: &AppointmentId) -> Result, AppError> +where + E: sqlx::Executor<'e, Database = Postgres>, +{ + let appointment = query_as!( + Appointment, + "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \ + status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \ + proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \ + cancelled_by AS \"cancelled_by: UserId\", \ + cancel_reason AS \"cancel_reason: AppointmentReason\", \ + reject_reason AS \"reject_reason: AppointmentReason\", \ + created_at AS \"created_at: Timestamp\" \ + FROM appointment WHERE id = $1", + id.uuid() + ) + .fetch_optional(executor) + .await?; + Ok(appointment) +} + pub async fn read( db: &Database, id: &AppointmentId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + read_on(db, id).await } /// The row, insisting it is still open for a decision. pub async fn read_pending(db: &Database, id: &AppointmentId) -> Result { - let appointment = read(db, id).await?.ok_or(AppError::NotFound)?; - if appointment.status != AppointmentStatus::Pending { + read_pending_on(db, id).await +} + +/// [`read_pending`] against any executor (the approval's transaction). +pub(crate) async fn read_pending_on<'e, E>( + executor: E, + id: &AppointmentId, +) -> Result +where + E: sqlx::Executor<'e, Database = Postgres>, +{ + let appointment = read_on(executor, id).await?.ok_or(AppError::NotFound)?; + if appointment.get_status() != AppointmentStatus::Pending { return Err(AppError::Conflict("the appointment is no longer pending")); } Ok(appointment) @@ -94,42 +140,152 @@ pub async fn list_for_requester( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "appointment WHERE requester = $requester", - "ORDER BY id DESC", - ) - .bind("requester", requester.record()) - .run(limit, offset, db) - .await + PagedList::new("appointment WHERE requester = $1", "ORDER BY id DESC") + .bind(requester.uuid()) + .run(limit, offset, db) + .await } -/// Every booking aimed at `teacher`, across all their slots — the teacher's -/// request inbox. +/// Every booking aimed at `teacher`, across all their slots — the +/// teacher's request inbox. The teacher lives on the slot row now, so +/// this is a join; the page and its count share the one predicate, and +/// the columns are spelled out so the join's duplicate slot-column names +/// can never leak into the row decode. pub async fn list_for_teacher( db: &Database, teacher: &UserId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "appointment WHERE slot.teacher = $teacher", - "ORDER BY id DESC", - ) - .bind("teacher", teacher.record()) - .run(limit, offset, db) - .await + match limit { + None => { + let rows = query_as!( + Appointment, + "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \ + a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \ + a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \ + a.cancelled_by AS \"cancelled_by: UserId\", \ + a.cancel_reason AS \"cancel_reason: AppointmentReason\", \ + a.reject_reason AS \"reject_reason: AppointmentReason\", \ + a.created_at AS \"created_at: Timestamp\" \ + FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ + WHERE s.teacher = $1 \ + ORDER BY a.id DESC", + teacher.uuid() + ) + .fetch_all(db) + .await?; + Ok((rows, rows.len() as i64)) + } + Some(limit) => { + let rows = query_as!( + Appointment, + "SELECT a.id AS \"id: AppointmentId\", a.slot AS \"slot: AppointmentSlotId\", a.requester AS \"requester: UserId\", \ + a.status AS \"status: AppointmentStatus\", a.reason AS \"reason: AppointmentReason\", \ + a.proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + a.proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + a.proposed_by AS \"proposed_by: UserId\", a.decided_by AS \"decided_by: UserId\", \ + a.cancelled_by AS \"cancelled_by: UserId\", \ + a.cancel_reason AS \"cancel_reason: AppointmentReason\", \ + a.reject_reason AS \"reject_reason: AppointmentReason\", \ + a.created_at AS \"created_at: Timestamp\" \ + FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ + WHERE s.teacher = $1 \ + ORDER BY a.id DESC LIMIT $2 OFFSET $3", + teacher.uuid(), + limit, + offset + ) + .fetch_all(db) + .await?; + let total = query!( + "SELECT count(*) AS total \ + FROM appointment a JOIN appointment_slot s ON a.slot = s.id \ + WHERE s.teacher = $1", + teacher.uuid() + ) + .fetch_one(db) + .await? + .total; + Ok((rows, total)) + } + } } pub async fn list_for_slot( db: &Database, slot: &AppointmentSlotId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM appointment WHERE slot = $slot ORDER BY id DESC") - .bind(("slot", slot.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = query_as!( + Appointment, + "SELECT id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \ + status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \ + proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \ + cancelled_by AS \"cancelled_by: UserId\", \ + cancel_reason AS \"cancel_reason: AppointmentReason\", \ + reject_reason AS \"reject_reason: AppointmentReason\", \ + created_at AS \"created_at: Timestamp\" \ + FROM appointment WHERE slot = $1 ORDER BY id DESC", + slot.uuid() + ) + .fetch_all(db) + .await?; + Ok(rows) +} + +/// Request `slot`: take the slot's one seat and write the pending booking +/// in a single statement — two racing requests cannot both find the slot +/// free however they interleave, and a refused insert takes its own seat +/// bump back with it. Zero rows means "full, or the slot was deleted since +/// the caller read it": the marker is one, and the caller re-reads to pick +/// the 404/409. +pub async fn claim_slot_and_create( + db: &Database, + appointment: Appointment, +) -> Result, AppError> { + match query_as!( + Appointment, + "WITH seat AS ( + UPDATE appointment_slot SET occupied = occupied + 1 + WHERE id = $1 AND occupied < 1 + RETURNING 1) + INSERT INTO appointment (id, slot, requester, status, reason, proposed_starts_at, \ + proposed_ends_at, proposed_by, decided_by, cancelled_by, \ + cancel_reason, reject_reason, created_at) + SELECT $2, $1, $3, 'pending', $4, NULL, NULL, NULL, NULL, NULL, NULL, NULL, $5 + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \ + status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \ + proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \ + cancelled_by AS \"cancelled_by: UserId\", \ + cancel_reason AS \"cancel_reason: AppointmentReason\", \ + reject_reason AS \"reject_reason: AppointmentReason\", \ + created_at AS \"created_at: Timestamp\"", + appointment + .get_slot() + .map(|s| s.uuid()) + .expect("a new booking always carries its slot"), + appointment.get_id().uuid(), + appointment.get_requester().uuid(), + appointment.get_reason().as_str(), + appointment.get_created_at().as_millis(), + ) + .fetch_optional(db) + .await + { + Ok(Some(row)) => Ok(Claimed::Made(row)), + Ok(None) => Ok(Claimed::Full), + // The id is freshly minted on a table keyed by it; no rival can + // have aimed at it, and the seat gate excludes any slot the insert + // could dangle from — no other verdict exists on this path. + Err(err) => Err(err.into()), + } } /// Write the decision only while the stored row still carries the state it @@ -144,57 +300,77 @@ pub async fn list_for_slot( /// least one of the four. The fields only a terminal transition writes /// (`cancelled_by`, `cancel_reason`, `reject_reason`) need no compare of /// their own: they always travel with a `status` change into a state no -/// later decision is allowed from. All four are top-level columns, so an -/// absent one reads back as `NONE` and `NONE = NONE` holds — the object-key -/// dropping that forces `settings` to compare a rebuilt projection cannot -/// bite here. -/// -/// A store-level write conflict is reported the same way as a miss: it -/// means a concurrent write committed on this row, which is exactly the -/// "reload and re-decide" case. +/// later decision is allowed from. Absent values compare truthfully under +/// `IS NOT DISTINCT FROM`. /// /// A transition out of a live status (reject, cancel) hands the slot's -/// `occupied` seat back, in this same transaction — the counter is the +/// `occupied` seat back in the same transaction — the counter is the /// authority on whether the slot is taken, so it must move if and only if -/// the status did. The decrement is `WHERE`-gated on the CAS having written +/// the status did. The decrement is gated on the CAS having written /// something, so a lost race frees nothing. pub async fn save_if_unchanged( db: &Database, expected: &Appointment, new: Appointment, ) -> Result, AppError> { - let frees_the_slot = expected.status.is_live() && !new.status.is_live(); - let attempted = async { - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $done = (UPDATE $id CONTENT $new \ - WHERE status = $status \ - AND proposed_starts_at = $proposed_starts_at \ - AND proposed_ends_at = $proposed_ends_at \ - AND decided_by = $decided_by); - UPDATE $slot SET occupied = math::max([(occupied ?? 0) - 1, 0]) - WHERE $frees AND array::len($done) > 0; - RETURN $done; - COMMIT TRANSACTION;", - ) - .bind(("slot", expected.slot.record())) - .bind(("frees", frees_the_slot)) - .bind(("id", expected.id.record())) - .bind(("status", expected.status)) - .bind(("proposed_starts_at", expected.proposed_starts_at)) - .bind(("proposed_ends_at", expected.proposed_ends_at)) - .bind(("decided_by", expected.decided_by.clone())) - .bind(("new", new)) - .await? - .check()?; - // BEGIN, the LET, and the counter write take a slot each. - result.take::>(3) - } - .await; - match attempted { - Ok(rows) => Ok(rows.into_iter().next()), - Err(err) if lost_the_race(&err) => Ok(None), - Err(err) => Err(err.into()), + tx_with_retry(db, false, async |tx| { + decision_cas(&mut *tx, expected, new.clone()).await + }) + .await +} + +/// The decision's compare-and-set against any executor: one conditional +/// `UPDATE`, plus the seat release when the status left the live set. A +/// single statement decides under Postgres's row locking, so no retry +/// budget and no store-level "write conflict" class exists anymore — a miss +/// is simply `None`, the reload-and-re-decide answer. +pub(crate) async fn decision_cas( + tx: &mut PgConnection, + expected: &Appointment, + new: Appointment, +) -> Result, AppError> { + let frees_the_slot = expected.get_status().is_live() && !new.get_status().is_live(); + let done = query_as!( + Appointment, + "UPDATE appointment SET status = $2, proposed_starts_at = $3, proposed_ends_at = $4, \ + proposed_by = $5, decided_by = $6, cancelled_by = $7, cancel_reason = $8, \ + reject_reason = $9 \ + WHERE id = $1 AND status = $10 \ + AND proposed_starts_at IS NOT DISTINCT FROM $11 \ + AND proposed_ends_at IS NOT DISTINCT FROM $12 \ + AND decided_by IS NOT DISTINCT FROM $13 \ + RETURNING id AS \"id: AppointmentId\", slot AS \"slot: AppointmentSlotId\", requester AS \"requester: UserId\", \ + status AS \"status: AppointmentStatus\", reason AS \"reason: AppointmentReason\", \ + proposed_starts_at AS \"proposed_starts_at: Timestamp\", \ + proposed_ends_at AS \"proposed_ends_at: Timestamp\", \ + proposed_by AS \"proposed_by: UserId\", decided_by AS \"decided_by: UserId\", \ + cancelled_by AS \"cancelled_by: UserId\", \ + cancel_reason AS \"cancel_reason: AppointmentReason\", \ + reject_reason AS \"reject_reason: AppointmentReason\", \ + created_at AS \"created_at: Timestamp\"", + new.get_id().uuid(), + new.get_status().as_str(), + new.get_proposed_starts_at().map(|t| t.as_millis()), + new.get_proposed_ends_at().map(|t| t.as_millis()), + new.get_proposed_by().map(|u| u.uuid()), + new.get_decided_by().map(|u| u.uuid()), + new.get_cancelled_by().map(|u| u.uuid()), + new.get_cancel_reason().map(|r| r.as_str().to_string()), + new.get_reject_reason().map(|r| r.as_str().to_string()), + expected.get_status().as_str(), + expected.get_proposed_starts_at().map(|t| t.as_millis()), + expected.get_proposed_ends_at().map(|t| t.as_millis()), + expected.get_decided_by().map(|u| u.uuid()), + ) + .fetch_optional(&mut *tx) + .await?; + if frees_the_slot && done.is_some() { + sqlx::query!( + "UPDATE appointment_slot SET occupied = GREATEST(occupied - 1, 0) WHERE id = $1", + expected.get_slot().map(|s| s.uuid()), + ) + .execute(tx) + .await?; } + Ok(done) } diff --git a/src/db/appointment_slot.rs b/src/db/appointment_slot.rs index 0776ae9..ee23ab7 100644 --- a/src/db/appointment_slot.rs +++ b/src/db/appointment_slot.rs @@ -1,23 +1,22 @@ -//! The `appointment_slot` table: row reads and listings, the overlap probes -//! behind the publish guard, the role-claimed INSERT every publish writes -//! through, and the delete whose own `WHERE` is the no-live-booking guard. -//! The workflows that sequence these under -//! [`crate::service::appointment::APPOINTMENT_LOCK`] live in +//! The `appointment_slot` table: row reads and listings, the role-claimed +//! INSERT every publish writes through, and the delete whose own `WHERE` +//! is the no-live-booking guard. The workflows live in //! [`crate::service::appointment_slot`]. +//! +//! Publish overlap is a database guarantee now: the +//! `appointment_slot_teacher_span` exclusion constraint refuses a second +//! window overlapping one the teacher already holds (SQLSTATE `23505`, +//! mapped to the same 409 the old check produced). The pre-insert reads in +//! [`crate::service::appointment_slot`] remain for their precise refusal +//! texts; the constraint is the authority a racing publish answers to. -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::constant::{APPOINTMENT_SLOT_TABLE, ROLES}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; -use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotSeries}; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId, SlotNote, SlotSeries}; use crate::domain::role::Role; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; - -/// The publisher fell below `teacher` while the publish was in flight. -const UNFIT_MARK: &str = "slot_not_staff"; +use sqlx::{query, query_as}; /// Write a whole publish — one occurrence or fifty-two — while the publisher /// still *holds* a teaching role. @@ -27,124 +26,145 @@ const UNFIT_MARK: &str = "slot_not_staff"; /// snapshot can see, and a slot landing after that snapshot would survive it /// under a role that may not publish — reachable by no route afterwards, /// since the calendar hides a demoted teacher's slots and the deletes are -/// `teacher`-gated. So the teacher's own record is claimed beside the insert -/// ([`cap::role_claim`]), which is the key the demotion writes: either the -/// sweep sees these slots, or this write sees the new role and publishes -/// nothing. +/// `teacher`-gated. So the teacher's own row is claimed beside the inserts +/// (the role-handshake recipe in [`crate::db::cap`]): the transaction takes +/// the teacher's row `FOR NO KEY UPDATE` — the same key the demotion +/// writes — and the Rust check refuses unless the role still reaches the +/// teaching bar. Either the sweep sees these slots, or this write sees the +/// new role and publishes nothing. /// -/// The bar is read off the hierarchy rather than spelled out, so a new role -/// cannot drift out of it. +/// Overlap is the `appointment_slot_teacher_span` exclusion constraint: a +/// racing publish or a window colliding with an already-published one +/// refuses the whole batch (`23505`), which the caller maps to its own +/// overlap 409 (`overlap_refusal` carries the exact text the caller owes — +/// single publish and weekly series refuse with different words). /// -/// Admissible for [`transaction_with_retry`]: the claim is `SELECT`/`UPDATE` -/// only, and the `INSERT` carries freshly minted ULIDs on a table with no -/// `UNIQUE` index, so no rival can make it answer "already exists". +/// All-or-nothing: one transaction, so a collision at week 7 of 10 leaves +/// no stray weeks behind. pub async fn insert_claimed( db: &Database, teacher: &UserId, rows: Vec, + overlap_refusal: AppError, ) -> Result, AppError> { - let staff = ROLES - .iter() - .filter(|role| role.at_least(Role::Teacher)) - .map(|role| format!("'{}'", role.as_str())) - .collect::>() - .join(", "); - let held = cap::role_claim("teacher", &format!("NOT IN [{staff}]"), UNFIT_MARK); - let sql = format!( - "BEGIN TRANSACTION;\n{};\nINSERT INTO {APPOINTMENT_SLOT_TABLE} $rows;\n\ - COMMIT TRANSACTION;", - held.join(";\n") - ); - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("teacher".into(), teacher.record().into_value()), - ("rows".into(), rows.into_value()), - ], - &[UNFIT_MARK], - ) - .await?; - // Demoted while this ran — the same refusal `RequireTeacher` makes a - // moment earlier, and the only one that can arrive after it. - if errors - .values() - .any(|error| error.to_string().contains(UNFIT_MARK)) - { - return Err(AppError::Forbidden( - "that account no longer holds a teaching role", - )); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // BEGIN plus the claim's own statements — counted, not tallied by hand, - // so a statement added there cannot read back the wrong result. - Ok(result.take::>(held.len() + 1)?) -} - -/// Does the teacher already have a published slot whose window collides with -/// `[starts_at, ends_at)`? Half-open, so a slot ending exactly where the new -/// one starts is *not* a conflict — that is how a teacher's hour is carved -/// into back-to-back slots. Caller must hold -/// [`crate::service::appointment::APPOINTMENT_LOCK`] for the -/// answer to still be true by the time the insert lands. -pub async fn conflicts_existing( - db: &Database, - teacher: &UserId, - starts_at: Timestamp, - ends_at: Timestamp, -) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM appointment_slot \ - WHERE teacher = $teacher AND starts_at < $ends AND ends_at > $starts \ - LIMIT 1", + tx_with_retry(db, false, async |tx| { + // The role handshake. The bar is read off the hierarchy rather than + // spelled out, so a new role cannot drift out of it. + let held = sqlx::query!( + "SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE", + teacher.uuid() ) - .bind(("teacher", teacher.record())) - .bind(("starts", starts_at.as_millis())) - .bind(("ends", ends_at.as_millis())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) + .fetch_optional(&mut *tx) + .await?; + let fit = held + .as_ref() + .and_then(|row| Role::try_from_str(&row.role).ok()) + .is_some_and(|role| role.at_least(Role::Teacher)); + if !fit { + // Demoted (or gone) while this ran — the same refusal + // `RequireTeacher` makes a moment earlier, and the only one + // that can arrive after it. + return Err(AppError::Forbidden( + "that account no longer holds a teaching role", + )); + } + let mut saved = Vec::with_capacity(rows.len()); + for row in rows { + match query_as!( + AppointmentSlot, + "INSERT INTO appointment_slot (id, teacher, starts_at, ends_at, note, series, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7) + RETURNING id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\"", + row.get_id().uuid(), + row.get_teacher().uuid(), + row.get_starts_at().as_millis(), + row.get_ends_at().as_millis(), + row.get_note().map(|n| n.as_str().to_string()), + row.get_series().map(|s| s.as_str().to_string()), + row.get_created_at().as_millis(), + ) + .fetch_one(&mut *tx) + .await + { + Ok(row) => saved.push(row), + // A teacher cannot publish two overlapping windows: the + // exclusion constraint, answering the caller's overlap 409. + Err(err) if unique_violation(&err) == Some("appointment_slot_teacher_span") => { + return Err(overlap_refusal); + } + Err(err) => return Err(err.into()), + } + } + Ok(saved) + }) + .await } /// Every window this teacher already published that intersects the envelope /// `[from, to)`. One read for a whole batch: a stored row that overlaps *any* /// window in the batch necessarily overlaps the envelope spanning them all, /// so filtering the envelope and comparing in memory is exactly the -/// per-window [`conflicts_existing`] check, -/// hoisted out of the loop — which is what keeps -/// [`crate::service::appointment::APPOINTMENT_LOCK`] down -/// to two round trips instead of one per occurrence. +/// per-window overlap check hoisted out of the loop. The exclusion +/// constraint remains the authority; this read exists for the batch's +/// precise refusal texts. pub async fn windows_in_span( db: &Database, teacher: &UserId, from: Timestamp, to: Timestamp, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot \ - WHERE teacher = $teacher AND starts_at < $to AND ends_at > $from", - ) - .bind(("teacher", teacher.record())) - .bind(("from", from.as_millis())) - .bind(("to", to.as_millis())) - .await? - .check()?; - Ok(result - .take::>(0)? + let rows = query!( + "SELECT starts_at, ends_at FROM appointment_slot \ + WHERE teacher = $1 AND starts_at < $3 AND ends_at > $2", + teacher.uuid(), + from.as_millis(), + to.as_millis() + ) + .fetch_all(db) + .await?; + Ok(rows .into_iter() - .map(|slot| (slot.starts_at, slot.ends_at)) + .map(|row| (Timestamp::from_millis(row.starts_at), Timestamp::from_millis(row.ends_at))) .collect()) } +pub(crate) async fn read_on<'e, E>( + executor: E, + id: &AppointmentSlotId, +) -> Result, AppError> +where + E: sqlx::Executor<'e, Database = sqlx::Postgres>, +{ + let slot = query_as!( + AppointmentSlot, + "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ + FROM appointment_slot WHERE id = $1", + id.uuid() + ) + .fetch_optional(executor) + .await?; + Ok(slot) +} + pub async fn read( db: &Database, id: &AppointmentSlotId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let slot = query_as!( + AppointmentSlot, + "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ + FROM appointment_slot WHERE id = $1", + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(slot) } /// A teacher's own calendar, earliest first. @@ -152,15 +172,18 @@ pub async fn list_for_teacher( db: &Database, teacher: &UserId, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE teacher = $teacher \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("teacher", teacher.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let slots = query_as!( + AppointmentSlot, + "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ + FROM appointment_slot WHERE teacher = $1 \ + ORDER BY starts_at ASC, id ASC", + teacher.uuid() + ) + .fetch_all(db) + .await?; + Ok(slots) } /// Every slot whose window has not opened yet, earliest first — the bookable @@ -177,30 +200,36 @@ pub async fn list_upcoming( db: &Database, from: Timestamp, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE starts_at > $from \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("from", from.as_millis())) - .await? - .check()?; - Ok(result.take::>(0)?) + let slots = query_as!( + AppointmentSlot, + "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ + FROM appointment_slot WHERE starts_at > $1 \ + ORDER BY starts_at ASC, id ASC", + from.as_millis() + ) + .fetch_all(db) + .await?; + Ok(slots) } pub async fn list_for_series( db: &Database, series: &SlotSeries, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM appointment_slot WHERE series = $series \ - ORDER BY starts_at ASC, id ASC", - ) - .bind(("series", series.as_str().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?) + let slots = query_as!( + AppointmentSlot, + "SELECT id AS \"id: AppointmentSlotId\", teacher AS \"teacher: UserId\", starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\", note AS \"note: SlotNote\", \ + series AS \"series: SlotSeries\", created_at AS \"created_at: Timestamp\" \ + FROM appointment_slot WHERE series = $1 \ + ORDER BY starts_at ASC, id ASC", + series.as_str() + ) + .fetch_all(db) + .await?; + Ok(slots) } /// Shared body of both deletes: drop every named slot, but only while its @@ -208,48 +237,58 @@ pub async fn list_for_series( /// `WHERE` is the guard, which is what makes it hold against a booking /// landing in the middle of it (a separate read-then-delete could not). /// -/// All-or-nothing across the whole list: if fewer rows go than were named, -/// the transaction is thrown away, so a series never loses its free weeks -/// and keeps the booked one. Whether that shortfall was a live booking or a -/// slot that no longer exists is read off what survived — the occupied rows -/// are still there, a vanished one is not — which is the 409/404 the caller -/// used to get from a separate check. +/// Settled bookings (rejected/cancelled) of the free slots are swept first +/// so the parent delete's foreign key is never the thing that refuses. One +/// transaction, all-or-nothing across the whole list: if fewer rows go than +/// were named, the transaction is thrown away, so a series never loses its +/// free weeks and keeps the booked one. Whether that shortfall was a live +/// booking or a slot that no longer exists is read off what survived — the +/// occupied rows are still there, a vanished one is not — which is the +/// 409/404 the caller expects. pub async fn delete_free(db: &Database, ids: &[AppointmentSlotId]) -> Result<(), AppError> { - let records: Vec = ids.iter().map(|id| id.record()).collect(); - let (_, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $gone = (DELETE $slots WHERE (occupied ?? 0) = 0 RETURN BEFORE); - IF array::len($gone) != array::len($slots) { - THROW IF array::len((SELECT VALUE id FROM appointment_slot - WHERE id IN $slots)) > 0 { 'slot_occupied' } ELSE { 'slot_missing' } - }; - DELETE appointment WHERE slot IN $slots; - RETURN $gone; - COMMIT TRANSACTION;", - &[("slots".into(), records.into_value())], - &["slot_occupied", "slot_missing"], - ) - .await?; - // An aborted transaction errors every slot; only the THROW's own slot - // names the marker (the `Exam::update` treatment), and a round lost to - // a booking landing on `occupied` mid-flight is re-sent rather than - // reported (see [`transaction_with_retry`]). - let thrown = |marker: &str| { - errors - .values() - .any(|error| error.to_string().contains(marker)) - }; - if thrown("slot_occupied") { - return Err(AppError::Conflict( - "the slot has a pending or approved booking", - )); - } - if thrown("slot_missing") { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - Ok(()) + tx_with_retry(db, false, async |tx| { + // The settled bookings of the *free* slots go first; a booked slot's + // rows survive (its occupied counter excludes it from both sweeps). + sqlx::query!( + "DELETE FROM appointment a + USING appointment_slot s + WHERE a.slot = s.id AND s.id = ANY($1) AND s.occupied < 1", + ids + ) + .execute(&mut *tx) + .await?; + let gone: Vec = query_as!( + AppointmentSlotId, + "DELETE FROM appointment_slot WHERE id = ANY($1) AND occupied < 1 RETURNING id", + ids + ) + .fetch_all(&mut *tx) + .await?; + if gone.len() == ids.len() { + return Ok(()); + } + // Shortfall: distinguish "a live booking holds one" from "one was + // never there" off what still exists. + let remaining = sqlx::query!( + "SELECT count(*) AS standing FROM appointment_slot WHERE id = ANY($1)", + ids + ) + .fetch_one(&mut *tx) + .await? + .standing; + if remaining > 0 { + Err(AppError::Conflict( + "the slot has a pending or approved booking", + )) + } else { + Err(AppError::NotFound) + } + }) + .await } + +// The overlap probe behind the old publish guard — `conflicts_existing` — +// is gone as a *decision*: the exclusion constraint decides overlap at +// insert time. The service layer still reads [`windows_in_span`] ahead of a +// weekly publish so its precise refusal texts survive; a racing writer that +// slips past any read answers to the constraint. diff --git a/src/db/attendance.rs b/src/db/attendance.rs index 8f481c1..9460044 100644 --- a/src/db/attendance.rs +++ b/src/db/attendance.rs @@ -1,41 +1,24 @@ -//! The `attendance` table: event roll call. Every write is a single -//! transaction whose gates ride inside it (the event-existence proof), so -//! the whole module is the persistence half; the workflow that decides it -//! lives in [`crate::service::attendance`]. +//! The `attendance` table: event roll call. Every write is one guarded +//! statement whose gates ride inside it, so the whole module is the +//! persistence half; the workflow that decides it lives in +//! [`crate::service::attendance`]. -use surrealdb::types::SurrealValue; - -use crate::constant::REGISTRATION_COUNT_FIELD; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, foreign_key_violation}; use crate::db::page::PagedList; -use crate::domain::attendance::{Attendance, AttendanceId, AttendanceStatus}; +use crate::domain::attendance::{Attendance, AttendanceStatus}; use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; -/// Record (or overwrite) `user`'s status for `event`. One row per (event, -/// user), keyed by a deterministic composite id so this is a single atomic -/// UPSERT — concurrent marks for the same pair can no longer both insert and -/// collide on the unique index (a 500); they converge on the one row. -/// -/// The event's existence is proved *inside* the write, the twin of the gate -/// in [`crate::db::session_attendance::mark`]: the handler's event read sits -/// several round trips in front of this, so a bare upsert left a mark on an -/// event [`crate::domain::event::Event`]'s cascade -/// (`DELETE attendance WHERE event = $ev`) had already swept — counted -/// forever in `GET /attendance/{user}` on an event no page shows. Reading -/// the event here would not have closed it either: SurrealDB 3.2.3 -/// conflict-checks write sets, not read sets, so the proof has to *move* a -/// value on the event row. It is the bump-and-restore of -/// [`crate::domain::exam_answer::ExamAnswer::save`], on the counter the -/// event already carries: matching nothing is the existence gate, writing -/// the key the delete removes is the collision, and the restore is by -/// captured value (`NONE` included) so no seat is spent or freed. +/// Record (or overwrite) `user`'s status for `event`. The pair is the +/// table's primary key, so this is a single atomic upsert — concurrent +/// marks for the same pair converge on the one row instead of racing. /// -/// Admissible for [`transaction_with_retry`]: no statement can answer -/// "already exists" — the `UPSERT`'s composite id is bijective with the -/// `attendance_event_user` unique tuple, so it resolves onto the row it -/// names instead of colliding with it. +/// The event's existence is proved by the foreign key itself: a mark naming +/// an event whose row is gone is refused `23503`, mapped to the same 404 the +/// old existence-proof transaction produced. No bump-and-restore trick, no +/// retry loop — one statement decides. pub async fn mark( db: &Database, event: &EventId, @@ -43,52 +26,28 @@ pub async fn mark( status: AttendanceStatus, marked_by: &UserId, ) -> Result { - let attendance = Attendance { - id: AttendanceId::composite(event, user), - event: event.clone(), - user: user.clone(), - status, - marked_by: marked_by.clone(), - }; - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $was = (SELECT VALUE {REGISTRATION_COUNT_FIELD} FROM ONLY $ev); - LET $alive = (UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = - ({REGISTRATION_COUNT_FIELD} ?? 0) + 1 RETURN VALUE id); - IF array::len($alive) = 0 {{ THROW 'event_missing' }}; - UPDATE $ev SET {REGISTRATION_COUNT_FIELD} = $was; - LET $after = (UPSERT $id CONTENT $row RETURN AFTER); - RETURN $after; - COMMIT TRANSACTION;" - ), - &[ - ("ev".into(), event.record().into_value()), - ("id".into(), attendance.id.record().into_value()), - ("row".into(), attendance.into_value()), - ], - &["event_missing"], + match query_as!( + Attendance, + "INSERT INTO attendance (event, app_user, status, marked_by) + VALUES ($1, $2, $3, $4) + ON CONFLICT (event, app_user) DO UPDATE SET status = $3, marked_by = $4 + RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ + status, marked_by AS \"marked_by: UserId\"", + event.uuid(), + user.uuid(), + status.as_str(), + marked_by.uuid() ) - .await?; - // An aborted transaction errors every slot and only the THROW's own - // slot names the marker. - if errors - .values() - .any(|error| error.to_string().contains("event_missing")) + .fetch_one(db) + .await { - return Err(AppError::NotFound); + Ok(row) => Ok(row), + // The event row is gone: exactly today's "no such event" refusal. + // (The other foreign keys name users the routes already authenticated; + // a violation there stays a database error, as before.) + Err(err) if foreign_key_violation(&err) => Err(AppError::NotFound), + Err(err) => Err(err.into()), } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The trailing `RETURN` is always the last statement before `COMMIT`. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to mark attendance".into())) } pub async fn list_for_event( @@ -97,21 +56,33 @@ pub async fn list_for_event( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("attendance WHERE event = $ev", "ORDER BY id DESC") - .bind("ev", event.record()) - .run(limit, offset, db) - .await + // The composite key's text form ordered the old listing; on the natural + // key that order is (event, then user). + PagedList::new( + "attendance WHERE event = $1", + "ORDER BY event DESC, app_user DESC", + ) + .bind(event.uuid()) + .run(limit, offset, db) + .await } /// Every event-attendance row recorded for `user` — the events half of the /// attendance report. pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM attendance WHERE user = $usr ORDER BY id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let rows = query_as!( + Attendance, + "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \ + status AS \"status: AttendanceStatus\", \ + marked_by AS \"marked_by: UserId\" \ + FROM attendance + WHERE app_user = $1 + ORDER BY event DESC, app_user DESC", + user.uuid() + ) + .fetch_all(db) + .await?; + Ok(rows) } pub async fn remove( @@ -119,13 +90,18 @@ pub async fn remove( event: &EventId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("DELETE attendance WHERE event = $ev AND user = $usr RETURN BEFORE") - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let gone = query_as!( + Attendance, + "DELETE FROM attendance WHERE event = $1 AND app_user = $2 + RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", \ + status AS \"status: AttendanceStatus\", \ + marked_by AS \"marked_by: UserId\"", + event.uuid(), + user.uuid() + ) + .fetch_optional(db) + .await?; + Ok(gone) } #[cfg(test)] diff --git a/src/db/chatbot_message.rs b/src/db/chatbot_message.rs index 4830a7b..8b59f38 100644 --- a/src/db/chatbot_message.rs +++ b/src/db/chatbot_message.rs @@ -4,48 +4,68 @@ //! flight. The task that owns the bridge round trip then flips it to //! `complete` (with the text) or `failed` (with a code), and the boot sweep //! in `database.rs` fails whatever a process death left behind past the -//! staleness window. Every turn is written *through* its thread's own row -//! ([`touch_and_write`]), so a turn can never outlive the thread it belongs -//! to. The row shape lives in [`crate::domain::chatbot_message`]. - -use surrealdb::types::SurrealValue; +//! staleness window. Every turn is written *through* its thread's own row — +//! its guarded statement bumps `updated_at`, so a turn can never outlive +//! the thread it belongs to. The row shape lives in +//! [`crate::domain::chatbot_message`]. use crate::constant::MAX_ERROR_CODE_LEN; use crate::database::Database; -use crate::db::chatbot_thread::touch_and_write; use crate::db::page::PagedList; use crate::domain::chatbot_message::{ - ChatContent, ChatbotMessage, ChatbotMessageId, MessageStatus, + ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus, }; use crate::domain::chatbot_thread::ChatbotThreadId; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; -/// Write one turn *through its thread's own row* ([`touch_and_write`]), -/// which is what makes the thread's existence something this write writes -/// rather than something the caller read and then trusted: a -/// [`delete`](crate::db::chatbot_thread::delete) -/// racing it touches the very key this transaction moves, so the two cannot -/// both commit and no turn is left under a thread that is gone. It also +/// Write one turn *through its thread's own row*: the thread's activity +/// bump and the turn's insert are a single guarded statement, which is what +/// makes the thread's existence something this write writes rather than +/// something the caller read and then trusted — a +/// [`delete`](crate::db::chatbot_thread::delete) racing it touches the very +/// row this statement's gate updates, so under Postgres's row locking the +/// two serialize and no turn is left under a thread that is gone. It also /// carries the thread's activity stamp, so a turn and its `updated_at` land -/// together. +/// together. The stamp is written strictly upwards — +/// `GREATEST($now, updated_at + 1)` — because a turn's two rows routinely +/// land inside one millisecond and `updated_at` is the thread list's +/// ordering key. /// /// [`AppError::NotFound`] = the thread is gone, and nothing was written. async fn insert(db: &Database, message: ChatbotMessage) -> Result { - let thread = message.thread_id.clone(); - let id = message.id.record(); - touch_and_write( - db, - &thread, - "CREATE $id CONTENT $row RETURN AFTER", - vec![ - ("id".into(), id.into_value()), - ("row".into(), message.into_value()), - ], + let inserted = query_as!( + ChatbotMessage, + "WITH touch AS ( + UPDATE chatbot_thread SET updated_at = GREATEST($2, updated_at + 1) + WHERE id = $1 + RETURNING 1) + INSERT INTO chatbot_message (id, thread_id, user_id, role, content, status, \ + truncated, error_code, created_at, completed_at) + SELECT $3, $1, $4, $5, $6, $7, $8, $9, $10, $11 + WHERE EXISTS (SELECT 1 FROM touch) + RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"", + message.get_thread_id().uuid(), + Timestamp::now().as_millis(), + message.get_id().uuid(), + message.user_id.uuid(), + message.role.as_str(), + message.content.as_str(), + message.status.as_str(), + message.truncated, + message.error_code, + message.created_at.as_millis(), + message.completed_at.map(|t| t.as_millis()), ) - .await? - .ok_or_else(|| AppError::Internal("failed to create chat message".into())) + .fetch_optional(db) + .await?; + inserted.ok_or_else(|| AppError::Internal("failed to create chat message".into())) } /// Append the user's prompt. Nothing is awaited for it, so it is born @@ -109,10 +129,10 @@ pub async fn list_for_thread( offset: i64, ) -> Result<(Vec, i64), AppError> { let (rows, total) = PagedList::new( - "chatbot_message WHERE thread_id = $conv", + "chatbot_message WHERE thread_id = $1", "ORDER BY created_at ASC, id ASC", ) - .bind("conv", thread.record()) + .bind(thread.uuid()) .run::(limit, offset, db) .await?; Ok(( @@ -129,20 +149,20 @@ pub async fn list_tail( thread: &ChatbotThreadId, limit: usize, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv \ - ORDER BY created_at DESC, id DESC LIMIT $limit", - ) - .bind(("conv", thread.record())) - .bind(("limit", limit as i64)) - .await? - .check()?; - let mut messages: Vec = result - .take::>(0)? - .into_iter() - .map(ChatbotMessage::projected) - .collect(); + let mut messages: Vec = query_as!( + ChatbotMessage, + "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ + FROM chatbot_message WHERE thread_id = $1 \ + ORDER BY created_at DESC, id DESC LIMIT $2", + thread.uuid(), + limit as i64 + ) + .fetch_all(db) + .await?; messages.reverse(); Ok(messages) } @@ -158,17 +178,21 @@ pub async fn list_settled_tail( thread: &ChatbotThreadId, limit: usize, ) -> Result, AppError> { - let mut result = db - .query( - "SELECT * FROM chatbot_message WHERE thread_id = $conv \ - AND status = 'complete' AND content != '' \ - ORDER BY created_at DESC, id DESC LIMIT $limit", - ) - .bind(("conv", thread.record())) - .bind(("limit", limit as i64)) - .await? - .check()?; - let mut messages: Vec = result.take(0)?; + let mut messages: Vec = query_as!( + ChatbotMessage, + "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ + FROM chatbot_message WHERE thread_id = $1 \ + AND status = 'complete' AND content <> '' \ + ORDER BY created_at DESC, id DESC LIMIT $2", + thread.uuid(), + limit as i64 + ) + .fetch_all(db) + .await?; messages.reverse(); Ok(messages) } @@ -185,7 +209,19 @@ pub async fn prompt_of( db: &Database, id: &ChatbotMessageId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let message = query_as!( + ChatbotMessage, + "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ + FROM chatbot_message WHERE id = $1", + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(message) } /// Read one turn only if `user` owns it — the poll loop's read. @@ -194,7 +230,18 @@ pub async fn read_for( id: &ChatbotMessageId, user: &UserId, ) -> Result, AppError> { - let message: Option = db.select(id.record()).await?; + let message = query_as!( + ChatbotMessage, + "SELECT id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\" \ + FROM chatbot_message WHERE id = $1", + id.uuid() + ) + .fetch_optional(db) + .await?; Ok(message .filter(|message| &message.user_id == user) .map(ChatbotMessage::projected)) @@ -236,29 +283,27 @@ async fn settle( } else { MessageStatus::Failed }; - let mut result = db - .query( - "UPDATE $id SET content = $content, status = $status, truncated = $truncated, \ - error_code = $code, completed_at = $now WHERE status = 'pending' RETURN AFTER", - ) - .bind(("id", id.record())) - .bind(("content", text.map(|t| t.0).unwrap_or_default())) - .bind(("status", status.as_str().to_string())) - .bind(("truncated", truncated)) - .bind(( - "code", - error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::()), - )) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let settled = query_as!( + ChatbotMessage, + "UPDATE chatbot_message SET content = $2, status = $3, truncated = $4, \ + error_code = $5, completed_at = $6 \ + WHERE id = $1 AND status = 'pending' \ + RETURNING id AS \"id: ChatbotMessageId\", thread_id AS \"thread_id: ChatbotThreadId\", \ + user_id AS \"user_id: UserId\", role AS \"role: MessageRole\", content AS \"content: ChatContent\", \ + status AS \"status: MessageStatus\", truncated, \ + error_code AS \"error_code: String\", \ + created_at AS \"created_at: Timestamp\", completed_at AS \"completed_at: Timestamp\"", + id.uuid(), + text.map(|t| t.as_str().to_string()).unwrap_or_default(), + status.as_str(), + truncated, + error_code.map(|code| code.chars().take(MAX_ERROR_CODE_LEN).collect::()), + Timestamp::now().as_millis(), + ) + .fetch_optional(db) + .await?; + settled.ok_or(AppError::NotFound) } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/chatbot_thread.rs b/src/db/chatbot_thread.rs index f471b3c..f020d18 100644 --- a/src/db/chatbot_thread.rs +++ b/src/db/chatbot_thread.rs @@ -4,142 +4,67 @@ //! [`crate::domain::chatbot_thread`]; this module is where their rows are //! read and written. -use surrealdb::types::{SurrealValue, Value}; - -use crate::constant::{ - CHATBOT_THREAD_COUNT_FIELD, DEFAULT_MAX_CHATBOT_THREADS, SETTINGS_KEY, SETTINGS_TABLE, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::cap; +use crate::constant::DEFAULT_MAX_CHATBOT_THREADS; +use crate::database::{Database, tx_with_retry}; use crate::db::page::PagedList; use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; - -/// Move the thread's `updated_at` **and** run `statement` — a write to a turn -/// hanging off that thread — in one transaction, handing back the row it -/// returned. [`AppError::NotFound`] means the thread is gone and `statement` -/// wrote nothing. -/// -/// The bump is what ties a turn's fate to its thread, and reading the thread -/// first does not: [`delete`] sweeps `chatbot_message` and drops -/// the thread in one transaction, so a create landing after that sweep but -/// before its commit reads a thread that is still there (uncommitted) while the -/// sweep ran on a snapshot predating the new row — both commit, and the turn -/// outlives the thread it was deleted with, readable and deletable by nothing. -/// Reads do not conflict; only a write that *moves* a value on a key the delete -/// also writes does. That is the shape -/// [`bump_menu_and_write`](crate::domain::menu::bump_menu_and_write) and -/// [`ExamAnswer::save`](crate::domain::exam_answer::ExamAnswer::save) already -/// use, and the sweep's ordering inside the delete stops mattering once it is -/// in place. -/// -/// `updated_at` is the value moved, and it doubles as the stamp the thread list -/// sorts on — this *is* the activity touch the send path used to issue -/// afterwards as a separate, best-effort query whose failure was only logged. -/// It is written strictly upwards rather than to `$now`: an `UPDATE` that -/// leaves the document unchanged is elided and never reaches the store's write -/// set, a turn's two rows are routinely written inside one millisecond, and a -/// write that does not happen collides with nothing. The stamp can therefore -/// sit a few milliseconds ahead of the clock, which an ordering key does not -/// care about. -/// -/// Admissible for [`transaction_with_retry`] as long as `statement` is: the -/// `UPDATE`, the `IF`/`THROW` and the `RETURN` can never answer "already -/// exists", and neither can a `CREATE` on a freshly minted ULID on a table with -/// no `UNIQUE` index — no rival can have aimed at it, and a lost round wrote -/// nothing, so re-sending it is the recovery. -pub(crate) async fn touch_and_write( - db: &Database, - thread: &ChatbotThreadId, - statement: &str, - mut bindings: Vec<(String, Value)>, -) -> Result, AppError> { - bindings.push(("conv".into(), thread.record().into_value())); - bindings.push(("now".into(), Timestamp::now().as_millis().into_value())); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $touched = (UPDATE $conv SET updated_at = \ - math::max([$now, updated_at + 1]) RETURN VALUE id); - IF array::len($touched) = 0 {{ THROW 'no_thread' }}; - LET $row = ({statement}); - RETURN $row; - COMMIT TRANSACTION;" - ), - &bindings, - &["no_thread"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic "not - // executed" — only the THROW's own slot names the reason. - if errors - .values() - .any(|error| error.to_string().contains("no_thread")) - { - return Err(AppError::NotFound); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the LET, the IF and the second LET: the RETURN is 4. - Ok(result.take::>(4)?.into_iter().next()) -} +use sqlx::query_as; /// Start a thread unless `user` is already at the school's -/// `max_chatbot_threads`. The slot is taken on the user row in the same -/// transaction as the thread ([`cap::claim_live_and_create`]) — an atomic -/// single-record write, so two requests racing the same user's last slot -/// cannot both win and the counter can never count a row that did not -/// commit. +/// `max_chatbot_threads`. The claim recipe of one: the slot bump on the +/// user row, the live cap read, and the thread's insert are a single +/// statement — two requests racing the same user's last slot cannot both +/// win, and the counter can never count a row that did not commit. /// /// The cap is the one *live* on the settings singleton, sub-queried inside /// that same conditional write rather than bound as a number: this cap does /// not live on the parent row (the seat is on the user, the limit is the /// school's), and a snapshot of it admits every request already in flight -/// when a `PATCH /settings` lowers it. The subquery costs one extra record -/// read per claim on a path that already reads the row it writes. -/// `DEFAULT_MAX_CHATBOT_THREADS` is the fallback the settings row's own -/// absent column means — no row, or a school that never set the knob. +/// when a `PATCH /settings` lowers it. `DEFAULT_MAX_CHATBOT_THREADS` is the +/// fallback the settings row's own NULL means — no row, or a school that +/// never set the knob. +/// +/// The seat is taken on the user's own row, which is also the key a role +/// change writes, so this write already contends with a demotion — no +/// separate holder claim is needed. pub async fn create_capped( db: &Database, user: &UserId, title: Option, ) -> Result { let now = Timestamp::now(); - let thread = ChatbotThread { - id: ChatbotThreadId::generate(), - user_id: user.clone(), - title, - created_at: now, - updated_at: now, - }; - match cap::claim_live_and_create( - &user.record(), - CHATBOT_THREAD_COUNT_FIELD, - &format!( - "(SELECT VALUE max_chatbot_threads FROM ONLY {SETTINGS_TABLE}:{SETTINGS_KEY}) ?? $num" - ), + match query_as!( + ChatbotThread, + "WITH seat AS ( + UPDATE app_user SET chatbot_thread_count = chatbot_thread_count + 1 + WHERE id = $1 + AND chatbot_thread_count < COALESCE( + (SELECT max_chatbot_threads FROM settings WHERE id = 'school'), + $2) + RETURNING 1) + INSERT INTO chatbot_thread (id, user_id, title AS \"title: ChatbotThreadTitle\", created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\") + SELECT $3, $1, $4, $5, $5 + WHERE EXISTS (SELECT 1 FROM seat) + RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + user.uuid(), DEFAULT_MAX_CHATBOT_THREADS, - // No holder claim: the parent row *is* the user's, so this write - // already lands on the key a role change writes. - None, - (&thread.id.record(), &thread), - db, + ChatbotThreadId::generate().uuid(), + title.map(|t| t.as_str().to_string()), + now.as_millis(), ) + .fetch_optional(db) .await? { - cap::Claimed::Made(saved) => Ok(saved), + Some(saved) => Ok(saved), // Full, or the user's row is gone — the conditional write matches - // nothing either way. - cap::Claimed::Full => Err(AppError::Conflict( + // nothing either way, as before. + None => Err(AppError::Conflict( "you have reached the school's limit on saved threads — delete one first", )), - // The id is a freshly minted ULID on a table with no UNIQUE index, - // so no rival can have aimed at it. - cap::Claimed::Duplicate => Err(AppError::Internal("thread id collided".into())), } } @@ -152,27 +77,23 @@ pub async fn list_for_user( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "chatbot_thread WHERE user_id = $usr", + "chatbot_thread WHERE user_id = $1", "ORDER BY updated_at DESC, id DESC", ) - .bind("usr", user.record()) + .bind(user.uuid()) .run(limit, offset, db) .await } /// How many threads `user` keeps — the `max_chatbot_threads` cap check. pub async fn count_for_user(db: &Database, user: &UserId) -> Result { - let mut result = db - .query("SELECT VALUE count() FROM chatbot_thread WHERE user_id = $usr GROUP ALL") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .first() - .copied() - .unwrap_or_default() - .max(0) as usize) + let row = sqlx::query!( + "SELECT count(*) AS threads FROM chatbot_thread WHERE user_id = $1", + user.uuid() + ) + .fetch_one(db) + .await?; + Ok(row.threads.unwrap_or(0).max(0) as usize) } /// Read a thread only if `user` owns it — a foreign id reads as absent, so @@ -182,75 +103,93 @@ pub async fn read_for( id: &ChatbotThreadId, user: &UserId, ) -> Result, AppError> { - let thread: Option = db.select(id.record()).await?; + let thread = query_as!( + ChatbotThread, + "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", + id + ) + .fetch_optional(db) + .await?; Ok(thread.filter(|thread| &thread.user_id == user)) } -// Stamping new activity is not a call of its own: it is the bump inside -// [`touch_and_write`], which every turn already rides, so a stamp can no -// longer be lost (it used to be a best-effort query after the two creates, -// whose failure was a `warn!`) and no turn can be written without it. +// Stamping new activity is not a call of its own: it is the monotonic bump +// inside every write that touches the thread (a turn's insert, the rename, +// the delete below), so a stamp can no longer be lost (it used to be a +// best-effort query after the two creates, whose failure was a `warn!`) and +// no turn can be written without it. /// Rename the thread (`None` clears the name back to untitled), stamping -/// the edit as activity. Field-scoped for the same reason as -/// [`touch_and_write`]: a turn may be landing concurrently. +/// the edit as activity. Field-scoped: a turn may be landing concurrently. +/// The stamp is written strictly upwards — `GREATEST($now, updated_at + 1)` +/// — because a thread's writes routinely land inside one millisecond and +/// `updated_at` is the list's ordering key; the stamp may sit a few +/// milliseconds ahead of the clock, which an ordering key does not care +/// about. Zero rows: the thread is gone, the same 404 the delete answers. pub async fn rename( db: &Database, thread: &ChatbotThread, title: Option, ) -> Result { - let mut result = db - .query("UPDATE $id SET title = $title, updated_at = $now RETURN AFTER") - .bind(("id", thread.id.record())) - .bind(("title", title.map(|title| title.0))) - .bind(("now", Timestamp::now().as_millis())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let updated = query_as!( + ChatbotThread, + "UPDATE chatbot_thread SET title = $2, updated_at = GREATEST($3, updated_at + 1) \ + WHERE id = $1 \ + RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title AS \"title: ChatbotThreadTitle\", \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + thread.get_id().uuid(), + title.map(|t| t.as_str().to_string()), + Timestamp::now().as_millis(), + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) } /// Delete the thread and every turn in it — one transaction, so a crash /// can't orphan messages under a vanished thread. The owner's slot comes /// back in that same transaction, or the cap would ratchet shut. /// -/// A turn, a rename and this delete all write the thread row (see -/// [`touch_and_write`]), so the store aborting one of them is ordinary -/// here — that collision is exactly what keeps a turn from outliving the -/// thread — and a lost round is re-sent rather than reported as the `500` -/// it used to be. Re-sending is sound: every statement is a `DELETE` or a -/// field-scoped `UPDATE`, none of which can ever answer "already exists" -/// (see [`transaction_with_retry`]). On the re-sent round the thread is -/// already gone, so the `RETURN` is empty and the caller gets the `404` -/// that is the truth. +/// A turn's insert (see [`crate::db::chatbot_message`]) writes *through* +/// the thread's row — its guarded statement moves `updated_at`, the key +/// this delete's final write removes — so under Postgres's row locking the +/// two serialize: either the turn saw the thread and committed first (the +/// delete then refuses nothing, the sweep takes the turn), or the thread +/// was gone and the turn's gate matched nothing. No turn outlives its +/// thread. On a re-sent round the thread is already gone, so the caller +/// gets the `404` that is the truth. pub async fn delete(db: &Database, thread: ChatbotThread) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE chatbot_message WHERE thread_id = $conv; - LET $gone = (DELETE $conv RETURN BEFORE); - UPDATE $usr SET chatbot_thread_count = math::max([(chatbot_thread_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", - &[ - ("conv".into(), thread.id.record().into_value()), - ("usr".into(), thread.user_id.record().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Slots count BEGIN, the cascade, the LET and the UPDATE: the RETURN - // is slot 4. - let deleted: Option = result.take::>(4)?.into_iter().next(); - deleted.ok_or(AppError::NotFound) + tx_with_retry(db, false, async |tx| { + // Children first: the foreign key would refuse the parent while a + // turn still names it. + sqlx::query!( + "DELETE FROM chatbot_message WHERE thread_id = $1", + thread.get_id().uuid() + ) + .execute(&mut *tx) + .await?; + let gone = query_as!( + ChatbotThread, + "DELETE FROM chatbot_thread WHERE id = $1 \ + RETURNING id AS \"id: ChatbotThreadId\", user_id AS \"user_id: UserId\", title, \ + created_at AS \"created_at: Timestamp\", updated_at AS \"updated_at: Timestamp\"", + thread.get_id().uuid() + ) + .fetch_optional(&mut *tx) + .await?; + if let Some(gone) = &gone { + sqlx::query!( + "UPDATE app_user SET chatbot_thread_count = GREATEST(chatbot_thread_count - 1, 0) \ + WHERE id = $1", + gone.get_user_id() + ) + .execute(&mut *tx) + .await?; + } + gone.ok_or(AppError::NotFound) + }) + .await } - #[cfg(test)] mod tests { use super::*; diff --git a/src/db/event.rs b/src/db/event.rs index 9712f73..f1c71f4 100644 --- a/src/db/event.rs +++ b/src/db/event.rs @@ -2,91 +2,108 @@ //! audience's live membership resolution — the point check behind marking //! ([`includes`]) and the who-missed report's backbone ([`members`]). -use surrealdb::types::SurrealValue; - -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; -use crate::domain::class_member::{ClassMember, ClassMemberId}; -use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; +use crate::db::page::Param; +use crate::domain::class_group::ClassGroupId; +use crate::domain::course::CourseId; +use crate::domain::event::{ + Event, EventAudience, EventAudienceKind, EventDescription, EventId, EventTitle, +}; +use crate::domain::role::Role; use crate::domain::timestamp::{Timestamp, range_error}; use crate::domain::user::{User, UserId}; use crate::error::AppError; +use sqlx::query_as; -/// Is `user` in `audience`'s roster right now? The point check behind -/// marking — cheaper than resolving the whole roster when the target is -/// known. `event` must be the event this audience came from: the -/// registration kind resolves against that event's signup rows. -pub async fn includes( - db: &Database, - audience: &EventAudience, - event: &EventId, - user: &User, -) -> Result { - match audience { - EventAudience::School => Ok(true), - EventAudience::Role { role } => Ok(user.get_role() == *role), - EventAudience::Course { course } => { - Ok( - crate::db::enrollment::read_for_user(db, course, user.get_id()) +/// Is `user` in this event's audience roster right now? The point check +/// behind marking — cheaper than resolving the whole roster when the target +/// is known. The audience comes off the row itself: the registration kind +/// resolves against that event's signup rows. +pub async fn includes(db: &Database, event: &Event, user: &User) -> Result { + match event.get_audience_kind() { + crate::domain::event::EventAudienceKind::School => Ok(true), + crate::domain::event::EventAudienceKind::Role => { + Ok(Some(user.get_role()) == event.get_audience_role()) + } + crate::domain::event::EventAudienceKind::Course => { + match event.get_audience_course() { + Some(course) => Ok(crate::db::enrollment::read_for_user(db, course, user.get_id()) .await? - .is_some(), - ) + .is_some()), + None => Ok(false), + } } - // The (class, user) pair is the membership row's own id, so the - // point check is a single select — no scan, no index needed. - EventAudience::Class { class } => { - let member: Option = db - .select(ClassMemberId::composite(class, user.get_id()).record()) + // The (class, user) pair is the membership row's own primary key, so + // the point check is one existence probe — no scan, no index needed. + crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { + Some(class) => { + let row = sqlx::query!( + "SELECT EXISTS(SELECT 1 FROM class_member WHERE class = $1 AND app_user = $2) + AS present", + class.uuid(), + user.get_id().uuid() + ) + .fetch_one(db) .await?; - Ok(member.is_some()) - } - EventAudience::Registration { .. } => { - Ok(crate::db::registration::read_for_user(db, event, user.get_id()) + Ok(row.present) + } + None => Ok(false), + }, + crate::domain::event::EventAudienceKind::Registration => { + Ok(crate::db::registration::read_for_user(db, event.get_id(), user.get_id()) .await? .is_some()) } } } -/// `event`'s full roster, as it stands right now — the who-missed +/// The event's full roster, as it stands right now — the who-missed /// report's backbone. Registered ids that no longer resolve to a user row /// are kept; the caller degrades their display like any stale reference. -pub async fn members( - db: &Database, - audience: &EventAudience, - event: &EventId, -) -> Result, AppError> { - match audience { - EventAudience::School => Ok(crate::db::user::list_all(db, None, 0) +pub async fn members(db: &Database, event: &Event) -> Result, AppError> { + match event.get_audience_kind() { + crate::domain::event::EventAudienceKind::School => Ok(crate::db::user::list_all(db, None, 0) .await? .0 .iter() .map(|user| user.get_id().clone()) .collect()), - EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role) - .await? - .iter() - .map(|user| user.get_id().clone()) - .collect()), - EventAudience::Course { course } => { - Ok(crate::db::enrollment::list_for_course(db, course, None, 0) + crate::domain::event::EventAudienceKind::Role => { + match event.get_audience_role() { + Some(role) => Ok(crate::db::user::list_by_role(db, role) + .await? + .iter() + .map(|user| user.get_id().clone()) + .collect()), + None => Ok(Vec::new()), + } + } + crate::domain::event::EventAudienceKind::Course => match event.get_audience_course() { + Some(course) => Ok(crate::db::enrollment::list_for_course(db, course, None, 0) .await? .0 .iter() .map(|enrollment| enrollment.get_user().clone()) + .collect()), + None => Ok(Vec::new()), + }, + crate::domain::event::EventAudienceKind::Class => match event.get_audience_class() { + Some(class) => Ok(crate::db::class_member::list_for_class(db, class, None, 0) + .await? + .0 + .iter() + .map(|member| member.get_user().clone()) + .collect()), + None => Ok(Vec::new()), + }, + crate::domain::event::EventAudienceKind::Registration => { + Ok(crate::db::registration::list_for_event(db, event.get_id()) + .await? + .iter() + .map(|registration| registration.get_user().clone()) .collect()) } - EventAudience::Class { class } => Ok(crate::db::class_member::list_for_class(db, class, None, 0) - .await? - .0 - .iter() - .map(|member| member.get_user().clone()) - .collect()), - EventAudience::Registration { .. } => Ok(crate::db::registration::list_for_event(db, event) - .await? - .iter() - .map(|registration| registration.get_user().clone()) - .collect()), } } @@ -99,29 +116,70 @@ pub async fn create( starts_at: Option, ends_at: Option, ) -> Result { - let event = Event { - id: EventId::generate(), - creator: creator.clone(), - title, - description, - audience, - starts_at, - ends_at, - }; - let created: Option = db.create(event.id.record()).content(event).await?; - created.ok_or_else(|| AppError::Internal("failed to create event".into())) + // The audience payload moves as one unit with its kind; the validated + // bundle guarantees only the matching payload is ever non-NULL. + let created = query_as!( + Event, + "INSERT INTO event (id, creator, title AS \"title: EventTitle\", description AS \"description: EventDescription\", audience_kind, audience_role, \ + audience_course, audience_class, audience_capacity, starts_at, ends_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) + RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ + audience_kind AS \"audience_kind: EventAudienceKind\", \ + audience_role AS \"audience_role: Role\", \ + audience_course AS \"audience_course: CourseId\", \ + audience_class AS \"audience_class: ClassGroupId\", \ + audience_capacity, starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\"", + EventId::generate().uuid(), + creator.uuid(), + title.as_str(), + description.as_str(), + audience.kind, + audience.role.map(|r| r.as_str().to_string()), + audience.course.map(|c| c.uuid()), + audience.class.map(|c| c.uuid()), + audience.capacity, + starts_at.map(|t| t.as_millis()), + ends_at.map(|t| t.as_millis()), + ) + .fetch_one(db) + .await?; + Ok(created) } pub async fn read(db: &Database, id: &EventId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let event = query_as!( + Event, + "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ + audience_kind AS \"audience_kind: EventAudienceKind\", \ + audience_role AS \"audience_role: Role\", \ + audience_course AS \"audience_course: CourseId\", \ + audience_class AS \"audience_class: ClassGroupId\", \ + audience_capacity, starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\" \ + FROM event WHERE id = $1", + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(event) } pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM event ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) + let events = query_as!( + Event, + "SELECT id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ + audience_kind AS \"audience_kind: EventAudienceKind\", \ + audience_role AS \"audience_role: Role\", \ + audience_course AS \"audience_course: CourseId\", \ + audience_class AS \"audience_class: ClassGroupId\", \ + audience_capacity, starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\" \ + FROM event ORDER BY id DESC", + ) + .fetch_all(db) + .await?; + Ok(events) } /// 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, AppError> { /// alone does not prevent that, the values have to come from the request. /// The schedule columns are nullable, so they take the outer/inner /// `Option>`: `None` = omitted (keep), `Some(None)` = clear. +/// +/// The audience is five columns moving as one unit: when the request +/// carries an audience, all five are written (the non-matching payload as +/// NULL); when it carries none, none are. pub async fn update( db: &Database, event: Event, @@ -140,12 +202,47 @@ pub async fn update( starts_at: Option>, ends_at: Option>, ) -> Result { - FieldUpdate::new(event.id.record()) - .set("title", title) - .set("description", description) - .set("audience", audience) - .set("starts_at", starts_at) - .set("ends_at", ends_at) + FieldUpdate::new("event", event.get_id().uuid()) + .set( + "title", + title.map(|title| Param::Text(title.as_str().to_string())), + ) + .set( + "description", + description.map(|d| Param::Text(d.as_str().to_string())), + ) + .set( + "audience_kind", + audience + .as_ref() + .map(|a| Param::Text(a.kind.as_str().to_string())), + ) + .set( + "audience_role", + audience + .as_ref() + .map(|a| Param::OptText(a.role.map(|r| r.as_str().to_string()))), + ) + .set( + "audience_course", + audience.as_ref().map(|a| Param::OptUuid(a.course.map(|c| c.uuid()))), + ) + .set( + "audience_class", + audience.as_ref().map(|a| Param::OptUuid(a.class.map(|c| c.uuid()))), + ) + .set( + "audience_capacity", + audience.as_ref().map(|a| Param::OptI64(a.capacity)), + ) + .set( + "starts_at", + starts_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))), + ) + .set( + "ends_at", + ends_at.map(|at| Param::OptI64(at.map(|at| at.as_millis()))), + ) .ordered("starts_at", "ends_at", range_error()) .run::(db) .await @@ -153,44 +250,42 @@ pub async fn update( /// Delete the event and cascade-remove its attendance and signup rows. /// -/// Children first, and all of it in one transaction the way -/// [`crate::db::course::delete`] does it: run as two queries, a -/// registration or a mark that committed in between outlived its event — -/// an orphan no read path can ever reach and no delete can ever reclaim, -/// since every one of them is keyed on the event that is now gone. +/// Children first, all of it in one guarded transaction: run as separate +/// statements, a registration or a mark committing in between would outlive +/// its event — an orphan no read path can ever reach and no delete can ever +/// reclaim, since every one of them is keyed on the event that is now gone. /// -/// Re-sent while the store answers "conflict, retry", the way -/// [`crate::db::course_session::delete`] is: now that -/// [`crate::domain::attendance::Attendance::mark`] writes the event row to -/// prove it exists, a mark landing in this window really does contend for -/// it — and without the retry the *delete* is the side that loses, turning -/// a race the store resolved correctly into a 500 (measured 4 rounds in 4). -/// Admissible: every statement is a `DELETE`, which can never answer -/// "already exists", and a lost round wrote nothing. +/// `cascade` retry: a mark landing while the cascade is in flight contends +/// for the event row (its insert's foreign key proves the event the moment +/// it lands), so a lost round re-sends instead of answering 500. pub async fn delete(db: &Database, event: Event) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE attendance WHERE event = $ev; - DELETE registration WHERE event = $ev; - LET $gone = (DELETE $ev RETURN BEFORE); - RETURN $gone; - COMMIT TRANSACTION;", - &[("ev".into(), event.id.record().into_value())], - // No THROW of its own — an unconditional cascade. - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, never a hand-counted slot. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + tx_with_retry(db, true, async |tx| { + sqlx::query!("DELETE FROM attendance WHERE event = $1", event.get_id().uuid()) + .execute(&mut *tx) + .await?; + sqlx::query!( + "DELETE FROM registration WHERE event = $1", + event.get_id().uuid() + ) + .execute(&mut *tx) + .await?; + let gone = query_as!( + Event, + "DELETE FROM event WHERE id = $1 \ + RETURNING id AS \"id: EventId\", creator AS \"creator: UserId\", title AS \"title: EventTitle\", description AS \"description: EventDescription\", \ + audience_kind AS \"audience_kind: EventAudienceKind\", \ + audience_role AS \"audience_role: Role\", \ + audience_course AS \"audience_course: CourseId\", \ + audience_class AS \"audience_class: ClassGroupId\", \ + audience_capacity, starts_at AS \"starts_at: Timestamp\", \ + ends_at AS \"ends_at: Timestamp\"", + event.get_id().uuid() + ) + .fetch_optional(&mut *tx) + .await?; + gone.ok_or(AppError::NotFound) + }) + .await } #[cfg(test)] diff --git a/src/db/message.rs b/src/db/message.rs index 1bd1aa9..ec62ef1 100644 --- a/src/db/message.rs +++ b/src/db/message.rs @@ -4,13 +4,14 @@ //! [`crate::domain::message`]. use crate::database::Database; -use crate::db::page::PagedList; +use crate::db::page::{PagedList, Param}; use crate::domain::message::{ Folder, Message, MessageBody, MessageId, MessageLabel, MessageSubject, }; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; pub async fn send( db: &Database, @@ -20,30 +21,40 @@ pub async fn send( body: MessageBody, label: Option, ) -> Result { - let message = Message { - id: MessageId::generate(), - sender: sender.clone(), - recipient: recipient.clone(), - subject, - body, - label, - sent_at: Timestamp::now(), - read: false, - sender_folder: Folder::Sent, - recipient_folder: Folder::Inbox, - sender_origin: None, - recipient_origin: None, - }; - let created: Option = db.create(message.id.record()).content(message).await?; - created.ok_or_else(|| AppError::Internal("failed to create message".into())) + let message = query_as!( + Message, + "INSERT INTO message (id, sender, recipient, subject, body, label, sent_at, read, \ + sender_folder, recipient_folder, sender_origin, recipient_origin) + VALUES ($1, $2, $3, $4, $5, $6, $7, false, 'sent', 'inbox', NULL, NULL) + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + MessageId::generate().uuid(), + sender.uuid(), + recipient.uuid(), + subject.as_str(), + body.as_str(), + label.map(|l| l.as_str().to_string()), + Timestamp::now().as_millis(), + ) + .fetch_one(db) + .await?; + Ok(message) } /// One folder view for `user`, newest first. `inbox` is recipient-side, /// `sent` is sender-side, and `archive`/`trash` are each the union of both /// sides' filed copies (either party may archive or trash their own copy). /// `read` narrows to that flag state (`false` on the inbox is the unread -/// view; on `sent`, receipts pending) — the folder condition is -/// parenthesized because `archive`'s and `trash`'s are ORs. +/// view; on `sent`, receipts pending). +/// +/// The folder predicates are the four closed shapes the domain's folder +/// vocabulary admits, spelled as one `WHERE` each — the same shapes the old +/// dynamic string assembled, minus the interpolation. They ride the +/// [`PagedList`] builder (the paged-list exemption), so the page and its +/// count always see the same predicate. pub async fn list_folder( db: &Database, user: &UserId, @@ -52,32 +63,34 @@ pub async fn list_folder( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - let condition = match folder { - Folder::Sent => "sender = $usr AND sender_folder = 'sent'", + let home_arm = folder == Folder::Inbox; + let mut from = match folder { + Folder::Sent => "message WHERE sender = $1 AND sender_folder = 'sent'".to_string(), Folder::Archive => { - "(recipient = $usr AND recipient_folder = 'archive') \ - OR (sender = $usr AND sender_folder = 'archive')" + "message WHERE (recipient = $1 AND recipient_folder = 'archive') \ + OR (sender = $1 AND sender_folder = 'archive')" + .to_string() } Folder::Trash => { - "(recipient = $usr AND recipient_folder = 'trash') \ - OR (sender = $usr AND sender_folder = 'trash')" + "message WHERE (recipient = $1 AND recipient_folder = 'trash') \ + OR (sender = $1 AND sender_folder = 'trash')" + .to_string() } - _ => "recipient = $usr AND recipient_folder = $folder", - }; - let read_clause = if read.is_some() { - " AND read = $read" - } else { - "" + _ => "message WHERE recipient = $1 AND recipient_folder = $2".to_string(), }; - PagedList::new( - format!("message WHERE ({condition}){read_clause}"), - "ORDER BY id DESC", - ) - .bind("usr", user.record()) - .bind("folder", folder.as_str().to_string()) - .bind("read", read.unwrap_or_default()) - .run(limit, offset, db) - .await + // The `read` filter binds after whichever placeholders the folder shape + // spent (`$1` is always the user; the home-folder arm spends `$2`). + if read.is_some() { + from.push_str(&format!(" AND read = ${}", if home_arm { 3 } else { 2 })); + } + let mut builder = PagedList::new(from, "ORDER BY id DESC").bind(user); + if home_arm { + builder = builder.bind(folder.as_str().to_string()); + } + if let Some(read) = read { + builder = builder.bind(Param::Bool(read)); + } + builder.run(limit, offset, db).await } /// Read a message only if `user` is its sender or recipient and their @@ -87,7 +100,18 @@ pub async fn read_for( id: &MessageId, user: &UserId, ) -> Result, AppError> { - let message: Option = db.select(id.record()).await?; + let message = query_as!( + Message, + "SELECT id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\" \ + FROM message WHERE id = $1", + id.uuid() + ) + .fetch_optional(db) + .await?; Ok(message.filter(|message| { (&message.sender == user || &message.recipient == user) && message.folder_of(user) != Folder::Deleted @@ -97,17 +121,20 @@ pub async fn read_for( /// Flip the recipient's read flag. Field-scoped write: the sender may be /// filing their side concurrently, and a whole-row save would clobber it. pub async fn set_read(db: &Database, message: Message, read: bool) -> Result { - let mut result = db - .query("UPDATE $id SET read = $read RETURN AFTER") - .bind(("id", message.id.record())) - .bind(("read", read)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + let updated = query_as!( + Message, + "UPDATE message SET read = $1 WHERE id = $2 \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + read, + message.get_id(), + ) + .fetch_optional(db) + .await?; + updated.ok_or(AppError::NotFound) } /// File `user`'s side into `folder` (already validated against that @@ -128,31 +155,47 @@ pub async fn move_to( folder: Folder, ) -> Result { let current = message.folder_of(user); - let (field, origin_field) = if message.is_sender(user) { - ("sender_folder", "sender_origin") - } else { - ("recipient_folder", "recipient_origin") - }; let origin = match folder { _ if !folder.is_filed() => None, _ if current == folder => message.origin_of(user), _ if current.is_restore_target() => Some(current), _ => None, }; - let mut result = db - .query(format!( - "UPDATE $id SET {field} = $folder, {origin_field} = $origin RETURN AFTER" - )) - .bind(("id", message.id.record())) - .bind(("folder", folder.as_str().to_string())) - .bind(("origin", origin.map(|origin| origin.as_str().to_string()))) + let origin = origin.map(|origin| origin.as_str().to_string()); + // One static statement per side: the field pair written is the caller's + // own, so the sender can never clobber the recipient's filing flags. + let updated = if message.is_sender(user) { + query_as!( + Message, + "UPDATE message SET sender_folder = $1, sender_origin = $2 WHERE id = $3 \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + folder.as_str(), + origin, + message.get_id().uuid(), + ) + .fetch_optional(db) + .await? + } else { + query_as!( + Message, + "UPDATE message SET recipient_folder = $1, recipient_origin = $2 WHERE id = $3 \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + folder.as_str(), + origin, + message.get_id().uuid(), + ) + .fetch_optional(db) .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::NotFound) + }; + updated.ok_or(AppError::NotFound) } /// Permanently drop `user`'s side — only if that side currently sits in @@ -162,28 +205,53 @@ pub async fn move_to( /// post-write row, so two concurrent deletes can't leak an all-deleted /// row. pub async fn delete_for(db: &Database, message: Message, user: &UserId) -> Result<(), AppError> { - let (field, origin_field) = if message.is_sender(user) { - ("sender_folder", "sender_origin") + let after = if message.is_sender(user) { + query_as!( + Message, + "UPDATE message SET sender_folder = 'deleted', sender_origin = NULL \ + WHERE id = $1 AND sender_folder = 'trash' \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + message.get_id().uuid(), + ) + .fetch_optional(db) + .await? } else { - ("recipient_folder", "recipient_origin") - }; - let mut result = db - .query(format!( - "UPDATE $id SET {field} = $deleted, {origin_field} = NONE \ - WHERE {field} = $trash RETURN AFTER" - )) - .bind(("id", message.id.record())) - .bind(("deleted", Folder::Deleted.as_str().to_string())) - .bind(("trash", Folder::Trash.as_str().to_string())) + query_as!( + Message, + "UPDATE message SET recipient_folder = 'deleted', recipient_origin = NULL \ + WHERE id = $1 AND recipient_folder = 'trash' \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + message.get_id().uuid(), + ) + .fetch_optional(db) .await? - .check()?; - let Some(after) = result.take::>(0)?.into_iter().next() else { + }; + let Some(after) = after else { return Err(AppError::Conflict( "only messages in the trash can be permanently deleted", )); }; if after.sender_folder == Folder::Deleted && after.recipient_folder == Folder::Deleted { - let _: Option = db.delete(after.id.record()).await?; + query_as!( + Message, + "DELETE FROM message WHERE id = $1 \ + RETURNING id AS \"id: MessageId\", sender AS \"sender: UserId\", recipient AS \"recipient: UserId\", \ + subject, body, label AS \"label: MessageLabel\", \ + sent_at AS \"sent_at: Timestamp\", read, \ + sender_folder AS \"sender_folder: Folder\", recipient_folder AS \"recipient_folder: Folder\", \ + sender_origin AS \"sender_origin: Folder\", recipient_origin AS \"recipient_origin: Folder\"", + after.get_id().uuid(), + ) + .fetch_optional(db) + .await?; } Ok(()) } diff --git a/src/db/parent_link.rs b/src/db/parent_link.rs index 367cd34..691fcaf 100644 --- a/src/db/parent_link.rs +++ b/src/db/parent_link.rs @@ -1,12 +1,13 @@ -//! The `parent_link` table: the composite-id upsert, the existence probe, +//! The `parent_link` table: the composite-PK upsert, the existence probe, //! the per-parent listing, and the delete. The *decisions* over these rows //! — who may be tied, and which reads a live link grants — live in //! [`crate::service::parent_link`]. use crate::database::Database; -use crate::domain::parent_link::{ParentLink, ParentLinkId}; +use crate::domain::parent_link::ParentLink; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; pub async fn link( db: &Database, @@ -14,34 +15,53 @@ pub async fn link( student: &UserId, linked_by: &UserId, ) -> Result { - let link = ParentLink { - id: ParentLinkId::composite(parent, student), - parent: parent.clone(), - student: student.clone(), - linked_by: linked_by.clone(), - }; - let saved: Option = db.upsert(link.id.record()).content(link).await?; - saved.ok_or_else(|| AppError::Internal("failed to link student to parent".into())) + // The pair is the primary key, so the upsert is one atomic statement — + // no find-then-insert race to lose, and a re-link restamps `linked_by`. + let link = query_as!( + ParentLink, + "INSERT INTO parent_link (parent, student, linked_by) + VALUES ($1, $2, $3) + ON CONFLICT (parent, student) DO UPDATE SET linked_by = $3 + RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \ + linked_by AS \"linked_by: UserId\"", + parent.uuid(), + student.uuid(), + linked_by.uuid() + ) + .fetch_one(db) + .await?; + Ok(link) } /// True iff a link row exists for the (parent, student) pair — the storage /// half of the grant. The live half (the student side still holding the /// role) is [`crate::service::parent_link::links_live`]. pub async fn exists(db: &Database, parent: &UserId, student: &UserId) -> Result { - let found: Option = db - .select(ParentLinkId::composite(parent, student).record()) - .await?; - Ok(found.is_some()) + let row = sqlx::query!( + "SELECT EXISTS(SELECT 1 FROM parent_link WHERE parent = $1 AND student = $2) AS present", + parent.uuid(), + student.uuid() + ) + .fetch_one(db) + .await?; + Ok(row.present) } -/// Every student `parent` observes, newest link first. +/// Every student `parent` observes. The composite key's text form ordered +/// the old listing, which for one parent means the student ids — the same +/// order on the natural key. pub async fn list_for_parent(db: &Database, parent: &UserId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM parent_link WHERE parent = $parent ORDER BY id DESC") - .bind(("parent", parent.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let links = query_as!( + ParentLink, + "SELECT parent AS \"parent: UserId\", student AS \"student: UserId\", \ + linked_by AS \"linked_by: UserId\" \ + FROM parent_link WHERE parent = $1 + ORDER BY student DESC", + parent.uuid() + ) + .fetch_all(db) + .await?; + Ok(links) } pub async fn remove( @@ -49,11 +69,15 @@ pub async fn remove( parent: &UserId, student: &UserId, ) -> Result, AppError> { - let mut result = db - .query("DELETE parent_link WHERE parent = $parent AND student = $student RETURN BEFORE") - .bind(("parent", parent.record())) - .bind(("student", student.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let gone = query_as!( + ParentLink, + "DELETE FROM parent_link WHERE parent = $1 AND student = $2 + RETURNING parent AS \"parent: UserId\", student AS \"student: UserId\", \ + linked_by AS \"linked_by: UserId\"", + parent.uuid(), + student.uuid() + ) + .fetch_optional(db) + .await?; + Ok(gone) } diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs index f4c50b6..be86811 100644 --- a/src/db/pomodoro.rs +++ b/src/db/pomodoro.rs @@ -3,60 +3,88 @@ //! the study streak are all decided inside [`finish`]'s one transaction — //! the whole rule is the batch itself. -use surrealdb::types::SurrealValue; - use crate::constant::{ - MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD, - POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, - STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, + CAP_WRITE_TRIES, MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, }; -use crate::database::{Database, transaction_with_retry}; +use crate::database::{Database, backoff, tx_with_retry, unique_violation}; use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId}; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; -/// Start a session for `user`, stamped with the server clock. `UPSERT` on -/// the deterministic open id makes this atomic and always succeed: a -/// dangling unfinished session (the browser died mid-timer) is replaced — +/// Start a session for `user`, stamped with the server clock. The open slot +/// is the partial unique index (`pomodoro_session_open_stint`): one row per +/// user with `finished_at IS NULL`. A dangling unfinished session (the +/// browser died mid-timer) is deleted and replaced in the same statement — /// it never counted, and blocking the next start behind it would only /// punish the student for a crash. /// +/// Two racing starts cannot both insert: the index refuses the second +/// (`23505`), which is retried — the re-run deletes the winner's open row +/// and replaces it, the same last-write-wins the old deterministic-key +/// upsert had. +/// /// `label` is the student's own name for the stint, validated and trimmed -/// upstream and stored verbatim. A `None` binds NONE, which an -/// `option` field stores as absent — an unnamed start reads back -/// unnamed. +/// upstream and stored verbatim. A `None` binds NULL — an unnamed start +/// reads back unnamed. pub async fn start( db: &Database, user: &UserId, label: Option, ) -> Result { - let mut result = db - .query("UPSERT $open CONTENT { user: $usr, started_at: $at, label: $label }") - .bind(("open", PomodoroSessionId::open_for(user).record())) - .bind(("usr", user.record())) - .bind(("at", Timestamp::now())) - .bind(("label", label)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into())) + let started_at = Timestamp::now(); + let id = PomodoroSessionId::generate(); + // The statement is one atomic delete-and-replace; the only contention + // is a rival start, and the index's verdict sends the loser around + // again to overwrite. + for attempt in 0..CAP_WRITE_TRIES { + backoff(attempt).await; + let started = match query_as!( + PomodoroSession, + "WITH gone AS ( + DELETE FROM pomodoro_session + WHERE app_user = $1 AND finished_at IS NULL + RETURNING 1) + INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + SELECT $2, $1, $3, NULL, NULL, $4 + RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ + started_at AS \"started_at: Timestamp\", \ + finished_at AS \"finished_at: Timestamp\", counted, label", + user.uuid(), + id.uuid(), + started_at.as_millis(), + label + ) + .fetch_one(db) + .await + { + Ok(row) => row, + // The winner of a race holds the open slot; one more round. + Err(err) if unique_violation(&err) == Some("pomodoro_session_open_stint") => { + continue; + } + Err(err) => return Err(err.into()), + }; + return Ok(started); + } + Err(AppError::Internal( + "failed to start pomodoro session".into(), + )) } -/// Close `user`'s running session: atomically take the open row and -/// re-file it under a ULID id, freeing the open slot for the next start. -/// Take and re-file share one transaction — a failed re-file rolls the -/// take back, so a session can never vanish half-closed. Of two racing -/// finishes exactly one receives the row (the other gets the conflict). +/// Close `user`'s running session, deciding the counting verdict, the +/// lifetime badge counters, and the study streak in one transaction. /// -/// A lost round is re-sent rather than reported (`transaction_with_retry`): -/// the abort wrote nothing, so the whole cascade is safe to repeat, and the -/// `CREATE` cannot answer "already exists" on the way back — the table -/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. -/// Only the guard's own `THROW` is a decision, and it stays a 409. +/// The open row is taken by a guarded `DELETE … WHERE finished_at IS NULL +/// RETURNING` — of two racing finishes exactly one receives the row, and +/// the other is refused (`no pomodoro session running`), the old abort +/// marker now an ordinary early return. The user row carries every counter family +/// this decision moves, so the transaction takes it `FOR NO KEY UPDATE`, +/// decides in Rust, and writes once: no interleaving can tear the streak +/// pair, and a rival finish is serialized on the row lock instead of +/// aborting. `longest` is written as `max(longest, current)`, which cannot +/// come down under any interleaving. /// /// `finished_at` is floored at the row's own `started_at`. Both stamps come /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move @@ -67,186 +95,130 @@ pub async fn start( /// count honest and its duration merely understated. Nothing downstream may /// then read a negative duration (`ProfileStats::load` sums these). /// -/// The lifetime badge counters on the user row move in this same -/// transaction, so they can never count a stint the log does not hold (nor -/// miss one it does), and a retried round re-applies nothing — the abort -/// rolled the increment back with the rest. They are written field-scoped: -/// the row also carries admin-owned data (`role`), which a whole-row save -/// would silently revert. The clamped duration is the *same* expression the -/// `CREATE` stores (both read `$ms`), so the counter can never take a -/// negative summand and nothing downstream needs a floor. Only *finished* -/// stints reach here — an open row is a `pomodoro_session` row and nothing -/// else — and there is no student-facing delete for a stint, so neither -/// counter ever decrements. -/// -/// They move only for a stint that **counts**, which is -/// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most +/// The lifetime badge counters move only for a stint that **counts**, which +/// is [`MIN_COUNTED_POMODORO_MS`] of real focus and at most /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] /// argues about from the other end: finishing is self-service, one stint is /// two requests and no second person, so a counter moved once per -/// round-trip is farmable — two hundred pairs inside the rate limit bought -/// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked. -/// Both stamps are the server's own clock, so the duration needs no -/// distrusting, only a floor. +/// round-trip is farmable. Both stamps are the server's own clock, so the +/// duration needs no distrusting, only a floor. /// /// The verdict is *stamped* on the closed row (`counted`), not re-derived /// later: the thresholds are compiled in and will move, and a reader that /// re-judged an old stint against today's numbers would answer something -/// other than what was credited. Nothing debits these counters today; the -/// stamp is what lets one be added without that asymmetry. A stint below -/// the bar is still recorded, still listed, and still sums into the log's -/// `total_focus_ms` — the rule bounds what *counts*, never what is kept. -/// -/// The re-filed row carries the start's `label` through verbatim -/// (`$before[0].label`): the close copies whatever the student named the -/// stint. On a row that predates the field that read is NONE — exactly what -/// an `option` column stores, so no backfill is owed (the same -/// ruling as the `counted` stamp). +/// other than what was credited. A stint below the bar is still recorded, +/// still listed, and still sums into the log's focus total — the rule +/// bounds what *counts*, never what is kept. /// -/// The day quota is bucketed like the streak below (midnight UTC, -/// [`Timestamp::day_number`]) and rolls in its own statement ahead of the -/// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting -/// it, which resolves against the row as it was *before* the statement — -/// the same rule that forces the streak pair apart, used here on purpose. A -/// row that predates the two columns reads as no day at all (`?? -1`), so -/// the first finish after this deploy opens a fresh bucket and no backfill -/// is owed. The bucket write happens whether the stint counts or not; only -/// the `+ 1` sits behind the verdict. +/// The day quota is bucketed like the streak (midnight UTC, +/// [`Timestamp::day_number`]) and rolls whether the stint counts or not; +/// only the `+ 1` sits behind the verdict. /// /// The **study streak** rides the same transaction, and the same verdict: a -/// study day is a UTC calendar day on which a stint *counted*, so a day -/// bought with one instant round-trip is not a day studied (midnight UTC, like every -/// other day calculation here — no timezone is stored anywhere): the same +/// study day is a UTC calendar day on which a stint *counted* — the same /// day again changes nothing, the next day extends the run, any other gap -/// starts a new one at 1. It is written as **two** statements, not one: -/// every field reference on the right-hand side of a `SET` resolves -/// against the row as it was *before* that statement, so a single -/// `SET current = …, longest = math::max([longest, current])` would take -/// the *old* `current` and lag one write behind forever (probed on a real -/// 3.2.3 server: day two left `current = 2, longest = 1`). Across -/// statements *inside a transaction* the read does see the prior write, so -/// the pair is correct and still atomic. Absent columns are read through -/// `?? 0` (and `?? -1` for the day — a sentinel no real day number -/// reaches), because `math::max` errors outright on a `NONE` argument and -/// every account older than these columns carries none of them. -/// -/// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two -/// lines up: a plain `UPDATE` hands back an array, so a user row that is -/// missing (a `record` column checks only the table of the id) simply -/// yields nothing to index and the second statement matches no row either. -/// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero -/// rows; it errors on *many* — but a `null` is a shape the read then has to -/// special-case, so the file's existing idiom wins. +/// starts a new one at 1. /// -/// No `cap::counter_lock` is taken, deliberately. The pair cannot tear: -/// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts -/// a rival that touched the row in between — `transaction_with_retry` then -/// re-sends the whole round. And `longest` is written as -/// `max(longest, current)`, which cannot come down under *any* -/// interleaving, so even a torn pair could only under-count `current`, -/// never lower the high-water mark the badges read. The lock would only -/// serialize this process's writers (its other job, keeping the in-memory -/// test engine deterministic, is moot here — these tests are sequential). -/// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent -/// finishes for one user left `current = 60, longest = 60` with no -/// anomaly; a rival write forced *between* the two statements (a `sleep` -/// wedged into the batch) aborted the whole cascade with a write conflict, -/// wrote nothing, and left the rival's value standing. -/// -/// Streaks begin at this deploy: nothing reconstructs history from the -/// stint log, so every account starts with no streak columns and its first -/// finish sets a run of 1. +/// The closed stint is re-filed under a freshly minted id: the open slot is +/// the partial index, so the closed row releases it by no longer matching +/// `finished_at IS NULL`. pub async fn finish(db: &Database, user: &UserId) -> Result { let done = Timestamp::now(); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $before = (DELETE $open RETURN BEFORE); - IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; - LET $end = math::max([$before[0].started_at, $done]); - LET $ms = $end - $before[0].started_at; - LET $bucket = (UPDATE $usr SET - {POMODORO_COUNTED_TODAY_FIELD} = - IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day - THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END, - {POMODORO_COUNTED_DAY_FIELD} = $day - RETURN AFTER); - LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS}) - AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0) - < {MAX_COUNTED_POMODORO_PER_DAY}); - IF $counted {{ - UPDATE $usr SET - {POMODORO_FINISHED_TOTAL_FIELD} = - ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, - {POMODORO_FOCUS_MS_TOTAL_FIELD} = - ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms, - {POMODORO_COUNTED_TODAY_FIELD} = - ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1; - LET $streak = (UPDATE $usr SET - {STUDY_STREAK_CURRENT_FIELD} = - IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day - THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) - ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) - THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) - ELSE 1 END, - {STUDY_STREAK_LAST_DAY_FIELD} = $day - RETURN AFTER); - UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), - ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]) - }}; - CREATE $closed CONTENT {{ - user: $before[0].user, - started_at: $before[0].started_at, - finished_at: $end, - counted: $counted, - label: $before[0].label, - }}; - COMMIT TRANSACTION;" - ), - &[ - ( - "open".into(), - PomodoroSessionId::open_for(user).record().into_value(), - ), - ("usr".into(), user.record().into_value()), - ( - "closed".into(), - PomodoroSessionId::generate().record().into_value(), - ), - ("done".into(), done.into_value()), - ("day".into(), done.day_number().into_value()), - ], - &["no_pomodoro_running"], - ) + let day = done.day_number(); + let saved = tx_with_retry(db, false, async |tx| { + // Take the open row. Empty means nothing is running. + let open = sqlx::query!( + "DELETE FROM pomodoro_session + WHERE app_user = $1 AND finished_at IS NULL + RETURNING started_at AS \"started_at: Timestamp\", label", + user.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(open) = open else { + return Err(AppError::Conflict("no pomodoro session running")); + }; + let end = Timestamp::from_millis(open.started_at.as_millis().max(done.as_millis())); + let ms = end.as_millis() - open.started_at.as_millis(); + + // Every counter this decision moves lives on the user row; the row + // lock decides the whole verdict against one consistent read. + let counts = sqlx::query!( + "SELECT pomodoro_counted_today, pomodoro_counted_day, pomodoro_finished_total, \ + pomodoro_focus_ms_total, study_streak_current, study_streak_last_day, \ + study_streak_longest \ + FROM app_user WHERE id = $1 \ + FOR NO KEY UPDATE", + user.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(c) = counts else { + // The foreign key on the stint would refuse the insert below + // anyway; the honest answer for a user who does not exist. + return Err(AppError::NotFound); + }; + + // Day-bucket roll: a finish on a new day reopens the quota. + let counted_today = if c.pomodoro_counted_day == Some(day) { + c.pomodoro_counted_today + } else { + 0 + }; + let counted = + ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY; + if counted { + let current = match c.study_streak_last_day { + Some(last) if last == day => c.study_streak_current, + Some(last) if last == day - 1 => c.study_streak_current + 1, + _ => 1, + }; + sqlx::query!( + "UPDATE app_user SET pomodoro_finished_total = pomodoro_finished_total + 1, \ + pomodoro_focus_ms_total = pomodoro_focus_ms_total + $2, \ + pomodoro_counted_today = $3, pomodoro_counted_day = $4, \ + study_streak_current = $5, study_streak_last_day = $4, \ + study_streak_longest = GREATEST(study_streak_longest, $5) \ + WHERE id = $1", + user.uuid(), + ms, + counted_today + 1, + day, + current, + ) + .execute(&mut *tx) + .await?; + } else if c.pomodoro_counted_day != Some(day) { + sqlx::query!( + "UPDATE app_user SET pomodoro_counted_today = 0, pomodoro_counted_day = $2 \ + WHERE id = $1", + user.uuid(), + day + ) + .execute(&mut *tx) + .await?; + } + + let closed = query_as!( + PomodoroSession, + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ + started_at AS \"started_at: Timestamp\", \ + finished_at AS \"finished_at: Timestamp\", counted, label", + PomodoroSessionId::generate().uuid(), + user.uuid(), + open.started_at.as_millis(), + Some(end.as_millis()), + Some(counted), + open.label, + ) + .fetch_one(&mut *tx) + .await?; + Ok(closed) + }) .await?; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the THROW's own slot names the reason, so scan - // them all for the marker instead of trusting the first. - if errors - .values() - .any(|error| error.to_string().contains("no_pomodoro_running")) - { - return Err(AppError::Conflict("no pomodoro session running")); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The `CREATE` is deliberately kept the last statement before `COMMIT` - // (the counter `UPDATE` sits ahead of it — same transaction, so the - // order is free), which is what lets its slot follow the statement - // count instead of a hand-kept number: `num_statements` counts `BEGIN` - // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a - // hand-kept slot caused. - let slot = result.num_statements().saturating_sub(2); - let saved: Option = result - .take::>(slot)? - .into_iter() - .next(); - let saved = - saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?; // A badge is a decoration on top of the stint: losing one to a // transient database error must never fail the finish, and the next // counter move re-runs this and heals it. @@ -257,20 +229,24 @@ pub async fn finish(db: &Database, user: &UserId) -> Result Result, AppError> { - let mut result = db - .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let sessions = query_as!( + PomodoroSession, + "SELECT id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \ + started_at AS \"started_at: Timestamp\", \ + finished_at AS \"finished_at: Timestamp\", counted, label \ + FROM pomodoro_session WHERE app_user = $1 \ + ORDER BY started_at DESC, id DESC", + user.uuid() + ) + .fetch_all(db) + .await?; + Ok(sessions) } - #[cfg(test)] mod tests { use ulid::Ulid; diff --git a/src/db/registration.rs b/src/db/registration.rs index 207ba4e..1dc6d32 100644 --- a/src/db/registration.rs +++ b/src/db/registration.rs @@ -3,11 +3,13 @@ //! workflow itself (the cap claim and its conflict mapping) lives in //! [`crate::service::registration`]. -use crate::database::Database; +use crate::database::{Database, tx_with_retry, unique_violation}; +use crate::db::cap::Claimed; use crate::domain::event::EventId; use crate::domain::registration::Registration; use crate::domain::user::UserId; use crate::error::AppError; +use sqlx::query_as; /// Some(_) iff `user` holds a seat on `event` — the audience point check. pub async fn read_for_user( @@ -15,22 +17,84 @@ pub async fn read_for_user( event: &EventId, user: &UserId, ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM registration WHERE event = $ev AND user = $usr LIMIT 1") - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let seat = query_as!( + Registration, + "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \ + registered_by AS \"registered_by: UserId\" \ + FROM registration + WHERE event = $1 AND app_user = $2 + LIMIT 1", + event.uuid(), + user.uuid() + ) + .fetch_optional(db) + .await?; + Ok(seat) } pub async fn list_for_event(db: &Database, event: &EventId) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM registration WHERE event = $ev ORDER BY id DESC") - .bind(("ev", event.record())) - .await? - .check()?; - Ok(result.take::>(0)?) + let seats = query_as!( + Registration, + "SELECT event AS \"event: EventId\", app_user AS \"user: UserId\", \ + registered_by AS \"registered_by: UserId\" \ + FROM registration + WHERE event = $1 + ORDER BY event DESC, app_user DESC", + event.uuid() + ) + .fetch_all(db) + .await?; + Ok(seats) +} + +/// Take a seat for `user` on `event` — the cap claim of one: the seat bump, +/// the holder's role handshake, and the row insert are a single statement, +/// so neither a racing placement nor a concurrent capacity lowering can +/// over-admit (the capacity is read off the event row as it is decided, not +/// off a snapshot), and a demotion to `parent` cannot strand a seat the +/// sweep would miss: the handshake takes the holder's row +/// `FOR NO KEY UPDATE`, the same key the demotion writes, so either this +/// sees the parent and inserts nothing, or the sweep sees this row. +/// +/// The verdict maps exactly like the old guard layer's: `Made` — seated; +/// `Duplicate` — a rival placement of the same pair won (23505 on +/// `registration_event_user`); `Full` — the event is at its capacity, was +/// deleted, or the holder fell to `parent` (all one marker; the caller +/// re-reads to pick the message). +pub async fn claim_seat( + db: &Database, + event: &EventId, + user: &UserId, + registered_by: &UserId, +) -> Result, AppError> { + match query_as!( + Registration, + "WITH seat AS ( + UPDATE event SET registration_count = registration_count + 1 + WHERE id = $1 + AND (audience_capacity IS NULL OR registration_count < audience_capacity) + RETURNING 1), + person AS ( + SELECT 1 FROM app_user WHERE id = $2 AND role IS DISTINCT FROM 'parent' + FOR NO KEY UPDATE) + INSERT INTO registration (event, app_user, registered_by) + SELECT $1, $2, $3 + WHERE EXISTS (SELECT 1 FROM seat) AND EXISTS (SELECT 1 FROM person) + RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"", + event.uuid(), + user.uuid(), + registered_by.uuid() + ) + .fetch_optional(db) + .await + { + Ok(Some(row)) => Ok(Claimed::Made(row)), + Ok(None) => Ok(Claimed::Full), + Err(err) if unique_violation(&err) == Some("registration_event_user") => { + Ok(Claimed::Duplicate) + } + Err(err) => Err(err.into()), + } } pub async fn remove( @@ -39,17 +103,26 @@ pub async fn remove( user: &UserId, ) -> Result, AppError> { // The seat comes back in the same transaction as the row that held it. - let mut result = db - .query( - "BEGIN TRANSACTION; - LET $gone = (DELETE registration WHERE event = $ev AND user = $usr RETURN BEFORE); - UPDATE $ev SET registration_count = math::max([(registration_count ?? 0) - array::len($gone), 0]); - RETURN $gone; - COMMIT TRANSACTION;", + tx_with_retry(db, false, async |tx| { + let gone = query_as!( + Registration, + "DELETE FROM registration WHERE event = $1 AND app_user = $2 + RETURNING event AS \"event: EventId\", app_user AS \"user: UserId\", registered_by AS \"registered_by: UserId\"", + event.uuid(), + user.uuid() ) - .bind(("ev", event.record())) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(3)?.into_iter().next()) + .fetch_optional(&mut *tx) + .await?; + if gone.is_some() { + sqlx::query!( + "UPDATE event SET registration_count = GREATEST(registration_count - 1, 0) + WHERE id = $1", + event.uuid() + ) + .execute(&mut *tx) + .await?; + } + Ok(gone) + }) + .await } diff --git a/src/domain/appointment.rs b/src/domain/appointment.rs index 4367584..578bc1c 100644 --- a/src/domain/appointment.rs +++ b/src/domain/appointment.rs @@ -17,14 +17,15 @@ //! with nothing to sweep. //! - **No double-booked teacher window.** Two overlapping published windows //! cannot both exist — the `appointment_slot` exclusion constraint refuses -//! the second insert at the store, which is what replaced the -//! [`crate::service::appointment::APPOINTMENT_LOCK`] serialization. +//! the second insert at the store, which is what replaced the process +//! lock the appointment workflows used to hold. //! //! The *single-row* invariant — a decision must be written onto the state it //! was validated against — is a compare-and-set //! ([`crate::db::appointment::save_if_unchanged`]), decided by a conditional //! `UPDATE`. +use uuid::Uuid; use crate::constant::{MAX_APPOINTMENT_REASON_LEN}; use crate::domain::appointment_slot::{AppointmentSlot, AppointmentSlotId}; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/appointment_slot.rs b/src/domain/appointment_slot.rs index 1cc0d41..1a47ee5 100644 --- a/src/domain/appointment_slot.rs +++ b/src/domain/appointment_slot.rs @@ -15,10 +15,11 @@ //! outrun. Two overlapping windows of one teacher cannot both be published: //! the `appointment_slot` span exclusion constraint refuses the second //! insert, which is what replaced the -//! [`crate::service::appointment::APPOINTMENT_LOCK`]. The reads and writes +//! the old process lock the appointment workflows used to hold. The reads and writes //! live in [`crate::db::appointment_slot`]; the publish and delete workflows //! in [`crate::service::appointment_slot`]. +use uuid::Uuid; use crate::constant::{ MAX_APPOINTMENT_NOTE_LEN, MAX_SLOT_OCCURRENCES, MILLIS_PER_WEEK, }; diff --git a/src/domain/chatbot_message.rs b/src/domain/chatbot_message.rs index 768cde1..2c0c48e 100644 --- a/src/domain/chatbot_message.rs +++ b/src/domain/chatbot_message.rs @@ -9,6 +9,7 @@ //! ([`ChatbotMessage::projected`]) — the durable repair for a dead process //! happens once, at mint, in `database.rs`'s school migration sweep. +use uuid::Uuid; use crate::constant::{ CHATBOT_PENDING_STALE_SECS, MAX_CHATBOT_MESSAGE_LEN, STALE_ERROR_CODE, }; diff --git a/src/domain/chatbot_thread.rs b/src/domain/chatbot_thread.rs index f47bd47..1fe23ca 100644 --- a/src/domain/chatbot_thread.rs +++ b/src/domain/chatbot_thread.rs @@ -4,6 +4,7 @@ //! [`crate::db::chatbot_message`], and deleting a thread cascades them; the //! threads' own persistence lives in [`crate::db::chatbot_thread`]. +use uuid::Uuid; use crate::constant::{MAX_CHATBOT_THREAD_TITLE_LEN}; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; diff --git a/src/domain/event.rs b/src/domain/event.rs index 61101b9..c0498cc 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -1,3 +1,4 @@ +use uuid::Uuid; use crate::constant::{MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; use crate::domain::class_group::ClassGroupId; use crate::domain::course::CourseId; @@ -165,6 +166,32 @@ impl EventAudience { } } +/// The five audience columns as one value — the write-side bundle. The row +/// keeps them flat; every write spells them as a unit, so a kind and its +/// payload always land together and only the payload matching `kind` is +/// ever non-NULL. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventAudience { + pub kind: EventAudienceKind, + pub role: Option, + pub course: Option, + pub class: Option, + pub capacity: Option, +} + +impl EventAudience { + /// The audience of a row read back from the store. + pub fn of_row(event: &Event) -> Self { + Self { + kind: event.get_audience_kind(), + role: event.get_audience_role(), + course: event.get_audience_course().copied(), + class: event.get_audience_class().copied(), + capacity: event.get_audience_capacity(), + } + } +} + impl Event { pub fn get_id(&self) -> &EventId { &self.id diff --git a/src/lib.rs b/src/lib.rs index 882f03f..508cfef 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,618 +14,4 @@ pub mod tenant; pub mod validate; pub mod web; -use axum::extract::{MatchedPath, Request}; -use axum::http::{HeaderName, HeaderValue, Method, header}; -use axum::middleware::{self, Next}; -use axum::response::{IntoResponse, Response}; -use axum::routing::get; -use axum::{Json, Router}; -use serde_json::json; -use tower_http::cors::{AllowOrigin, CorsLayer}; -use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer}; -use tower_http::trace::TraceLayer; -use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme}; -use utoipa::{Modify, OpenApi}; -use utoipa_axum::router::OpenApiRouter; -use utoipa_axum::routes; -use utoipa_swagger_ui::SwaggerUi; - -use crate::constant::MAX_REQUEST_ID_LEN; -use crate::error::AppError; -use crate::module::Module; -use crate::rate_limit::RateLimiter; -use crate::state::AppState; -use crate::telemetry::SchoolSlot; -use crate::web::module_gate::gate; - -/// Top-level OpenAPI document. Per-path operations and schemas are collected -/// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. -#[derive(OpenApi)] -#[openapi( - info( - title = "Hezarfen Backend API", - version = env!("CARGO_PKG_VERSION"), - 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.", - ), - modifiers(&SecurityAddon), - tags( - (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"), - (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"), - (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."), - (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 `.` (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`"), - (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"), - (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`"), - (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"), - (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"), - (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"), - (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"), - (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"), - (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."), - (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=