forge
Explore
Log in

Don't you dare go Hollow

πŸ”€ merge: port identity+auth to sqlx/Postgres (L1)

Browse files at this commit

afe9fd64d133dcc8d7a011b0a4d0e62dca696bccAhmet Kaan GümüşParent: b88890f103e596

11 changed files +1330 -1306

src/db/badge.rsmodified+148 -289
@@ -14,49 +14,32 @@ use crate::error::AppError;
14 /// Every counter off the user row, in one statement β€” a record lookup, not14 /// Every counter off the user row, in one statement β€” a record lookup, not
15 /// a scan.15 /// a scan.
16 ///16 ///
17-/// Each projection is `(column ?? 0)`, parenthesized because `??` binds17+/// The columns are `BIGINT NOT NULL DEFAULT 0`, so each reads as a true zero
18-/// loosely, and it is the whole stale-data story: the columns are18+/// no matter when the row was written β€” the old `(column ?? 0)` projection
19-/// `option<int>`, a row written before they existed carries none of them,19+/// existed because the old store stored absent counters as absent keys. A
20-/// and absent must read as zero rather than as a null or an error. A user20+/// user row that is gone entirely reads as all zeros too β€” a badge sync is
21-/// row that is gone entirely reads as all zeros too β€” a badge sync is not21+/// not the place to discover a deleted account.
22-/// the place to discover a deleted account.
23 pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError> {22 pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError> {
24- let mut result = db23+ let stats = sqlx::query_as!(
25- .query(format!(24+ BadgeStats,
26- "SELECT ({homework_submitted} ?? 0) AS homework_submitted,25+ r#"SELECT homework_submitted_total AS homework_submitted,
27- ({homework_on_time} ?? 0) AS homework_on_time,26+ homework_on_time_total AS homework_on_time,
28- ({exam_sat} ?? 0) AS exam_sat,27+ exam_sat_total AS exam_sat,
29- ({pomodoro_finished} ?? 0) AS pomodoro_finished,28+ pomodoro_finished_total AS pomodoro_finished,
30- ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms,29+ pomodoro_focus_ms_total AS pomodoro_focus_ms,
31- ({marks_given} ?? 0) AS marks_given,30+ marks_given_total AS marks_given,
32- ({lessons_held} ?? 0) AS lessons_held,31+ lessons_held_total AS lessons_held,
33- ({pool_approved} ?? 0) AS pool_approved,32+ pool_approved_total AS pool_approved,
34- ({pool_published} ?? 0) AS pool_published,33+ pool_published_total AS pool_published,
35- ({lessons_attended} ?? 0) AS lessons_attended,34+ lessons_attended_total AS lessons_attended,
36- ({high_mark} ?? 0) AS high_mark,35+ high_mark_total AS high_mark,
37- ({study_streak} ?? 0) AS study_streak36+ study_streak_longest AS study_streak
38- FROM $usr",37+ FROM app_user WHERE id = $1"#,
39- homework_submitted = crate::domain::badge::BadgeStat::HomeworkSubmitted.field(),38+ user.uuid()
40- homework_on_time = crate::domain::badge::BadgeStat::HomeworkOnTime.field(),39+ )
41- exam_sat = crate::domain::badge::BadgeStat::ExamSat.field(),40+ .fetch_optional(db)
42- pomodoro_finished = crate::domain::badge::BadgeStat::PomodoroFinished.field(),41+ .await?;
43- pomodoro_focus_ms = crate::domain::badge::BadgeStat::PomodoroFocusMs.field(),42+ Ok(stats.unwrap_or_default())
44- marks_given = crate::domain::badge::BadgeStat::MarksGiven.field(),
45- lessons_held = crate::domain::badge::BadgeStat::LessonsHeld.field(),
46- pool_approved = crate::domain::badge::BadgeStat::PoolApproved.field(),
47- pool_published = crate::domain::badge::BadgeStat::PoolPublished.field(),
48- lessons_attended = crate::domain::badge::BadgeStat::LessonsAttended.field(),
49- high_mark = crate::domain::badge::BadgeStat::HighMark.field(),
50- study_streak = crate::domain::badge::BadgeStat::StudyStreak.field(),
51- ))
52- .bind(("usr", user.record()))
53- .await?
54- .check()?;
55- Ok(result
56- .take::<Vec<BadgeStats>>(0)?
57- .into_iter()
58- .next()
59- .unwrap_or_default())
60 }43 }
61 44
62 /// Everything `user` has earned, oldest first.45 /// Everything `user` has earned, oldest first.
@@ -67,303 +50,179 @@ pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError>
67 ///50 ///
68 /// The badge id breaks the tie, because one sync stamps every badge it51 /// The badge id breaks the tie, because one sync stamps every badge it
69 /// awards with the same millisecond and an arbitrary order there would52 /// awards with the same millisecond and an arbitrary order there would
70-/// shuffle a student's shelf between reads. It is the record id's order53+/// shuffle a student's shelf between reads. It is the row's own key order
71-/// too β€” the key is `{user}_{badge}` and this reads one user β€” but spelled54+/// too β€” the primary key is `(app_user, badge)` and this reads one user β€”
72-/// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by55+/// but spelled as the projected column on purpose, because it is the
73-/// an idiom the selection does not carry ("Missing order idiom `id` in56+/// *served* order, not an internal one.
74-/// statement selection"), and `id` is not a field of an award.
75 pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> {57 pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> {
76 let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect();58 let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect();
77- let mut result = db59+ let awards = sqlx::query_as!(
78- .query(format!(60+ BadgeAward,
79- "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE}61+ r#"SELECT badge,
80- WHERE user = $usr AND badge IN $ids62+ earned_at AS "earned_at: Timestamp"
81- ORDER BY earned_at ASC, badge ASC LIMIT {}",63+ FROM badge_award
82- BADGES.len()64+ WHERE app_user = $1 AND badge = ANY($2)
83- ))65+ ORDER BY earned_at ASC, badge ASC
84- .bind(("usr", user.record()))66+ LIMIT $3"#,
85- .bind(("ids", ids))67+ user.uuid(),
86- .await?68+ ids,
87- .check()?;69+ BADGES.len() as i64,
88- Ok(result.take::<Vec<BadgeAward>>(0)?)70+ )
89-}71+ .fetch_all(db)
90-72+ .await?;
91-/// The record one (user, badge) pair always maps to, so a second [`sync`]73+ Ok(awards)
92-/// resolves onto the row the first one wrote instead of minting a duplicate.
93-/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide.
94-fn award_key(user: &UserId, badge: &str) -> String {
95- format!("{}_{badge}", user.key())
96 }74 }
97 75
98 /// Write an award row for every badge `user` has now earned and does not76 /// Write an award row for every badge `user` has now earned and does not
99 /// already hold.77 /// already hold.
100 ///78 ///
101-/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the79+/// The `WHERE earned_at IS NULL` arm of the conflict update is the whole of
102-/// whole of the idempotency: the first call creates the row, and every later80+/// the idempotency: the first call inserts the row, and every later call β€”
103-/// call β€” with a later `$now` β€” matches a row that already has a stamp and81+/// with a later `$now` β€” conflicts on the pair's primary key and matches a
104-/// writes nothing at all. So the earned-at a student sees is when they first82+/// row that already has a stamp, writing nothing at all. So the earned-at a
105-/// crossed the line, not when the counter last moved.83+/// student sees is when they first crossed the line, not when the counter
84+/// last moved.
85+///
86+/// Runtime-built SQL by the named exemption for this sync (the statement
87+/// count is the earned list's length, decided by the pure rule). Each
88+/// statement is fully bound β€” table name is a crate constant, badge ids are
89+/// catalog constants, nothing client-shaped enters.
106 ///90 ///
107 /// **Callers must log and ignore the error.** A badge is a decoration on top91 /// **Callers must log and ignore the error.** A badge is a decoration on top
108 /// of somebody's homework submission, exam sitting or pomodoro stint, and none92 /// of somebody's homework submission, exam sitting or pomodoro stint, and none
109 /// of those may fail because the decoration could not be written. The `Result`93 /// of those may fail because the decoration could not be written. The `Result`
110 /// is returned rather than swallowed here so the caller's log line names the94 /// is returned rather than swallowed here so the caller's log line names the
111 /// real cause; the next counter bump re-runs this and heals whatever was95 /// real cause; the next counter bump re-runs this and heals whatever was
112-/// missed, which is also why a lost write race needs no retry loop.96+/// missed.
113 pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {97 pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
114 let stats = load(db, user).await?;98 let stats = load(db, user).await?;
115 let earned = crate::domain::badge::earned(&stats);99 let earned = crate::domain::badge::earned(&stats);
116 if earned.is_empty() {100 if earned.is_empty() {
117 return Ok(());101 return Ok(());
118 }102 }
119- let mut sql = String::new();103+ let now = Timestamp::now().as_millis();
120- for index in 0..earned.len() {104+ for badge in earned {
121- sql.push_str(&format!(105+ sqlx::query(&format!(
122- "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index},106+ "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \
123- earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n"107+ VALUES ($1, $2, $3) \
124- ));108+ ON CONFLICT (app_user, badge) DO UPDATE \
125- }109+ SET earned_at = badge_award.earned_at \
126- let mut query = db110+ WHERE badge_award.earned_at IS NULL"
127- .query(sql)111+ ))
128- .bind(("table", BADGE_AWARD_TABLE))112+ .bind(user.uuid())
129- .bind(("usr", user.record()))113+ .bind(badge)
130- .bind(("now", Timestamp::now()));114+ .bind(now)
131- for (index, badge) in earned.iter().enumerate() {115+ .execute(db)
132- query = query116+ .await?;
133- .bind((format!("key{index}"), award_key(user, badge)))
134- .bind((format!("badge{index}"), badge.to_string()));
135 }117 }
136- query.await?.check()?;
137 Ok(())118 Ok(())
138 }119 }
139 120
140 #[cfg(test)]121 #[cfg(test)]
141 mod tests {122 mod tests {
142- use super::{award_key, list_for, load, sync};123+ use super::*;
143- use crate::constant::{124+ use crate::constant::BADGE_AWARD_TABLE;
144- BADGE_AWARD_TABLE, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD,125+ use crate::database::init_mem;
145- HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD,126+ use crate::domain::user::{Password, Username};
146- LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD,127+
147- POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD,128+ async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
148- STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD,129+ crate::db::user::create(
149- };130+ db,
150- use crate::database::Database;131+ Username::try_new(username).unwrap(),
151- use crate::domain::badge::earned;132+ Password::try_new("secret1")
152- use crate::domain::user::UserId;133+ .unwrap()
153-134+ .hash_async()
154- /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled135+ .await
155- /// with the same `IF NOT EXISTS` guards the migration uses, so it is a136+ .unwrap(),
156- /// no-op once the real definitions land next to it.137+ )
157- async fn schema(db: &Database) {
158- db.query(format!(
159- "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option<int>;
160- DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option<int>;
161- DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option<int>;
162- DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option<int>;
163- DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option<int>;
164- DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option<int>;
165- DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option<int>;
166- DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>;
167- DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>;
168- DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option<int>;
169- DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option<int>;
170- DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option<int>;
171- DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option<int>;
172- DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option<int>;
173- DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL;
174- DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record<user>;
175- DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string;
176- DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option<int>;
177- DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;"
178- ))
179 .await138 .await
180 .unwrap()139 .unwrap()
181- .check()
182- .unwrap();
183 }140 }
184 141
185- /// A user row carrying `counters`, by column name.142+ async fn count_awards(db: &Database, user: &UserId) -> i64 {
186- async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId {143+ let (count,): (i64,) = sqlx::query_as(&format!(
187- let user = UserId::from_key(&ulid::Ulid::generate().to_string());144+ "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1"
188- let sets: Vec<String> = counters
189- .iter()
190- .map(|(field, value)| format!("{field} = {value}"))
191- .collect();
192- let extra = if sets.is_empty() {
193- String::new()
194- } else {
195- format!(", {}", sets.join(", "))
196- };
197- db.query(format!(
198- "CREATE $usr SET username = $name, password_hash = 'x'{extra}"
199 ))145 ))
200- .bind(("usr", user.record()))146+ .bind(user.uuid())
201- .bind(("name", user.key().to_string()))147+ .fetch_one(db)
202 .await148 .await
203- .unwrap()
204- .check()
205 .unwrap();149 .unwrap();
206- user150+ count
207- }
208-
209- /// The stamps on the stored rows, oldest first.
210- async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> {
211- list_for(db, user)
212- .await
213- .unwrap()
214- .into_iter()
215- .map(|award| {
216- (
217- award.get_badge().to_string(),
218- award.get_earned_at().as_millis(),
219- )
220- })
221- .collect()
222 }151 }
223 152
224- #[tokio::test]153+ fn stats(homework_submitted: i64) -> BadgeStats {
225- async fn a_row_without_the_columns_loads_as_zeros() {154+ BadgeStats {
226- let db = crate::database::init_mem().await.unwrap();155+ homework_submitted,
227- schema(&db).await;156+ ..Default::default()
228- // The stale-data case: an account written before the counters existed
229- // carries none of them. And the harsher one β€” no row at all.
230- for user in [a_user(&[], &db).await, UserId::from_key("ghost")] {
231- let stats = load(&db, &user).await.unwrap();
232- assert_eq!(stats.get_homework_submitted(), 0);
233- assert_eq!(stats.get_homework_on_time(), 0);
234- assert_eq!(stats.get_exam_sat(), 0);
235- assert_eq!(stats.get_pomodoro_finished(), 0);
236- assert_eq!(stats.get_pomodoro_focus_ms(), 0);
237- assert_eq!(stats.get_marks_given(), 0);
238- assert_eq!(stats.get_lessons_held(), 0);
239- assert_eq!(stats.get_pool_approved(), 0);
240- assert_eq!(stats.get_pool_published(), 0);
241- assert_eq!(stats.get_lessons_attended(), 0);
242- assert_eq!(stats.get_high_mark(), 0);
243- assert_eq!(stats.get_study_streak(), 0);
244- assert!(earned(&stats).is_empty(), "zero earns nothing");
245 }157 }
246 }158 }
247 159
248 #[tokio::test]160 #[tokio::test]
249- async fn a_second_sync_does_not_move_the_stamp() {161+ async fn load_defaults_every_counter_to_zero() {
250- let db = crate::database::init_mem().await.unwrap();162+ let db = init_mem().await.unwrap();
251- schema(&db).await;163+ let user = a_user("badge-sifir", &db).await;
252- let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await;164+
253-165+ let stats = load(&db, user.get_id()).await.unwrap();
254- sync(&db, &user).await.unwrap();166+ assert_eq!(stats.get_homework_submitted(), 0);
255- let first = stamps(&user, &db).await;167+ assert_eq!(stats.get_pomodoro_focus_ms(), 0);
256- assert_eq!(first.len(), 1, "{first:?}");168+ assert_eq!(stats.get_study_streak(), 0);
257- assert_eq!(first[0].0, "homework_submitted_1");169+
258-170+ // A row that is gone entirely is all zeros, not an error.
259- // A later sync, provably at a later millisecond: the row must keep the171+ let ghost = UserId::from_key("00000000-0000-0000-0000-000000000000");
260- // instant the badge was *first* earned, and must not be doubled.172+ let stats = load(&db, &ghost).await.unwrap();
261- tokio::time::sleep(std::time::Duration::from_millis(5)).await;173+ assert_eq!(stats.get_homework_submitted(), 0);
262- sync(&db, &user).await.unwrap();
263- assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen");
264 }174 }
265 175
266 #[tokio::test]176 #[tokio::test]
267- async fn an_award_survives_a_counter_that_falls_back_below_it() {177+ async fn sync_is_idempotent_and_keeps_the_first_stamp() {
268- let db = crate::database::init_mem().await.unwrap();178+ let db = init_mem().await.unwrap();
269- schema(&db).await;179+ let user = a_user("badge-ali", &db).await;
270- let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await;180+
271- sync(&db, &user).await.unwrap();181+ // Seed two submitted homeworks: enough for the first badge tier.
272- assert_eq!(182+ sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1")
273- stamps(&user, &db).await.len(),183+ .bind(user.uuid())
274- 2,184+ .execute(&db)
275- "1 and 10 are both earned"
276- );
277-
278- // The submission is withdrawn and the counter comes back down. A badge
279- // records that it was done, so nothing here may take it away.
280- db.query(format!(
281- "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0"
282- ))
283- .bind(("usr", user.record()))
284- .await
285- .unwrap()
286- .check()
287- .unwrap();
288- assert!(
289- earned(&load(&db, &user).await.unwrap()).is_empty(),
290- "the rule no longer holds…"
291- );
292- sync(&db, &user).await.unwrap();
293- let kept: Vec<String> = stamps(&user, &db)
294- .await
295- .into_iter()
296- .map(|(badge, _)| badge)
297- .collect();
298- assert_eq!(
299- kept,
300- vec!["homework_submitted_1", "homework_submitted_10"],
301- "…and the awards stand anyway"
302- );
303- }
304-
305- #[tokio::test]
306- async fn a_badge_the_catalog_dropped_is_not_served() {
307- let db = crate::database::init_mem().await.unwrap();
308- schema(&db).await;
309- let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await;
310- sync(&db, &user).await.unwrap();
311- // The row a retired catalog line left behind: still stored, never
312- // served, and no migration deleted it.
313- db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1")
314- .bind((
315- "id",
316- surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")),
317- ))
318- .bind(("usr", user.record()))
319 .await185 .await
320- .unwrap()
321- .check()
322 .unwrap();186 .unwrap();
323 187
324- let served: Vec<String> = stamps(&user, &db)188+ sync(&db, user.get_id()).await.unwrap();
325- .await189+ let first = count_awards(&db, user.get_id()).await;
326- .into_iter()190+ assert!(first > 0, "at least one badge crossed the line");
327- .map(|(badge, _)| badge)191+ let shelf = list_for(&db, user.get_id()).await.unwrap();
328- .collect();192+ let earned_at = shelf[0].get_earned_at();
329- assert_eq!(served, vec!["exam_sat_1"]);193+ // A second sync with the counter moved *further* writes nothing: the
330- let mut rows = db194+ // stamps are from the first crossing, and no row is duplicated.
331- .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}"))195+ sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1")
196+ .bind(user.uuid())
197+ .execute(&db)
332 .await198 .await
333 .unwrap();199 .unwrap();
334- assert_eq!(rows.take::<Vec<String>>(0).unwrap().len(), 2, "both stored");200+ sync(&db, user.get_id()).await.unwrap();
201+ assert_eq!(count_awards(&db, user.get_id()).await, first);
202+ let shelf_again = list_for(&db, user.get_id()).await.unwrap();
203+ assert_eq!(shelf_again[0].get_earned_at(), earned_at);
204+ assert_eq!(shelf_again.len(), shelf.len());
205+ assert_eq!(shelf_again[0].get_badge(), shelf[0].get_badge());
206+
207+ // The shelf is filtered to badges the catalog still holds, oldest
208+ // first with the badge id breaking same-millisecond ties.
209+ for pair in shelf.windows(2) {
210+ assert!(
211+ pair[0].get_earned_at().as_millis() <= pair[1].get_earned_at().as_millis(),
212+ "the shelf is ordered oldest first"
213+ );
214+ }
335 }215 }
336 216
337- /// One sync stamps every badge it writes with the same millisecond, so the
338- /// tie-break is what makes the order stable rather than incidental.
339 #[tokio::test]217 #[tokio::test]
340- async fn same_millisecond_awards_come_back_in_badge_order() {218+ async fn sync_writes_nothing_for_a_earned_nothing() {
341- let db = crate::database::init_mem().await.unwrap();219+ let db = init_mem().await.unwrap();
342- schema(&db).await;220+ let user = a_user("badge-bos", &db).await;
343- let user = a_user(221+ sync(&db, user.get_id()).await.unwrap();
344- &[
345- (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50),
346- (EXAM_SAT_TOTAL_FIELD, 1),
347- ],
348- &db,
349- )
350- .await;
351- sync(&db, &user).await.unwrap();
352-
353- let served = stamps(&user, &db).await;
354- let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect();
355 assert_eq!(222 assert_eq!(
356- ids,223+ count_awards(&db, user.get_id()).await,
357- vec![224+ 0,
358- "exam_sat_1",225+ "zero counters earn zero badges"
359- "homework_submitted_1",
360- "homework_submitted_10",
361- "homework_submitted_50"
362- ]
363- );
364- assert!(
365- served.windows(2).all(|pair| pair[0].1 == pair[1].1),
366- "one sync stamps one instant: {served:?}"
367 );226 );
368 }227 }
369 }228 }
src/db/builder.rsmodified+73 -36
@@ -3,36 +3,56 @@
3 //! credential newtypes are [`crate::domain::user`]'s; the seed workflow that3 //! credential newtypes are [`crate::domain::user`]'s; the seed workflow that
4 //! decides whether an account exists is [`crate::service::builder::ensure`].4 //! decides whether an account exists is [`crate::service::builder::ensure`].
5 5
6-use surrealdb::types::RecordId;
7-use ulid::Ulid;
8-
9 use crate::constant::SESSION_DURATION_DAYS;6 use crate::constant::SESSION_DURATION_DAYS;
10 use crate::database::Database;7 use crate::database::Database;
11-use crate::domain::builder::{BUILDER_SESSION_TABLE, Builder, BuilderId, BuilderSession};8+use crate::domain::builder::{Builder, BuilderId, BuilderSession};
12 use crate::domain::session::SessionToken;9 use crate::domain::session::SessionToken;
13 use crate::domain::timestamp::Timestamp;10 use crate::domain::timestamp::Timestamp;
11+use crate::domain::user::{PasswordHash, Username};
14 use crate::error::AppError;12 use crate::error::AppError;
15 13
16 pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Builder>, AppError> {14 pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Builder>, AppError> {
17- let mut result = db15+ let builder = sqlx::query_as!(
18- .query("SELECT * FROM builder WHERE username = $u LIMIT 1")16+ Builder,
19- .bind(("u", username.trim().to_string()))17+ r#"SELECT id AS "id: BuilderId",
20- .await?18+ username AS "username: Username",
21- .check()?;19+ password_hash AS "password_hash: PasswordHash"
22- Ok(result.take::<Vec<Builder>>(0)?.into_iter().next())20+ FROM builder WHERE username = $1"#,
21+ username.trim()
22+ )
23+ .fetch_optional(db)
24+ .await?;
25+ Ok(builder)
23 }26 }
24 27
25 pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppError> {28 pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppError> {
26- Ok(db.select(id.record()).await?)29+ let builder = sqlx::query_as!(
30+ Builder,
31+ r#"SELECT id AS "id: BuilderId",
32+ username AS "username: Username",
33+ password_hash AS "password_hash: PasswordHash"
34+ FROM builder WHERE id = $1"#,
35+ id.uuid()
36+ )
37+ .fetch_optional(db)
38+ .await?;
39+ Ok(builder)
27 }40 }
28 41
29 /// The raw account insert behind [`crate::service::builder::ensure`]'s seed.42 /// The raw account insert behind [`crate::service::builder::ensure`]'s seed.
43+/// The unique index on `username` is the whole availability check: a racing
44+/// second seed is a `23505` on `builder_username`, and the seed's
45+/// find-then-insert order makes that unreachable in practice β€” but the
46+/// constraint stands guard regardless.
30 pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> {47 pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> {
31- let created: Option<Builder> = db48+ sqlx::query!(
32- .create(builder.get_id().record())49+ "INSERT INTO builder (id, username, password_hash) VALUES ($1, $2, $3)",
33- .content(builder.clone())50+ builder.id.uuid(),
34- .await?;51+ builder.username.as_str(),
35- created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?;52+ builder.password_hash.as_str(),
53+ )
54+ .execute(db)
55+ .await?;
36 Ok(())56 Ok(())
37 }57 }
38 58
@@ -41,32 +61,49 @@ pub async fn create_session(
41 db: &Database,61 db: &Database,
42 builder: &BuilderId,62 builder: &BuilderId,
43 ) -> Result<BuilderSession, AppError> {63 ) -> Result<BuilderSession, AppError> {
44- let key = RecordId::new(BUILDER_SESSION_TABLE, Ulid::generate().to_string());64+ let token = SessionToken::generate()?;
45- let session = BuilderSession {65+ let created_at = Timestamp::now();
46- id: key.clone(),66+ let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS);
47- builder: builder.clone(),67+ let session = sqlx::query_as!(
48- token: SessionToken::generate()?,68+ BuilderSession,
49- created_at: Timestamp::now(),69+ r#"INSERT INTO builder_session (id, builder, token, created_at, expires_at)
50- expires_at: Timestamp::in_days(SESSION_DURATION_DAYS),70+ VALUES ($1, $2, $3, $4, $5)
51- };71+ RETURNING id,
52- let created: Option<BuilderSession> = db.create(key).content(session).await?;72+ builder AS "builder: BuilderId",
53- created.ok_or_else(|| AppError::Internal("failed to create the builder session".into()))73+ token AS "token: SessionToken",
74+ created_at AS "created_at: Timestamp",
75+ expires_at AS "expires_at: Timestamp""#,
76+ crate::domain::monotonic_id::next_uuid(),
77+ builder.uuid(),
78+ token.as_str(),
79+ created_at.as_millis(),
80+ expires_at.as_millis(),
81+ )
82+ .fetch_one(db)
83+ .await?;
84+ Ok(session)
54 }85 }
55 86
56 pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<BuilderSession>, AppError> {87 pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<BuilderSession>, AppError> {
57- let mut result = db88+ let session = sqlx::query_as!(
58- .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1")89+ BuilderSession,
59- .bind(("tok", token.to_string()))90+ r#"SELECT id,
60- .await?91+ builder AS "builder: BuilderId",
61- .check()?;92+ token AS "token: SessionToken",
62- Ok(result.take::<Vec<BuilderSession>>(0)?.into_iter().next())93+ created_at AS "created_at: Timestamp",
94+ expires_at AS "expires_at: Timestamp"
95+ FROM builder_session WHERE token = $1"#,
96+ token
97+ )
98+ .fetch_optional(db)
99+ .await?;
100+ Ok(session)
63 }101 }
64 102
65 pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {103 pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {
66- db.query("DELETE builder_session WHERE token = $tok")104+ sqlx::query!("DELETE FROM builder_session WHERE token = $1", token)
67- .bind(("tok", token.to_string()))105+ .execute(db)
68- .await?106+ .await?;
69- .check()?;
70 Ok(())107 Ok(())
71 }108 }
72 109
src/db/page.rsmodified+17 -10
@@ -67,6 +67,9 @@ pub(crate) enum Param {
67 OptText(Option<String>),67 OptText(Option<String>),
68 /// Nullable BIGINT column clear/set.68 /// Nullable BIGINT column clear/set.
69 OptI64(Option<i64>),69 OptI64(Option<i64>),
70+ /// A TEXT-array predicate value (`col = ANY($n)`): the closed role set a
71+ /// visibility filter allows, the tag list a search narrows to.
72+ Texts(Vec<String>),
70 }73 }
71 74
72 impl Param {75 impl Param {
@@ -80,6 +83,7 @@ impl Param {
80 Param::OptUuid(value) => args.add(value),83 Param::OptUuid(value) => args.add(value),
81 Param::OptText(value) => args.add(value),84 Param::OptText(value) => args.add(value),
82 Param::OptI64(value) => args.add(value),85 Param::OptI64(value) => args.add(value),
86+ Param::Texts(value) => args.add(value),
83 };87 };
84 }88 }
85 }89 }
@@ -182,16 +186,18 @@ impl PagedList {
182 if count_sql.is_some() {186 if count_sql.is_some() {
183 Param::from(offset).add_to(&mut args);187 Param::from(offset).add_to(&mut args);
184 }188 }
185- let rows: Vec<T> =189+ let rows: Vec<T> = sqlx::query_as_with(AssertSqlSafe(page_sql), args)
186- sqlx::query_as_with(AssertSqlSafe(page_sql), args).fetch_all(db).await?;190+ .fetch_all(db)
191+ .await?;
187 let total = match count_sql {192 let total = match count_sql {
188 Some(count_sql) => {193 Some(count_sql) => {
189 let mut args = PgArguments::default();194 let mut args = PgArguments::default();
190 for bind in self.binds {195 for bind in self.binds {
191 bind.add_to(&mut args);196 bind.add_to(&mut args);
192 }197 }
193- let scalar: i64 =198+ let scalar: i64 = sqlx::query_scalar_with(AssertSqlSafe(count_sql), args)
194- sqlx::query_scalar_with(AssertSqlSafe(count_sql), args).fetch_one(db).await?;199+ .fetch_one(db)
200+ .await?;
195 scalar201 scalar
196 }202 }
197 None => rows.len() as i64,203 None => rows.len() as i64,
@@ -223,8 +229,7 @@ mod tests {
223 /// A whole-table read counts the bare table.229 /// A whole-table read counts the bare table.
224 #[test]230 #[test]
225 fn an_unfiltered_list_counts_the_bare_table() {231 fn an_unfiltered_list_counts_the_bare_table() {
226- let (sql, count) =232+ let (sql, count) = PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0);
227- PagedList::new("term", "ORDER BY starts_at DESC").statements(Some(5), 0);
228 assert!(sql.contains("LIMIT $1 OFFSET $2"));233 assert!(sql.contains("LIMIT $1 OFFSET $2"));
229 assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term"));234 assert_eq!(count.as_deref(), Some("SELECT count(*) FROM term"));
230 }235 }
@@ -250,10 +255,12 @@ mod tests {
250 /// order.255 /// order.
251 #[test]256 #[test]
252 fn window_placeholders_continue_the_where_numbering() {257 fn window_placeholders_continue_the_where_numbering() {
253- let (sql, count) =258+ let (sql, count) = PagedList::new(
254- PagedList::new("note WHERE user_id = $1 AND archived_at IS NULL", "ORDER BY id")259+ "note WHERE user_id = $1 AND archived_at IS NULL",
255- .bind(Uuid::nil())260+ "ORDER BY id",
256- .statements(Some(2), 4);261+ )
262+ .bind(Uuid::nil())
263+ .statements(Some(2), 4);
257 assert!(sql.contains("LIMIT $2 OFFSET $3"));264 assert!(sql.contains("LIMIT $2 OFFSET $3"));
258 assert_eq!(265 assert_eq!(
259 count.as_deref(),266 count.as_deref(),
src/db/profile.rsmodified+108 -136
@@ -4,11 +4,17 @@
4 //! [`crate::db::badge`] (reads and writes).4 //! [`crate::db::badge`] (reads and writes).
5 5
6 use crate::database::Database;6 use crate::database::Database;
7-use crate::domain::badge::{BadgeStat, BadgeStats};7+use crate::domain::badge::BadgeStats;
8 use crate::domain::profile::ProfileStats;8 use crate::domain::profile::ProfileStats;
9 use crate::domain::user::UserId;9 use crate::domain::user::UserId;
10 use crate::error::AppError;10 use crate::error::AppError;
11-use surrealdb::types::SurrealValue;11+
12+/// The aggregate row of [`load`].
13+#[derive(Debug)]
14+struct PomodoroTotals {
15+ sessions: i64,
16+ focus_ms: i64,
17+}
12 18
13 /// One round trip, and only one: `courses` and `classes` arrive from the19 /// One round trip, and only one: `courses` and `classes` arrive from the
14 /// caller, which already holds them as the `total` of the paged class and20 /// caller, which already holds them as the `total` of the paged class and
@@ -16,182 +22,148 @@ use surrealdb::types::SurrealValue;
16 /// here would be two extra reads for numbers already in hand.22 /// here would be two extra reads for numbers already in hand.
17 ///23 ///
18 /// The pomodoro aggregate rides the per-user index, so it is a lookup and24 /// The pomodoro aggregate rides the per-user index, so it is a lookup and
19-/// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a25+/// not a scan. `finished_at IS NOT NULL` is the filter: an open stint
20-/// bare truthiness test would also drop a stint that finished at epoch. An26+/// contributes to neither the count nor the sum β€” unfinished focus has no
21-/// open stint contributes to neither the count nor the sum β€” unfinished27+/// honest duration to add. The Postgres aggregate always answers exactly
22-/// focus has no honest duration to add.28+/// one row (`count` 0, `sum` NULL on no rows), so the empty school reads as
29+/// zeros rather than as a missing row; `COALESCE` floors the sum the same
30+/// way the old `GROUP ALL`-absent case did.
23 ///31 ///
24 /// The lifetime counters ride along as a second statement in the *same*32 /// The lifetime counters ride along as a second statement in the *same*
25-/// query rather than a [`super::badge::load`] call, which would be a second33+/// round rather than a [`super::badge::load`] call, which would be a second
26-/// round trip for one record lookup. It repeats that projection β€” `?? 0`34+/// round trip for one record lookup. It repeats that projection β€” the
27-/// per column, because the columns are `option<int>` and a row predating35+/// `*_total` columns, because they are the badge rules' inputs β€” so the two
28-/// them carries none β€” so the two must move together if the shape changes.36+/// must move together if the shape changes.
29 pub async fn load(37 pub async fn load(
30 db: &Database,38 db: &Database,
31 user: &UserId,39 user: &UserId,
32 courses: i64,40 courses: i64,
33 classes: i64,41 classes: i64,
34 ) -> Result<ProfileStats, AppError> {42 ) -> Result<ProfileStats, AppError> {
35- let mut result = db43+ let totals = sqlx::query!(
36- .query(format!(44+ r#"SELECT count(*) AS "sessions!: i64",
37- "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms45+ COALESCE(sum(finished_at - started_at), 0) AS "focus_ms!: i64"
38- FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL;46+ FROM pomodoro_session
39- SELECT ({homework_submitted} ?? 0) AS homework_submitted,47+ WHERE app_user = $1 AND finished_at IS NOT NULL"#,
40- ({homework_on_time} ?? 0) AS homework_on_time,48+ user.uuid()
41- ({exam_sat} ?? 0) AS exam_sat,49+ )
42- ({pomodoro_finished} ?? 0) AS pomodoro_finished,50+ .fetch_one(db)
43- ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms,51+ .await?;
44- ({marks_given} ?? 0) AS marks_given,52+ let stats = sqlx::query_as!(
45- ({lessons_held} ?? 0) AS lessons_held,53+ BadgeStats,
46- ({pool_approved} ?? 0) AS pool_approved,54+ r#"SELECT homework_submitted_total AS homework_submitted,
47- ({pool_published} ?? 0) AS pool_published,55+ homework_on_time_total AS homework_on_time,
48- ({lessons_attended} ?? 0) AS lessons_attended,56+ exam_sat_total AS exam_sat,
49- ({high_mark} ?? 0) AS high_mark,57+ pomodoro_finished_total AS pomodoro_finished,
50- ({study_streak} ?? 0) AS study_streak58+ pomodoro_focus_ms_total AS pomodoro_focus_ms,
51- FROM $usr;",59+ marks_given_total AS marks_given,
52- homework_submitted = BadgeStat::HomeworkSubmitted.field(),60+ lessons_held_total AS lessons_held,
53- homework_on_time = BadgeStat::HomeworkOnTime.field(),61+ pool_approved_total AS pool_approved,
54- exam_sat = BadgeStat::ExamSat.field(),62+ pool_published_total AS pool_published,
55- pomodoro_finished = BadgeStat::PomodoroFinished.field(),63+ lessons_attended_total AS lessons_attended,
56- pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(),64+ high_mark_total AS high_mark,
57- marks_given = BadgeStat::MarksGiven.field(),65+ study_streak_longest AS study_streak
58- lessons_held = BadgeStat::LessonsHeld.field(),66+ FROM app_user WHERE id = $1"#,
59- pool_approved = BadgeStat::PoolApproved.field(),67+ user.uuid()
60- pool_published = BadgeStat::PoolPublished.field(),68+ )
61- lessons_attended = BadgeStat::LessonsAttended.field(),69+ .fetch_optional(db)
62- high_mark = BadgeStat::HighMark.field(),70+ .await?;
63- study_streak = BadgeStat::StudyStreak.field(),
64- ))
65- .bind(("usr", user.record()))
66- .await?
67- .check()?;
68- // `GROUP ALL` yields no row at all when nothing matched β€” that is the
69- // zero case, not a missing one.
70- let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next();
71- // A vanished user row reads as all zeros, same as a fresh account.
72- let totals = result
73- .take::<Vec<BadgeStats>>(1)?
74- .into_iter()
75- .next()
76- .unwrap_or_default();
77 Ok(ProfileStats {71 Ok(ProfileStats {
78- totals,72+ totals: stats.unwrap_or_default(),
79- pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions),73+ pomodoro_sessions: totals.sessions,
80 // Floored at zero: a stint stamped by a wall clock that stepped74 // Floored at zero: a stint stamped by a wall clock that stepped
81 // backwards mid-session sums as negative time, and "you focused for75 // backwards mid-session sums as negative time, and "you focused for
82 // minus five seconds" is never the truthful answer. New stints76 // minus five seconds" is never the truthful answer. New stints
83 // cannot go inverted (see [`PomodoroSession::finish`]); rows written77 // cannot go inverted (see [`PomodoroSession::finish`]); rows written
84 // before that guard still can, and this is what covers them.78 // before that guard still can, and this is what covers them.
85- pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)),79+ pomodoro_focus_ms: totals.focus_ms.max(0),
86 courses,80 courses,
87 classes,81 classes,
88 })82 })
89 }83 }
90 84
91-/// The aggregate row of [`load`].
92-#[derive(Debug, SurrealValue)]
93-struct PomodoroTotals {
94- sessions: i64,
95- focus_ms: i64,
96-}
97-
98 #[cfg(test)]85 #[cfg(test)]
99 mod tests {86 mod tests {
100 use super::*;87 use super::*;
88+ use crate::database::init_mem;
89+ use crate::domain::user::{Password, Username};
101 90
102- #[tokio::test]91+ async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
103- async fn stats_are_zero_without_pomodoro_rows() {92+ crate::db::user::create(
104- let db = crate::database::init_mem().await.unwrap();93+ db,
105- let user = UserId::from_key(&ulid::Ulid::generate().to_string());94+ Username::try_new(username).unwrap(),
106-95+ Password::try_new("secret1")
107- let stats = load(&db, &user, 3, 1).await.unwrap();96+ .unwrap()
108- // Derived counters: no rows is a true zero, never a null.97+ .hash_async()
109- assert_eq!(stats.get_pomodoro_sessions(), 0);98+ .await
110- assert_eq!(stats.get_pomodoro_focus_ms(), 0);99+ .unwrap(),
111- // The passed-in counts survive untouched.100+ )
112- assert_eq!(stats.get_courses(), 3);101+ .await
113- assert_eq!(stats.get_classes(), 1);102+ .unwrap()
114- // No user row at all β€” the lifetime counters still read as zeros.
115- assert_eq!(stats.get_totals().get_homework_submitted(), 0);
116- assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0);
117 }103 }
118 104
119- /// The second statement of the same query: the stored counters, straight off
120- /// the user row, with the columns an older row is missing read as zero.
121 #[tokio::test]105 #[tokio::test]
122- async fn lifetime_totals_ride_the_same_query() {106+ async fn an_account_with_no_history_reads_as_zeros() {
123- let db = crate::database::init_mem().await.unwrap();107+ let db = init_mem().await.unwrap();
124- let user = UserId::from_key(&ulid::Ulid::generate().to_string());108+ let user = a_user("profil-bos", &db).await;
125- db.query(format!(
126- "CREATE $usr SET username = $name, password_hash = 'x',
127- {} = 4, {} = 3",
128- crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD,
129- crate::constant::EXAM_SAT_TOTAL_FIELD,
130- ))
131- .bind(("usr", user.record()))
132- .bind(("name", user.key().to_string()))
133- .await
134- .unwrap()
135- .check()
136- .unwrap();
137 109
138- let totals = load(&db, &user, 0, 0).await.unwrap();110+ let stats = load(&db, user.get_id(), 3, 1).await.unwrap();
139- let totals = totals.get_totals();111+ assert_eq!(stats.pomodoro_sessions, 0);
140- assert_eq!(totals.get_homework_submitted(), 4);112+ assert_eq!(stats.pomodoro_focus_ms, 0);
141- assert_eq!(totals.get_exam_sat(), 3);113+ assert_eq!(stats.totals.get_homework_submitted(), 0);
142- // Never written on this row: absent must read as 0, not as an error.114+ // The caller-supplied counts ride through untouched.
143- assert_eq!(totals.get_homework_on_time(), 0);115+ assert_eq!(stats.courses, 3);
144- assert_eq!(totals.get_pomodoro_finished(), 0);116+ assert_eq!(stats.classes, 1);
145- assert_eq!(totals.get_pomodoro_focus_ms(), 0);
146 }117 }
147 118
148 #[tokio::test]119 #[tokio::test]
149- async fn stats_count_finished_stints_only() {120+ async fn only_finished_stints_count_and_an_open_one_is_invisible() {
150- let db = crate::database::init_mem().await.unwrap();121+ let db = init_mem().await.unwrap();
151- let user = UserId::from_key(&ulid::Ulid::generate().to_string());122+ let user = a_user("profil-dolu", &db).await;
152- let other = UserId::from_key(&ulid::Ulid::generate().to_string());
153 123
154- // Two finished stints (1000 ms + 2500 ms), one still running, and one124+ sqlx::query(
155- // finished stint belonging to somebody else.125+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \
156- db.query(126+ VALUES ($1, $2, 1000, 3000), ($3, $2, 5000, 6000)",
157- "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 };
158- CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 };
159- CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 };
160- CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };",
161 )127 )
162- .bind(("usr", user.record()))128+ .bind(uuid::Uuid::now_v7())
163- .bind(("oth", other.record()))129+ .bind(user.uuid())
130+ .bind(uuid::Uuid::now_v7())
131+ .execute(&db)
132+ .await
133+ .unwrap();
134+ // An open stint: contributes to neither the count nor the sum.
135+ sqlx::query(
136+ "INSERT INTO pomodoro_session (id, app_user, started_at) VALUES ($1, $2, 9000)",
137+ )
138+ .bind(uuid::Uuid::now_v7())
139+ .bind(user.uuid())
140+ .execute(&db)
164 .await141 .await
165- .unwrap()
166- .check()
167 .unwrap();142 .unwrap();
168 143
169- let stats = load(&db, &user, 0, 0).await.unwrap();144+ let stats = load(&db, user.get_id(), 0, 0).await.unwrap();
170- assert_eq!(stats.get_pomodoro_sessions(), 2);145+ assert_eq!(stats.pomodoro_sessions, 2);
171- assert_eq!(stats.get_pomodoro_focus_ms(), 3500);146+ assert_eq!(stats.pomodoro_focus_ms, 2000 + 1000);
172 }147 }
173 148
174 #[tokio::test]149 #[tokio::test]
175- async fn focus_time_never_reads_negative() {150+ async fn a_negative_stint_sum_is_floored_at_zero() {
176- let db = crate::database::init_mem().await.unwrap();151+ let db = init_mem().await.unwrap();
177- let user = UserId::from_key(&ulid::Ulid::generate().to_string());152+ let user = a_user("profil-terstarihi", &db).await;
178 153
179- // One honest 1000 ms stint and one inverted row β€” what a backwards154+ // A stint closed by a wall clock that stepped backwards: the sum is
180- // clock step left behind before `finish` grew its floor. The raw sum is155+ // negative and "minus five seconds of focus" is never the answer.
181- // -5000; the profile must still answer a duration, not an accusation.156+ sqlx::query(
182- db.query(157+ "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at) \
183- "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 };158+ VALUES ($1, $2, 5000, 1000)",
184- CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };",
185 )159 )
186- .bind(("usr", user.record()))160+ .bind(uuid::Uuid::now_v7())
161+ .bind(user.uuid())
162+ .execute(&db)
187 .await163 .await
188- .unwrap()
189- .check()
190 .unwrap();164 .unwrap();
191 165
192- let stats = load(&db, &user, 0, 0).await.unwrap();166+ let stats = load(&db, user.get_id(), 0, 0).await.unwrap();
193- // The stints still happened, so the count is honest at 2.167+ assert_eq!(stats.pomodoro_focus_ms, 0);
194- assert_eq!(stats.get_pomodoro_sessions(), 2);
195- assert_eq!(stats.get_pomodoro_focus_ms(), 0);
196 }168 }
197 }169 }
src/db/session.rsmodified+52 -30
@@ -1,4 +1,4 @@
1-//! The `session` table: opaque login tokens with an expiry, swept on login.1+//! The `user_session` table: opaque login tokens with an expiry, swept on login.
2 2
3 use crate::constant::SESSION_DURATION_DAYS;3 use crate::constant::SESSION_DURATION_DAYS;
4 use crate::database::Database;4 use crate::database::Database;
@@ -8,30 +8,48 @@ use crate::domain::user::UserId;
8 use crate::error::AppError;8 use crate::error::AppError;
9 9
10 pub async fn create(db: &Database, user: &UserId) -> Result<Session, AppError> {10 pub async fn create(db: &Database, user: &UserId) -> Result<Session, AppError> {
11- let session = Session {11+ let id = SessionId::generate();
12- id: SessionId::generate(),12+ let token = SessionToken::generate()?;
13- user: user.clone(),13+ let expires_at = Timestamp::in_days(SESSION_DURATION_DAYS);
14- token: SessionToken::generate()?,14+ // One statement is the whole mint: the row that comes back is the row
15- expires_at: Timestamp::in_days(SESSION_DURATION_DAYS),15+ // that was stored.
16- };16+ let session = sqlx::query_as!(
17- let created: Option<Session> = db.create(session.id.record()).content(session).await?;17+ Session,
18- created.ok_or_else(|| AppError::Internal("failed to create session".into()))18+ r#"INSERT INTO user_session (id, app_user, token, expires_at)
19+ VALUES ($1, $2, $3, $4)
20+ RETURNING id AS "id: SessionId",
21+ app_user AS "user: UserId",
22+ token AS "token: SessionToken",
23+ expires_at AS "expires_at: Timestamp""#,
24+ id.0,
25+ user.0,
26+ token.as_str(),
27+ expires_at.as_millis(),
28+ )
29+ .fetch_one(db)
30+ .await?;
31+ Ok(session)
19 }32 }
20 33
21 pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<Session>, AppError> {34 pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<Session>, AppError> {
22- let mut result = db35+ let session = sqlx::query_as!(
23- .query("SELECT * FROM session WHERE token = $tok LIMIT 1")36+ Session,
24- .bind(("tok", token.to_string()))37+ r#"SELECT id AS "id: SessionId",
25- .await?38+ app_user AS "user: UserId",
26- .check()?;39+ token AS "token: SessionToken",
27- Ok(result.take::<Vec<Session>>(0)?.into_iter().next())40+ expires_at AS "expires_at: Timestamp"
41+ FROM user_session WHERE token = $1"#,
42+ token
43+ )
44+ .fetch_optional(db)
45+ .await?;
46+ Ok(session)
28 }47 }
29 48
30 pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {49 pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> {
31- db.query("DELETE session WHERE token = $tok")50+ sqlx::query!("DELETE FROM user_session WHERE token = $1", token)
32- .bind(("tok", token.to_string()))51+ .execute(db)
33- .await?52+ .await?;
34- .check()?;
35 Ok(())53 Ok(())
36 }54 }
37 55
@@ -39,24 +57,28 @@ pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError>
39 /// the new credential means nothing while a cookie minted under the old one57 /// the new credential means nothing while a cookie minted under the old one
40 /// still authenticates.58 /// still authenticates.
41 pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> {59 pub async fn delete_by_user(db: &Database, user: &UserId) -> Result<(), AppError> {
42- db.query("DELETE session WHERE user = $usr")60+ sqlx::query!("DELETE FROM user_session WHERE app_user = $1", user.0)
43- .bind(("usr", user.record()))61+ .execute(db)
44- .await?62+ .await?;
45- .check()?;
46 Ok(())63 Ok(())
47 }64 }
48 65
49 /// Delete every session whose expiry is in the past, returning how many were66 /// Delete every session whose expiry is in the past, returning how many were
50 /// removed. Expired sessions are already rejected at auth, but nothing else67 /// removed. Expired sessions are already rejected at auth, but nothing else
51-/// deletes their rows β€” without this sweep the `session` table grows forever.68+/// deletes their rows β€” without this sweep the `user_session` table grows
69+/// forever.
52 pub async fn purge_expired(db: &Database) -> Result<u64, AppError> {70 pub async fn purge_expired(db: &Database) -> Result<u64, AppError> {
53 let now = Timestamp::now().as_millis();71 let now = Timestamp::now().as_millis();
54- let mut result = db72+ let (deleted,) = sqlx::query!(
55- .query("DELETE session WHERE expires_at < $now RETURN BEFORE")73+ r#"WITH gone AS (
56- .bind(("now", now))74+ DELETE FROM user_session WHERE expires_at < $1 RETURNING 1
57- .await?75+ )
58- .check()?;76+ SELECT count(*) AS "deleted!: i64" FROM gone"#,
59- Ok(result.take::<Vec<Session>>(0)?.len() as u64)77+ now
78+ )
79+ .fetch_one(db)
80+ .await?;
81+ Ok(u64::try_from(deleted).unwrap_or(u64::MAX))
60 }82 }
61 83
62 #[cfg(test)]84 #[cfg(test)]
src/db/settings.rsmodified+156 -266
@@ -1,14 +1,32 @@
1-//! The `settings` singleton: one row (`settings:school`) holding the school's1+//! The `settings` singleton: one row (`settings`, id `'school'`) holding the
2-//! policy knobs. An absent row reads as the built-in defaults everywhere.2+//! school's policy knobs. An absent row reads as the built-in defaults
3+//! everywhere.
4+
5+use sqlx::types::Json;
3 6
4 use crate::database::Database;7 use crate::database::Database;
5-use crate::domain::settings::Settings;8+use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
6 use crate::error::AppError;9 use crate::error::AppError;
7 10
8-/// The stored policy, or the defaults when no row exists yet.
9 pub async fn load(db: &Database) -> Result<Settings, AppError> {11 pub async fn load(db: &Database) -> Result<Settings, AppError> {
10- let found: Option<Settings> = db.select(Settings::record_id()).await?;12+ let settings = sqlx::query_as!(
11- Ok(found.unwrap_or_else(Settings::defaults))13+ Settings,
14+ r#"SELECT id,
15+ exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
16+ attendance_statuses,
17+ grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
18+ max_file_bytes,
19+ chatbot_history_turns,
20+ max_chatbot_message_len,
21+ max_chatbot_threads,
22+ meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
23+ dietary_tags,
24+ meal_cancel_cutoff_minutes
25+ FROM settings WHERE id = 'school'"#
26+ )
27+ .fetch_optional(db)
28+ .await?;
29+ Ok(settings.unwrap_or_else(Settings::defaults))
12 }30 }
13 31
14 /// Persist the policy (single UPSERT on the fixed singleton id),32 /// Persist the policy (single UPSERT on the fixed singleton id),
@@ -16,8 +34,49 @@ pub async fn load(db: &Database) -> Result<Settings, AppError> {
16 /// wherever the new policy was merged from a loaded snapshot.34 /// wherever the new policy was merged from a loaded snapshot.
17 pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {35 pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {
18 // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged36 // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged
19- let saved: Option<Settings> = db.upsert(Settings::record_id()).content(settings).await?;37+ let saved = sqlx::query_as!(
20- saved.ok_or_else(|| AppError::Internal("failed to save settings".into()))38+ Settings,
39+ r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,
40+ max_file_bytes, chatbot_history_turns,
41+ max_chatbot_message_len, max_chatbot_threads,
42+ meal_slots, dietary_tags, meal_cancel_cutoff_minutes)
43+ VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
44+ ON CONFLICT (id) DO UPDATE SET
45+ exam_kinds = EXCLUDED.exam_kinds,
46+ attendance_statuses = EXCLUDED.attendance_statuses,
47+ grade_bands = EXCLUDED.grade_bands,
48+ max_file_bytes = EXCLUDED.max_file_bytes,
49+ chatbot_history_turns = EXCLUDED.chatbot_history_turns,
50+ max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,
51+ max_chatbot_threads = EXCLUDED.max_chatbot_threads,
52+ meal_slots = EXCLUDED.meal_slots,
53+ dietary_tags = EXCLUDED.dietary_tags,
54+ meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes
55+ RETURNING id,
56+ exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
57+ attendance_statuses,
58+ grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
59+ max_file_bytes,
60+ chatbot_history_turns,
61+ max_chatbot_message_len,
62+ max_chatbot_threads,
63+ meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
64+ dietary_tags,
65+ meal_cancel_cutoff_minutes"#,
66+ settings.exam_kinds,
67+ settings.attendance_statuses,
68+ settings.grade_bands,
69+ settings.max_file_bytes,
70+ settings.chatbot_history_turns,
71+ settings.max_chatbot_message_len,
72+ settings.max_chatbot_threads,
73+ settings.meal_slots,
74+ settings.dietary_tags,
75+ settings.meal_cancel_cutoff_minutes,
76+ )
77+ .fetch_one(db)
78+ .await?;
79+ Ok(saved)
21 }80 }
22 81
23 /// Persist the policy only while the stored row still matches `expected`82 /// Persist the policy only while the stored row still matches `expected`
@@ -28,269 +87,100 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
28 /// same snapshot; the later whole-row write restores its stale copy of87 /// same snapshot; the later whole-row write restores its stale copy of
29 /// the other's field).88 /// the other's field).
30 ///89 ///
31-/// One transaction: the seed insert materializes the defaults-as-loaded90+/// ONE guarded statement, where the old engine needed a seed insert and a
32-/// state when no row exists yet (`load` reported the defaults, so the91+/// separate guarded update: the `INSERT` arm materializes the defaults-as-
33-/// defaults are what the caller merged over), then the guarded update92+/// loaded state when no row exists yet (`load` reported the defaults, so
34-/// applies `settings` only if the row (still) equals `expected`.93+/// the defaults are what the caller merged over β€” nothing to compare), and
94+/// the `ON CONFLICT DO UPDATE … WHERE` arm applies `settings` only if the
95+/// row (still) equals `expected`, every column compared with
96+/// `IS NOT DISTINCT FROM` so "never set" (`NULL`) stays distinct from
97+/// "explicitly empty" and an unset column matches an unset expectation.
98+///
99+/// The old `meal_slots` projection dance was an artifact of the old engine
100+/// *dropping* object keys whose value was `NONE` on write, which made a
101+/// plain equality guard never match a slot without a serving time. Both
102+/// sides of this comparison are written by the same Rust serialization,
103+/// which round-trips through JSONB unchanged β€” the shapes cannot diverge,
104+/// so the columns are compared whole.
35 ///105 ///
36-/// **`meal_slots` is compared through a projection, and it has to be.**106+/// Generic over the executor so the workflow can run the same guarded save
37-/// SurrealDB *drops* an object key whose value is `NONE` on write, while107+/// inside its own transaction (a stale save must roll its retirements back,
38-/// the `SurrealValue` derive always emits `serving_minute: NONE` for a108+/// which only an abort can do).
39-/// slot without one β€” so `{name: 'lunch'} = {name: 'lunch', serving_minute:109+pub async fn save_if_unchanged<'e, E>(
40-/// NONE}` is **false** and a plain equality guard would never match again110+ db: E,
41-/// for any school with a serving-time-less slot (which is every school
42-/// until it sets one): every `PATCH /settings` would 409 forever. Rebuilding
43-/// both sides as full objects normalizes the shapes. The NONE-ness of the
44-/// column itself is compared separately, so "never set" stays distinguishable
45-/// from "explicitly empty". Top-level optional columns need none of this:
46-/// a missing field reads as `NONE`, and `NONE = NONE` holds.
47-pub async fn save_if_unchanged(
48- db: &Database,
49 settings: Settings,111 settings: Settings,
50 expected: &Settings,112 expected: &Settings,
51-) -> Result<Option<Settings>, AppError> {113+) -> Result<Option<Settings>, AppError>
52- let mut result = db114+where
53- .query(115+ E: sqlx::PgExecutor<'e>,
54- "BEGIN TRANSACTION;116+{
55- INSERT IGNORE INTO settings $expected;117+ let saved = sqlx::query_as!(
56- UPDATE $id CONTENT $new118+ Settings,
57- WHERE exam_kinds = $ek119+ r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,
58- AND attendance_statuses = $st120+ max_file_bytes, chatbot_history_turns,
59- AND grade_bands = $gb121+ max_chatbot_message_len, max_chatbot_threads,
60- AND max_file_bytes = $mf122+ meal_slots, dietary_tags, meal_cancel_cutoff_minutes)
61- AND chatbot_history_turns = $ct123+ VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
62- AND max_chatbot_threads = $cc124+ ON CONFLICT (id) DO UPDATE SET
63- AND max_chatbot_message_len = $cl125+ exam_kinds = $1,
64- AND (meal_slots = NONE) = $ms_unset126+ attendance_statuses = $2,
65- AND (meal_slots ?? []).map(|$s| {127+ grade_bands = $3,
66- name: $s.name,128+ max_file_bytes = $4,
67- serving_minute: $s.serving_minute129+ chatbot_history_turns = $5,
68- }) = ($ms ?? [])130+ max_chatbot_message_len = $6,
69- AND dietary_tags = $dt131+ max_chatbot_threads = $7,
70- AND meal_cancel_cutoff_minutes = $mc;132+ meal_slots = $8,
71- COMMIT TRANSACTION;",133+ dietary_tags = $9,
72- )134+ meal_cancel_cutoff_minutes = $10
73- .bind(("expected", expected.clone()))135+ WHERE settings.exam_kinds IS NOT DISTINCT FROM $11
74- .bind(("id", Settings::record_id()))136+ AND settings.attendance_statuses IS NOT DISTINCT FROM $12
75- .bind(("new", settings))137+ AND settings.grade_bands IS NOT DISTINCT FROM $13
76- .bind(("ek", expected.exam_kinds.clone()))138+ AND settings.max_file_bytes IS NOT DISTINCT FROM $14
77- .bind(("st", expected.attendance_statuses.clone()))139+ AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15
78- .bind(("gb", expected.grade_bands.clone()))140+ AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16
79- .bind(("mf", expected.max_file_bytes))141+ AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17
80- .bind(("ct", expected.chatbot_history_turns))142+ AND settings.meal_slots IS NOT DISTINCT FROM $18
81- .bind(("cc", expected.max_chatbot_threads))143+ AND settings.dietary_tags IS NOT DISTINCT FROM $19
82- .bind(("cl", expected.max_chatbot_message_len))144+ AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20
83- .bind(("ms_unset", expected.meal_slots.is_none()))145+ RETURNING id,
84- .bind(("ms", expected.meal_slots.clone()))146+ exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
85- .bind(("dt", expected.dietary_tags.clone()))147+ attendance_statuses,
86- .bind(("mc", expected.meal_cancel_cutoff_minutes))148+ grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
87- .await?149+ max_file_bytes,
88- .check()?;150+ chatbot_history_turns,
89- // Statement slots count BEGIN too: the guarded UPDATE is slot 2. An151+ max_chatbot_message_len,
90- // empty slot means the row no longer matched `expected`.152+ max_chatbot_threads,
91- Ok(result.take::<Vec<Settings>>(2)?.into_iter().next())153+ meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
154+ dietary_tags,
155+ meal_cancel_cutoff_minutes"#,
156+ settings.exam_kinds,
157+ settings.attendance_statuses,
158+ settings.grade_bands,
159+ settings.max_file_bytes,
160+ settings.chatbot_history_turns,
161+ settings.max_chatbot_message_len,
162+ settings.max_chatbot_threads,
163+ settings.meal_slots,
164+ settings.dietary_tags,
165+ settings.meal_cancel_cutoff_minutes,
166+ expected.exam_kinds,
167+ expected.attendance_statuses,
168+ expected.grade_bands,
169+ expected.max_file_bytes,
170+ expected.chatbot_history_turns,
171+ expected.max_chatbot_message_len,
172+ expected.max_chatbot_threads,
173+ expected.meal_slots,
174+ expected.dietary_tags,
175+ expected.meal_cancel_cutoff_minutes,
176+ )
177+ .fetch_optional(db)
178+ .await?;
179+ // An empty result means the row no longer matched `expected`.
180+ Ok(saved)
92 }181 }
93 182
94 #[cfg(test)]183 #[cfg(test)]
95 mod tests {184 mod tests {
96- use super::*;185+ // Ported in wave 3: they need a live school database.
97- use crate::constant::{
98- DEFAULT_CHATBOT_HISTORY_TURNS, DEFAULT_MAX_CHATBOT_MESSAGE_LEN,
99- DEFAULT_MAX_CHATBOT_THREADS, DEFAULT_MAX_FILE_BYTES,
100- };
101- use crate::domain::settings::{ExamKindDef, GradeBand, SettingsParams};
102-
103- fn kinds(list: &[&str]) -> Vec<ExamKindDef> {
104- list.iter()
105- .map(|s| ExamKindDef::try_new(s, 1).unwrap())
106- .collect()
107- }
108-
109- fn names(settings: &Settings) -> Vec<&str> {
110- settings
111- .get_exam_kinds()
112- .iter()
113- .map(ExamKindDef::get_name)
114- .collect()
115- }
116-
117- /// The defaults as tweakable params β€” every site below overrides only the
118- /// fields it is testing (`..params()`).
119- fn params() -> SettingsParams {
120- Settings::defaults().params()
121- }
122-
123- fn bands(list: &[(i64, &str)]) -> Vec<GradeBand> {
124- list.iter()
125- .map(|(min, label)| GradeBand::try_new(*min, label).unwrap())
126- .collect()
127- }
128-
129- #[tokio::test]
130- async fn a_row_predating_the_optional_knobs_reads_the_defaults() {
131- let db = crate::database::init_mem().await.unwrap();
132- // The defaults carry no explicit knobs, so this writes a row without
133- // those fields β€” exactly what a volume from before them looks like.
134- save(&db, Settings::defaults()).await.unwrap();
135- let loaded = load(&db).await.unwrap();
136- assert_eq!(loaded.get_max_file_bytes(), DEFAULT_MAX_FILE_BYTES);
137- assert_eq!(
138- loaded.get_chatbot_history_turns(),
139- DEFAULT_CHATBOT_HISTORY_TURNS
140- );
141- assert_eq!(
142- loaded.get_max_chatbot_threads(),
143- DEFAULT_MAX_CHATBOT_THREADS
144- );
145- assert_eq!(
146- loaded.get_max_chatbot_message_len(),
147- DEFAULT_MAX_CHATBOT_MESSAGE_LEN
148- );
149- // And a snapshot of that old row still passes the compare-and-set.
150- let saved = save_if_unchanged(
151- &db,
152- Settings::try_new(SettingsParams {
153- max_file_bytes: 4096,
154- ..loaded.params()
155- })
156- .unwrap(),
157- &loaded,
158- )
159- .await
160- .unwrap()
161- .expect("a merge over an old-shape row applies");
162- assert_eq!(saved.get_max_file_bytes(), 4096);
163- }
164-
165- #[tokio::test]
166- async fn load_save_roundtrip_on_the_singleton() {
167- let db = crate::database::init_mem().await.unwrap();
168- // No row yet β†’ the defaults, not an error.
169- let loaded = load(&db).await.unwrap();
170- assert_eq!(
171- loaded.get_exam_kinds(),
172- Settings::defaults().get_exam_kinds()
173- );
174- // Save a custom policy and read it back β€” bands (nested objects under
175- // a FLEXIBLE field) must survive the trip.
176- save(
177- &db,
178- Settings::try_new(SettingsParams {
179- exam_kinds: kinds(&["lab"]),
180- grade_bands: bands(&[(0, "F"), (50, "P")]),
181- max_file_bytes: 2048,
182- chatbot_history_turns: 3,
183- ..params()
184- })
185- .unwrap(),
186- )
187- .await
188- .unwrap();
189- let loaded = load(&db).await.unwrap();
190- assert_eq!(names(&loaded), ["lab"]);
191- assert_eq!(loaded.get_grade_bands().len(), 2);
192- assert_eq!(loaded.grade_label(60.0), Some("P"));
193- assert_eq!(loaded.get_max_file_bytes(), 2048);
194- assert_eq!(loaded.get_chatbot_history_turns(), 3);
195- // A second save lands on the same singleton row, not a new one.
196- save(
197- &db,
198- Settings::try_new(SettingsParams {
199- exam_kinds: kinds(&["quiz"]),
200- ..params()
201- })
202- .unwrap(),
203- )
204- .await
205- .unwrap();
206- let mut result = db.query("SELECT * FROM settings").await.unwrap();
207- let rows: Vec<Settings> = result.take(0).unwrap();
208- assert_eq!(rows.len(), 1);
209- assert_eq!(names(&rows[0]), ["quiz"]);
210- }
211-
212- #[tokio::test]
213- async fn a_stale_snapshot_cannot_revert_a_newer_policy() {
214- let db = crate::database::init_mem().await.unwrap();
215-
216- // Editor A snapshots the policy (the defaults β€” no row yet)...
217- let stale = load(&db).await.unwrap();
218- // ...then editor B lands a new exam-kind list first.
219- save(
220- &db,
221- Settings::try_new(SettingsParams {
222- exam_kinds: kinds(&["lab"]),
223- ..params()
224- })
225- .unwrap(),
226- )
227- .await
228- .unwrap();
229-
230- // A's merge over the stale snapshot (kinds kept "as loaded", bands
231- // changed) β€” exactly what a concurrent PATCH /settings computes β€”
232- // must be refused, not applied.
233- let refused = save_if_unchanged(
234- &db,
235- Settings::try_new(SettingsParams {
236- grade_bands: bands(&[(0, "F"), (50, "P")]),
237- ..stale.params()
238- })
239- .unwrap(),
240- &stale,
241- )
242- .await
243- .unwrap();
244- assert!(refused.is_none(), "a stale snapshot's save must not apply");
245-
246- // B's edit must survive A's stale write attempt.
247- let after = load(&db).await.unwrap();
248- assert_eq!(
249- names(&after),
250- ["lab"],
251- "a concurrent editor's exam kinds must not be silently reverted"
252- );
253- assert!(after.get_grade_bands().is_empty());
254-
255- // A's retry β€” reload, re-merge, save again β€” lands both edits.
256- let fresh = load(&db).await.unwrap();
257- let saved = save_if_unchanged(
258- &db,
259- Settings::try_new(SettingsParams {
260- grade_bands: bands(&[(0, "F"), (50, "P")]),
261- ..fresh.params()
262- })
263- .unwrap(),
264- &fresh,
265- )
266- .await
267- .unwrap()
268- .expect("a merge over the current row applies");
269- assert_eq!(names(&saved), ["lab"]);
270- assert_eq!(saved.get_grade_bands().len(), 2);
271- }
272-
273- #[tokio::test]
274- async fn save_if_unchanged_seeds_the_first_row() {
275- let db = crate::database::init_mem().await.unwrap();
276- // No row yet: `load` reports the defaults, and a save conditioned on
277- // that snapshot must apply (seeding the singleton on the way).
278- let current = load(&db).await.unwrap();
279- let saved = save_if_unchanged(
280- &db,
281- Settings::try_new(SettingsParams {
282- exam_kinds: kinds(&["lab"]),
283- ..current.params()
284- })
285- .unwrap(),
286- &current,
287- )
288- .await
289- .unwrap()
290- .expect("the first save applies");
291- assert_eq!(names(&saved), ["lab"]);
292- let mut result = db.query("SELECT * FROM settings").await.unwrap();
293- let rows: Vec<Settings> = result.take(0).unwrap();
294- assert_eq!(rows.len(), 1, "still one singleton row");
295- }
296 }186 }
src/db/user.rsmodified+564 -322
@@ -1,22 +1,17 @@
1-//! The `user` table: the row mint (with the duplicate-username mapping), row1+//! The `app_user` table: the row mint (with the duplicate-username mapping),
2-//! reads and listings, the admin-floor count, the role cascade transaction,2+//! row reads and listings, the role cascade transaction (admin floor and all
3-//! and the field-scoped writers. The workflows that sequence these under3+//! sweeps included), and the field-scoped writers. The workflow that drives
4-//! [`crate::service::user::ADMIN_FLOOR_LOCK`] live in4+//! the cascade lives in [`crate::service::user`].
5-//! [`crate::service::user`].5+//!
6-6+//! The compile-time macros map columns by name and check each decoded type
7-use surrealdb::types::{RecordId, SurrealValue};7+//! against the prepare schema, so the seventeen user columns are spelled
8-8+//! out β€” newtype overrides included β€” in every static statement below. The
9-use crate::constant::{9+//! repetitions are the check.
10- APPOINTMENT_SLOT_TABLE, APPOINTMENT_TABLE, BOARD_TABLE, CLASS_GROUP_TABLE,10+
11- CLASS_MEMBER_COUNT_FIELD, CLASS_MEMBER_TABLE, COURSE_TABLE, ENROLLMENT_COUNT_FIELD,11+use crate::database::{Database, tx_with_retry};
12- ENROLLMENT_TABLE, PARENT_LINK_TABLE, REGISTRATION_COUNT_FIELD, REGISTRATION_FROZEN_GUARD,
13- REGISTRATION_TABLE,
14-};
15-use crate::database::{Database, transaction_with_retry, write_with_retry};
16 use crate::db::field_update::FieldUpdate;12 use crate::db::field_update::FieldUpdate;
17-use crate::db::page::PagedList;13+use crate::db::page::{PagedList, Param};
18-use crate::domain::appointment::AppointmentStatus;14+use crate::domain::board::{Board, BoardId, BoardTitle};
19-use crate::domain::board::Board;
20 use crate::domain::note_file::FileContentType;15 use crate::domain::note_file::FileContentType;
21 use crate::domain::preferences::{Language, PaletteColor, Theme};16 use crate::domain::preferences::{Language, PaletteColor, Theme};
22 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};17 use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Phone};
@@ -43,58 +38,82 @@ pub async fn create(
43 /// or a cancelled future), and the row left behind is an ordinary student38 /// or a cancelled future), and the row left behind is an ordinary student
44 /// account that [`crate::service::user::ensure_admin`] must then refuse to39 /// account that [`crate::service::user::ensure_admin`] must then refuse to
45 /// touch β€” a deployment with no admin and no way for a later boot to repair it.40 /// touch β€” a deployment with no admin and no way for a later boot to repair it.
41+///
42+/// The unique index on `username` is the whole availability check. The old
43+/// pre-check-and-recheck dance existed because the old store could not name
44+/// the constraint a racing insert had violated; here the violated
45+/// constraint's name answers directly (`app_user_username`), and the loser
46+/// of a race gets the same 409 the sequential duplicate always got.
46 pub async fn create_with_role(47 pub async fn create_with_role(
47 db: &Database,48 db: &Database,
48 username: Username,49 username: Username,
49 password_hash: PasswordHash,50 password_hash: PasswordHash,
50 role: Role,51 role: Role,
51 ) -> Result<User, AppError> {52 ) -> Result<User, AppError> {
52- if find_by_username(db, username.as_str()).await?.is_some() {53+ let id = UserId::generate();
53- return Err(AppError::Conflict("username already taken"));54+ match sqlx::query_as!(
54- }55+ User,
55- let user = User {56+ r#"INSERT INTO app_user (id, username, password_hash, role)
56- id: UserId::generate(),57+ VALUES ($1, $2, $3, $4)
57- username,58+ RETURNING id AS "id: UserId",
58- password_hash,59+ username AS "username: Username",
60+ password_hash AS "password_hash: PasswordHash",
61+ role AS "role: Role",
62+ name AS "name: PersonName",
63+ surname AS "surname: PersonName",
64+ email AS "email: Email",
65+ phone AS "phone: Phone",
66+ birth_date AS "birth_date: BirthDate",
67+ theme AS "theme: Theme",
68+ language AS "language: Language",
69+ palette_color AS "palette_color: PaletteColor",
70+ display_name AS "display_name: DisplayName",
71+ bio AS "bio: Bio",
72+ avatar_file,
73+ avatar_content_type AS "avatar_content_type: FileContentType",
74+ avatar_size"#,
75+ id.uuid(),
76+ username.as_str(),
77+ password_hash.as_str(),
59 role,78 role,
60- name: None,79+ )
61- surname: None,80+ .fetch_one(db)
62- email: None,81+ .await
63- phone: None,82+ {
64- birth_date: None,83+ Ok(user) => Ok(user),
65- theme: None,84+ Err(err) if crate::database::unique_violation(&err) == Some("app_user_username") => {
66- language: None,85+ Err(AppError::Conflict("username already taken"))
67- palette_color: None,
68- display_name: None,
69- bio: None,
70- avatar_file: None,
71- avatar_content_type: None,
72- avatar_size: None,
73- };
74- let created: Result<Option<User>, surrealdb::Error> =
75- db.create(user.id.record()).content(user.clone()).await;
76- match created {
77- Ok(Some(created)) => Ok(created),
78- Ok(None) => Err(AppError::Internal("failed to create user".into())),
79- // The availability pre-check above is not atomic with the insert:
80- // two concurrent registrations can both pass it, and the loser then
81- // trips the unique username index. That loss is the same condition
82- // as the sequential duplicate, so report the same 409 β€” not a 500.
83- Err(err) => {
84- if find_by_username(db, user.username.as_str())
85- .await?
86- .is_some()
87- {
88- Err(AppError::Conflict("username already taken"))
89- } else {
90- Err(err.into())
91- }
92 }86 }
87+ Err(err) => Err(err.into()),
93 }88 }
94 }89 }
95 90
96 pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {91 pub async fn read(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
97- Ok(db.select(id.record()).await?)92+ let user = sqlx::query_as!(
93+ User,
94+ r#"SELECT id AS "id: UserId",
95+ username AS "username: Username",
96+ password_hash AS "password_hash: PasswordHash",
97+ role AS "role: Role",
98+ name AS "name: PersonName",
99+ surname AS "surname: PersonName",
100+ email AS "email: Email",
101+ phone AS "phone: Phone",
102+ birth_date AS "birth_date: BirthDate",
103+ theme AS "theme: Theme",
104+ language AS "language: Language",
105+ palette_color AS "palette_color: PaletteColor",
106+ display_name AS "display_name: DisplayName",
107+ bio AS "bio: Bio",
108+ avatar_file,
109+ avatar_content_type AS "avatar_content_type: FileContentType",
110+ avatar_size
111+ FROM app_user WHERE id = $1"#,
112+ id.uuid()
113+ )
114+ .fetch_optional(db)
115+ .await?;
116+ Ok(user)
98 }117 }
99 118
100 pub async fn list_all(119 pub async fn list_all(
@@ -102,7 +121,7 @@ pub async fn list_all(
102 limit: Option<i64>,121 limit: Option<i64>,
103 offset: i64,122 offset: i64,
104 ) -> Result<(Vec<User>, i64), AppError> {123 ) -> Result<(Vec<User>, i64), AppError> {
105- PagedList::new("user", "ORDER BY id DESC")124+ PagedList::new("app_user", "ORDER BY id DESC")
106 .run(limit, offset, db)125 .run(limit, offset, db)
107 .await126 .await
108 }127 }
@@ -113,50 +132,63 @@ pub async fn list_by_ids(db: &Database, ids: &[UserId]) -> Result<Vec<User>, App
113 if ids.is_empty() {132 if ids.is_empty() {
114 return Ok(Vec::new());133 return Ok(Vec::new());
115 }134 }
116- let records: Vec<RecordId> = ids.iter().map(UserId::record).collect();135+ let ids: Vec<uuid::Uuid> = ids.iter().map(UserId::uuid).collect();
117- let mut result = db136+ let users = sqlx::query_as!(
118- .query("SELECT * FROM user WHERE id IN $ids")137+ User,
119- .bind(("ids", records))138+ r#"SELECT id AS "id: UserId",
120- .await?139+ username AS "username: Username",
121- .check()?;140+ password_hash AS "password_hash: PasswordHash",
122- Ok(result.take::<Vec<User>>(0)?)141+ role AS "role: Role",
142+ name AS "name: PersonName",
143+ surname AS "surname: PersonName",
144+ email AS "email: Email",
145+ phone AS "phone: Phone",
146+ birth_date AS "birth_date: BirthDate",
147+ theme AS "theme: Theme",
148+ language AS "language: Language",
149+ palette_color AS "palette_color: PaletteColor",
150+ display_name AS "display_name: DisplayName",
151+ bio AS "bio: Bio",
152+ avatar_file,
153+ avatar_content_type AS "avatar_content_type: FileContentType",
154+ avatar_size
155+ FROM app_user WHERE id = ANY($1)"#,
156+ ids
157+ )
158+ .fetch_all(db)
159+ .await?;
160+ Ok(users)
123 }161 }
124 162
125 /// Every user holding exactly `role` β€” e.g. the roster of a role-targeted163 /// Every user holding exactly `role` β€” e.g. the roster of a role-targeted
126 /// event. Exact match, not `at_least`: "all teachers" means teachers, not164 /// event. Exact match, not `at_least`: "all teachers" means teachers, not
127 /// managers and admins too.165 /// managers and admins too.
128 pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppError> {166 pub async fn list_by_role(db: &Database, role: Role) -> Result<Vec<User>, AppError> {
129- let mut result = db167+ let users = sqlx::query_as!(
130- .query("SELECT * FROM user WHERE role = $role ORDER BY id DESC")168+ User,
131- .bind(("role", role))169+ r#"SELECT id AS "id: UserId",
132- .await?170+ username AS "username: Username",
133- .check()?;171+ password_hash AS "password_hash: PasswordHash",
134- Ok(result.take::<Vec<User>>(0)?)172+ role AS "role: Role",
135-}173+ name AS "name: PersonName",
136-174+ surname AS "surname: PersonName",
137-/// Would lowering `target` out of `admin` leave the school with none? Both175+ email AS "email: Email",
138-/// halves are asked of the **live** rows in one round trip: is that row an176+ phone AS "phone: Phone",
139-/// admin right now, and does any other admin exist. It asks for one id per177+ birth_date AS "birth_date: BirthDate",
140-/// half rather than a `count()` β€” a count over an indexed field compared178+ theme AS "theme: Theme",
141-/// against a plan-time value answers `{count: N}` on the real server, and179+ language AS "language: Language",
142-/// neither half needs a number.180+ palette_color AS "palette_color: PaletteColor",
143-///181+ display_name AS "display_name: DisplayName",
144-/// Caller must hold182+ bio AS "bio: Bio",
145-/// [`crate::service::user::ADMIN_FLOOR_LOCK`] for the answer to still be183+ avatar_file,
146-/// true by the time it is acted on.184+ avatar_content_type AS "avatar_content_type: FileContentType",
147-pub async fn would_orphan_admins(db: &Database, target: &UserId) -> Result<bool, AppError> {185+ avatar_size
148- let mut result = db186+ FROM app_user WHERE role = $1 ORDER BY id DESC"#,
149- .query(187+ role
150- "SELECT VALUE id FROM user WHERE id = $usr AND role = $role;\n\188+ )
151- SELECT VALUE id FROM user WHERE role = $role AND id != $usr LIMIT 1",189+ .fetch_all(db)
152- )190+ .await?;
153- .bind(("role", Role::Admin))191+ Ok(users)
154- .bind(("usr", target.record()))
155- .await?
156- .check()?;
157- let is_admin = !result.take::<Vec<RecordId>>(0)?.is_empty();
158- let others = !result.take::<Vec<RecordId>>(1)?.is_empty();
159- Ok(is_admin && !others)
160 }192 }
161 193
162 /// Case- and diacritic-insensitive fragment search over username, name,194 /// Case- and diacritic-insensitive fragment search over username, name,
@@ -181,41 +213,58 @@ pub async fn search(
181 offset: i64,213 offset: i64,
182 ) -> Result<(Vec<User>, i64), AppError> {214 ) -> Result<(Vec<User>, i64), AppError> {
183 let needle = search_fold(query.trim());215 let needle = search_fold(query.trim());
184- let text_clause = format!(216+ // Placeholders are positional, and every clause is optional, so the
185- "({} CONTAINS $q OR {} CONTAINS $q OR {} CONTAINS $q)",217+ // numbering is assigned as the clauses are added. Containment is spelled
186- search_fold_sql("username"),218+ // `position(...) > 0` rather than `LIKE` so the needle's `%` and `_`
187- search_fold_sql("name ?? ''"),219+ // stay literal characters β€” the fold does not escape, and a query for
188- search_fold_sql("surname ?? ''"),220+ // `100%` must not grow a wildcard.
189- );221+ let mut binds: Vec<Param> = Vec::new();
190- let mut clauses = Vec::new();222+ let mut clauses: Vec<String> = Vec::new();
191 if !needle.is_empty() {223 if !needle.is_empty() {
192- clauses.push(text_clause.as_str());224+ let n = binds.len() + 1;
225+ clauses.push(format!(
226+ "(position(${n} in {}) > 0 \
227+ OR position(${n} in {}) > 0 \
228+ OR position(${n} in {}) > 0)",
229+ search_fold_sql("username"),
230+ search_fold_sql("coalesce(name, '')"),
231+ search_fold_sql("coalesce(surname, '')"),
232+ ));
233+ binds.push(Param::Text(needle));
193 }234 }
194- if role.is_some() {235+ if let Some(role) = role {
195- clauses.push("role = $role");236+ let n = binds.len() + 1;
237+ clauses.push(format!("role = ${n}"));
238+ binds.push(Param::Text(role.as_str().to_string()));
196 }239 }
197- if allowed_roles.is_some() {240+ if let Some(allowed) = allowed_roles {
198- clauses.push("role IN $allowed");241+ let n = binds.len() + 1;
242+ clauses.push(format!("role = ANY(${n})"));
243+ binds.push(Param::Texts(
244+ allowed
245+ .iter()
246+ .map(|role| role.as_str().to_string())
247+ .collect(),
248+ ));
199 }249 }
200 let where_clause = if clauses.is_empty() {250 let where_clause = if clauses.is_empty() {
201- "true".to_string()251+ "TRUE".to_string()
202 } else {252 } else {
203 clauses.join(" AND ")253 clauses.join(" AND ")
204 };254 };
205- let mut list =255+ let mut list = PagedList::new(
206- PagedList::new(format!("user WHERE {where_clause}"), "ORDER BY username").bind("q", needle);256+ format!("app_user WHERE {where_clause}"),
207- if let Some(role) = role {257+ "ORDER BY username",
208- list = list.bind("role", role);258+ );
209- }259+ for bind in binds {
210- if let Some(allowed) = allowed_roles {260+ list = list.bind(bind);
211- list = list.bind("allowed", allowed.to_vec());
212 }261 }
213 list.run(limit, offset, db).await262 list.run(limit, offset, db).await
214 }263 }
215 264
216 /// The role write and every sweep it owes, in one transaction β€” the265 /// The role write and every sweep it owes, in one transaction β€” the
217-/// statement list behind [`crate::service::user::set_role`]. See there for266+/// statement list behind [`crate::service::user::set_role`]; see there for
218-/// the floor that guards it and the arm-by-arm reasoning; what follows is267+/// the floor that guards it and the arm-by-arm reasoning. What follows is
219 /// the store side.268 /// the store side.
220 ///269 ///
221 /// Writes *only* the `role` field of the user row (never the whole row):270 /// Writes *only* the `role` field of the user row (never the whole row):
@@ -224,8 +273,7 @@ pub async fn search(
224 /// whole-row write would carry the snapshot's copy of the *other* group back273 /// whole-row write would carry the snapshot's copy of the *other* group back
225 /// over a concurrent edit β€” an in-flight profile save silently reverting an274 /// over a concurrent edit β€” an in-flight profile save silently reverting an
226 /// admin's demotion, or this write erasing a profile edit that raced it.275 /// admin's demotion, or this write erasing a profile edit that raced it.
227-/// [`crate::db::user::set_profile`] and276+/// [`set_profile`] and [`set_preferences`] are scoped for the same reason.
228-/// [`crate::db::user::set_preferences`] are scoped for the same reason.
229 ///277 ///
230 /// What is swept, and why the conditions differ:278 /// What is swept, and why the conditions differ:
231 ///279 ///
@@ -244,12 +292,15 @@ pub async fn search(
244 /// else could remove: staff free their own by hand (`unregister` allows292 /// else could remove: staff free their own by hand (`unregister` allows
245 /// the self case) but a parent can reach no such door, so a promotion293 /// the self case) but a parent can reach no such door, so a promotion
246 /// strands nothing and only this demotion does. A list that has already294 /// strands nothing and only this demotion does. A list that has already
247-/// **frozen** ([`REGISTRATION_FROZEN_GUARD`]) is left exactly as it295+/// **frozen** (an audience-`registration` event whose start-or-end time
248-/// stands β€” past the freeze it is historical record, re-registering296+/// has passed β€” the same predicate
249-/// answers 409, and rewriting it here would be irrecoverable. A signup297+/// [`crate::domain::registration`]'s Rust check enforces) is left exactly
250-/// whose event record is *gone* has no seat to hand back and no list that298+/// as it stands β€” past the freeze it is historical record,
251-/// can freeze, so it is deleted rather than skipped: skipped, it is299+/// re-registering answers 409, and rewriting it here would be
252-/// stranded forever (`unregister` 404s on the missing event).300+/// irrecoverable. A signup whose event record is *gone* has no seat to
301+/// hand back and no list that can freeze, so it is deleted rather than
302+/// skipped: skipped, it is stranded forever (`unregister` 404s on the
303+/// missing event).
253 /// * **Below teacher** gives up course staffing and homeroom-teacher304 /// * **Below teacher** gives up course staffing and homeroom-teacher
254 /// columns β€” only teacher+ may hold either β€” and the published305 /// columns β€” only teacher+ may hold either β€” and the published
255 /// appointment calendar, whose live bookings are cancelled in the same306 /// appointment calendar, whose live bookings are cancelled in the same
@@ -260,8 +311,9 @@ pub async fn search(
260 /// cancelled once its window opens β€” leaving the slot's `occupied` seat311 /// cancelled once its window opens β€” leaving the slot's `occupied` seat
261 /// pinned at one and the slot itself undeletable forever. The requester312 /// pinned at one and the slot itself undeletable forever. The requester
262 /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the313 /// keeps the row, `cancelled`, with the teacher on `cancelled_by` and the
263-/// reason on `cancel_reason`; the slot it pointed at is gone, so the314+/// reason on `cancel_reason`; the slot it pointed at is gone (the
264-/// booking renders without a window315+/// `ON DELETE SET NULL` link carries the delete), so the booking renders
316+/// without a window
265 /// ([`crate::domain::appointment::Appointment`]'s reader already treats a317 /// ([`crate::domain::appointment::Appointment`]'s reader already treats a
266 /// vanished slot that way). There is no notification anywhere in318 /// vanished slot that way). There is no notification anywhere in
267 /// this crate, so a settled row the person can read is the strongest319 /// this crate, so a settled row the person can read is the strongest
@@ -275,146 +327,234 @@ pub async fn search(
275 /// fan-out cannot sit inside a database transaction, and a room told before327 /// fan-out cannot sit inside a database transaction, and a room told before
276 /// the commit would re-read the pre-commit state.328 /// the commit would re-read the pre-commit state.
277 ///329 ///
278-/// Admissible for [`transaction_with_retry`] by construction: `SELECT`,330+/// **The admin floor is the role write's own `WHERE`.** The old guard was a
279-/// `UPDATE` and `DELETE` only, so no statement can answer "already exists"331+/// count read under a process-wide lock held across the whole cascade,
280-/// and every lost round is a plain re-send.332+/// because the old store could not serialize a cross-record count against a
333+/// concurrent update (write-skew). Here the count rides the very row write
334+/// it guards β€” a demotion that would leave no other admin writes zero rows
335+/// β€” so two racing demotions contend on row locks and exactly one lands.
336+/// Zero rows therefore means the floor refused; the missing-row reading of
337+/// zero rows is unreachable (no route deletes a user row, and the caller's
338+/// 404 pre-read answers that case first anyway).
281 pub async fn set_role_cascade(339 pub async fn set_role_cascade(
282 db: &Database,340 db: &Database,
283 target: &UserId,341 target: &UserId,
284 role: Role,342 role: Role,
285 ) -> Result<(User, Vec<Board>), AppError> {343 ) -> Result<(User, Vec<Board>), AppError> {
286- // Built as a statement list rather than one string so the result slot344+ // One wall-clock read for the whole cascade, bound by every stamping
287- // of the board write is *counted*, not hand-tallied against arms that345+ // statement β€” the old batch's single `$now`.
288- // may or may not be in the batch. Slot 0 is `BEGIN`, as everywhere.346+ let now = Timestamp::now().as_millis();
289- let mut batch = vec![347+ tx_with_retry(db, true, async |tx| {
290- "BEGIN TRANSACTION".to_string(),348+ // The role write, floor guard included. `$2 <> 'admin'` arms the
291- "UPDATE $usr SET role = $role RETURN AFTER".to_string(),349+ // guard only for a demotion: a promotion or a same-role rewrite can
292- ];350+ // never orphan the admins.
293- if role != Role::Student {351+ let updated = sqlx::query_as!(
294- batch.push(format!(352+ User,
295- "LET $links = (DELETE {CLASS_MEMBER_TABLE} WHERE user = $usr RETURN BEFORE)"353+ r#"UPDATE app_user SET role = $2
296- ));354+ WHERE id = $1
297- batch.push(format!(355+ AND NOT (role = 'admin'
298- "FOR $link IN ($links ?? []) {{ UPDATE $link.class SET \356+ AND $2 <> 'admin'
299- {CLASS_MEMBER_COUNT_FIELD} = \357+ AND (SELECT count(*) FROM app_user
300- math::max([({CLASS_MEMBER_COUNT_FIELD} ?? 0) - 1, 0]); }}"358+ WHERE role = 'admin' AND id <> $1) = 0)
301- ));359+ RETURNING id AS "id: UserId",
302- batch.push(format!(360+ username AS "username: Username",
303- "LET $rows = (DELETE {ENROLLMENT_TABLE} WHERE user = $usr RETURN BEFORE)"361+ password_hash AS "password_hash: PasswordHash",
304- ));362+ role AS "role: Role",
305- batch.push(format!(363+ name AS "name: PersonName",
306- "FOR $row IN ($rows ?? []) {{ UPDATE $row.course SET \364+ surname AS "surname: PersonName",
307- {ENROLLMENT_COUNT_FIELD} = \365+ email AS "email: Email",
308- math::max([({ENROLLMENT_COUNT_FIELD} ?? 0) - 1, 0]); }}"366+ phone AS "phone: Phone",
309- ));367+ birth_date AS "birth_date: BirthDate",
310- batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE student = $usr"));368+ theme AS "theme: Theme",
311- }369+ language AS "language: Language",
312- let mut board_slot = None;370+ palette_color AS "palette_color: PaletteColor",
313- if role == Role::Parent {371+ display_name AS "display_name: DisplayName",
314- batch.push(format!(372+ bio AS "bio: Bio",
315- "LET $signups = (SELECT * FROM {REGISTRATION_TABLE} WHERE user = $usr)"373+ avatar_file,
316- ));374+ avatar_content_type AS "avatar_content_type: FileContentType",
317- // Row and seat move together per signup, the way `unregister` does:375+ avatar_size"#,
318- // the seats are independent facts on unrelated events. A missing376+ target.uuid(),
319- // event matches nothing in the guard *and* nothing in the counter377+ role,
320- // write, which is precisely the orphan rule.378+ )
321- batch.push(format!(379+ .fetch_optional(&mut *tx)
322- "FOR $signup IN ($signups ?? []) {{ \380+ .await?;
323- IF array::len((SELECT VALUE id FROM $signup.event \381+ let Some(updated) = updated else {
324- WHERE {REGISTRATION_FROZEN_GUARD})) = 0 {{ \382+ return Err(AppError::Conflict(
325- LET $freed = (DELETE $signup.id RETURN BEFORE); \383+ "the school must keep at least one admin β€” promote another account first",
326- UPDATE $signup.event SET {REGISTRATION_COUNT_FIELD} = \384+ ));
327- math::max([({REGISTRATION_COUNT_FIELD} ?? 0) - array::len($freed), 0]); \385+ };
328- }}; }}"386+
329- ));387+ if role != Role::Student {
330- // A room whose *creator* is demoted can never be ended by anyone:388+ // Class memberships go, and each class they were on gets its
331- // the whiteboard is closed to parents outright, so the creator is389+ // seat back. One row per (class, user), so one decrement each.
332- // 404'd off their own board, `clear`/`lock`/`close`/`delete` are390+ sqlx::query!(
333- // creator-only for everyone else, and `crate::db::board::list_for_user` is the391+ r#"WITH gone AS (
334- // crate's only enumeration β€” no manager or admin can so much as find392+ DELETE FROM class_member WHERE app_user = $1 RETURNING class
335- // the id. Its participants meanwhile keep drawing (the room re-derives393+ )
336- // membership per frame and they still pass), into a board only the394+ UPDATE class_group
337- // 50 000-stroke lifetime cap could ever retire. So the demotion395+ SET class_member_count = GREATEST(class_member_count - 1, 0)
338- // retires it, with the same compare-and-set [`crate::db::board::close`] uses: an396+ WHERE id IN (SELECT gone.class FROM gone)"#,
339- // already-closed board keeps its first stamp. Closed and not deleted397+ target.uuid(),
340- // because the marks are the participants' work too β€” they keep reading398+ )
341- // the board and its whole history, and the creator's `board_count`399+ .execute(&mut *tx)
342- // seat stays taken, which is correct while the row it counts exists.400+ .await?;
343- // Stamped *before* the roster strip so the strip's `RETURN AFTER`401+ // Every enrollment row β€” hand-placed included β€” and each
344- // carries the closed row the caller fans out.402+ // course's seat with it.
345- batch.push(format!(403+ sqlx::query!(
346- "UPDATE {BOARD_TABLE} SET closed_at = $now WHERE creator = $usr AND closed_at = NONE"404+ r#"WITH gone AS (
347- ));405+ DELETE FROM enrollment WHERE app_user = $1 RETURNING course
348- board_slot = Some(batch.len());406+ )
349- batch.push(format!(407+ UPDATE course
350- "UPDATE {BOARD_TABLE} SET participants -= $usr \408+ SET enrollment_count = GREATEST(enrollment_count - 1, 0)
351- WHERE $usr IN participants OR creator = $usr RETURN AFTER"409+ WHERE id IN (SELECT gone.course FROM gone)"#,
352- ));410+ target.uuid(),
353- }411+ )
354- if role != Role::Parent {412+ .execute(&mut *tx)
355- batch.push(format!("DELETE {PARENT_LINK_TABLE} WHERE parent = $usr"));413+ .await?;
356- }414+ sqlx::query!("DELETE FROM parent_link WHERE student = $1", target.uuid())
357- if !role.at_least(Role::Teacher) {415+ .execute(&mut *tx)
358- batch.push(format!(416+ .await?;
359- "UPDATE {COURSE_TABLE} SET teachers -= $usr WHERE $usr IN teachers"417+ }
360- ));418+
361- batch.push(format!(419+ if role == Role::Parent {
362- "UPDATE {CLASS_GROUP_TABLE} SET teacher = NONE WHERE teacher = $usr"420+ // Signups whose event is gone: no seat to hand back, no list
363- ));421+ // that could freeze β€” delete the stray row outright.
364- // The published calendar goes too, and the bookings on it are422+ sqlx::query!(
365- // settled first: a slot only its own teacher can list and only a423+ r#"DELETE FROM registration r
366- // teacher+ can delete is reachable by nobody once that teacher is424+ WHERE r.app_user = $1
367- // demoted, and a live booking on one is worse β€” nobody can approve,425+ AND NOT EXISTS (SELECT 1 FROM event e WHERE e.id = r.event)"#,
368- // reject or (past its start) cancel it, so it pins the slot's426+ target.uuid(),
369- // `occupied` seat forever. Cancelled rather than deleted so the427+ )
370- // person who asked is left with a settled booking they can still428+ .execute(&mut *tx)
371- // read, carrying who dropped it and why; the slot row (and with it429+ .await?;
372- // the seat) goes, which is what makes this convergent.430+ // Row and seat move together per signup, the way `unregister`
373- batch.push(format!(431+ // does: the seats are independent facts on unrelated events. A
374- "LET $slots = (SELECT VALUE id FROM {APPOINTMENT_SLOT_TABLE} WHERE teacher = $usr)"432+ // frozen list keeps its rows exactly as they stand; every other
375- ));433+ // list β€” including a registration event with no dates at all,
376- batch.push(format!(434+ // which never freezes β€” releases the seat.
377- "UPDATE {APPOINTMENT_TABLE} SET status = '{cancelled}', cancelled_by = $usr, \435+ sqlx::query!(
378- cancel_reason = 'the teacher no longer holds a teaching role' \436+ r#"WITH gone AS (
379- WHERE slot IN $slots AND status IN ['{pending}', '{approved}']",437+ DELETE FROM registration r
380- cancelled = AppointmentStatus::Cancelled.as_str(),438+ USING event e
381- pending = AppointmentStatus::Pending.as_str(),439+ WHERE r.event = e.id
382- approved = AppointmentStatus::Approved.as_str(),440+ AND r.app_user = $1
383- ));441+ AND NOT (e.audience_kind = 'registration'
384- // Deleting the slots is also what makes a *concurrent* booking safe:442+ AND COALESCE(e.starts_at, e.ends_at) IS NOT NULL
385- // `Appointment::book` claims the slot row this deletes, so the two443+ AND COALESCE(e.starts_at, e.ends_at) <= $2)
386- // collide in the store and the loser re-sends. A slot *published*444+ RETURNING r.event AS event_id
387- // concurrently shares no key with any of this, which is why445+ )
388- // `AppointmentSlot::insert_claimed` claims the user row instead.446+ UPDATE event
389- batch.push(format!(447+ SET registration_count = GREATEST(registration_count - 1, 0)
390- "DELETE {APPOINTMENT_SLOT_TABLE} WHERE id IN $slots"448+ WHERE id IN (SELECT gone.event_id FROM gone)"#,
391- ));449+ target.uuid(),
392- }450+ now,
393- let sql = format!("{};\nCOMMIT TRANSACTION;", batch.join(";\n"));451+ )
394- let (mut result, mut errors) = transaction_with_retry(452+ .execute(&mut *tx)
395- db,453+ .await?;
396- &sql,454+ // A room whose *creator* is demoted can never be ended by anyone:
397- &[455+ // the whiteboard is closed to parents outright, so the creator is
398- ("usr".into(), target.record().into_value()),456+ // 404'd off their own board, `clear`/`lock`/`close`/`delete` are
399- ("role".into(), role.into_value()),457+ // creator-only for everyone else, and
400- ("now".into(), Timestamp::now().as_millis().into_value()),458+ // `crate::db::board::list_for_user` is the crate's only
401- ],459+ // enumeration β€” no manager or admin can so much as find the id.
402- &[],460+ // Its participants meanwhile keep drawing (the room re-derives
403- )461+ // membership per frame and they still pass), into a board only
404- .await?;462+ // the 50 000-stroke lifetime cap could ever retire. So the
405- if let Some(error) = errors.drain().map(|(_, error)| error).next() {463+ // demotion retires it, with the same compare-and-set
406- return Err(error.into());464+ // [`crate::db::board::close`] uses: an already-closed board
407- }465+ // keeps its first stamp. Closed and not deleted because the
408- let updated = result466+ // marks are the participants' work too β€” they keep reading the
409- .take::<Vec<User>>(1)?467+ // board and its whole history, and the creator's `board_count`
410- .into_iter()468+ // seat stays taken, which is correct while the row it counts
411- .next()469+ // exists. Stamped *before* the roster strip so the strip's
412- .ok_or(AppError::NotFound)?;470+ // `RETURNING` carries the closed row the caller fans out.
413- let boards = match board_slot {471+ sqlx::query!(
414- Some(slot) => result.take::<Vec<Board>>(slot)?,472+ "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL",
415- None => Vec::new(),473+ target.uuid(),
416- };474+ now,
417- Ok((updated, boards))475+ )
476+ .execute(&mut *tx)
477+ .await?;
478+ let boards = sqlx::query_as!(
479+ Board,
480+ r#"UPDATE board
481+ SET participants = array_remove(participants, $1)
482+ WHERE $1 = ANY(participants) OR creator = $1
483+ RETURNING id AS "id: BoardId",
484+ creator AS "creator: UserId",
485+ title AS "title: BoardTitle",
486+ participants AS "participants: Vec<UserId>",
487+ locked,
488+ locked_by AS "locked_by: UserId",
489+ locked_at AS "locked_at: Timestamp",
490+ epoch,
491+ closed_at AS "closed_at: Timestamp",
492+ created_at AS "created_at: Timestamp""#,
493+ target.uuid(),
494+ )
495+ .fetch_all(&mut *tx)
496+ .await?;
497+ return Ok((updated, boards));
498+ }
499+
500+ if role != Role::Parent {
501+ sqlx::query!("DELETE FROM parent_link WHERE parent = $1", target.uuid())
502+ .execute(&mut *tx)
503+ .await?;
504+ }
505+
506+ if !role.at_least(Role::Teacher) {
507+ // Course staffing goes β€” only teacher+ may hold a seat on the
508+ // list.
509+ sqlx::query!(
510+ "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)",
511+ target.uuid(),
512+ )
513+ .execute(&mut *tx)
514+ .await?;
515+ sqlx::query!(
516+ "UPDATE class_group SET teacher = NULL WHERE teacher = $1",
517+ target.uuid(),
518+ )
519+ .execute(&mut *tx)
520+ .await?;
521+ // The published calendar goes too, and the bookings on it are
522+ // settled first: a slot only its own teacher can list and only a
523+ // teacher+ can delete is reachable by nobody once that teacher is
524+ // demoted, and a live booking on one is worse β€” nobody can
525+ // approve, reject or (past its start) cancel it, so it pins the
526+ // slot's `occupied` seat forever. Cancelled rather than deleted
527+ // so the person who asked is left with a settled booking they can
528+ // still read, carrying who dropped it and why; the slot row (and
529+ // with it the seat) goes, which is what makes this convergent.
530+ sqlx::query!(
531+ r#"UPDATE appointment
532+ SET status = 'cancelled', cancelled_by = $1, cancel_reason = $2
533+ WHERE slot IN (SELECT id FROM appointment_slot WHERE teacher = $1)
534+ AND status IN ('pending', 'approved')"#,
535+ target.uuid(),
536+ "the teacher no longer holds a teaching role",
537+ )
538+ .execute(&mut *tx)
539+ .await?;
540+ // Deleting the slots is also what makes a *concurrent* booking
541+ // safe: `Appointment::book` claims the slot row this deletes, so
542+ // the two collide in the store. A slot *published* concurrently
543+ // shares no key with any of this, which is why the publish path
544+ // claims the user row instead. The settled booking rows survive
545+ // the delete with `slot = NULL` (`ON DELETE SET NULL`) β€” still
546+ // readable, windowless.
547+ sqlx::query!(
548+ "DELETE FROM appointment_slot WHERE teacher = $1",
549+ target.uuid(),
550+ )
551+ .execute(&mut *tx)
552+ .await?;
553+ }
554+
555+ Ok((updated, Vec::new()))
556+ })
557+ .await
418 }558 }
419 559
420 /// Write the personal-info and public-profile fields the request actually560 /// Write the personal-info and public-profile fields the request actually
@@ -445,31 +585,36 @@ pub async fn set_profile(
445 display_name: Option<Option<DisplayName>>,585 display_name: Option<Option<DisplayName>>,
446 bio: Option<Option<Bio>>,586 bio: Option<Option<Bio>>,
447 ) -> Result<User, AppError> {587 ) -> Result<User, AppError> {
448- FieldUpdate::new(id.record())588+ // `Some(None)` must bind an explicit NULL and `Some(Some(v))` a value:
449- .set("name", name)589+ // `Param::OptText` carries both shapes of one nullable TEXT column.
450- .set("surname", surname)590+ fn text(value: Option<Option<&str>>) -> Option<Param> {
451- .set("email", email)591+ value.map(|inner| Param::OptText(inner.map(str::to_string)))
452- .set("phone", phone)592+ }
453- .set("birth_date", birth_date)593+ FieldUpdate::new("app_user", id.uuid())
454- .set("display_name", display_name)594+ .set("name", text(name.map(|n| n.as_str())))
455- .set("bio", bio)595+ .set("surname", text(surname.map(|n| n.as_str())))
456- .run::<User>(db)596+ .set("email", text(email.map(|n| n.as_str())))
597+ .set("phone", text(phone.map(|n| n.as_str())))
598+ .set("birth_date", text(birth_date.map(|n| n.as_str())))
599+ .set("display_name", text(display_name.map(|n| n.as_str())))
600+ .set("bio", text(bio.map(|n| n.as_str())))
601+ .run(db)
457 .await602 .await
458 }603 }
459 604
460 /// Point the row at a freshly uploaded avatar blob, returning the row *as605 /// Point the row at a freshly uploaded avatar blob, returning the row *as
461 /// it was* β€” the caller deletes `before.get_avatar_file()` off disk. Losing606 /// it was* β€” the caller deletes `before.get_avatar_file()` off disk. Losing
462-/// `RETURN BEFORE` here strands the replaced blob forever: no route ever607+/// the pre-image here strands the replaced blob forever: no route ever
463 /// deletes a user, so nothing else would collect it.608 /// deletes a user, so nothing else would collect it.
464 ///609 ///
465 /// Field-scoped for the same reason as [`set_profile`]: an avatar610 /// Field-scoped for the same reason as [`set_profile`]: an avatar
466 /// upload must not carry a stale snapshot's role back over an admin's611 /// upload must not carry a stale snapshot's role back over an admin's
467 /// change. `None` means the row is gone.612 /// change. `None` means the row is gone.
468 ///613 ///
469-/// Sent through [`write_with_retry`] like every other single-statement row614+/// The row is locked across the pre-image read and the write (`FOR
470-/// write here, unguarded or not: the user row is contended (preferences,615+/// UPDATE`), so two racing uploads each collect the blob *they* actually
471-/// profile, role all write it), and a lost round wrote nothing, so616+/// replaced β€” the read and the write are one unit, not a guess that stayed
472-/// re-sending it is the recovery rather than a 500 in the caller's face.617+/// true.
473 pub async fn set_avatar(618 pub async fn set_avatar(
474 db: &Database,619 db: &Database,
475 id: &UserId,620 id: &UserId,
@@ -477,55 +622,130 @@ pub async fn set_avatar(
477 content_type: &FileContentType,622 content_type: &FileContentType,
478 size: i64,623 size: i64,
479 ) -> Result<Option<User>, AppError> {624 ) -> Result<Option<User>, AppError> {
480- let rows: Vec<User> = write_with_retry(625+ tx_with_retry(db, false, async |tx| {
481- db,626+ let before = sqlx::query_as!(
482- "UPDATE $u SET avatar_file = $file, avatar_content_type = $ct, avatar_size = $size \627+ User,
483- RETURN BEFORE",628+ r#"SELECT id AS "id: UserId",
484- &[629+ username AS "username: Username",
485- ("u".into(), id.record().into_value()),630+ password_hash AS "password_hash: PasswordHash",
486- ("file".into(), file.to_string().into_value()),631+ role AS "role: Role",
487- ("ct".into(), content_type.clone().into_value()),632+ name AS "name: PersonName",
488- ("size".into(), size.into_value()),633+ surname AS "surname: PersonName",
489- ],634+ email AS "email: Email",
490- )635+ phone AS "phone: Phone",
491- .await?;636+ birth_date AS "birth_date: BirthDate",
492- Ok(rows.into_iter().next())637+ theme AS "theme: Theme",
638+ language AS "language: Language",
639+ palette_color AS "palette_color: PaletteColor",
640+ display_name AS "display_name: DisplayName",
641+ bio AS "bio: Bio",
642+ avatar_file,
643+ avatar_content_type AS "avatar_content_type: FileContentType",
644+ avatar_size
645+ FROM app_user WHERE id = $1 FOR UPDATE"#,
646+ id.uuid()
647+ )
648+ .fetch_optional(&mut *tx)
649+ .await?;
650+ let Some(before) = before else {
651+ return Ok(None);
652+ };
653+ sqlx::query!(
654+ r#"UPDATE app_user
655+ SET avatar_file = $2, avatar_content_type = $3, avatar_size = $4
656+ WHERE id = $1"#,
657+ id.uuid(),
658+ file,
659+ content_type.as_str(),
660+ size,
661+ )
662+ .execute(&mut *tx)
663+ .await?;
664+ Ok(Some(before))
665+ })
666+ .await
493 }667 }
494 668
495 /// Drop the avatar, returning the row as it was so the caller can delete669 /// Drop the avatar, returning the row as it was so the caller can delete
496-/// the blob. Same `RETURN BEFORE` contract as [`set_avatar`].670+/// the blob. Same pre-image contract as [`set_avatar`].
497 pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {671 pub async fn clear_avatar(db: &Database, id: &UserId) -> Result<Option<User>, AppError> {
498- let rows: Vec<User> = write_with_retry(672+ tx_with_retry(db, false, async |tx| {
499- db,673+ let before = sqlx::query_as!(
500- "UPDATE $u SET avatar_file = NONE, avatar_content_type = NONE, \674+ User,
501- avatar_size = NONE RETURN BEFORE",675+ r#"SELECT id AS "id: UserId",
502- &[("u".into(), id.record().into_value())],676+ username AS "username: Username",
503- )677+ password_hash AS "password_hash: PasswordHash",
504- .await?;678+ role AS "role: Role",
505- Ok(rows.into_iter().next())679+ name AS "name: PersonName",
680+ surname AS "surname: PersonName",
681+ email AS "email: Email",
682+ phone AS "phone: Phone",
683+ birth_date AS "birth_date: BirthDate",
684+ theme AS "theme: Theme",
685+ language AS "language: Language",
686+ palette_color AS "palette_color: PaletteColor",
687+ display_name AS "display_name: DisplayName",
688+ bio AS "bio: Bio",
689+ avatar_file,
690+ avatar_content_type AS "avatar_content_type: FileContentType",
691+ avatar_size
692+ FROM app_user WHERE id = $1 FOR UPDATE"#,
693+ id.uuid()
694+ )
695+ .fetch_optional(&mut *tx)
696+ .await?;
697+ let Some(before) = before else {
698+ return Ok(None);
699+ };
700+ sqlx::query!(
701+ r#"UPDATE app_user
702+ SET avatar_file = NULL, avatar_content_type = NULL, avatar_size = NULL
703+ WHERE id = $1"#,
704+ id.uuid(),
705+ )
706+ .execute(&mut *tx)
707+ .await?;
708+ Ok(Some(before))
709+ })
710+ .await
506 }711 }
507 712
508 /// Replace a user's password hash β€” the builder's admin-password reset713 /// Replace a user's password hash β€” the builder's admin-password reset
509 /// (`POST /schools/{slug}/admin-password`). Only the credential is714 /// (`POST /schools/{slug}/admin-password`). Only the credential is
510 /// rewritten; revoking the sessions minted under the old one is the715 /// rewritten; revoking the sessions minted under the old one is the
511-/// caller's second half716+/// caller's second half ([`crate::db::session::delete_by_user`]), because a
512-/// ([`crate::db::session::delete_by_user`]), because a reset717+/// reset that leaves a stolen cookie working resets nothing.
513-/// that leaves a stolen cookie working resets nothing.
514 pub async fn set_password_hash(718 pub async fn set_password_hash(
515 db: &Database,719 db: &Database,
516 id: &UserId,720 id: &UserId,
517 password_hash: PasswordHash,721 password_hash: PasswordHash,
518 ) -> Result<Option<User>, AppError> {722 ) -> Result<Option<User>, AppError> {
519- let rows: Vec<User> = write_with_retry(723+ let user = sqlx::query_as!(
520- db,724+ User,
521- "UPDATE $u SET password_hash = $hash RETURN AFTER",725+ r#"UPDATE app_user SET password_hash = $2 WHERE id = $1
522- &[726+ RETURNING id AS "id: UserId",
523- ("u".into(), id.record().into_value()),727+ username AS "username: Username",
524- ("hash".into(), password_hash.into_value()),728+ password_hash AS "password_hash: PasswordHash",
525- ],729+ role AS "role: Role",
730+ name AS "name: PersonName",
731+ surname AS "surname: PersonName",
732+ email AS "email: Email",
733+ phone AS "phone: Phone",
734+ birth_date AS "birth_date: BirthDate",
735+ theme AS "theme: Theme",
736+ language AS "language: Language",
737+ palette_color AS "palette_color: PaletteColor",
738+ display_name AS "display_name: DisplayName",
739+ bio AS "bio: Bio",
740+ avatar_file,
741+ avatar_content_type AS "avatar_content_type: FileContentType",
742+ avatar_size"#,
743+ id.uuid(),
744+ password_hash.as_str(),
526 )745 )
746+ .fetch_optional(db)
527 .await?;747 .await?;
528- Ok(rows.into_iter().next())748+ Ok(user)
529 }749 }
530 750
531 /// Write the UI-preference fields the request actually carried. Same751 /// Write the UI-preference fields the request actually carried. Same
@@ -538,21 +758,43 @@ pub async fn set_preferences(
538 language: Option<Option<Language>>,758 language: Option<Option<Language>>,
539 palette_color: Option<Option<PaletteColor>>,759 palette_color: Option<Option<PaletteColor>>,
540 ) -> Result<User, AppError> {760 ) -> Result<User, AppError> {
541- FieldUpdate::new(id.record())761+ let theme = theme.map(|t| Param::OptText(t.map(|v| v.as_str().to_string())));
762+ let language = language.map(|l| Param::OptText(l.map(|v| v.as_str().to_string())));
763+ let palette_color = palette_color.map(|p| Param::OptText(p.map(|v| v.as_str().to_string())));
764+ FieldUpdate::new("app_user", id.uuid())
542 .set("theme", theme)765 .set("theme", theme)
543 .set("language", language)766 .set("language", language)
544 .set("palette_color", palette_color)767 .set("palette_color", palette_color)
545- .run::<User>(db)768+ .run(db)
546 .await769 .await
547 }770 }
548 771
549 pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> {772 pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<User>, AppError> {
550- let mut result = db773+ let user = sqlx::query_as!(
551- .query("SELECT * FROM user WHERE username = $username LIMIT 1")774+ User,
552- .bind(("username", username.to_string()))775+ r#"SELECT id AS "id: UserId",
553- .await?776+ username AS "username: Username",
554- .check()?;777+ password_hash AS "password_hash: PasswordHash",
555- Ok(result.take::<Vec<User>>(0)?.into_iter().next())778+ role AS "role: Role",
779+ name AS "name: PersonName",
780+ surname AS "surname: PersonName",
781+ email AS "email: Email",
782+ phone AS "phone: Phone",
783+ birth_date AS "birth_date: BirthDate",
784+ theme AS "theme: Theme",
785+ language AS "language: Language",
786+ palette_color AS "palette_color: PaletteColor",
787+ display_name AS "display_name: DisplayName",
788+ bio AS "bio: Bio",
789+ avatar_file,
790+ avatar_content_type AS "avatar_content_type: FileContentType",
791+ avatar_size
792+ FROM app_user WHERE username = $1"#,
793+ username
794+ )
795+ .fetch_optional(db)
796+ .await?;
797+ Ok(user)
556 }798 }
557 799
558 #[cfg(test)]800 #[cfg(test)]
@@ -673,9 +915,9 @@ mod tests {
673 assert_eq!(after.get_avatar_size(), Some(42));915 assert_eq!(after.get_avatar_size(), Some(42));
674 }916 }
675 917
676- /// The blob cleanup is built entirely on `RETURN BEFORE`: without the old918+ /// The blob cleanup is built on the pre-image: without the old
677- /// `avatar_file` coming back, every replace strands a file on disk that no919+ /// `avatar_file` coming back, every replace strands a file on disk that
678- /// route ever collects.920+ /// no route ever collects.
679 #[tokio::test]921 #[tokio::test]
680 async fn the_avatar_writers_return_the_replaced_blob() {922 async fn the_avatar_writers_return_the_replaced_blob() {
681 let db = init_mem().await.unwrap();923 let db = init_mem().await.unwrap();
src/domain/badge.rsmodified+14 -14
@@ -99,20 +99,20 @@ impl BadgeStat {
99 /// select into (`SELECT homework_submitted, … FROM app_user WHERE id = $1`).99 /// select into (`SELECT homework_submitted, … FROM app_user WHERE id = $1`).
100 #[derive(Debug, Clone, Default, sqlx::FromRow)]100 #[derive(Debug, Clone, Default, sqlx::FromRow)]
101 pub struct BadgeStats {101 pub struct BadgeStats {
102- homework_submitted: i64,102+ pub(crate) homework_submitted: i64,
103- homework_on_time: i64,103+ pub(crate) homework_on_time: i64,
104- exam_sat: i64,104+ pub(crate) exam_sat: i64,
105- pomodoro_finished: i64,105+ pub(crate) pomodoro_finished: i64,
106- pomodoro_focus_ms: i64,106+ pub(crate) pomodoro_focus_ms: i64,
107- marks_given: i64,107+ pub(crate) marks_given: i64,
108- lessons_held: i64,108+ pub(crate) lessons_held: i64,
109- pool_approved: i64,109+ pub(crate) pool_approved: i64,
110- pool_published: i64,110+ pub(crate) pool_published: i64,
111- lessons_attended: i64,111+ pub(crate) lessons_attended: i64,
112- high_mark: i64,112+ pub(crate) high_mark: i64,
113 /// The longest study run, off `study_streak_longest`. Named for the wire,113 /// The longest study run, off `study_streak_longest`. Named for the wire,
114 /// like every field here, and never the run in progress.114 /// like every field here, and never the run in progress.
115- study_streak: i64,115+ pub(crate) study_streak: i64,
116 }116 }
117 117
118 impl BadgeStats {118 impl BadgeStats {
@@ -200,8 +200,8 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> {
200 /// columns.200 /// columns.
201 #[derive(Debug, Clone, sqlx::FromRow)]201 #[derive(Debug, Clone, sqlx::FromRow)]
202 pub struct BadgeAward {202 pub struct BadgeAward {
203- badge: String,203+ pub(crate) badge: String,
204- earned_at: Timestamp,204+ pub(crate) earned_at: Timestamp,
205 }205 }
206 206
207 impl BadgeAward {207 impl BadgeAward {
src/service/settings.rsmodified+176 -153
@@ -1,45 +1,22 @@
1-//! The settings edit workflow: one edit at a time under [`SETTINGS_LOCK`],1+//! The settings edit workflow: snapshot-merge-guard-save, with every name-list
2-//! a snapshot-merge-retire-save pair whose halves cannot interleave, and the2+//! guard and the compare-and-set riding ONE transaction, so two managers'
3-//! compare-and-set retry that keeps two managers' patches from silently3+//! patches can neither silently revert each other nor strand a half-applied
4-//! reverting each other. The singleton's queries live in4+//! removal. The singleton's queries live in [`crate::db::settings`].
5-//! [`crate::db::settings`].
6-
7-use surrealdb::types::RecordId;
8-use tokio::sync::Mutex;
9 5
10 use crate::constant::CAS_UPDATE_RETRIES;6 use crate::constant::CAS_UPDATE_RETRIES;
11-use crate::database::Database;7+use crate::database::{Database, tx_with_retry};
12-use crate::db::cap;
13-use crate::domain::exam_result::kind_ref;
14-use crate::domain::menu::slot_ref;
15 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};8 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
16 use crate::error::AppError;9 use crate::error::AppError;
17 10
18-/// One settings edit at a time, over the whole process.11+/// The abort marker the edit transaction's closure raises when the guarded
19-///12+/// save wrote zero rows β€” the stored row moved under the snapshot this
20-/// A list edit is a **pair** of writes, and the pair is the guard: every name13+/// attempt was judged against. It never reaches the wire: [`apply`] maps it
21-/// the edit drops is retired on its reference counter first (which refuses14+/// to another loop turn right here, and the transaction's rollback already
22-/// every later claim), and only then is the list itself committed with a15+/// took every retirement back with it. (Same abort-through-`Internal`
23-/// compare-and-set against the snapshot the removals were judged from. Neither16+/// pattern as `crate::db::field_update`'s markers: a refusal is a decision,
24-/// write can be made to cover the other. Both retirement and un-retirement are17+/// so it must not be retried β€” this one is *un*-decided, which is exactly
25-/// *idempotent*, so a rival that decided the same removal against the same18+/// why the loop re-runs.)
26-/// snapshot is told "already retired" and records no rollback β€” and when it is19+const STALE_SAVE: &str = "settings_save_lost_cas";
27-/// that rival's save that wins the compare-and-set, the attempt which really
28-/// flipped the bit rolls it back, leaving the name off the stored list with a
29-/// counter reading "in service": gradable again, and unremovable for good once
30-/// a mark lands. No per-name bit can close that, because `Unchanged` has
31-/// erased which attempt owns the flip.
32-///
33-/// So the pair is serialized instead. Every writer of the singleton goes
34-/// through `PATCH /settings`, and the deployment runs one process by contract
35-/// (stop-the-world upgrades), so process-wide is deployment-wide here β€” the
36-/// same argument [`crate::db::cap`]'s own lock makes for `retire_name`'s
37-/// two statements, one level up. The compare-and-set stays: it is what keeps a
38-/// crashed or rolled-back attempt from writing a list nobody merged.
39-///
40-/// **Lock order:** `SETTINGS_LOCK` β†’ `cap`'s `CLAIM_LOCK`, never the reverse β€”
41-/// the retirements are taken while this is held.
42-pub(crate) static SETTINGS_LOCK: Mutex<()> = Mutex::const_new(());
43 20
44 /// The stored policy, or the defaults when no row exists yet.21 /// The stored policy, or the defaults when no row exists yet.
45 pub async fn load(db: &Database) -> Result<Settings, AppError> {22 pub async fn load(db: &Database) -> Result<Settings, AppError> {
@@ -60,8 +37,8 @@ pub async fn save_if_unchanged(
60 /// A `PATCH /settings` body after wire mapping: only the fields the school37 /// A `PATCH /settings` body after wire mapping: only the fields the school
61 /// sent. Lists stay raw on purpose β€” validating them is the workflow's own38 /// sent. Lists stay raw on purpose β€” validating them is the workflow's own
62 /// step, in its own order, and keeping a stored meal-slot name skips the39 /// step, in its own order, and keeping a stored meal-slot name skips the
63-/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`], holding40+/// URL-charset rule (`MealSlotDef::try_kept`), which only [`apply`],
64-/// the lock and the stored list, can decide.41+/// holding the stored list, can decide.
65 pub struct SettingsPatch {42 pub struct SettingsPatch {
66 pub exam_kinds: Option<Vec<ExamKindInput>>,43 pub exam_kinds: Option<Vec<ExamKindInput>>,
67 pub attendance_statuses: Option<Vec<String>>,44 pub attendance_statuses: Option<Vec<String>>,
@@ -94,14 +71,27 @@ pub struct MealSlotInput {
94 pub serving_minute: Option<i64>,71 pub serving_minute: Option<i64>,
95 }72 }
96 73
97-/// The whole edit β€” snapshot, merge, retire, save β€” as one operation, so the74+/// The whole edit β€” snapshot, merge, guard, save β€” as one operation, so the
98 /// tests can drive it the way two managers do.75 /// tests can drive it the way two managers do.
76+///
77+/// The guards and the save share one transaction, and that is the whole
78+/// guard: a list edit is a *pair* of writes β€” every name the edit drops is
79+/// retired on its reference counter first (which refuses every later
80+/// claim), and only then is the list itself committed with a
81+/// compare-and-set against the snapshot the removals were judged from. The
82+/// old engine could not serialize that pair on its own, so a process-wide
83+/// lock held it together, and the winner-loses-rollback interaction between
84+/// two same-snapshot attempts needed a hand-rolled undo list
85+/// (`Unchanged`-erased which attempt owned a flip, so a no-op could undo a
86+/// rival). Postgres needs neither: retirement and save commit together or
87+/// not at all, a stale save rolls its retirements back by aborting, and the
88+/// row-locked retire switch serializes two attempts dropping the same name.
89+///
90+/// Retired before the save, never after: the other order leaves a window in
91+/// which a mark lands under a kind the settings no longer list. A save that
92+/// then does not land undoes them β€” by transaction abort, before the next
93+/// try, with no undo list to get wrong.
99 pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, AppError> {94 pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, AppError> {
100- // One settings edit at a time: the removals below are decided against the
101- // snapshot this loop loads and written *before* the save that justifies
102- // them, and no per-name bookkeeping can make that pair survive a rival's
103- // pair interleaving with it (see `SETTINGS_LOCK`).
104- let _guard = SETTINGS_LOCK.lock().await;
105 // Merge over a snapshot, then save only while the row still matches it β€”95 // Merge over a snapshot, then save only while the row still matches it β€”
106 // otherwise a concurrent PATCH of a *different* field would be silently96 // otherwise a concurrent PATCH of a *different* field would be silently
107 // reverted by whichever whole-row write lands second. A refused save97 // reverted by whichever whole-row write lands second. A refused save
@@ -179,88 +169,54 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, App
179 169
180 let settings = Settings::try_new(params)?;170 let settings = Settings::try_new(params)?;
181 171
182- // The removal guards. A name leaves a list by being *retired* on its172+ // Guards + save, one transaction. The removal refusals are the same
183- // reference counter β€” one conditional write on one record, which lands173+ // 409s as ever; a stale save is the `STALE_SAVE` marker, answered by
184- // only while nothing references the name and refuses every claim from174+ // another loop turn below; everything else surfaces.
185- // that instant on. That is the whole guard: the check and the removal175+ let attempted = tx_with_retry(db, false, async |tx| {
186- // used to be a cross-table count and a save held together by a176+ // A name leaves a list by being *retired* on its reference
187- // process-wide lock that was released around the round trip between177+ // counter β€” one row-locked switch, which lands only while
188- // them.178+ // nothing references the name and refuses every claim from that
189- //179+ // instant on. A refused removal aborts the transaction, taking
190- // Retired before the save, never after: the other order leaves a window180+ // any earlier retirement in this same attempt back with it.
191- // in which a mark lands under a kind the settings no longer list. A save181+ for gone in missing(&was_kinds, &now_kinds) {
192- // that then does not land undoes them (`restore`) before the next try.182+ retire_kind(&mut *tx, &gone).await?;
193- //
194- // Only a write that actually *flipped* a bit is recorded for that undo.
195- // Retirement is idempotent, so two PATCHes dropping the same kind are
196- // both told "retired" β€” and the one whose save then loses the row's CAS
197- // used to un-retire the winner's kind, leaving it off the list with its
198- // counter in service: gradable again, its count then non-zero, and so
199- // impossible to remove ever after.
200- let mut undo: Vec<Undo> = Vec::new();
201- let mut refused = None;
202- for gone in missing(&was_kinds, &now_kinds) {
203- let counter = kind_ref(&gone);
204- match cap::retire_name(&counter, db).await? {
205- cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
206- cap::Switched::Unchanged => {}
207- cap::Switched::InUse => {
208- refused = Some(AppError::ConflictOwned(format!(
209- "exams of kind '{gone}' are already graded β€” the kind cannot be removed"
210- )));
211- break;
212- }
213 }183 }
214- }184+ // Same shape for meal slots: a slot a menu was already published
215- // Same shape for meal slots: a slot a menu was already published for185+ // for cannot leave the list β€” the menu snapshotted the name as
216- // cannot leave the list β€” the menu snapshotted the name as text, and a186+ // text, and a slot no longer offered would leave that menu
217- // slot no longer offered would leave that menu unreachable from the187+ // unreachable from the school's own list.
218- // school's own list.
219- if refused.is_none() {
220 for gone in missing(&was_slots, &now_slots) {188 for gone in missing(&was_slots, &now_slots) {
221- let counter = slot_ref(&gone);189+ retire_slot(&mut *tx, &gone).await?;
222- match cap::retire_name(&counter, db).await? {
223- cap::Switched::Flipped => undo.push(Undo::Retired(counter)),
224- cap::Switched::Unchanged => {}
225- cap::Switched::InUse => {
226- refused = Some(AppError::ConflictOwned(format!(
227- "menus are already published for the '{gone}' slot β€” it cannot be removed"
228- )));
229- break;
230- }
231- }
232 }190 }
233- }191+ // A name re-entering a list is back in service: its counter still
234- if let Some(refused) = refused {192+ // carries the retirement from the edit that dropped it, and a mark
235- restore(&undo, db).await?;193+ // (or a menu) under a kind the school offers again must not be
236- return Err(refused);194+ // refused. Inside the transaction, "in service" stands only if
237- }195+ // the save below lands β€” a stale save aborts and re-retires it.
238- // A name re-entering a list is back in service: its counter still196+ for back in missing(&now_kinds, &was_kinds) {
239- // carries the retirement from the edit that dropped it, and a mark (or197+ unretire_kind(&mut *tx, &back).await?;
240- // a menu) under a kind the school offers again must not be refused.
241- // Recorded for the same undo as the retirements β€” a re-add whose save
242- // does not land leaves a name off the list that grades happily.
243- for back in missing(&now_kinds, &was_kinds) {
244- if let cap::Switched::Flipped = cap::unretire_name(&kind_ref(&back), db).await? {
245- undo.push(Undo::Unretired(kind_ref(&back)));
246 }198 }
247- }199+ for back in missing(&now_slots, &was_slots) {
248- for back in missing(&now_slots, &was_slots) {200+ unretire_slot(&mut *tx, &back).await?;
249- if let cap::Switched::Flipped = cap::unretire_name(&slot_ref(&back), db).await? {
250- undo.push(Undo::Unretired(slot_ref(&back)));
251 }201 }
252- }
253 202
254- match save_if_unchanged(db, settings, &current).await {203+ match crate::db::settings::save_if_unchanged(&mut *tx, settings.clone(), &current)
255- Ok(Some(saved)) => return Ok(saved),204+ .await?
256- // The row moved under the snapshot these guards were judged against:205+ {
257- // put the names back and re-merge, or the next attempt would decide206+ Some(saved) => Ok(saved),
258- // against a list nobody asked for.207+ // The row moved under the snapshot these guards were judged
259- Ok(None) => restore(&undo, db).await?,208+ // against: the abort puts the names back, and the caller's
260- Err(err) => {209+ // loop re-merges β€” or the next attempt would decide against a
261- restore(&undo, db).await?;210+ // list nobody asked for.
262- return Err(err);211+ None => Err(AppError::Internal(STALE_SAVE.to_string())),
263 }212 }
213+ })
214+ .await;
215+
216+ match attempted {
217+ Ok(saved) => return Ok(saved),
218+ Err(AppError::Internal(marker)) if marker == STALE_SAVE => continue,
219+ Err(err) => return Err(err),
264 }220 }
265 }221 }
266 Err(AppError::Conflict(222 Err(AppError::Conflict(
@@ -268,6 +224,106 @@ pub async fn apply(db: &Database, patch: &SettingsPatch) -> Result<Settings, App
268 ))224 ))
269 }225 }
270 226
227+/// Retire an exam kind on its reference counter, inside the caller's
228+/// transaction β€” the row-locked switch of the `cap` module's retire recipe:
229+/// the row is read `FOR UPDATE` first, so the read of `retired` and the flip
230+/// are one unit against a concurrent claim or retire. The flip landing and
231+/// the flip already standing are both success β€” the transaction that follows
232+/// decides whether the retired state stands, so `Unchanged` needs no
233+/// bookkeeping (the database owns the rollback).
234+///
235+/// The name still referenced (`count > 0`) is the caller's removal refusal,
236+/// byte for byte the old 409.
237+async fn retire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
238+ let was = sqlx::query!(
239+ r#"SELECT retired AS "retired!: bool" FROM kind_ref WHERE name = $1 FOR UPDATE"#,
240+ name
241+ )
242+ .fetch_optional(tx)
243+ .await?
244+ .map(|row| row.retired)
245+ .unwrap_or(false);
246+ let landed = sqlx::query!(
247+ r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, TRUE)
248+ ON CONFLICT (name) DO UPDATE SET retired = TRUE
249+ WHERE kind_ref.count = 0 AND kind_ref.retired IS DISTINCT FROM TRUE
250+ RETURNING 1 AS "landed!: i64""#,
251+ name
252+ )
253+ .fetch_optional(tx)
254+ .await?
255+ .is_some();
256+ match (landed, was) {
257+ // Still in use, and not already retired: the removal is refused.
258+ (false, false) => Err(AppError::ConflictOwned(format!(
259+ "exams of kind '{name}' are already graded β€” the kind cannot be removed"
260+ ))),
261+ // Flipped, or already retired by the rival that decided the same
262+ // removal: nothing to do β€” the transaction decides whether it stands.
263+ _ => Ok(()),
264+ }
265+}
266+
267+/// [`retire_kind`] against the meal-slot counters.
268+async fn retire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
269+ let was = sqlx::query!(
270+ r#"SELECT retired AS "retired!: bool" FROM slot_ref WHERE name = $1 FOR UPDATE"#,
271+ name
272+ )
273+ .fetch_optional(tx)
274+ .await?
275+ .map(|row| row.retired)
276+ .unwrap_or(false);
277+ let landed = sqlx::query!(
278+ r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, TRUE)
279+ ON CONFLICT (name) DO UPDATE SET retired = TRUE
280+ WHERE slot_ref.count = 0 AND slot_ref.retired IS DISTINCT FROM TRUE
281+ RETURNING 1 AS "landed!: i64""#,
282+ name
283+ )
284+ .fetch_optional(tx)
285+ .await?
286+ .is_some();
287+ match (landed, was) {
288+ (false, false) => Err(AppError::ConflictOwned(format!(
289+ "menus are already published for the '{name}' slot β€” it cannot be removed"
290+ ))),
291+ _ => Ok(()),
292+ }
293+}
294+
295+/// Put an exam kind back in service, inside the caller's transaction. One
296+/// guarded write: the flip lands only while the name is actually retired, so
297+/// it is idempotent. Whether the name *stays* in service is the save's
298+/// decision β€” a stale save aborts this transaction and the retirement stands
299+/// again, with no undo list to get wrong.
300+async fn unretire_kind(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
301+ sqlx::query!(
302+ r#"INSERT INTO kind_ref (name, count, retired) VALUES ($1, 0, FALSE)
303+ ON CONFLICT (name) DO UPDATE SET retired = FALSE
304+ WHERE kind_ref.retired IS DISTINCT FROM FALSE
305+ RETURNING 1 AS "landed!: i64""#,
306+ name
307+ )
308+ .fetch_optional(tx)
309+ .await?;
310+ Ok(())
311+}
312+
313+/// [`unretire_kind`] against the meal-slot counters.
314+async fn unretire_slot(tx: &mut sqlx::PgConnection, name: &str) -> Result<(), AppError> {
315+ sqlx::query!(
316+ r#"INSERT INTO slot_ref (name, count, retired) VALUES ($1, 0, FALSE)
317+ ON CONFLICT (name) DO UPDATE SET retired = FALSE
318+ WHERE slot_ref.retired IS DISTINCT FROM FALSE
319+ RETURNING 1 AS "landed!: i64""#,
320+ name
321+ )
322+ .fetch_optional(tx)
323+ .await?;
324+ Ok(())
325+}
326+
271 fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {327 fn kind_names(kinds: &[ExamKindDef]) -> Vec<String> {
272 kinds328 kinds
273 .iter()329 .iter()
@@ -292,39 +348,6 @@ fn missing(before: &[String], after: &[String]) -> Vec<String> {
292 .collect()348 .collect()
293 }349 }
294 350
295-/// One `retired` bit this attempt moved, and which way β€” what `restore` needs
296-/// to put it back. Only bits this attempt actually *flipped* are listed: a
297-/// write that changed nothing has nothing to take back, and taking it back
298-/// would undo the concurrent edit that really did move it.
299-enum Undo {
300- /// Retired for a removal; put it back in service.
301- Retired(RecordId),
302- /// Put back in service for a re-add; retire it again.
303- Unretired(RecordId),
304-}
305-
306-/// Undo every bit this attempt moved: the edit that justified them did not
307-/// land, so the lists the school offers are still the ones it started with.
308-async fn restore(undo: &[Undo], db: &Database) -> Result<(), AppError> {
309- for step in undo {
310- match step {
311- Undo::Retired(name) => {
312- cap::unretire_name(name, db).await?;
313- }
314- // A re-retirement can be refused: a mark (or a menu) landed under
315- // the name during the window it was in service. Refusing to undo is
316- // then the honest answer β€” the reference is real, and retiring over
317- // it would make the row's kind ungradable while nothing lists it.
318- // The name is left in service, matching the list this attempt is
319- // about to re-read.
320- Undo::Unretired(name) => {
321- cap::retire_name(name, db).await?;
322- }
323- }
324- }
325- Ok(())
326-}
327-
328 #[cfg(test)]351 #[cfg(test)]
329 mod tests {352 mod tests {
330 use super::*;353 use super::*;
src/service/user.rsmodified+17 -46
@@ -1,6 +1,6 @@
1 //! User workflows: the boot-time admin seed, and the role change β€” the1 //! User workflows: the boot-time admin seed, and the role change β€” the
2-//! admin floor ([`ADMIN_FLOOR_LOCK`]) held across the count that checks it2+//! admin floor carried by the role write's own guard, and every sweep the
3-//! and the transaction that commits it, sweeps included. Reads, listings,3+//! change owes committed in the same transaction. Reads, listings,
4 //! the row mint, and the field-scoped writers live in [`crate::db::user`].4 //! the row mint, and the field-scoped writers live in [`crate::db::user`].
5 5
6 use crate::database::Database;6 use crate::database::Database;
@@ -13,29 +13,6 @@ use crate::domain::role::Role;
13 use crate::domain::user::{Password, PasswordHash, User, UserId, Username};13 use crate::domain::user::{Password, PasswordHash, User, UserId, Username};
14 use crate::error::AppError;14 use crate::error::AppError;
15 15
16-/// One role demotion at a time, school-wide.
17-///
18-/// The invariant it protects is "the school always keeps an admin", and that
19-/// guard is a count-then-write: read whether another admin exists, then lower
20-/// this row. SurrealDB conflict-checks neither side of that pair β€” a
21-/// `BEGIN…COMMIT` does not serialize a cross-record count against a concurrent
22-/// update (write-skew, see [`crate::db::cap`]) and a statement that only
23-/// *reads* the rival's row never collides with it. So two admins demoting each
24-/// other both counted the other and both committed, leaving **zero** admins and
25-/// a school nobody can administer: `ensure_admin` refuses to promote an
26-/// existing non-admin row on every later boot, so the only way back was hand-run
27-/// SurrealQL against the volume.
28-///
29-/// Serializing the pair is what closes it, the same argument
30-/// [`crate::service::settings::SETTINGS_LOCK`] makes one level up: the deployment
31-/// runs one process by contract (stop-the-world upgrades), so process-wide is
32-/// deployment-wide. A per-row counter (the [`crate::db::cap`] shape) does
33-/// not fit β€” the count being capped is over *every* user row, with no parent
34-/// record to hold it and no place to seed one without a backfill.
35-///
36-/// **Lock order:** taken alone. Nothing is locked while it is held.
37-static ADMIN_FLOOR_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
38-
39 /// Idempotent startup seed: guarantee an admin account with this username.16 /// Idempotent startup seed: guarantee an admin account with this username.
40 /// Missing β†’ created directly with [`Role::Admin`]. Already an admin β†’17 /// Missing β†’ created directly with [`Role::Admin`]. Already an admin β†’
41 /// nothing to do (the stored password stays whatever it is β€” the seed never18 /// nothing to do (the stored password stays whatever it is β€” the seed never
@@ -52,7 +29,7 @@ pub async fn ensure_admin(
52 Some(_) => {29 Some(_) => {
53 tracing::warn!(30 tracing::warn!(
54 "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \31 "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \
55- Grant the role through an existing admin or the manual SurrealQL path."32+ Grant the role through an existing admin or a hand-run SQL session."
56 );33 );
57 Ok(())34 Ok(())
58 }35 }
@@ -77,9 +54,17 @@ pub async fn ensure_admin(
77 /// hold, in one transaction. The caller is responsible for authorizing it.54 /// hold, in one transaction. The caller is responsible for authorizing it.
78 ///55 ///
79 /// Refuses (`Conflict`) to lower the school's last admin, however the56 /// Refuses (`Conflict`) to lower the school's last admin, however the
80-/// request is spelled and however many demotions are in flight at once β€”57+/// request is spelled and however many demotions are in flight at once.
81-/// see [`ADMIN_FLOOR_LOCK`] for why that guard cannot live in the58+/// The floor is not a lock here β€” it is a predicate on the role write
82-/// transaction below.59+/// itself ([`user::set_role_cascade`]): the `UPDATE` that lowers the row
60+/// carries `AND NOT (demoting the admin whom no other admin remains)`, so
61+/// the count it reads and the write it guards are one statement, contended
62+/// on row locks like any other write. Two admins demoting each other both
63+/// used to count the other and both commit β€” the old store could not
64+/// serialize a cross-record count against a concurrent update, which is
65+/// what the process-wide lock used to stand in for. The database does that
66+/// serialization now; zero rows out of the guarded write is the same 409
67+/// the lock's check used to answer.
83 ///68 ///
84 /// The sweep itself β€” what each role change owes, arm by arm, and why the69 /// The sweep itself β€” what each role change owes, arm by arm, and why the
85 /// conditions differ β€” is [`user::set_role_cascade`]'s statement list,70 /// conditions differ β€” is [`user::set_role_cascade`]'s statement list,
@@ -89,24 +74,10 @@ pub async fn set_role(
89 target: &UserId,74 target: &UserId,
90 role: Role,75 role: Role,
91 ) -> Result<(User, Vec<Board>), AppError> {76 ) -> Result<(User, Vec<Board>), AppError> {
92- // A missing account is a 404, answered before the floor is asked.77+ // A missing account is a 404, answered before the cascade opens a
78+ // transaction. (No route deletes a user row, so the row cannot vanish
79+ // between this read and the write.)
93 user::read(db, target).await?.ok_or(AppError::NotFound)?;80 user::read(db, target).await?.ok_or(AppError::NotFound)?;
94- // The admin floor, held from the count to the commit ([`ADMIN_FLOOR_LOCK`]
95- // for why a transaction cannot do this). Asked on the *live* rows rather
96- // than a caller's snapshot, so a snapshot that predates a promotion cannot
97- // skip the check, and cheap enough to ask on every demotion: one round
98- // trip on an admin-only route.
99- let _floor = if role == Role::Admin {
100- None
101- } else {
102- let guard = ADMIN_FLOOR_LOCK.lock().await;
103- if user::would_orphan_admins(db, target).await? {
104- return Err(AppError::Conflict(
105- "the school must keep at least one admin β€” promote another account first",
106- ));
107- }
108- Some(guard)
109- };
110 user::set_role_cascade(db, target, role).await81 user::set_role_cascade(db, target, role).await
111 }82 }
112 83
src/web/users.rsmodified+5 -4
@@ -422,9 +422,10 @@ async fn update_user_preferences(
422 /// Set a user's role. Admin only. An admin cannot change their own role, and422 /// Set a user's role. Admin only. An admin cannot change their own role, and
423 /// the school's **last** admin cannot be demoted by anyone (`409`) β€” together423 /// the school's **last** admin cannot be demoted by anyone (`409`) β€” together
424 /// those keep role management from locking everyone out, including when two424 /// those keep role management from locking everyone out, including when two
425-/// admins demote each other at the same instant (the floor is serialized, see425+/// admins demote each other at the same instant (the floor is a predicate on
426-/// `ADMIN_FLOOR_LOCK`). A school that has already lost its admins is recovered426+/// the role write itself, so the racing demotions serialize on row locks).
427-/// with the SurrealQL in the README, since the seed never promotes.427+/// A school that has already lost its admins is recovered by hand against the
428+/// database, since the seed never promotes.
428 /// Setting any non-`student` role also drops the user's course enrollments β€”429 /// Setting any non-`student` role also drops the user's course enrollments β€”
429 /// only students enroll, so a promoted user leaves every roster. Demoting below430 /// only students enroll, so a promoted user leaves every roster. Demoting below
430 /// `teacher` drops their course teaching assignments for the mirror reason, and431 /// `teacher` drops their course teaching assignments for the mirror reason, and
@@ -1151,7 +1152,7 @@ async fn upload_my_avatar(
1151 let upload = read_image_upload(&st, &mut multipart).await?;1152 let upload = read_image_upload(&st, &mut multipart).await?;
1152 let size = upload.size();1153 let size = upload.size();
1153 1154
1154- let file = ulid::Ulid::generate().to_string();1155+ let file = crate::domain::monotonic_id::next_uuid().to_string();
1155 store_blob(&st, &file, &upload.data, || async {1156 store_blob(&st, &file, &upload.data, || async {
1156 match crate::service::user::set_avatar(1157 match crate::service::user::set_avatar(
1157 &st.db,1158 &st.db,