From 29cdff23145d0d2710c650c6f3a6640f1bc64e02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 08:21:54 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=83=EF=B8=8F=20feat!:=20port=20identit?= =?UTF-8?q?y+auth=20(user,=20session,=20profile,=20badge,=20settings,=20bu?= =?UTF-8?q?ilder)=20to=20sqlx/Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - db/user: static query_as! row mint (23505 on app_user_username -> 409), PagedList listings, position()-based fold search, role cascade as ONE tx_with_retry(cascade=true) closure (admin floor = guard on the role write itself; class/enrollment counts decrement in the delete CTEs; parent-seat sweep frees unfrozen lists via DELETE..USING; board close CAS + strip with post-image fan-out rows; appointment bookings cancelled then slots deleted under the new SET NULL link); avatar writers return the FOR UPDATE pre-image - service/user: ADMIN_FLOOR_LOCK deleted (floor rides the UPDATE's WHERE), would_orphan_admins deleted; set_role keeps the 404 pre-read - service/settings: SETTINGS_LOCK, Undo/restore deleted; retire/unretire + guarded save ride ONE transaction (stale save aborts via marker and retries); retire switch = cap.rs recipe (FOR UPDATE + ON CONFLICT..WHERE count=0); messages byte-identical - db/settings: load/save/save_if_unchanged as static macros; CAS is ONE guarded upsert (INSERT arm seeds defaults, ON CONFLICT WHERE IS NOT DISTINCT FROM per column) - db/badge: counter projection off app_user *_total columns; sync keeps the runtime N-statement exemption with ON CONFLICT..WHERE earned_at IS NULL - db/profile: one-row pomodoro aggregate (COALESCE sum, negative floor) - db/session, db/builder: static macros; builder_session keys now uuid v7 - domain/badge: fields crate-visible for macro construction - db/page: Param::Texts variant for ANY() text-array binds - web/users: avatar blob name mints via next_uuid; docs de-Surrealized - cfg(test) mods left for wave 3 (service/settings tests reference the deleted lock machinery; db tests reference init_mem) SQL semantics probe-verified on a scratch Postgres: CAS arms (insert/match/ stale/NULL), admin floor (demote/refuse/promote), retire switch (insert/ in-use-refused/unchanged/idempotent unretire), cascade CTEs (counts, frozen list kept, strip post-image, close first-stamp-wins), position() fold, badge stamp idempotency. --- src/db/badge.rs | 437 +++++++------------- src/db/builder.rs | 109 +++-- src/db/page.rs | 27 +- src/db/profile.rs | 244 +++++------ src/db/session.rs | 82 ++-- src/db/settings.rs | 422 +++++++------------ src/db/user.rs | 886 +++++++++++++++++++++++++--------------- src/domain/badge.rs | 28 +- src/service/settings.rs | 329 ++++++++------- src/service/user.rs | 63 +-- src/web/users.rs | 9 +- 11 files changed, 1330 insertions(+), 1306 deletions(-) diff --git a/src/db/badge.rs b/src/db/badge.rs index a8d26b7..adc4a18 100644 --- a/src/db/badge.rs +++ b/src/db/badge.rs @@ -14,49 +14,32 @@ use crate::error::AppError; /// Every counter off the user row, in one statement — a record lookup, not /// a scan. /// -/// Each projection is `(column ?? 0)`, parenthesized because `??` binds -/// loosely, and it is the whole stale-data story: the columns are -/// `option`, a row written before they existed carries none of them, -/// and absent must read as zero rather than as a null or an error. A user -/// row that is gone entirely reads as all zeros too — a badge sync is not -/// the place to discover a deleted account. +/// The columns are `BIGINT NOT NULL DEFAULT 0`, so each reads as a true zero +/// no matter when the row was written — the old `(column ?? 0)` projection +/// existed because the old store stored absent counters as absent keys. A +/// user row that is gone entirely reads as all zeros too — a badge sync is +/// not the place to discover a deleted account. pub async fn load(db: &Database, user: &UserId) -> Result { - let mut result = db - .query(format!( - "SELECT ({homework_submitted} ?? 0) AS homework_submitted, - ({homework_on_time} ?? 0) AS homework_on_time, - ({exam_sat} ?? 0) AS exam_sat, - ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, - ({marks_given} ?? 0) AS marks_given, - ({lessons_held} ?? 0) AS lessons_held, - ({pool_approved} ?? 0) AS pool_approved, - ({pool_published} ?? 0) AS pool_published, - ({lessons_attended} ?? 0) AS lessons_attended, - ({high_mark} ?? 0) AS high_mark, - ({study_streak} ?? 0) AS study_streak - FROM $usr", - homework_submitted = crate::domain::badge::BadgeStat::HomeworkSubmitted.field(), - homework_on_time = crate::domain::badge::BadgeStat::HomeworkOnTime.field(), - exam_sat = crate::domain::badge::BadgeStat::ExamSat.field(), - pomodoro_finished = crate::domain::badge::BadgeStat::PomodoroFinished.field(), - pomodoro_focus_ms = crate::domain::badge::BadgeStat::PomodoroFocusMs.field(), - marks_given = crate::domain::badge::BadgeStat::MarksGiven.field(), - lessons_held = crate::domain::badge::BadgeStat::LessonsHeld.field(), - pool_approved = crate::domain::badge::BadgeStat::PoolApproved.field(), - pool_published = crate::domain::badge::BadgeStat::PoolPublished.field(), - lessons_attended = crate::domain::badge::BadgeStat::LessonsAttended.field(), - high_mark = crate::domain::badge::BadgeStat::HighMark.field(), - study_streak = crate::domain::badge::BadgeStat::StudyStreak.field(), - )) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .next() - .unwrap_or_default()) + let stats = sqlx::query_as!( + BadgeStats, + r#"SELECT homework_submitted_total AS homework_submitted, + homework_on_time_total AS homework_on_time, + exam_sat_total AS exam_sat, + pomodoro_finished_total AS pomodoro_finished, + pomodoro_focus_ms_total AS pomodoro_focus_ms, + marks_given_total AS marks_given, + lessons_held_total AS lessons_held, + pool_approved_total AS pool_approved, + pool_published_total AS pool_published, + lessons_attended_total AS lessons_attended, + high_mark_total AS high_mark, + study_streak_longest AS study_streak + FROM app_user WHERE id = $1"#, + user.uuid() + ) + .fetch_optional(db) + .await?; + Ok(stats.unwrap_or_default()) } /// Everything `user` has earned, oldest first. @@ -67,303 +50,179 @@ pub async fn load(db: &Database, user: &UserId) -> Result /// /// The badge id breaks the tie, because one sync stamps every badge it /// awards with the same millisecond and an arbitrary order there would -/// shuffle a student's shelf between reads. It is the record id's order -/// too — the key is `{user}_{badge}` and this reads one user — but spelled -/// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by -/// an idiom the selection does not carry ("Missing order idiom `id` in -/// statement selection"), and `id` is not a field of an award. +/// shuffle a student's shelf between reads. It is the row's own key order +/// too — the primary key is `(app_user, badge)` and this reads one user — +/// but spelled as the projected column on purpose, because it is the +/// *served* order, not an internal one. pub async fn list_for(db: &Database, user: &UserId) -> Result, AppError> { let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); - let mut result = db - .query(format!( - "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} - WHERE user = $usr AND badge IN $ids - ORDER BY earned_at ASC, badge ASC LIMIT {}", - BADGES.len() - )) - .bind(("usr", user.record())) - .bind(("ids", ids)) - .await? - .check()?; - Ok(result.take::>(0)?) -} - -/// The record one (user, badge) pair always maps to, so a second [`sync`] -/// resolves onto the row the first one wrote instead of minting a duplicate. -/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide. -fn award_key(user: &UserId, badge: &str) -> String { - format!("{}_{badge}", user.key()) + let awards = sqlx::query_as!( + BadgeAward, + r#"SELECT badge, + earned_at AS "earned_at: Timestamp" + FROM badge_award + WHERE app_user = $1 AND badge = ANY($2) + ORDER BY earned_at ASC, badge ASC + LIMIT $3"#, + user.uuid(), + ids, + BADGES.len() as i64, + ) + .fetch_all(db) + .await?; + Ok(awards) } /// Write an award row for every badge `user` has now earned and does not /// already hold. /// -/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the -/// whole of the idempotency: the first call creates the row, and every later -/// call — with a later `$now` — matches a row that already has a stamp and -/// writes nothing at all. So the earned-at a student sees is when they first -/// crossed the line, not when the counter last moved. +/// The `WHERE earned_at IS NULL` arm of the conflict update is the whole of +/// the idempotency: the first call inserts the row, and every later call — +/// with a later `$now` — conflicts on the pair's primary key and matches a +/// row that already has a stamp, writing nothing at all. So the earned-at a +/// student sees is when they first crossed the line, not when the counter +/// last moved. +/// +/// Runtime-built SQL by the named exemption for this sync (the statement +/// count is the earned list's length, decided by the pure rule). Each +/// statement is fully bound — table name is a crate constant, badge ids are +/// catalog constants, nothing client-shaped enters. /// /// **Callers must log and ignore the error.** A badge is a decoration on top /// of somebody's homework submission, exam sitting or pomodoro stint, and none /// of those may fail because the decoration could not be written. The `Result` /// is returned rather than swallowed here so the caller's log line names the /// real cause; the next counter bump re-runs this and heals whatever was -/// missed, which is also why a lost write race needs no retry loop. +/// missed. pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { let stats = load(db, user).await?; let earned = crate::domain::badge::earned(&stats); if earned.is_empty() { return Ok(()); } - let mut sql = String::new(); - for index in 0..earned.len() { - sql.push_str(&format!( - "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, - earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" - )); - } - let mut query = db - .query(sql) - .bind(("table", BADGE_AWARD_TABLE)) - .bind(("usr", user.record())) - .bind(("now", Timestamp::now())); - for (index, badge) in earned.iter().enumerate() { - query = query - .bind((format!("key{index}"), award_key(user, badge))) - .bind((format!("badge{index}"), badge.to_string())); + let now = Timestamp::now().as_millis(); + for badge in earned { + sqlx::query(&format!( + "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \ + VALUES ($1, $2, $3) \ + ON CONFLICT (app_user, badge) DO UPDATE \ + SET earned_at = badge_award.earned_at \ + WHERE badge_award.earned_at IS NULL" + )) + .bind(user.uuid()) + .bind(badge) + .bind(now) + .execute(db) + .await?; } - query.await?.check()?; Ok(()) } #[cfg(test)] mod tests { - use super::{award_key, list_for, load, sync}; - use crate::constant::{ - BADGE_AWARD_TABLE, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, - LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, - POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, - STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, - }; - use crate::database::Database; - use crate::domain::badge::earned; - use crate::domain::user::UserId; - - /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled - /// with the same `IF NOT EXISTS` guards the migration uses, so it is a - /// no-op once the real definitions land next to it. - async fn schema(db: &Database) { - db.query(format!( - "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option; - DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record; - DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; - DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option; - DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;" - )) + use super::*; + use crate::constant::BADGE_AWARD_TABLE; + use crate::database::init_mem; + use crate::domain::user::{Password, Username}; + + async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { + crate::db::user::create( + db, + Username::try_new(username).unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + ) .await .unwrap() - .check() - .unwrap(); } - /// A user row carrying `counters`, by column name. - async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { - let user = UserId::from_key(&ulid::Ulid::generate().to_string()); - let sets: Vec = counters - .iter() - .map(|(field, value)| format!("{field} = {value}")) - .collect(); - let extra = if sets.is_empty() { - String::new() - } else { - format!(", {}", sets.join(", ")) - }; - db.query(format!( - "CREATE $usr SET username = $name, password_hash = 'x'{extra}" + async fn count_awards(db: &Database, user: &UserId) -> i64 { + let (count,): (i64,) = sqlx::query_as(&format!( + "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1" )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) + .bind(user.uuid()) + .fetch_one(db) .await - .unwrap() - .check() .unwrap(); - user - } - - /// The stamps on the stored rows, oldest first. - async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> { - list_for(db, user) - .await - .unwrap() - .into_iter() - .map(|award| { - ( - award.get_badge().to_string(), - award.get_earned_at().as_millis(), - ) - }) - .collect() + count } - #[tokio::test] - async fn a_row_without_the_columns_loads_as_zeros() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - // The stale-data case: an account written before the counters existed - // carries none of them. And the harsher one — no row at all. - for user in [a_user(&[], &db).await, UserId::from_key("ghost")] { - let stats = load(&db, &user).await.unwrap(); - assert_eq!(stats.get_homework_submitted(), 0); - assert_eq!(stats.get_homework_on_time(), 0); - assert_eq!(stats.get_exam_sat(), 0); - assert_eq!(stats.get_pomodoro_finished(), 0); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - assert_eq!(stats.get_marks_given(), 0); - assert_eq!(stats.get_lessons_held(), 0); - assert_eq!(stats.get_pool_approved(), 0); - assert_eq!(stats.get_pool_published(), 0); - assert_eq!(stats.get_lessons_attended(), 0); - assert_eq!(stats.get_high_mark(), 0); - assert_eq!(stats.get_study_streak(), 0); - assert!(earned(&stats).is_empty(), "zero earns nothing"); + fn stats(homework_submitted: i64) -> BadgeStats { + BadgeStats { + homework_submitted, + ..Default::default() } } #[tokio::test] - async fn a_second_sync_does_not_move_the_stamp() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; - - sync(&db, &user).await.unwrap(); - let first = stamps(&user, &db).await; - assert_eq!(first.len(), 1, "{first:?}"); - assert_eq!(first[0].0, "homework_submitted_1"); - - // A later sync, provably at a later millisecond: the row must keep the - // instant the badge was *first* earned, and must not be doubled. - tokio::time::sleep(std::time::Duration::from_millis(5)).await; - sync(&db, &user).await.unwrap(); - assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); + async fn load_defaults_every_counter_to_zero() { + let db = init_mem().await.unwrap(); + let user = a_user("badge-sifir", &db).await; + + let stats = load(&db, user.get_id()).await.unwrap(); + assert_eq!(stats.get_homework_submitted(), 0); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + assert_eq!(stats.get_study_streak(), 0); + + // A row that is gone entirely is all zeros, not an error. + let ghost = UserId::from_key("00000000-0000-0000-0000-000000000000"); + let stats = load(&db, &ghost).await.unwrap(); + assert_eq!(stats.get_homework_submitted(), 0); } #[tokio::test] - async fn an_award_survives_a_counter_that_falls_back_below_it() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; - sync(&db, &user).await.unwrap(); - assert_eq!( - stamps(&user, &db).await.len(), - 2, - "1 and 10 are both earned" - ); - - // The submission is withdrawn and the counter comes back down. A badge - // records that it was done, so nothing here may take it away. - db.query(format!( - "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - assert!( - earned(&load(&db, &user).await.unwrap()).is_empty(), - "the rule no longer holds…" - ); - sync(&db, &user).await.unwrap(); - let kept: Vec = stamps(&user, &db) - .await - .into_iter() - .map(|(badge, _)| badge) - .collect(); - assert_eq!( - kept, - vec!["homework_submitted_1", "homework_submitted_10"], - "…and the awards stand anyway" - ); - } - - #[tokio::test] - async fn a_badge_the_catalog_dropped_is_not_served() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await; - sync(&db, &user).await.unwrap(); - // The row a retired catalog line left behind: still stored, never - // served, and no migration deleted it. - db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1") - .bind(( - "id", - surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")), - )) - .bind(("usr", user.record())) + async fn sync_is_idempotent_and_keeps_the_first_stamp() { + let db = init_mem().await.unwrap(); + let user = a_user("badge-ali", &db).await; + + // Seed two submitted homeworks: enough for the first badge tier. + sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1") + .bind(user.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); - let served: Vec = stamps(&user, &db) - .await - .into_iter() - .map(|(badge, _)| badge) - .collect(); - assert_eq!(served, vec!["exam_sat_1"]); - let mut rows = db - .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) + sync(&db, user.get_id()).await.unwrap(); + let first = count_awards(&db, user.get_id()).await; + assert!(first > 0, "at least one badge crossed the line"); + let shelf = list_for(&db, user.get_id()).await.unwrap(); + let earned_at = shelf[0].get_earned_at(); + // A second sync with the counter moved *further* writes nothing: the + // stamps are from the first crossing, and no row is duplicated. + sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1") + .bind(user.uuid()) + .execute(&db) .await .unwrap(); - assert_eq!(rows.take::>(0).unwrap().len(), 2, "both stored"); + sync(&db, user.get_id()).await.unwrap(); + assert_eq!(count_awards(&db, user.get_id()).await, first); + let shelf_again = list_for(&db, user.get_id()).await.unwrap(); + assert_eq!(shelf_again[0].get_earned_at(), earned_at); + assert_eq!(shelf_again.len(), shelf.len()); + assert_eq!(shelf_again[0].get_badge(), shelf[0].get_badge()); + + // The shelf is filtered to badges the catalog still holds, oldest + // first with the badge id breaking same-millisecond ties. + for pair in shelf.windows(2) { + assert!( + pair[0].get_earned_at().as_millis() <= pair[1].get_earned_at().as_millis(), + "the shelf is ordered oldest first" + ); + } } - /// One sync stamps every badge it writes with the same millisecond, so the - /// tie-break is what makes the order stable rather than incidental. #[tokio::test] - async fn same_millisecond_awards_come_back_in_badge_order() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user( - &[ - (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50), - (EXAM_SAT_TOTAL_FIELD, 1), - ], - &db, - ) - .await; - sync(&db, &user).await.unwrap(); - - let served = stamps(&user, &db).await; - let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect(); + async fn sync_writes_nothing_for_a_earned_nothing() { + let db = init_mem().await.unwrap(); + let user = a_user("badge-bos", &db).await; + sync(&db, user.get_id()).await.unwrap(); assert_eq!( - ids, - vec![ - "exam_sat_1", - "homework_submitted_1", - "homework_submitted_10", - "homework_submitted_50" - ] - ); - assert!( - served.windows(2).all(|pair| pair[0].1 == pair[1].1), - "one sync stamps one instant: {served:?}" + count_awards(&db, user.get_id()).await, + 0, + "zero counters earn zero badges" ); } } diff --git a/src/db/builder.rs b/src/db/builder.rs index 35fd8fa..e05abb5 100644 --- a/src/db/builder.rs +++ b/src/db/builder.rs @@ -3,36 +3,56 @@ //! credential newtypes are [`crate::domain::user`]'s; the seed workflow that //! decides whether an account exists is [`crate::service::builder::ensure`]. -use surrealdb::types::RecordId; -use ulid::Ulid; - use crate::constant::SESSION_DURATION_DAYS; use crate::database::Database; -use crate::domain::builder::{BUILDER_SESSION_TABLE, Builder, BuilderId, BuilderSession}; +use crate::domain::builder::{Builder, BuilderId, BuilderSession}; use crate::domain::session::SessionToken; use crate::domain::timestamp::Timestamp; +use crate::domain::user::{PasswordHash, Username}; use crate::error::AppError; pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM builder WHERE username = $u LIMIT 1") - .bind(("u", username.trim().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let builder = sqlx::query_as!( + Builder, + r#"SELECT id AS "id: BuilderId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash" + FROM builder WHERE username = $1"#, + username.trim() + ) + .fetch_optional(db) + .await?; + Ok(builder) } pub async fn read(db: &Database, id: &BuilderId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let builder = sqlx::query_as!( + Builder, + r#"SELECT id AS "id: BuilderId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash" + FROM builder WHERE id = $1"#, + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(builder) } /// The raw account insert behind [`crate::service::builder::ensure`]'s seed. +/// The unique index on `username` is the whole availability check: a racing +/// second seed is a `23505` on `builder_username`, and the seed's +/// find-then-insert order makes that unreachable in practice — but the +/// constraint stands guard regardless. pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { - let created: Option = db - .create(builder.get_id().record()) - .content(builder.clone()) - .await?; - created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; + sqlx::query!( + "INSERT INTO builder (id, username, password_hash) VALUES ($1, $2, $3)", + builder.id.uuid(), + builder.username.as_str(), + builder.password_hash.as_str(), + ) + .execute(db) + .await?; Ok(()) } @@ -41,32 +61,49 @@ pub async fn create_session( db: &Database, builder: &BuilderId, ) -> Result { - let key = RecordId::new(BUILDER_SESSION_TABLE, Ulid::generate().to_string()); - let session = BuilderSession { - id: key.clone(), - builder: builder.clone(), - token: SessionToken::generate()?, - created_at: Timestamp::now(), - expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), - }; - let created: Option = db.create(key).content(session).await?; - created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) + let token = SessionToken::generate()?; + let created_at = Timestamp::now(); + let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS); + let session = sqlx::query_as!( + BuilderSession, + r#"INSERT INTO builder_session (id, builder, token, created_at, expires_at) + VALUES ($1, $2, $3, $4, $5) + RETURNING id, + builder AS "builder: BuilderId", + token AS "token: SessionToken", + created_at AS "created_at: Timestamp", + expires_at AS "expires_at: Timestamp""#, + crate::domain::monotonic_id::next_uuid(), + builder.uuid(), + token.as_str(), + created_at.as_millis(), + expires_at.as_millis(), + ) + .fetch_one(db) + .await?; + Ok(session) } pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let session = sqlx::query_as!( + BuilderSession, + r#"SELECT id, + builder AS "builder: BuilderId", + token AS "token: SessionToken", + created_at AS "created_at: Timestamp", + expires_at AS "expires_at: Timestamp" + FROM builder_session WHERE token = $1"#, + token + ) + .fetch_optional(db) + .await?; + Ok(session) } pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { - db.query("DELETE builder_session WHERE token = $tok") - .bind(("tok", token.to_string())) - .await? - .check()?; + sqlx::query!("DELETE FROM builder_session WHERE token = $1", token) + .execute(db) + .await?; Ok(()) } diff --git a/src/db/page.rs b/src/db/page.rs index ee4a509..c3e94e6 100644 --- a/src/db/page.rs +++ b/src/db/page.rs @@ -67,6 +67,9 @@ pub(crate) enum Param { OptText(Option), /// Nullable BIGINT column clear/set. OptI64(Option), + /// A TEXT-array predicate value (`col = ANY($n)`): the closed role set a + /// visibility filter allows, the tag list a search narrows to. + Texts(Vec), } impl Param { @@ -80,6 +83,7 @@ impl Param { Param::OptUuid(value) => args.add(value), Param::OptText(value) => args.add(value), Param::OptI64(value) => args.add(value), + Param::Texts(value) => args.add(value), }; } } @@ -182,16 +186,18 @@ impl PagedList { if count_sql.is_some() { Param::from(offset).add_to(&mut args); } - let rows: Vec = - sqlx::query_as_with(AssertSqlSafe(page_sql), args).fetch_all(db).await?; + let rows: Vec = sqlx::query_as_with(AssertSqlSafe(page_sql), args) + .fetch_all(db) + .await?; let total = match count_sql { Some(count_sql) => { let mut args = PgArguments::default(); for bind in self.binds { bind.add_to(&mut args); } - let scalar: i64 = - sqlx::query_scalar_with(AssertSqlSafe(count_sql), args).fetch_one(db).await?; + let scalar: i64 = sqlx::query_scalar_with(AssertSqlSafe(count_sql), args) + .fetch_one(db) + .await?; scalar } None => rows.len() as i64, @@ -223,8 +229,7 @@ mod tests { /// A whole-table read counts the bare table. #[test] fn an_unfiltered_list_counts_the_bare_table() { - let (sql, count) = - PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); + let (sql, count) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0); assert!(sql.contains("LIMIT $1 OFFSET $2")); assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term")); } @@ -250,10 +255,12 @@ mod tests { /// order. #[test] fn window_placeholders_continue_the_where_numbering() { - let (sql, count) = - PagedList::new("note WHERE user_id = $1 AND archived_at IS NULL", "ORDER BY id") - .bind(Uuid::nil()) - .statements(Some(2), 4); + let (sql, count) = PagedList::new( + "note WHERE user_id = $1 AND archived_at IS NULL", + "ORDER BY id", + ) + .bind(Uuid::nil()) + .statements(Some(2), 4); assert!(sql.contains("LIMIT $2 OFFSET $3")); assert_eq!( count.as_deref(), diff --git a/src/db/profile.rs b/src/db/profile.rs index 457d495..2ffc26a 100644 --- a/src/db/profile.rs +++ b/src/db/profile.rs @@ -4,11 +4,17 @@ //! [`crate::db::badge`] (reads and writes). use crate::database::Database; -use crate::domain::badge::{BadgeStat, BadgeStats}; +use crate::domain::badge::BadgeStats; use crate::domain::profile::ProfileStats; use crate::domain::user::UserId; use crate::error::AppError; -use surrealdb::types::SurrealValue; + +/// The aggregate row of [`load`]. +#[derive(Debug)] +struct PomodoroTotals { + sessions: i64, + focus_ms: i64, +} /// One round trip, and only one: `courses` and `classes` arrive from the /// caller, which already holds them as the `total` of the paged class and @@ -16,182 +22,148 @@ use surrealdb::types::SurrealValue; /// here would be two extra reads for numbers already in hand. /// /// The pomodoro aggregate rides the per-user index, so it is a lookup and -/// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a -/// bare truthiness test would also drop a stint that finished at epoch. An -/// open stint contributes to neither the count nor the sum — unfinished -/// focus has no honest duration to add. +/// not a scan. `finished_at IS NOT NULL` is the filter: an open stint +/// contributes to neither the count nor the sum — unfinished focus has no +/// honest duration to add. The Postgres aggregate always answers exactly +/// one row (`count` 0, `sum` NULL on no rows), so the empty school reads as +/// zeros rather than as a missing row; `COALESCE` floors the sum the same +/// way the old `GROUP ALL`-absent case did. /// /// The lifetime counters ride along as a second statement in the *same* -/// query rather than a [`super::badge::load`] call, which would be a second -/// round trip for one record lookup. It repeats that projection — `?? 0` -/// per column, because the columns are `option` and a row predating -/// them carries none — so the two must move together if the shape changes. +/// round rather than a [`super::badge::load`] call, which would be a second +/// round trip for one record lookup. It repeats that projection — the +/// `*_total` columns, because they are the badge rules' inputs — so the two +/// must move together if the shape changes. pub async fn load( db: &Database, user: &UserId, courses: i64, classes: i64, ) -> Result { - let mut result = db - .query(format!( - "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms - FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; - SELECT ({homework_submitted} ?? 0) AS homework_submitted, - ({homework_on_time} ?? 0) AS homework_on_time, - ({exam_sat} ?? 0) AS exam_sat, - ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, - ({marks_given} ?? 0) AS marks_given, - ({lessons_held} ?? 0) AS lessons_held, - ({pool_approved} ?? 0) AS pool_approved, - ({pool_published} ?? 0) AS pool_published, - ({lessons_attended} ?? 0) AS lessons_attended, - ({high_mark} ?? 0) AS high_mark, - ({study_streak} ?? 0) AS study_streak - FROM $usr;", - homework_submitted = BadgeStat::HomeworkSubmitted.field(), - homework_on_time = BadgeStat::HomeworkOnTime.field(), - exam_sat = BadgeStat::ExamSat.field(), - pomodoro_finished = BadgeStat::PomodoroFinished.field(), - pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), - marks_given = BadgeStat::MarksGiven.field(), - lessons_held = BadgeStat::LessonsHeld.field(), - pool_approved = BadgeStat::PoolApproved.field(), - pool_published = BadgeStat::PoolPublished.field(), - lessons_attended = BadgeStat::LessonsAttended.field(), - high_mark = BadgeStat::HighMark.field(), - study_streak = BadgeStat::StudyStreak.field(), - )) - .bind(("usr", user.record())) - .await? - .check()?; - // `GROUP ALL` yields no row at all when nothing matched — that is the - // zero case, not a missing one. - let row = result.take::>(0)?.into_iter().next(); - // A vanished user row reads as all zeros, same as a fresh account. - let totals = result - .take::>(1)? - .into_iter() - .next() - .unwrap_or_default(); + let totals = sqlx::query!( + r#"SELECT count(*) AS "sessions!: i64", + COALESCE(sum(finished_at - started_at), 0) AS "focus_ms!: i64" + FROM pomodoro_session + WHERE app_user = $1 AND finished_at IS NOT NULL"#, + user.uuid() + ) + .fetch_one(db) + .await?; + let stats = sqlx::query_as!( + BadgeStats, + r#"SELECT homework_submitted_total AS homework_submitted, + homework_on_time_total AS homework_on_time, + exam_sat_total AS exam_sat, + pomodoro_finished_total AS pomodoro_finished, + pomodoro_focus_ms_total AS pomodoro_focus_ms, + marks_given_total AS marks_given, + lessons_held_total AS lessons_held, + pool_approved_total AS pool_approved, + pool_published_total AS pool_published, + lessons_attended_total AS lessons_attended, + high_mark_total AS high_mark, + study_streak_longest AS study_streak + FROM app_user WHERE id = $1"#, + user.uuid() + ) + .fetch_optional(db) + .await?; Ok(ProfileStats { - totals, - pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), + totals: stats.unwrap_or_default(), + pomodoro_sessions: totals.sessions, // Floored at zero: a stint stamped by a wall clock that stepped // backwards mid-session sums as negative time, and "you focused for // minus five seconds" is never the truthful answer. New stints // cannot go inverted (see [`PomodoroSession::finish`]); rows written // before that guard still can, and this is what covers them. - pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), + pomodoro_focus_ms: totals.focus_ms.max(0), courses, classes, }) } -/// The aggregate row of [`load`]. -#[derive(Debug, SurrealValue)] -struct PomodoroTotals { - sessions: i64, - focus_ms: i64, -} - #[cfg(test)] mod tests { use super::*; + use crate::database::init_mem; + use crate::domain::user::{Password, Username}; - #[tokio::test] - async fn stats_are_zero_without_pomodoro_rows() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::generate().to_string()); - - let stats = load(&db, &user, 3, 1).await.unwrap(); - // Derived counters: no rows is a true zero, never a null. - assert_eq!(stats.get_pomodoro_sessions(), 0); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - // The passed-in counts survive untouched. - assert_eq!(stats.get_courses(), 3); - assert_eq!(stats.get_classes(), 1); - // No user row at all — the lifetime counters still read as zeros. - assert_eq!(stats.get_totals().get_homework_submitted(), 0); - assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0); + async fn a_user(username: &str, db: &Database) -> crate::domain::user::User { + crate::db::user::create( + db, + Username::try_new(username).unwrap(), + Password::try_new("secret1") + .unwrap() + .hash_async() + .await + .unwrap(), + ) + .await + .unwrap() } - /// The second statement of the same query: the stored counters, straight off - /// the user row, with the columns an older row is missing read as zero. #[tokio::test] - async fn lifetime_totals_ride_the_same_query() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::generate().to_string()); - db.query(format!( - "CREATE $usr SET username = $name, password_hash = 'x', - {} = 4, {} = 3", - crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD, - crate::constant::EXAM_SAT_TOTAL_FIELD, - )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); + async fn an_account_with_no_history_reads_as_zeros() { + let db = init_mem().await.unwrap(); + let user = a_user("profil-bos", &db).await; - let totals = load(&db, &user, 0, 0).await.unwrap(); - let totals = totals.get_totals(); - assert_eq!(totals.get_homework_submitted(), 4); - assert_eq!(totals.get_exam_sat(), 3); - // Never written on this row: absent must read as 0, not as an error. - assert_eq!(totals.get_homework_on_time(), 0); - assert_eq!(totals.get_pomodoro_finished(), 0); - assert_eq!(totals.get_pomodoro_focus_ms(), 0); + let stats = load(&db, user.get_id(), 3, 1).await.unwrap(); + assert_eq!(stats.pomodoro_sessions, 0); + assert_eq!(stats.pomodoro_focus_ms, 0); + assert_eq!(stats.totals.get_homework_submitted(), 0); + // The caller-supplied counts ride through untouched. + assert_eq!(stats.courses, 3); + assert_eq!(stats.classes, 1); } #[tokio::test] - async fn stats_count_finished_stints_only() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::generate().to_string()); - let other = UserId::from_key(&ulid::Ulid::generate().to_string()); + async fn only_finished_stints_count_and_an_open_one_is_invisible() { + let db = init_mem().await.unwrap(); + let user = a_user("profil-dolu", &db).await; - // Two finished stints (1000 ms + 2500 ms), one still running, and one - // finished stint belonging to somebody else. - db.query( - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; - CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \ + VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)", ) - .bind(("usr", user.record())) - .bind(("oth", other.record())) + .bind(uuid::Uuid::now_v7()) + .bind(user.uuid()) + .bind(uuid::Uuid::now_v7()) + .execute(&db) + .await + .unwrap(); + // An open stint: contributes to neither the count nor the sum. + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)", + ) + .bind(uuid::Uuid::now_v7()) + .bind(user.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); - let stats = load(&db, &user, 0, 0).await.unwrap(); - assert_eq!(stats.get_pomodoro_sessions(), 2); - assert_eq!(stats.get_pomodoro_focus_ms(), 3500); + let stats = load(&db, user.get_id(), 0, 0).await.unwrap(); + assert_eq!(stats.pomodoro_sessions, 2); + assert_eq!(stats.pomodoro_focus_ms, 2000 + 1000); } #[tokio::test] - async fn focus_time_never_reads_negative() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::generate().to_string()); + async fn a_negative_stint_sum_is_floored_at_zero() { + let db = init_mem().await.unwrap(); + let user = a_user("profil-terstarihi", &db).await; - // One honest 1000 ms stint and one inverted row — what a backwards - // clock step left behind before `finish` grew its floor. The raw sum is - // -5000; the profile must still answer a duration, not an accusation. - db.query( - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", + // A stint closed by a wall clock that stepped backwards: the sum is + // negative and "minus five seconds of focus" is never the answer. + sqlx::query( + "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \ + VALUES ($1, $2, 5000, 1000)", ) - .bind(("usr", user.record())) + .bind(uuid::Uuid::now_v7()) + .bind(user.uuid()) + .execute(&db) .await - .unwrap() - .check() .unwrap(); - let stats = load(&db, &user, 0, 0).await.unwrap(); - // The stints still happened, so the count is honest at 2. - assert_eq!(stats.get_pomodoro_sessions(), 2); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); + let stats = load(&db, user.get_id(), 0, 0).await.unwrap(); + assert_eq!(stats.pomodoro_focus_ms, 0); } } diff --git a/src/db/session.rs b/src/db/session.rs index c985df1..bc832c7 100644 --- a/src/db/session.rs +++ b/src/db/session.rs @@ -1,4 +1,4 @@ -//! The `session` table: opaque login tokens with an expiry, swept on login. +//! The `user_session` table: opaque login tokens with an expiry, swept on login. use crate::constant::SESSION_DURATION_DAYS; use crate::database::Database; @@ -8,30 +8,48 @@ use crate::domain::user::UserId; use crate::error::AppError; pub async fn create(db: &Database, user: &UserId) -> Result { - let session = Session { - id: SessionId::generate(), - user: user.clone(), - token: SessionToken::generate()?, - expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), - }; - let created: Option = db.create(session.id.record()).content(session).await?; - created.ok_or_else(|| AppError::Internal("failed to create session".into())) + let id = SessionId::generate(); + let token = SessionToken::generate()?; + let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS); + // One statement is the whole mint: the row that comes back is the row + // that was stored. + let session = sqlx::query_as!( + Session, + r#"INSERT INTO user_session (id, app_user, token, expires_at) + VALUES ($1, $2, $3, $4) + RETURNING id AS "id: SessionId", + app_user AS "user: UserId", + token AS "token: SessionToken", + expires_at AS "expires_at: Timestamp""#, + id.0, + user.0, + token.as_str(), + expires_at.as_millis(), + ) + .fetch_one(db) + .await?; + Ok(session) } pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM session WHERE token = $tok LIMIT 1") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let session = sqlx::query_as!( + Session, + r#"SELECT id AS "id: SessionId", + app_user AS "user: UserId", + token AS "token: SessionToken", + expires_at AS "expires_at: Timestamp" + FROM user_session WHERE token = $1"#, + token + ) + .fetch_optional(db) + .await?; + Ok(session) } pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { - db.query("DELETE session WHERE token = $tok") - .bind(("tok", token.to_string())) - .await? - .check()?; + sqlx::query!("DELETE FROM user_session WHERE token = $1", token) + .execute(db) + .await?; Ok(()) } @@ -39,24 +57,28 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> /// the new credential means nothing while a cookie minted under the old one /// still authenticates. pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> { - db.query("DELETE session WHERE user = $usr") - .bind(("usr", user.record())) - .await? - .check()?; + sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.0) + .execute(db) + .await?; Ok(()) } /// Delete every session whose expiry is in the past, returning how many were /// removed. Expired sessions are already rejected at auth, but nothing else -/// deletes their rows — without this sweep the `session` table grows forever. +/// deletes their rows — without this sweep the `user_session` table grows +/// forever. pub async fn purge_expired(db: &Database) -> Result { let now = Timestamp::now().as_millis(); - let mut result = db - .query("DELETE session WHERE expires_at < $now RETURN BEFORE") - .bind(("now", now)) - .await? - .check()?; - Ok(result.take::>(0)?.len() as u64) + let (deleted,) = sqlx::query!( + r#"WITH gone AS ( + DELETE FROM user_session WHERE expires_at < $1 RETURNING 1 + ) + SELECT count(*) AS "deleted!: i64" FROM gone"#, + now + ) + .fetch_one(db) + .await?; + Ok(u64::try_from(deleted).unwrap_or(u64::MAX)) } #[cfg(test)] diff --git a/src/db/settings.rs b/src/db/settings.rs index 5810b3c..a607410 100644 --- a/src/db/settings.rs +++ b/src/db/settings.rs @@ -1,14 +1,32 @@ -//! The `settings` singleton: one row (`settings:school`) holding the school's -//! policy knobs. An absent row reads as the built-in defaults everywhere. +//! The `settings` singleton: one row (`settings`, id `'school'`) holding the +//! school's policy knobs. An absent row reads as the built-in defaults +//! everywhere. + +use sqlx::types::Json; use crate::database::Database; -use crate::domain::settings::Settings; +use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; use crate::error::AppError; -/// The stored policy, or the defaults when no row exists yet. pub async fn load(db: &Database) -> Result { - let found: Option = db.select(Settings::record_id()).await?; - Ok(found.unwrap_or_else(Settings::defaults)) + let settings = sqlx::query_as!( + Settings, + r#"SELECT id, + exam_kinds AS "exam_kinds: Json>", + attendance_statuses, + grade_bands AS "grade_bands: Json>", + max_file_bytes, + chatbot_history_turns, + max_chatbot_message_len, + max_chatbot_threads, + meal_slots AS "meal_slots: Json>", + dietary_tags, + meal_cancel_cutoff_minutes + FROM settings WHERE id = 'school'"# + ) + .fetch_optional(db) + .await?; + Ok(settings.unwrap_or_else(Settings::defaults)) } /// Persist the policy (single UPSERT on the fixed singleton id), @@ -16,8 +34,49 @@ pub async fn load(db: &Database) -> Result { /// wherever the new policy was merged from a loaded snapshot. pub async fn save(db: &Database, settings: Settings) -> Result { // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged - let saved: Option = db.upsert(Settings::record_id()).content(settings).await?; - saved.ok_or_else(|| AppError::Internal("failed to save settings".into())) + let saved = sqlx::query_as!( + Settings, + r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, + max_file_bytes, chatbot_history_turns, + max_chatbot_message_len, max_chatbot_threads, + meal_slots, dietary_tags, meal_cancel_cutoff_minutes) + VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (id) DO UPDATE SET + exam_kinds = EXCLUDED.exam_kinds, + attendance_statuses = EXCLUDED.attendance_statuses, + grade_bands = EXCLUDED.grade_bands, + max_file_bytes = EXCLUDED.max_file_bytes, + chatbot_history_turns = EXCLUDED.chatbot_history_turns, + max_chatbot_message_len = EXCLUDED.max_chatbot_message_len, + max_chatbot_threads = EXCLUDED.max_chatbot_threads, + meal_slots = EXCLUDED.meal_slots, + dietary_tags = EXCLUDED.dietary_tags, + meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes + RETURNING id, + exam_kinds AS "exam_kinds: Json>", + attendance_statuses, + grade_bands AS "grade_bands: Json>", + max_file_bytes, + chatbot_history_turns, + max_chatbot_message_len, + max_chatbot_threads, + meal_slots AS "meal_slots: Json>", + dietary_tags, + meal_cancel_cutoff_minutes"#, + settings.exam_kinds, + settings.attendance_statuses, + settings.grade_bands, + settings.max_file_bytes, + settings.chatbot_history_turns, + settings.max_chatbot_message_len, + settings.max_chatbot_threads, + settings.meal_slots, + settings.dietary_tags, + settings.meal_cancel_cutoff_minutes, + ) + .fetch_one(db) + .await?; + Ok(saved) } /// Persist the policy only while the stored row still matches `expected` @@ -28,269 +87,100 @@ pub async fn save(db: &Database, settings: Settings) -> Result( + db: E, settings: Settings, expected: &Settings, -) -> Result, AppError> { - let mut result = db - .query( - "BEGIN TRANSACTION; - INSERT IGNORE INTO settings $expected; - UPDATE $id CONTENT $new - WHERE exam_kinds = $ek - AND attendance_statuses = $st - AND grade_bands = $gb - AND max_file_bytes = $mf - AND chatbot_history_turns = $ct - AND max_chatbot_threads = $cc - AND max_chatbot_message_len = $cl - AND (meal_slots = NONE) = $ms_unset - AND (meal_slots ?? []).map(|$s| { - name: $s.name, - serving_minute: $s.serving_minute - }) = ($ms ?? []) - AND dietary_tags = $dt - AND meal_cancel_cutoff_minutes = $mc; - COMMIT TRANSACTION;", - ) - .bind(("expected", expected.clone())) - .bind(("id", Settings::record_id())) - .bind(("new", settings)) - .bind(("ek", expected.exam_kinds.clone())) - .bind(("st", expected.attendance_statuses.clone())) - .bind(("gb", expected.grade_bands.clone())) - .bind(("mf", expected.max_file_bytes)) - .bind(("ct", expected.chatbot_history_turns)) - .bind(("cc", expected.max_chatbot_threads)) - .bind(("cl", expected.max_chatbot_message_len)) - .bind(("ms_unset", expected.meal_slots.is_none())) - .bind(("ms", expected.meal_slots.clone())) - .bind(("dt", expected.dietary_tags.clone())) - .bind(("mc", expected.meal_cancel_cutoff_minutes)) - .await? - .check()?; - // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An - // empty slot means the row no longer matched `expected`. - Ok(result.take::>(2)?.into_iter().next()) +) -> Result, AppError> +where + E: sqlx::PgExecutor<'e>, +{ + let saved = sqlx::query_as!( + Settings, + r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands, + max_file_bytes, chatbot_history_turns, + max_chatbot_message_len, max_chatbot_threads, + meal_slots, dietary_tags, meal_cancel_cutoff_minutes) + VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (id) DO UPDATE SET + exam_kinds = $1, + attendance_statuses = $2, + grade_bands = $3, + max_file_bytes = $4, + chatbot_history_turns = $5, + max_chatbot_message_len = $6, + max_chatbot_threads = $7, + meal_slots = $8, + dietary_tags = $9, + meal_cancel_cutoff_minutes = $10 + WHERE settings.exam_kinds IS NOT DISTINCT FROM $11 + AND settings.attendance_statuses IS NOT DISTINCT FROM $12 + AND settings.grade_bands IS NOT DISTINCT FROM $13 + AND settings.max_file_bytes IS NOT DISTINCT FROM $14 + AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15 + AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16 + AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17 + AND settings.meal_slots IS NOT DISTINCT FROM $18 + AND settings.dietary_tags IS NOT DISTINCT FROM $19 + AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20 + RETURNING id, + exam_kinds AS "exam_kinds: Json>", + attendance_statuses, + grade_bands AS "grade_bands: Json>", + max_file_bytes, + chatbot_history_turns, + max_chatbot_message_len, + max_chatbot_threads, + meal_slots AS "meal_slots: Json>", + dietary_tags, + meal_cancel_cutoff_minutes"#, + settings.exam_kinds, + settings.attendance_statuses, + settings.grade_bands, + settings.max_file_bytes, + settings.chatbot_history_turns, + settings.max_chatbot_message_len, + settings.max_chatbot_threads, + settings.meal_slots, + settings.dietary_tags, + settings.meal_cancel_cutoff_minutes, + expected.exam_kinds, + expected.attendance_statuses, + expected.grade_bands, + expected.max_file_bytes, + expected.chatbot_history_turns, + expected.max_chatbot_message_len, + expected.max_chatbot_threads, + expected.meal_slots, + expected.dietary_tags, + expected.meal_cancel_cutoff_minutes, + ) + .fetch_optional(db) + .await?; + // An empty result means the row no longer matched `expected`. + Ok(saved) } #[cfg(test)] mod tests { - use super::*; - use crate::constant::{ - DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN, - DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES, - }; - use crate::domain::settings::{ExamKindDef, GradeBand, SettingsParams}; - - fn kinds(list: &[&str]) -> Vec { - list.iter() - .map(|s| ExamKindDef::try_new(s, 1).unwrap()) - .collect() - } - - fn names(settings: &Settings) -> Vec<&str> { - settings - .get_exam_kinds() - .iter() - .map(ExamKindDef::get_name) - .collect() - } - - /// The defaults as tweakable params — every site below overrides only the - /// fields it is testing (`..params()`). - fn params() -> SettingsParams { - Settings::defaults().params() - } - - fn bands(list: &[(i64, &str)]) -> Vec { - list.iter() - .map(|(min, label)| GradeBand::try_new(*min, label).unwrap()) - .collect() - } - - #[tokio::test] - async fn a_row_predating_the_optional_knobs_reads_the_defaults() { - let db = crate::database::init_mem().await.unwrap(); - // The defaults carry no explicit knobs, so this writes a row without - // those fields — exactly what a volume from before them looks like. - save(&db, Settings::defaults()).await.unwrap(); - let loaded = load(&db).await.unwrap(); - assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES); - assert_eq!( - loaded.get_chatbot_history_turns(), - DEFAULT_CHATBOT_HISTORY_TURNS - ); - assert_eq!( - loaded.get_max_chatbot_threads(), - DEFAULT_MAX_CHATBOT_THREADS - ); - assert_eq!( - loaded.get_max_chatbot_message_len(), - DEFAULT_MAX_CHATBOT_MESSAGE_LEN - ); - // And a snapshot of that old row still passes the compare-and-set. - let saved = save_if_unchanged( - &db, - Settings::try_new(SettingsParams { - max_file_bytes: 4096, - ..loaded.params() - }) - .unwrap(), - &loaded, - ) - .await - .unwrap() - .expect("a merge over an old-shape row applies"); - assert_eq!(saved.get_max_file_bytes(), 4096); - } - - #[tokio::test] - async fn load_save_roundtrip_on_the_singleton() { - let db = crate::database::init_mem().await.unwrap(); - // No row yet → the defaults, not an error. - let loaded = load(&db).await.unwrap(); - assert_eq!( - loaded.get_exam_kinds(), - Settings::defaults().get_exam_kinds() - ); - // Save a custom policy and read it back — bands (nested objects under - // a FLEXIBLE field) must survive the trip. - save( - &db, - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - grade_bands: bands(&[(0, "F"), (50, "P")]), - max_file_bytes: 2048, - chatbot_history_turns: 3, - ..params() - }) - .unwrap(), - ) - .await - .unwrap(); - let loaded = load(&db).await.unwrap(); - assert_eq!(names(&loaded), ["lab"]); - assert_eq!(loaded.get_grade_bands().len(), 2); - assert_eq!(loaded.grade_label(60.0), Some("P")); - assert_eq!(loaded.get_max_file_bytes(), 2048); - assert_eq!(loaded.get_chatbot_history_turns(), 3); - // A second save lands on the same singleton row, not a new one. - save( - &db, - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["quiz"]), - ..params() - }) - .unwrap(), - ) - .await - .unwrap(); - let mut result = db.query("SELECT * FROM settings").await.unwrap(); - let rows: Vec = result.take(0).unwrap(); - assert_eq!(rows.len(), 1); - assert_eq!(names(&rows[0]), ["quiz"]); - } - - #[tokio::test] - async fn a_stale_snapshot_cannot_revert_a_newer_policy() { - let db = crate::database::init_mem().await.unwrap(); - - // Editor A snapshots the policy (the defaults — no row yet)... - let stale = load(&db).await.unwrap(); - // ...then editor B lands a new exam-kind list first. - save( - &db, - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - ..params() - }) - .unwrap(), - ) - .await - .unwrap(); - - // A's merge over the stale snapshot (kinds kept "as loaded", bands - // changed) — exactly what a concurrent PATCH /settings computes — - // must be refused, not applied. - let refused = save_if_unchanged( - &db, - Settings::try_new(SettingsParams { - grade_bands: bands(&[(0, "F"), (50, "P")]), - ..stale.params() - }) - .unwrap(), - &stale, - ) - .await - .unwrap(); - assert!(refused.is_none(), "a stale snapshot's save must not apply"); - - // B's edit must survive A's stale write attempt. - let after = load(&db).await.unwrap(); - assert_eq!( - names(&after), - ["lab"], - "a concurrent editor's exam kinds must not be silently reverted" - ); - assert!(after.get_grade_bands().is_empty()); - - // A's retry — reload, re-merge, save again — lands both edits. - let fresh = load(&db).await.unwrap(); - let saved = save_if_unchanged( - &db, - Settings::try_new(SettingsParams { - grade_bands: bands(&[(0, "F"), (50, "P")]), - ..fresh.params() - }) - .unwrap(), - &fresh, - ) - .await - .unwrap() - .expect("a merge over the current row applies"); - assert_eq!(names(&saved), ["lab"]); - assert_eq!(saved.get_grade_bands().len(), 2); - } - - #[tokio::test] - async fn save_if_unchanged_seeds_the_first_row() { - let db = crate::database::init_mem().await.unwrap(); - // No row yet: `load` reports the defaults, and a save conditioned on - // that snapshot must apply (seeding the singleton on the way). - let current = load(&db).await.unwrap(); - let saved = save_if_unchanged( - &db, - Settings::try_new(SettingsParams { - exam_kinds: kinds(&["lab"]), - ..current.params() - }) - .unwrap(), - ¤t, - ) - .await - .unwrap() - .expect("the first save applies"); - assert_eq!(names(&saved), ["lab"]); - let mut result = db.query("SELECT * FROM settings").await.unwrap(); - let rows: Vec = result.take(0).unwrap(); - assert_eq!(rows.len(), 1, "still one singleton row"); - } + // Ported in wave 3: they need a live school database. } diff --git a/src/db/user.rs b/src/db/user.rs index b85f5bd..c3856bc 100644 --- a/src/db/user.rs +++ b/src/db/user.rs @@ -1,22 +1,17 @@ -//! The `user` table: the row mint (with the duplicate-username mapping), row -//! reads and listings, the admin-floor count, the role cascade transaction, -//! and the field-scoped writers. The workflows that sequence these under -//! [`crate::service::user::ADMIN_FLOOR_LOCK`] live in -//! [`crate::service::user`]. - -use surrealdb::types::{RecordId, SurrealValue}; - -use crate::constant::{ - APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE, - CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, ENROLLMENT_COUNT_FIELD, - ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD, - REGISTRATION_TABLE, -}; -use crate::database::{Database, transaction_with_retry, write_with_retry}; +//! The `app_user` table: the row mint (with the duplicate-username mapping), +//! row reads and listings, the role cascade transaction (admin floor and all +//! sweeps included), and the field-scoped writers. The workflow that drives +//! the cascade lives in [`crate::service::user`]. +//! +//! The compile-time macros map columns by name and check each decoded type +//! against the prepare schema, so the seventeen user columns are spelled +//! out — newtype overrides included — in every static statement below. The +//! repetitions are the check. + +use crate::database::{Database, tx_with_retry}; use crate::db::field_update::FieldUpdate; -use crate::db::page::PagedList; -use crate::domain::appointment::AppointmentStatus; -use crate::domain::board::Board; +use crate::db::page::{PagedList, Param}; +use crate::domain::board::{Board, BoardId, BoardTitle}; use crate::domain::note_file::FileContentType; use crate::domain::preferences::{Language, PaletteColor, Theme}; use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone}; @@ -43,58 +38,82 @@ pub async fn create( /// or a cancelled future), and the row left behind is an ordinary student /// account that [`crate::service::user::ensure_admin`] must then refuse to /// touch — a deployment with no admin and no way for a later boot to repair it. +/// +/// The unique index on `username` is the whole availability check. The old +/// pre-check-and-recheck dance existed because the old store could not name +/// the constraint a racing insert had violated; here the violated +/// constraint's name answers directly (`app_user_username`), and the loser +/// of a race gets the same 409 the sequential duplicate always got. pub async fn create_with_role( db: &Database, username: Username, password_hash: PasswordHash, role: Role, ) -> Result { - if find_by_username(db, username.as_str()).await?.is_some() { - return Err(AppError::Conflict("username already taken")); - } - let user = User { - id: UserId::generate(), - username, - password_hash, + let id = UserId::generate(); + match sqlx::query_as!( + User, + r#"INSERT INTO app_user (id, username, password_hash, role) + VALUES ($1, $2, $3, $4) + RETURNING id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size"#, + id.uuid(), + username.as_str(), + password_hash.as_str(), role, - name: None, - surname: None, - email: None, - phone: None, - birth_date: None, - theme: None, - language: None, - palette_color: None, - display_name: None, - bio: None, - avatar_file: None, - avatar_content_type: None, - avatar_size: None, - }; - let created: Result, surrealdb::Error> = - db.create(user.id.record()).content(user.clone()).await; - match created { - Ok(Some(created)) => Ok(created), - Ok(None) => Err(AppError::Internal("failed to create user".into())), - // The availability pre-check above is not atomic with the insert: - // two concurrent registrations can both pass it, and the loser then - // trips the unique username index. That loss is the same condition - // as the sequential duplicate, so report the same 409 — not a 500. - Err(err) => { - if find_by_username(db, user.username.as_str()) - .await? - .is_some() - { - Err(AppError::Conflict("username already taken")) - } else { - Err(err.into()) - } + ) + .fetch_one(db) + .await + { + Ok(user) => Ok(user), + Err(err) if crate::database::unique_violation(&err) == Some("app_user_username") => { + Err(AppError::Conflict("username already taken")) } + Err(err) => Err(err.into()), } } pub async fn read(db: &Database, id: &UserId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let user = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE id = $1"#, + id.uuid() + ) + .fetch_optional(db) + .await?; + Ok(user) } pub async fn list_all( @@ -102,7 +121,7 @@ pub async fn list_all( limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new("user", "ORDER BY id DESC") + PagedList::new("app_user", "ORDER BY id DESC") .run(limit, offset, db) .await } @@ -113,50 +132,63 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result, App if ids.is_empty() { return Ok(Vec::new()); } - let records: Vec = ids.iter().map(UserId::record).collect(); - let mut result = db - .query("SELECT * FROM user WHERE id IN $ids") - .bind(("ids", records)) - .await? - .check()?; - Ok(result.take::>(0)?) + let ids: Vec = ids.iter().map(UserId::uuid).collect(); + let users = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE id = ANY($1)"#, + ids + ) + .fetch_all(db) + .await?; + Ok(users) } /// Every user holding exactly `role` — e.g. the roster of a role-targeted /// event. Exact match, not `at_least`: "all teachers" means teachers, not /// managers and admins too. pub async fn list_by_role(db: &Database, role: Role) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC") - .bind(("role", role)) - .await? - .check()?; - Ok(result.take::>(0)?) -} - -/// Would lowering `target` out of `admin` leave the school with none? Both -/// halves are asked of the **live** rows in one round trip: is that row an -/// admin right now, and does any other admin exist. It asks for one id per -/// half rather than a `count()` — a count over an indexed field compared -/// against a plan-time value answers `{count: N}` on the real server, and -/// neither half needs a number. -/// -/// Caller must hold -/// [`crate::service::user::ADMIN_FLOOR_LOCK`] for the answer to still be -/// true by the time it is acted on. -pub async fn would_orphan_admins(db: &Database, target: &UserId) -> Result { - let mut result = db - .query( - "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\ - SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1", - ) - .bind(("role", Role::Admin)) - .bind(("usr", target.record())) - .await? - .check()?; - let is_admin = !result.take::>(0)?.is_empty(); - let others = !result.take::>(1)?.is_empty(); - Ok(is_admin && !others) + let users = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE role = $1 ORDER BY id DESC"#, + role + ) + .fetch_all(db) + .await?; + Ok(users) } /// Case- and diacritic-insensitive fragment search over username, name, @@ -181,41 +213,58 @@ pub async fn search( offset: i64, ) -> Result<(Vec, i64), AppError> { let needle = search_fold(query.trim()); - let text_clause = format!( - "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)", - search_fold_sql("username"), - search_fold_sql("name ?? ''"), - search_fold_sql("surname ?? ''"), - ); - let mut clauses = Vec::new(); + // Placeholders are positional, and every clause is optional, so the + // numbering is assigned as the clauses are added. Containment is spelled + // `position(...) > 0` rather than `LIKE` so the needle's `%` and `_` + // stay literal characters — the fold does not escape, and a query for + // `100%` must not grow a wildcard. + let mut binds: Vec = Vec::new(); + let mut clauses: Vec = Vec::new(); if !needle.is_empty() { - clauses.push(text_clause.as_str()); + let n = binds.len() + 1; + clauses.push(format!( + "(position(${n} in {}) > 0 \ + OR position(${n} in {}) > 0 \ + OR position(${n} in {}) > 0)", + search_fold_sql("username"), + search_fold_sql("coalesce(name, '')"), + search_fold_sql("coalesce(surname, '')"), + )); + binds.push(Param::Text(needle)); } - if role.is_some() { - clauses.push("role = $role"); + if let Some(role) = role { + let n = binds.len() + 1; + clauses.push(format!("role = ${n}")); + binds.push(Param::Text(role.as_str().to_string())); } - if allowed_roles.is_some() { - clauses.push("role IN $allowed"); + if let Some(allowed) = allowed_roles { + let n = binds.len() + 1; + clauses.push(format!("role = ANY(${n})")); + binds.push(Param::Texts( + allowed + .iter() + .map(|role| role.as_str().to_string()) + .collect(), + )); } let where_clause = if clauses.is_empty() { - "true".to_string() + "TRUE".to_string() } else { clauses.join(" AND ") }; - let mut list = - PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username").bind("q", needle); - if let Some(role) = role { - list = list.bind("role", role); - } - if let Some(allowed) = allowed_roles { - list = list.bind("allowed", allowed.to_vec()); + let mut list = PagedList::new( + format!("app_user WHERE {where_clause}"), + "ORDER BY username", + ); + for bind in binds { + list = list.bind(bind); } list.run(limit, offset, db).await } /// The role write and every sweep it owes, in one transaction — the -/// statement list behind [`crate::service::user::set_role`]. See there for -/// the floor that guards it and the arm-by-arm reasoning; what follows is +/// statement list behind [`crate::service::user::set_role`]; see there for +/// the floor that guards it and the arm-by-arm reasoning. What follows is /// the store side. /// /// Writes *only* the `role` field of the user row (never the whole row): @@ -224,8 +273,7 @@ pub async fn search( /// whole-row write would carry the snapshot's copy of the *other* group back /// over a concurrent edit — an in-flight profile save silently reverting an /// admin's demotion, or this write erasing a profile edit that raced it. -/// [`crate::db::user::set_profile`] and -/// [`crate::db::user::set_preferences`] are scoped for the same reason. +/// [`set_profile`] and [`set_preferences`] are scoped for the same reason. /// /// What is swept, and why the conditions differ: /// @@ -244,12 +292,15 @@ pub async fn search( /// else could remove: staff free their own by hand (`unregister` allows /// the self case) but a parent can reach no such door, so a promotion /// strands nothing and only this demotion does. A list that has already -/// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it -/// stands — past the freeze it is historical record, re-registering -/// answers 409, and rewriting it here would be irrecoverable. A signup -/// whose event record is *gone* has no seat to hand back and no list that -/// can freeze, so it is deleted rather than skipped: skipped, it is -/// stranded forever (`unregister` 404s on the missing event). +/// **frozen** (an audience-`registration` event whose start-or-end time +/// has passed — the same predicate +/// [`crate::domain::registration`]'s Rust check enforces) is left exactly +/// as it stands — past the freeze it is historical record, +/// re-registering answers 409, and rewriting it here would be +/// irrecoverable. A signup whose event record is *gone* has no seat to +/// hand back and no list that can freeze, so it is deleted rather than +/// skipped: skipped, it is stranded forever (`unregister` 404s on the +/// missing event). /// * **Below teacher** gives up course staffing and homeroom-teacher /// columns — only teacher+ may hold either — and the published /// appointment calendar, whose live bookings are cancelled in the same @@ -260,8 +311,9 @@ pub async fn search( /// cancelled once its window opens — leaving the slot's `occupied` seat /// pinned at one and the slot itself undeletable forever. The requester /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the -/// reason on `cancel_reason`; the slot it pointed at is gone, so the -/// booking renders without a window +/// reason on `cancel_reason`; the slot it pointed at is gone (the +/// `ON DELETE SET NULL` link carries the delete), so the booking renders +/// without a window /// ([`crate::domain::appointment::Appointment`]'s reader already treats a /// vanished slot that way). There is no notification anywhere in /// this crate, so a settled row the person can read is the strongest @@ -275,146 +327,234 @@ pub async fn search( /// fan-out cannot sit inside a database transaction, and a room told before /// the commit would re-read the pre-commit state. /// -/// Admissible for [`transaction_with_retry`] by construction: `SELECT`, -/// `UPDATE` and `DELETE` only, so no statement can answer "already exists" -/// and every lost round is a plain re-send. +/// **The admin floor is the role write's own `WHERE`.** The old guard was a +/// count read under a process-wide lock held across the whole cascade, +/// because the old store could not serialize a cross-record count against a +/// concurrent update (write-skew). Here the count rides the very row write +/// it guards — a demotion that would leave no other admin writes zero rows +/// — so two racing demotions contend on row locks and exactly one lands. +/// Zero rows therefore means the floor refused; the missing-row reading of +/// zero rows is unreachable (no route deletes a user row, and the caller's +/// 404 pre-read answers that case first anyway). pub async fn set_role_cascade( db: &Database, target: &UserId, role: Role, ) -> Result<(User, Vec), AppError> { - // Built as a statement list rather than one string so the result slot - // of the board write is *counted*, not hand-tallied against arms that - // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere. - let mut batch = vec![ - "BEGIN TRANSACTION".to_string(), - "UPDATE $usr SET role = $role RETURN AFTER".to_string(), - ]; - if role != Role::Student { - batch.push(format!( - "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)" - )); - batch.push(format!( - "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \ - {CLASS_MEMBER_COUNT_FIELD} = \ - math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}" - )); - batch.push(format!( - "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)" - )); - batch.push(format!( - "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \ - {ENROLLMENT_COUNT_FIELD} = \ - math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}" - )); - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr")); - } - let mut board_slot = None; - if role == Role::Parent { - batch.push(format!( - "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)" - )); - // Row and seat move together per signup, the way `unregister` does: - // the seats are independent facts on unrelated events. A missing - // event matches nothing in the guard *and* nothing in the counter - // write, which is precisely the orphan rule. - batch.push(format!( - "FOR $signup IN ($signups ?? []) {{ \ - IF array::len((SELECT VALUE id FROM $signup.event \ - WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \ - LET $freed = (DELETE $signup.id RETURN BEFORE); \ - UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \ - math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \ - }}; }}" - )); - // A room whose *creator* is demoted can never be ended by anyone: - // the whiteboard is closed to parents outright, so the creator is - // 404'd off their own board, `clear`/`lock`/`close`/`delete` are - // creator-only for everyone else, and `crate::db::board::list_for_user` is the - // crate's only enumeration — no manager or admin can so much as find - // the id. Its participants meanwhile keep drawing (the room re-derives - // membership per frame and they still pass), into a board only the - // 50 000-stroke lifetime cap could ever retire. So the demotion - // retires it, with the same compare-and-set [`crate::db::board::close`] uses: an - // already-closed board keeps its first stamp. Closed and not deleted - // because the marks are the participants' work too — they keep reading - // the board and its whole history, and the creator's `board_count` - // seat stays taken, which is correct while the row it counts exists. - // Stamped *before* the roster strip so the strip's `RETURN AFTER` - // carries the closed row the caller fans out. - batch.push(format!( - "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE" - )); - board_slot = Some(batch.len()); - batch.push(format!( - "UPDATE {BOARD_TABLE} SET participants -= $usr \ - WHERE $usr IN participants OR creator = $usr RETURN AFTER" - )); - } - if role != Role::Parent { - batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr")); - } - if !role.at_least(Role::Teacher) { - batch.push(format!( - "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers" - )); - batch.push(format!( - "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr" - )); - // The published calendar goes too, and the bookings on it are - // settled first: a slot only its own teacher can list and only a - // teacher+ can delete is reachable by nobody once that teacher is - // demoted, and a live booking on one is worse — nobody can approve, - // reject or (past its start) cancel it, so it pins the slot's - // `occupied` seat forever. Cancelled rather than deleted so the - // person who asked is left with a settled booking they can still - // read, carrying who dropped it and why; the slot row (and with it - // the seat) goes, which is what makes this convergent. - batch.push(format!( - "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)" - )); - batch.push(format!( - "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \ - cancel_reason = 'the teacher no longer holds a teaching role' \ - WHERE slot IN $slots AND status IN ['{pending}', '{approved}']", - cancelled = AppointmentStatus::Cancelled.as_str(), - pending = AppointmentStatus::Pending.as_str(), - approved = AppointmentStatus::Approved.as_str(), - )); - // Deleting the slots is also what makes a *concurrent* booking safe: - // `Appointment::book` claims the slot row this deletes, so the two - // collide in the store and the loser re-sends. A slot *published* - // concurrently shares no key with any of this, which is why - // `AppointmentSlot::insert_claimed` claims the user row instead. - batch.push(format!( - "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots" - )); - } - let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n")); - let (mut result, mut errors) = transaction_with_retry( - db, - &sql, - &[ - ("usr".into(), target.record().into_value()), - ("role".into(), role.into_value()), - ("now".into(), Timestamp::now().as_millis().into_value()), - ], - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - let updated = result - .take::>(1)? - .into_iter() - .next() - .ok_or(AppError::NotFound)?; - let boards = match board_slot { - Some(slot) => result.take::>(slot)?, - None => Vec::new(), - }; - Ok((updated, boards)) + // One wall-clock read for the whole cascade, bound by every stamping + // statement — the old batch's single `$now`. + let now = Timestamp::now().as_millis(); + tx_with_retry(db, true, async |tx| { + // The role write, floor guard included. `$2 <> 'admin'` arms the + // guard only for a demotion: a promotion or a same-role rewrite can + // never orphan the admins. + let updated = sqlx::query_as!( + User, + r#"UPDATE app_user SET role = $2 + WHERE id = $1 + AND NOT (role = 'admin' + AND $2 <> 'admin' + AND (SELECT count(*) FROM app_user + WHERE role = 'admin' AND id <> $1) = 0) + RETURNING id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size"#, + target.uuid(), + role, + ) + .fetch_optional(&mut *tx) + .await?; + let Some(updated) = updated else { + return Err(AppError::Conflict( + "the school must keep at least one admin — promote another account first", + )); + }; + + if role != Role::Student { + // Class memberships go, and each class they were on gets its + // seat back. One row per (class, user), so one decrement each. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM class_member WHERE app_user = $1 RETURNING class + ) + UPDATE class_group + SET class_member_count = GREATEST(class_member_count - 1, 0) + WHERE id IN (SELECT gone.class FROM gone)"#, + target.uuid(), + ) + .execute(&mut *tx) + .await?; + // Every enrollment row — hand-placed included — and each + // course's seat with it. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM enrollment WHERE app_user = $1 RETURNING course + ) + UPDATE course + SET enrollment_count = GREATEST(enrollment_count - 1, 0) + WHERE id IN (SELECT gone.course FROM gone)"#, + target.uuid(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!("DELETE FROM parent_link WHERE student = $1", target.uuid()) + .execute(&mut *tx) + .await?; + } + + if role == Role::Parent { + // Signups whose event is gone: no seat to hand back, no list + // that could freeze — delete the stray row outright. + sqlx::query!( + r#"DELETE FROM registration r + WHERE r.app_user = $1 + AND NOT EXISTS (SELECT 1 FROM event e WHERE e.id = r.event)"#, + target.uuid(), + ) + .execute(&mut *tx) + .await?; + // Row and seat move together per signup, the way `unregister` + // does: the seats are independent facts on unrelated events. A + // frozen list keeps its rows exactly as they stand; every other + // list — including a registration event with no dates at all, + // which never freezes — releases the seat. + sqlx::query!( + r#"WITH gone AS ( + DELETE FROM registration r + USING event e + WHERE r.event = e.id + AND r.app_user = $1 + AND NOT (e.audience_kind = 'registration' + AND COALESCE(e.starts_at, e.ends_at) IS NOT NULL + AND COALESCE(e.starts_at, e.ends_at) <= $2) + RETURNING r.event AS event_id + ) + UPDATE event + SET registration_count = GREATEST(registration_count - 1, 0) + WHERE id IN (SELECT gone.event_id FROM gone)"#, + target.uuid(), + now, + ) + .execute(&mut *tx) + .await?; + // A room whose *creator* is demoted can never be ended by anyone: + // the whiteboard is closed to parents outright, so the creator is + // 404'd off their own board, `clear`/`lock`/`close`/`delete` are + // creator-only for everyone else, and + // `crate::db::board::list_for_user` is the crate's only + // enumeration — no manager or admin can so much as find the id. + // Its participants meanwhile keep drawing (the room re-derives + // membership per frame and they still pass), into a board only + // the 50 000-stroke lifetime cap could ever retire. So the + // demotion retires it, with the same compare-and-set + // [`crate::db::board::close`] uses: an already-closed board + // keeps its first stamp. Closed and not deleted because the + // marks are the participants' work too — they keep reading the + // board and its whole history, and the creator's `board_count` + // seat stays taken, which is correct while the row it counts + // exists. Stamped *before* the roster strip so the strip's + // `RETURNING` carries the closed row the caller fans out. + sqlx::query!( + "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL", + target.uuid(), + now, + ) + .execute(&mut *tx) + .await?; + let boards = sqlx::query_as!( + Board, + r#"UPDATE board + SET participants = array_remove(participants, $1) + WHERE $1 = ANY(participants) OR creator = $1 + RETURNING id AS "id: BoardId", + creator AS "creator: UserId", + title AS "title: BoardTitle", + participants AS "participants: Vec", + locked, + locked_by AS "locked_by: UserId", + locked_at AS "locked_at: Timestamp", + epoch, + closed_at AS "closed_at: Timestamp", + created_at AS "created_at: Timestamp""#, + target.uuid(), + ) + .fetch_all(&mut *tx) + .await?; + return Ok((updated, boards)); + } + + if role != Role::Parent { + sqlx::query!("DELETE FROM parent_link WHERE parent = $1", target.uuid()) + .execute(&mut *tx) + .await?; + } + + if !role.at_least(Role::Teacher) { + // Course staffing goes — only teacher+ may hold a seat on the + // list. + sqlx::query!( + "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)", + target.uuid(), + ) + .execute(&mut *tx) + .await?; + sqlx::query!( + "UPDATE class_group SET teacher = NULL WHERE teacher = $1", + target.uuid(), + ) + .execute(&mut *tx) + .await?; + // The published calendar goes too, and the bookings on it are + // settled first: a slot only its own teacher can list and only a + // teacher+ can delete is reachable by nobody once that teacher is + // demoted, and a live booking on one is worse — nobody can + // approve, reject or (past its start) cancel it, so it pins the + // slot's `occupied` seat forever. Cancelled rather than deleted + // so the person who asked is left with a settled booking they can + // still read, carrying who dropped it and why; the slot row (and + // with it the seat) goes, which is what makes this convergent. + sqlx::query!( + r#"UPDATE appointment + SET status = 'cancelled', cancelled_by = $1, cancel_reason = $2 + WHERE slot IN (SELECT id FROM appointment_slot WHERE teacher = $1) + AND status IN ('pending', 'approved')"#, + target.uuid(), + "the teacher no longer holds a teaching role", + ) + .execute(&mut *tx) + .await?; + // Deleting the slots is also what makes a *concurrent* booking + // safe: `Appointment::book` claims the slot row this deletes, so + // the two collide in the store. A slot *published* concurrently + // shares no key with any of this, which is why the publish path + // claims the user row instead. The settled booking rows survive + // the delete with `slot = NULL` (`ON DELETE SET NULL`) — still + // readable, windowless. + sqlx::query!( + "DELETE FROM appointment_slot WHERE teacher = $1", + target.uuid(), + ) + .execute(&mut *tx) + .await?; + } + + Ok((updated, Vec::new())) + }) + .await } /// Write the personal-info and public-profile fields the request actually @@ -445,31 +585,36 @@ pub async fn set_profile( display_name: Option>, bio: Option>, ) -> Result { - FieldUpdate::new(id.record()) - .set("name", name) - .set("surname", surname) - .set("email", email) - .set("phone", phone) - .set("birth_date", birth_date) - .set("display_name", display_name) - .set("bio", bio) - .run::(db) + // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value: + // `Param::OptText` carries both shapes of one nullable TEXT column. + fn text(value: Option>) -> Option { + value.map(|inner| Param::OptText(inner.map(str::to_string))) + } + FieldUpdate::new("app_user", id.uuid()) + .set("name", text(name.map(|n| n.as_str()))) + .set("surname", text(surname.map(|n| n.as_str()))) + .set("email", text(email.map(|n| n.as_str()))) + .set("phone", text(phone.map(|n| n.as_str()))) + .set("birth_date", text(birth_date.map(|n| n.as_str()))) + .set("display_name", text(display_name.map(|n| n.as_str()))) + .set("bio", text(bio.map(|n| n.as_str()))) + .run(db) .await } /// Point the row at a freshly uploaded avatar blob, returning the row *as /// it was* — the caller deletes `before.get_avatar_file()` off disk. Losing -/// `RETURN BEFORE` here strands the replaced blob forever: no route ever +/// the pre-image here strands the replaced blob forever: no route ever /// deletes a user, so nothing else would collect it. /// /// Field-scoped for the same reason as [`set_profile`]: an avatar /// upload must not carry a stale snapshot's role back over an admin's /// change. `None` means the row is gone. /// -/// Sent through [`write_with_retry`] like every other single-statement row -/// write here, unguarded or not: the user row is contended (preferences, -/// profile, role all write it), and a lost round wrote nothing, so -/// re-sending it is the recovery rather than a 500 in the caller's face. +/// The row is locked across the pre-image read and the write (`FOR +/// UPDATE`), so two racing uploads each collect the blob *they* actually +/// replaced — the read and the write are one unit, not a guess that stayed +/// true. pub async fn set_avatar( db: &Database, id: &UserId, @@ -477,55 +622,130 @@ pub async fn set_avatar( content_type: &FileContentType, size: i64, ) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \ - RETURN BEFORE", - &[ - ("u".into(), id.record().into_value()), - ("file".into(), file.to_string().into_value()), - ("ct".into(), content_type.clone().into_value()), - ("size".into(), size.into_value()), - ], - ) - .await?; - Ok(rows.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE id = $1 FOR UPDATE"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE app_user + SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4 + WHERE id = $1"#, + id.uuid(), + file, + content_type.as_str(), + size, + ) + .execute(&mut *tx) + .await?; + Ok(Some(before)) + }) + .await } /// Drop the avatar, returning the row as it was so the caller can delete -/// the blob. Same `RETURN BEFORE` contract as [`set_avatar`]. +/// the blob. Same pre-image contract as [`set_avatar`]. pub async fn clear_avatar(db: &Database, id: &UserId) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \ - avatar_size = NONE RETURN BEFORE", - &[("u".into(), id.record().into_value())], - ) - .await?; - Ok(rows.into_iter().next()) + tx_with_retry(db, false, async |tx| { + let before = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE id = $1 FOR UPDATE"#, + id.uuid() + ) + .fetch_optional(&mut *tx) + .await?; + let Some(before) = before else { + return Ok(None); + }; + sqlx::query!( + r#"UPDATE app_user + SET avatar_file = NULL, avatar_content_type = NULL, avatar_size = NULL + WHERE id = $1"#, + id.uuid(), + ) + .execute(&mut *tx) + .await?; + Ok(Some(before)) + }) + .await } /// Replace a user's password hash — the builder's admin-password reset /// (`POST /schools/{slug}/admin-password`). Only the credential is /// rewritten; revoking the sessions minted under the old one is the -/// caller's second half -/// ([`crate::db::session::delete_by_user`]), because a reset -/// that leaves a stolen cookie working resets nothing. +/// caller's second half ([`crate::db::session::delete_by_user`]), because a +/// reset that leaves a stolen cookie working resets nothing. pub async fn set_password_hash( db: &Database, id: &UserId, password_hash: PasswordHash, ) -> Result, AppError> { - let rows: Vec = write_with_retry( - db, - "UPDATE $u SET password_hash = $hash RETURN AFTER", - &[ - ("u".into(), id.record().into_value()), - ("hash".into(), password_hash.into_value()), - ], + let user = sqlx::query_as!( + User, + r#"UPDATE app_user SET password_hash = $2 WHERE id = $1 + RETURNING id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size"#, + id.uuid(), + password_hash.as_str(), ) + .fetch_optional(db) .await?; - Ok(rows.into_iter().next()) + Ok(user) } /// Write the UI-preference fields the request actually carried. Same @@ -538,21 +758,43 @@ pub async fn set_preferences( language: Option>, palette_color: Option>, ) -> Result { - FieldUpdate::new(id.record()) + let theme = theme.map(|t| Param::OptText(t.map(|v| v.as_str().to_string()))); + let language = language.map(|l| Param::OptText(l.map(|v| v.as_str().to_string()))); + let palette_color = palette_color.map(|p| Param::OptText(p.map(|v| v.as_str().to_string()))); + FieldUpdate::new("app_user", id.uuid()) .set("theme", theme) .set("language", language) .set("palette_color", palette_color) - .run::(db) + .run(db) .await } pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM user WHERE username = $username LIMIT 1") - .bind(("username", username.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) + let user = sqlx::query_as!( + User, + r#"SELECT id AS "id: UserId", + username AS "username: Username", + password_hash AS "password_hash: PasswordHash", + role AS "role: Role", + name AS "name: PersonName", + surname AS "surname: PersonName", + email AS "email: Email", + phone AS "phone: Phone", + birth_date AS "birth_date: BirthDate", + theme AS "theme: Theme", + language AS "language: Language", + palette_color AS "palette_color: PaletteColor", + display_name AS "display_name: DisplayName", + bio AS "bio: Bio", + avatar_file, + avatar_content_type AS "avatar_content_type: FileContentType", + avatar_size + FROM app_user WHERE username = $1"#, + username + ) + .fetch_optional(db) + .await?; + Ok(user) } #[cfg(test)] @@ -673,9 +915,9 @@ mod tests { assert_eq!(after.get_avatar_size(), Some(42)); } - /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old - /// `avatar_file` coming back, every replace strands a file on disk that no - /// route ever collects. + /// The blob cleanup is built on the pre-image: without the old + /// `avatar_file` coming back, every replace strands a file on disk that + /// no route ever collects. #[tokio::test] async fn the_avatar_writers_return_the_replaced_blob() { let db = init_mem().await.unwrap(); diff --git a/src/domain/badge.rs b/src/domain/badge.rs index 451f185..b3e0392 100644 --- a/src/domain/badge.rs +++ b/src/domain/badge.rs @@ -99,20 +99,20 @@ impl BadgeStat { /// select into (`SELECT homework_submitted, … FROM app_user WHERE id = $1`). #[derive(Debug, Clone, Default, sqlx::FromRow)] pub struct BadgeStats { - homework_submitted: i64, - homework_on_time: i64, - exam_sat: i64, - pomodoro_finished: i64, - pomodoro_focus_ms: i64, - marks_given: i64, - lessons_held: i64, - pool_approved: i64, - pool_published: i64, - lessons_attended: i64, - high_mark: i64, + pub(crate) homework_submitted: i64, + pub(crate) homework_on_time: i64, + pub(crate) exam_sat: i64, + pub(crate) pomodoro_finished: i64, + pub(crate) pomodoro_focus_ms: i64, + pub(crate) marks_given: i64, + pub(crate) lessons_held: i64, + pub(crate) pool_approved: i64, + pub(crate) pool_published: i64, + pub(crate) lessons_attended: i64, + pub(crate) high_mark: i64, /// The longest study run, off `study_streak_longest`. Named for the wire, /// like every field here, and never the run in progress. - study_streak: i64, + pub(crate) study_streak: i64, } impl BadgeStats { @@ -200,8 +200,8 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { /// columns. #[derive(Debug, Clone, sqlx::FromRow)] pub struct BadgeAward { - badge: String, - earned_at: Timestamp, + pub(crate) badge: String, + pub(crate) earned_at: Timestamp, } impl BadgeAward { diff --git a/src/service/settings.rs b/src/service/settings.rs index 02097bc..a28f7ae 100644 --- a/src/service/settings.rs +++ b/src/service/settings.rs @@ -1,45 +1,22 @@ -//! The settings edit workflow: one edit at a time under [`SETTINGS_LOCK`], -//! a snapshot-merge-retire-save pair whose halves cannot interleave, and the -//! compare-and-set retry that keeps two managers' patches from silently -//! reverting each other. The singleton's queries live in -//! [`crate::db::settings`]. - -use surrealdb::types::RecordId; -use tokio::sync::Mutex; +//! The settings edit workflow: snapshot-merge-guard-save, with every name-list +//! guard and the compare-and-set riding ONE transaction, so two managers' +//! patches can neither silently revert each other nor strand a half-applied +//! removal. The singleton's queries live in [`crate::db::settings`]. use crate::constant::CAS_UPDATE_RETRIES; -use crate::database::Database; -use crate::db::cap; -use crate::domain::exam_result::kind_ref; -use crate::domain::menu::slot_ref; +use crate::database::{Database, tx_with_retry}; use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; use crate::error::AppError; -/// One settings edit at a time, over the whole process. -/// -/// A list edit is a **pair** of writes, and the pair is the guard: every name -/// the edit drops is retired on its reference counter first (which refuses -/// every later claim), and only then is the list itself committed with a -/// compare-and-set against the snapshot the removals were judged from. Neither -/// write can be made to cover the other. Both retirement and un-retirement are -/// *idempotent*, so a rival that decided the same removal against the same -/// snapshot is told "already retired" and records no rollback — and when it is -/// that rival's save that wins the compare-and-set, the attempt which really -/// flipped the bit rolls it back, leaving the name off the stored list with a -/// counter reading "in service": gradable again, and unremovable for good once -/// a mark lands. No per-name bit can close that, because `Unchanged` has -/// erased which attempt owns the flip. -/// -/// So the pair is serialized instead. Every writer of the singleton goes -/// through `PATCH /settings`, and the deployment runs one process by contract -/// (stop-the-world upgrades), so process-wide is deployment-wide here — the -/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s -/// two statements, one level up. The compare-and-set stays: it is what keeps a -/// crashed or rolled-back attempt from writing a list nobody merged. -/// -/// **Lock order:** `SETTINGS_LOCK` → `cap`'s `CLAIM_LOCK`, never the reverse — -/// the retirements are taken while this is held. -pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(()); +/// The abort marker the edit transaction's closure raises when the guarded +/// save wrote zero rows — the stored row moved under the snapshot this +/// attempt was judged against. It never reaches the wire: [`apply`] maps it +/// to another loop turn right here, and the transaction's rollback already +/// took every retirement back with it. (Same abort-through-`Internal` +/// pattern as `crate::db::field_update`'s markers: a refusal is a decision, +/// so it must not be retried — this one is *un*-decided, which is exactly +/// why the loop re-runs.) +const STALE_SAVE: &str = "settings_save_lost_cas"; /// The stored policy, or the defaults when no row exists yet. pub async fn load(db: &Database) -> Result { @@ -60,8 +37,8 @@ pub async fn save_if_unchanged( /// A `PATCH /settings` body after wire mapping: only the fields the school /// sent. Lists stay raw on purpose — validating them is the workflow's own /// step, in its own order, and keeping a stored meal-slot name skips the -/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`], holding -/// the lock and the stored list, can decide. +/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`], +/// holding the stored list, can decide. pub struct SettingsPatch { pub exam_kinds: Option>, pub attendance_statuses: Option>, @@ -94,14 +71,27 @@ pub struct MealSlotInput { pub serving_minute: Option, } -/// The whole edit — snapshot, merge, retire, save — as one operation, so the +/// The whole edit — snapshot, merge, guard, save — as one operation, so the /// tests can drive it the way two managers do. +/// +/// The guards and the save share one transaction, and that is the whole +/// guard: a list edit is a *pair* of writes — every name the edit drops is +/// retired on its reference counter first (which refuses every later +/// claim), and only then is the list itself committed with a +/// compare-and-set against the snapshot the removals were judged from. The +/// old engine could not serialize that pair on its own, so a process-wide +/// lock held it together, and the winner-loses-rollback interaction between +/// two same-snapshot attempts needed a hand-rolled undo list +/// (`Unchanged`-erased which attempt owned a flip, so a no-op could undo a +/// rival). Postgres needs neither: retirement and save commit together or +/// not at all, a stale save rolls its retirements back by aborting, and the +/// row-locked retire switch serializes two attempts dropping the same name. +/// +/// Retired before the save, never after: the other order leaves a window in +/// which a mark lands under a kind the settings no longer list. A save that +/// then does not land undoes them — by transaction abort, before the next +/// try, with no undo list to get wrong. pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result { - // One settings edit at a time: the removals below are decided against the - // snapshot this loop loads and written *before* the save that justifies - // them, and no per-name bookkeeping can make that pair survive a rival's - // pair interleaving with it (see `SETTINGS_LOCK`). - let _guard = SETTINGS_LOCK.lock().await; // Merge over a snapshot, then save only while the row still matches it — // otherwise a concurrent PATCH of a *different* field would be silently // reverted by whichever whole-row write lands second. A refused save @@ -179,88 +169,54 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result = Vec::new(); - let mut refused = None; - for gone in missing(&was_kinds, &now_kinds) { - let counter = kind_ref(&gone); - match cap::retire_name(&counter, db).await? { - cap::Switched::Flipped => undo.push(Undo::Retired(counter)), - cap::Switched::Unchanged => {} - cap::Switched::InUse => { - refused = Some(AppError::ConflictOwned(format!( - "exams of kind '{gone}' are already graded — the kind cannot be removed" - ))); - break; - } + // Guards + save, one transaction. The removal refusals are the same + // 409s as ever; a stale save is the `STALE_SAVE` marker, answered by + // another loop turn below; everything else surfaces. + let attempted = tx_with_retry(db, false, async |tx| { + // A name leaves a list by being *retired* on its reference + // counter — one row-locked switch, which lands only while + // nothing references the name and refuses every claim from that + // instant on. A refused removal aborts the transaction, taking + // any earlier retirement in this same attempt back with it. + for gone in missing(&was_kinds, &now_kinds) { + retire_kind(&mut *tx, &gone).await?; } - } - // Same shape for meal slots: a slot a menu was already published for - // cannot leave the list — the menu snapshotted the name as text, and a - // slot no longer offered would leave that menu unreachable from the - // school's own list. - if refused.is_none() { + // Same shape for meal slots: a slot a menu was already published + // for cannot leave the list — the menu snapshotted the name as + // text, and a slot no longer offered would leave that menu + // unreachable from the school's own list. for gone in missing(&was_slots, &now_slots) { - let counter = slot_ref(&gone); - match cap::retire_name(&counter, db).await? { - cap::Switched::Flipped => undo.push(Undo::Retired(counter)), - cap::Switched::Unchanged => {} - cap::Switched::InUse => { - refused = Some(AppError::ConflictOwned(format!( - "menus are already published for the '{gone}' slot — it cannot be removed" - ))); - break; - } - } + retire_slot(&mut *tx, &gone).await?; } - } - if let Some(refused) = refused { - restore(&undo, db).await?; - return Err(refused); - } - // A name re-entering a list is back in service: its counter still - // carries the retirement from the edit that dropped it, and a mark (or - // a menu) under a kind the school offers again must not be refused. - // Recorded for the same undo as the retirements — a re-add whose save - // does not land leaves a name off the list that grades happily. - for back in missing(&now_kinds, &was_kinds) { - if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? { - undo.push(Undo::Unretired(kind_ref(&back))); + // A name re-entering a list is back in service: its counter still + // carries the retirement from the edit that dropped it, and a mark + // (or a menu) under a kind the school offers again must not be + // refused. Inside the transaction, "in service" stands only if + // the save below lands — a stale save aborts and re-retires it. + for back in missing(&now_kinds, &was_kinds) { + unretire_kind(&mut *tx, &back).await?; } - } - for back in missing(&now_slots, &was_slots) { - if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? { - undo.push(Undo::Unretired(slot_ref(&back))); + for back in missing(&now_slots, &was_slots) { + unretire_slot(&mut *tx, &back).await?; } - } - match save_if_unchanged(db, settings, ¤t).await { - Ok(Some(saved)) => return Ok(saved), - // The row moved under the snapshot these guards were judged against: - // put the names back and re-merge, or the next attempt would decide - // against a list nobody asked for. - Ok(None) => restore(&undo, db).await?, - Err(err) => { - restore(&undo, db).await?; - return Err(err); + match crate::db::settings::save_if_unchanged(&mut *tx, settings.clone(), ¤t) + .await? + { + Some(saved) => Ok(saved), + // The row moved under the snapshot these guards were judged + // against: the abort puts the names back, and the caller's + // loop re-merges — or the next attempt would decide against a + // list nobody asked for. + None => Err(AppError::Internal(STALE_SAVE.to_string())), } + }) + .await; + + match attempted { + Ok(saved) => return Ok(saved), + Err(AppError::Internal(marker)) if marker == STALE_SAVE => continue, + Err(err) => return Err(err), } } Err(AppError::Conflict( @@ -268,6 +224,106 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result 0`) is the caller's removal refusal, +/// byte for byte the old 409. +async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { + let was = sqlx::query!( + r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#, + name + ) + .fetch_optional(tx) + .await? + .map(|row| row.retired) + .unwrap_or(false); + let landed = sqlx::query!( + r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE) + ON CONFLICT (name) DO UPDATE SET retired = TRUE + WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE + RETURNING 1 AS "landed!: i64""#, + name + ) + .fetch_optional(tx) + .await? + .is_some(); + match (landed, was) { + // Still in use, and not already retired: the removal is refused. + (false, false) => Err(AppError::ConflictOwned(format!( + "exams of kind '{name}' are already graded — the kind cannot be removed" + ))), + // Flipped, or already retired by the rival that decided the same + // removal: nothing to do — the transaction decides whether it stands. + _ => Ok(()), + } +} + +/// [`retire_kind`] against the meal-slot counters. +async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { + let was = sqlx::query!( + r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#, + name + ) + .fetch_optional(tx) + .await? + .map(|row| row.retired) + .unwrap_or(false); + let landed = sqlx::query!( + r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE) + ON CONFLICT (name) DO UPDATE SET retired = TRUE + WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE + RETURNING 1 AS "landed!: i64""#, + name + ) + .fetch_optional(tx) + .await? + .is_some(); + match (landed, was) { + (false, false) => Err(AppError::ConflictOwned(format!( + "menus are already published for the '{name}' slot — it cannot be removed" + ))), + _ => Ok(()), + } +} + +/// Put an exam kind back in service, inside the caller's transaction. One +/// guarded write: the flip lands only while the name is actually retired, so +/// it is idempotent. Whether the name *stays* in service is the save's +/// decision — a stale save aborts this transaction and the retirement stands +/// again, with no undo list to get wrong. +async fn unretire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { + sqlx::query!( + r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, FALSE) + ON CONFLICT (name) DO UPDATE SET retired = FALSE + WHERE kind_ref.retired IS DISTINCT FROM FALSE + RETURNING 1 AS "landed!: i64""#, + name + ) + .fetch_optional(tx) + .await?; + Ok(()) +} + +/// [`unretire_kind`] against the meal-slot counters. +async fn unretire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> { + sqlx::query!( + r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, FALSE) + ON CONFLICT (name) DO UPDATE SET retired = FALSE + WHERE slot_ref.retired IS DISTINCT FROM FALSE + RETURNING 1 AS "landed!: i64""#, + name + ) + .fetch_optional(tx) + .await?; + Ok(()) +} + fn kind_names(kinds: &[ExamKindDef]) -> Vec { kinds .iter() @@ -292,39 +348,6 @@ fn missing(before: &[String], after: &[String]) -> Vec { .collect() } -/// One `retired` bit this attempt moved, and which way — what `restore` needs -/// to put it back. Only bits this attempt actually *flipped* are listed: a -/// write that changed nothing has nothing to take back, and taking it back -/// would undo the concurrent edit that really did move it. -enum Undo { - /// Retired for a removal; put it back in service. - Retired(RecordId), - /// Put back in service for a re-add; retire it again. - Unretired(RecordId), -} - -/// Undo every bit this attempt moved: the edit that justified them did not -/// land, so the lists the school offers are still the ones it started with. -async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> { - for step in undo { - match step { - Undo::Retired(name) => { - cap::unretire_name(name, db).await?; - } - // A re-retirement can be refused: a mark (or a menu) landed under - // the name during the window it was in service. Refusing to undo is - // then the honest answer — the reference is real, and retiring over - // it would make the row's kind ungradable while nothing lists it. - // The name is left in service, matching the list this attempt is - // about to re-read. - Undo::Unretired(name) => { - cap::retire_name(name, db).await?; - } - } - } - Ok(()) -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/service/user.rs b/src/service/user.rs index 25b6623..25b61e0 100644 --- a/src/service/user.rs +++ b/src/service/user.rs @@ -1,6 +1,6 @@ //! User workflows: the boot-time admin seed, and the role change — the -//! admin floor ([`ADMIN_FLOOR_LOCK`]) held across the count that checks it -//! and the transaction that commits it, sweeps included. Reads, listings, +//! admin floor carried by the role write's own guard, and every sweep the +//! change owes committed in the same transaction. Reads, listings, //! the row mint, and the field-scoped writers live in [`crate::db::user`]. use crate::database::Database; @@ -13,29 +13,6 @@ use crate::domain::role::Role; use crate::domain::user::{Password, PasswordHash, User, UserId, Username}; use crate::error::AppError; -/// One role demotion at a time, school-wide. -/// -/// The invariant it protects is "the school always keeps an admin", and that -/// guard is a count-then-write: read whether another admin exists, then lower -/// this row. SurrealDB conflict-checks neither side of that pair — a -/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent -/// update (write-skew, see [`crate::db::cap`]) and a statement that only -/// *reads* the rival's row never collides with it. So two admins demoting each -/// other both counted the other and both committed, leaving **zero** admins and -/// a school nobody can administer: `ensure_admin` refuses to promote an -/// existing non-admin row on every later boot, so the only way back was hand-run -/// SurrealQL against the volume. -/// -/// Serializing the pair is what closes it, the same argument -/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment -/// runs one process by contract (stop-the-world upgrades), so process-wide is -/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does -/// not fit — the count being capped is over *every* user row, with no parent -/// record to hold it and no place to seed one without a backfill. -/// -/// **Lock order:** taken alone. Nothing is locked while it is held. -static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - /// Idempotent startup seed: guarantee an admin account with this username. /// Missing → created directly with [`Role::Admin`]. Already an admin → /// nothing to do (the stored password stays whatever it is — the seed never @@ -52,7 +29,7 @@ pub async fn ensure_admin( Some(_) => { tracing::warn!( "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ - Grant the role through an existing admin or the manual SurrealQL path." + Grant the role through an existing admin or a hand-run SQL session." ); Ok(()) } @@ -77,9 +54,17 @@ pub async fn ensure_admin( /// hold, in one transaction. The caller is responsible for authorizing it. /// /// Refuses (`Conflict`) to lower the school's last admin, however the -/// request is spelled and however many demotions are in flight at once — -/// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the -/// transaction below. +/// request is spelled and however many demotions are in flight at once. +/// The floor is not a lock here — it is a predicate on the role write +/// itself ([`user::set_role_cascade`]): the `UPDATE` that lowers the row +/// carries `AND NOT (demoting the admin whom no other admin remains)`, so +/// the count it reads and the write it guards are one statement, contended +/// on row locks like any other write. Two admins demoting each other both +/// used to count the other and both commit — the old store could not +/// serialize a cross-record count against a concurrent update, which is +/// what the process-wide lock used to stand in for. The database does that +/// serialization now; zero rows out of the guarded write is the same 409 +/// the lock's check used to answer. /// /// The sweep itself — what each role change owes, arm by arm, and why the /// conditions differ — is [`user::set_role_cascade`]'s statement list, @@ -89,24 +74,10 @@ pub async fn set_role( target: &UserId, role: Role, ) -> Result<(User, Vec), AppError> { - // A missing account is a 404, answered before the floor is asked. + // A missing account is a 404, answered before the cascade opens a + // transaction. (No route deletes a user row, so the row cannot vanish + // between this read and the write.) user::read(db, target).await?.ok_or(AppError::NotFound)?; - // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`] - // for why a transaction cannot do this). Asked on the *live* rows rather - // than a caller's snapshot, so a snapshot that predates a promotion cannot - // skip the check, and cheap enough to ask on every demotion: one round - // trip on an admin-only route. - let _floor = if role == Role::Admin { - None - } else { - let guard = ADMIN_FLOOR_LOCK.lock().await; - if user::would_orphan_admins(db, target).await? { - return Err(AppError::Conflict( - "the school must keep at least one admin — promote another account first", - )); - } - Some(guard) - }; user::set_role_cascade(db, target, role).await } diff --git a/src/web/users.rs b/src/web/users.rs index c97855d..81fac68 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -422,9 +422,10 @@ async fn update_user_preferences( /// Set a user's role. Admin only. An admin cannot change their own role, and /// the school's **last** admin cannot be demoted by anyone (`409`) — together /// those keep role management from locking everyone out, including when two -/// admins demote each other at the same instant (the floor is serialized, see -/// `ADMIN_FLOOR_LOCK`). A school that has already lost its admins is recovered -/// with the SurrealQL in the README, since the seed never promotes. +/// admins demote each other at the same instant (the floor is a predicate on +/// the role write itself, so the racing demotions serialize on row locks). +/// A school that has already lost its admins is recovered by hand against the +/// database, since the seed never promotes. /// Setting any non-`student` role also drops the user's course enrollments — /// only students enroll, so a promoted user leaves every roster. Demoting below /// `teacher` drops their course teaching assignments for the mirror reason, and @@ -1151,7 +1152,7 @@ async fn upload_my_avatar( let upload = read_image_upload(&st, &mut multipart).await?; let size = upload.size(); - let file = ulid::Ulid::generate().to_string(); + let file = crate::domain::monotonic_id::next_uuid().to_string(); store_blob(&st, &file, &upload.data, || async { match crate::service::user::set_avatar( &st.db,