From 7f616c02dbe04b147612fe17c3d08a611314bdc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 11 Sep 2026 14:27:22 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B9=20chore:=20split=20profile,=20badg?= =?UTF-8?q?e,=20builder=20into=20domain/db/service=20layers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C3 identity lane. Moves, not rewrites: - badge: BadgeStats::load / BadgeAward::list_for / sync (UPSERT with the earned_at = NONE idempotency stays whole) -> db::badge, with the award-key mint and the persistence tests; BadgeStat/BadgeStats/earned/ BadgeAward (pure rules) stay in domain::badge; service::badge wraps list_for/sync for the web layer. - profile: ProfileStats::load (+ PomodoroTotals, persistence tests) -> db::profile; newtypes + getters stay; service::profile::load wraps. - builder: find_by_username/read/create(create_session)/find_by_token/ delete_by_token -> db::builder; the idempotent seed ensure -> service::builder (ensure_admin precedent); both tests ride their fns. - preferences, key: fully pure (validated newtypes, composite-id helpers) — stay domain-only, no db/service modules created. Entity fields the split constructs from are now pub(crate) (Builder, BuilderSession, ProfileStats), matching the user split. Callers re-pointed crate-wide: web/{users,exams/mod,questions,homework, sessions,auth,extractor,builder,tenant_state}, service/exam_attempt.rs (badge::sync after start), database.rs (control seed), tests/ {builder_api,e2e,integration}; cross-lane compile fixups in domain/pomodoro.rs and domain/session_attendance.rs (their lanes re-point on merge). constant.rs doc link -> crate::db::badge::list_for. --- src/constant.rs | 2 +- src/database.rs | 3 +- src/db/badge.rs | 369 +++++++++++++++++++++++++++++++ src/db/builder.rs | 108 +++++++++ src/db/mod.rs | 3 + src/db/profile.rs | 197 +++++++++++++++++ src/domain/badge.rs | 353 +---------------------------- src/domain/builder.rs | 179 +-------------- src/domain/pomodoro.rs | 9 +- src/domain/profile.rs | 197 +---------------- src/domain/session_attendance.rs | 8 +- src/service/badge.rs | 22 ++ src/service/builder.rs | 96 ++++++++ src/service/exam_attempt.rs | 3 +- src/service/mod.rs | 3 + src/service/profile.rs | 20 ++ src/web/auth.rs | 3 +- src/web/builder.rs | 33 +-- src/web/exams/mod.rs | 3 +- src/web/extractor.rs | 6 +- src/web/homework.rs | 3 +- src/web/questions.rs | 3 +- src/web/sessions.rs | 3 +- src/web/tenant_state.rs | 14 +- src/web/users.rs | 38 ++-- tests/builder_api.rs | 10 +- tests/e2e.rs | 4 +- tests/integration.rs | 14 +- 28 files changed, 918 insertions(+), 788 deletions(-) create mode 100644 src/db/badge.rs create mode 100644 src/db/builder.rs create mode 100644 src/db/profile.rs create mode 100644 src/service/badge.rs create mode 100644 src/service/builder.rs create mode 100644 src/service/profile.rs diff --git a/src/constant.rs b/src/constant.rs index 994c2b8..1d57641 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -1090,7 +1090,7 @@ pub const HIGH_MARK_MIN: i64 = 90; /// award row stores one forever. So an id is never reused for a different /// meaning; retiring one is done by deleting the line, and the awards that /// carry it simply stop being served (no data migration — -/// [`crate::domain::badge::BadgeAward::list_for`] filters to the live +/// [`crate::db::badge::list_for`] filters to the live /// catalog). pub const BADGES: [(&str, BadgeStat, i64); 34] = [ ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), diff --git a/src/database.rs b/src/database.rs index 56924fb..26cf28c 100644 --- a/src/database.rs +++ b/src/database.rs @@ -6,7 +6,6 @@ use surrealdb::opt::auth::Root; use crate::config::Config; use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; -use crate::domain::builder::Builder; use crate::domain::timestamp::Timestamp; use crate::domain::user::{Password, Username}; use crate::error::AppError; @@ -49,7 +48,7 @@ pub async fn init(cfg: &Config) -> Result { let db = std::sync::Arc::new(db); migrate_control(&db).await?; if let Some((username, password)) = builder { - Builder::ensure(username, password, &db).await?; + crate::service::builder::ensure(&db, username, password).await?; } Ok(Tenants::new_remote(db, cfg)) } diff --git a/src/db/badge.rs b/src/db/badge.rs new file mode 100644 index 0000000..9d89ad9 --- /dev/null +++ b/src/db/badge.rs @@ -0,0 +1,369 @@ +//! The badge counters' reads and the award rows' writes: the lifetime-counter +//! lookup off the user row, the shelf read, and the idempotent sync that +//! mints an award per newly earned badge. The rule deciding *which* badges +//! those are is [`crate::domain::badge::earned`] — pure, no I/O — and the +//! service wrappers the web layer calls live in [`crate::service::badge`]. + +use crate::constant::{BADGE_AWARD_TABLE, BADGES}; +use crate::database::Database; +use crate::domain::badge::{BadgeAward, BadgeStats}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Every counter off the user row, in one statement — a record lookup, not +/// a scan. +/// +/// Each projection is `(column ?? 0)`, parenthesized because `??` binds +/// loosely, and it is the whole stale-data story: the columns are +/// `option`, a row written before they existed carries none of them, +/// and absent must read as zero rather than as a null or an error. A user +/// row that is gone entirely reads as all zeros too — a badge sync is not +/// the place to discover a deleted account. +pub async fn load(db: &Database, user: &UserId) -> Result { + let mut result = db + .query(format!( + "SELECT ({homework_submitted} ?? 0) AS homework_submitted, + ({homework_on_time} ?? 0) AS homework_on_time, + ({exam_sat} ?? 0) AS exam_sat, + ({pomodoro_finished} ?? 0) AS pomodoro_finished, + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, + ({marks_given} ?? 0) AS marks_given, + ({lessons_held} ?? 0) AS lessons_held, + ({pool_approved} ?? 0) AS pool_approved, + ({pool_published} ?? 0) AS pool_published, + ({lessons_attended} ?? 0) AS lessons_attended, + ({high_mark} ?? 0) AS high_mark, + ({study_streak} ?? 0) AS study_streak + FROM $usr", + homework_submitted = crate::domain::badge::BadgeStat::HomeworkSubmitted.field(), + homework_on_time = crate::domain::badge::BadgeStat::HomeworkOnTime.field(), + exam_sat = crate::domain::badge::BadgeStat::ExamSat.field(), + pomodoro_finished = crate::domain::badge::BadgeStat::PomodoroFinished.field(), + pomodoro_focus_ms = crate::domain::badge::BadgeStat::PomodoroFocusMs.field(), + marks_given = crate::domain::badge::BadgeStat::MarksGiven.field(), + lessons_held = crate::domain::badge::BadgeStat::LessonsHeld.field(), + pool_approved = crate::domain::badge::BadgeStat::PoolApproved.field(), + pool_published = crate::domain::badge::BadgeStat::PoolPublished.field(), + lessons_attended = crate::domain::badge::BadgeStat::LessonsAttended.field(), + high_mark = crate::domain::badge::BadgeStat::HighMark.field(), + study_streak = crate::domain::badge::BadgeStat::StudyStreak.field(), + )) + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result + .take::>(0)? + .into_iter() + .next() + .unwrap_or_default()) +} + +/// Everything `user` has earned, oldest first. +/// +/// Filtered to the ids the catalog still holds: a badge retired from +/// `BADGES` stops being served without a data migration, and its rows stay +/// where they are in case the line comes back. +/// +/// The badge id breaks the tie, because one sync stamps every badge it +/// awards with the same millisecond and an arbitrary order there would +/// shuffle a student's shelf between reads. It is the record id's order +/// too — the key is `{user}_{badge}` and this reads one user — but spelled +/// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by +/// an idiom the selection does not carry ("Missing order idiom `id` in +/// statement selection"), and `id` is not a field of an award. +pub async fn list_for(db: &Database, user: &UserId) -> Result, AppError> { + let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); + let mut result = db + .query(format!( + "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} + WHERE user = $usr AND badge IN $ids + ORDER BY earned_at ASC, badge ASC LIMIT {}", + BADGES.len() + )) + .bind(("usr", user.record())) + .bind(("ids", ids)) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// The record one (user, badge) pair always maps to, so a second [`sync`] +/// resolves onto the row the first one wrote instead of minting a duplicate. +/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide. +fn award_key(user: &UserId, badge: &str) -> String { + format!("{}_{badge}", user.key()) +} + +/// Write an award row for every badge `user` has now earned and does not +/// already hold. +/// +/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the +/// whole of the idempotency: the first call creates the row, and every later +/// call — with a later `$now` — matches a row that already has a stamp and +/// writes nothing at all. So the earned-at a student sees is when they first +/// crossed the line, not when the counter last moved. +/// +/// **Callers must log and ignore the error.** A badge is a decoration on top +/// of somebody's homework submission, exam sitting or pomodoro stint, and none +/// of those may fail because the decoration could not be written. The `Result` +/// is returned rather than swallowed here so the caller's log line names the +/// real cause; the next counter bump re-runs this and heals whatever was +/// missed, which is also why a lost write race needs no retry loop. +pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { + let stats = load(db, user).await?; + let earned = crate::domain::badge::earned(&stats); + if earned.is_empty() { + return Ok(()); + } + let mut sql = String::new(); + for index in 0..earned.len() { + sql.push_str(&format!( + "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, + earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" + )); + } + let mut query = db + .query(sql) + .bind(("table", BADGE_AWARD_TABLE)) + .bind(("usr", user.record())) + .bind(("now", Timestamp::now())); + for (index, badge) in earned.iter().enumerate() { + query = query + .bind((format!("key{index}"), award_key(user, badge))) + .bind((format!("badge{index}"), badge.to_string())); + } + query.await?.check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{award_key, list_for, load, sync}; + use crate::constant::{ + BADGE_AWARD_TABLE, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, + LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, + POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, + STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, + }; + use crate::database::Database; + use crate::domain::badge::earned; + use crate::domain::user::UserId; + + /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled + /// with the same `IF NOT EXISTS` guards the migration uses, so it is a + /// no-op once the real definitions land next to it. + async fn schema(db: &Database) { + db.query(format!( + "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option; + DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option; + DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; + DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record; + DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; + DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option; + DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;" + )) + .await + .unwrap() + .check() + .unwrap(); + } + + /// A user row carrying `counters`, by column name. + async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + let sets: Vec = counters + .iter() + .map(|(field, value)| format!("{field} = {value}")) + .collect(); + let extra = if sets.is_empty() { + String::new() + } else { + format!(", {}", sets.join(", ")) + }; + db.query(format!( + "CREATE $usr SET username = $name, password_hash = 'x'{extra}" + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// The stamps on the stored rows, oldest first. + async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> { + list_for(db, user) + .await + .unwrap() + .into_iter() + .map(|award| { + ( + award.get_badge().to_string(), + award.get_earned_at().as_millis(), + ) + }) + .collect() + } + + #[tokio::test] + async fn a_row_without_the_columns_loads_as_zeros() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + // The stale-data case: an account written before the counters existed + // carries none of them. And the harsher one — no row at all. + for user in [a_user(&[], &db).await, UserId::from_key("ghost")] { + let stats = load(&db, &user).await.unwrap(); + assert_eq!(stats.get_homework_submitted(), 0); + assert_eq!(stats.get_homework_on_time(), 0); + assert_eq!(stats.get_exam_sat(), 0); + assert_eq!(stats.get_pomodoro_finished(), 0); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + assert_eq!(stats.get_marks_given(), 0); + assert_eq!(stats.get_lessons_held(), 0); + assert_eq!(stats.get_pool_approved(), 0); + assert_eq!(stats.get_pool_published(), 0); + assert_eq!(stats.get_lessons_attended(), 0); + assert_eq!(stats.get_high_mark(), 0); + assert_eq!(stats.get_study_streak(), 0); + assert!(earned(&stats).is_empty(), "zero earns nothing"); + } + } + + #[tokio::test] + async fn a_second_sync_does_not_move_the_stamp() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; + + sync(&db, &user).await.unwrap(); + let first = stamps(&user, &db).await; + assert_eq!(first.len(), 1, "{first:?}"); + assert_eq!(first[0].0, "homework_submitted_1"); + + // A later sync, provably at a later millisecond: the row must keep the + // instant the badge was *first* earned, and must not be doubled. + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + sync(&db, &user).await.unwrap(); + assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); + } + + #[tokio::test] + async fn an_award_survives_a_counter_that_falls_back_below_it() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; + sync(&db, &user).await.unwrap(); + assert_eq!( + stamps(&user, &db).await.len(), + 2, + "1 and 10 are both earned" + ); + + // The submission is withdrawn and the counter comes back down. A badge + // records that it was done, so nothing here may take it away. + db.query(format!( + "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + assert!( + earned(&load(&db, &user).await.unwrap()).is_empty(), + "the rule no longer holds…" + ); + sync(&db, &user).await.unwrap(); + let kept: Vec = stamps(&user, &db) + .await + .into_iter() + .map(|(badge, _)| badge) + .collect(); + assert_eq!( + kept, + vec!["homework_submitted_1", "homework_submitted_10"], + "…and the awards stand anyway" + ); + } + + #[tokio::test] + async fn a_badge_the_catalog_dropped_is_not_served() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await; + sync(&db, &user).await.unwrap(); + // The row a retired catalog line left behind: still stored, never + // served, and no migration deleted it. + db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1") + .bind(( + "id", + surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")), + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + + let served: Vec = stamps(&user, &db) + .await + .into_iter() + .map(|(badge, _)| badge) + .collect(); + assert_eq!(served, vec!["exam_sat_1"]); + let mut rows = db + .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) + .await + .unwrap(); + assert_eq!(rows.take::>(0).unwrap().len(), 2, "both stored"); + } + + /// One sync stamps every badge it writes with the same millisecond, so the + /// tie-break is what makes the order stable rather than incidental. + #[tokio::test] + async fn same_millisecond_awards_come_back_in_badge_order() { + let db = crate::database::init_mem().await.unwrap(); + schema(&db).await; + let user = a_user( + &[ + (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50), + (EXAM_SAT_TOTAL_FIELD, 1), + ], + &db, + ) + .await; + sync(&db, &user).await.unwrap(); + + let served = stamps(&user, &db).await; + let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect(); + assert_eq!( + ids, + vec![ + "exam_sat_1", + "homework_submitted_1", + "homework_submitted_10", + "homework_submitted_50" + ] + ); + assert!( + served.windows(2).all(|pair| pair[0].1 == pair[1].1), + "one sync stamps one instant: {served:?}" + ); + } +} diff --git a/src/db/builder.rs b/src/db/builder.rs new file mode 100644 index 0000000..eaa7803 --- /dev/null +++ b/src/db/builder.rs @@ -0,0 +1,108 @@ +//! The builder tables against the **control** database: the account lookup +//! and row insert, and the login sessions keyed by cookie token. The +//! credential newtypes are [`crate::domain::user`]'s; the seed workflow that +//! decides whether an account exists is [`crate::service::builder::ensure`]. + +use surrealdb::types::RecordId; +use ulid::Ulid; + +use crate::constant::SESSION_DURATION_DAYS; +use crate::database::Database; +use crate::domain::builder::{BUILDER_SESSION_TABLE, Builder, BuilderId, BuilderSession}; +use crate::domain::session::SessionToken; +use crate::domain::timestamp::Timestamp; +use crate::error::AppError; + +pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM builder WHERE username = $u LIMIT 1") + .bind(("u", username.trim().to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +pub async fn read(db: &Database, id: &BuilderId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// The raw account insert behind [`crate::service::builder::ensure`]'s seed. +pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { + let created: Option = db + .create(builder.get_id().record()) + .content(builder.clone()) + .await?; + created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; + Ok(()) +} + +/// Mint and store one builder login session. +pub async fn create_session( + db: &Database, + builder: &BuilderId, +) -> Result { + let key = RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()); + let session = BuilderSession { + id: key.clone(), + builder: builder.clone(), + token: SessionToken::generate()?, + created_at: Timestamp::now(), + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), + }; + let created: Option = db.create(key).content(session).await?; + created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) +} + +pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(result.take::>(0)?.into_iter().next()) +} + +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { + db.query("DELETE builder_session WHERE token = $tok") + .bind(("tok", token.to_string())) + .await? + .check()?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{create_session, delete_by_token, find_by_token, find_by_username}; + use crate::domain::user::{Password, Username}; + use crate::service::builder; + use crate::tenant::Tenants; + + #[tokio::test] + async fn a_builder_session_round_trips_and_deletes() { + let tenants = Tenants::new_mem().await.unwrap(); + let control = tenants.control(); + builder::ensure( + control, + Username::try_new("builder1").unwrap(), + Password::try_new("secret1").unwrap(), + ) + .await + .unwrap(); + let builder = find_by_username(control, "builder1") + .await + .unwrap() + .unwrap(); + + let session = create_session(control, builder.get_id()).await.unwrap(); + let token = session.token().as_str().to_string(); + let found = find_by_token(control, &token) + .await + .unwrap() + .expect("found by token"); + assert_eq!(found.builder(), builder.get_id()); + assert!(!found.is_expired()); + + delete_by_token(control, &token).await.unwrap(); + assert!(find_by_token(control, &token).await.unwrap().is_none()); + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..6d602d1 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -2,6 +2,8 @@ pub mod appointment; pub mod appointment_slot; +pub mod badge; +pub mod builder; pub mod cap; pub mod class_blueprint; pub mod course; @@ -15,6 +17,7 @@ pub mod meal_booking; pub mod note; pub mod page; pub mod payment_ledger; +pub mod profile; pub mod session; pub mod settings; pub mod user; diff --git a/src/db/profile.rs b/src/db/profile.rs new file mode 100644 index 0000000..7a34f63 --- /dev/null +++ b/src/db/profile.rs @@ -0,0 +1,197 @@ +//! The profile's motivational stats: the one aggregate read behind a profile +//! response. The counters themselves are [`crate::domain::profile`]'s; the +//! auto-earned badge rules next door are [`crate::domain::badge`] (pure) and +//! [`crate::db::badge`] (reads and writes). + +use crate::database::Database; +use crate::domain::badge::{BadgeStat, BadgeStats}; +use crate::domain::profile::ProfileStats; +use crate::domain::user::UserId; +use crate::error::AppError; +use surrealdb::types::SurrealValue; + +/// One round trip, and only one: `courses` and `classes` arrive from the +/// caller, which already holds them as the `total` of the paged class and +/// course readers it ran for the profile's own blocks — re-counting them +/// here would be two extra reads for numbers already in hand. +/// +/// The pomodoro aggregate rides the per-user index, so it is a lookup and +/// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a +/// bare truthiness test would also drop a stint that finished at epoch. An +/// open stint contributes to neither the count nor the sum — unfinished +/// focus has no honest duration to add. +/// +/// The lifetime counters ride along as a second statement in the *same* +/// query rather than a [`super::badge::load`] call, which would be a second +/// round trip for one record lookup. It repeats that projection — `?? 0` +/// per column, because the columns are `option` and a row predating +/// them carries none — so the two must move together if the shape changes. +pub async fn load( + db: &Database, + user: &UserId, + courses: i64, + classes: i64, +) -> Result { + let mut result = db + .query(format!( + "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms + FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; + SELECT ({homework_submitted} ?? 0) AS homework_submitted, + ({homework_on_time} ?? 0) AS homework_on_time, + ({exam_sat} ?? 0) AS exam_sat, + ({pomodoro_finished} ?? 0) AS pomodoro_finished, + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, + ({marks_given} ?? 0) AS marks_given, + ({lessons_held} ?? 0) AS lessons_held, + ({pool_approved} ?? 0) AS pool_approved, + ({pool_published} ?? 0) AS pool_published, + ({lessons_attended} ?? 0) AS lessons_attended, + ({high_mark} ?? 0) AS high_mark, + ({study_streak} ?? 0) AS study_streak + FROM $usr;", + homework_submitted = BadgeStat::HomeworkSubmitted.field(), + homework_on_time = BadgeStat::HomeworkOnTime.field(), + exam_sat = BadgeStat::ExamSat.field(), + pomodoro_finished = BadgeStat::PomodoroFinished.field(), + pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), + marks_given = BadgeStat::MarksGiven.field(), + lessons_held = BadgeStat::LessonsHeld.field(), + pool_approved = BadgeStat::PoolApproved.field(), + pool_published = BadgeStat::PoolPublished.field(), + lessons_attended = BadgeStat::LessonsAttended.field(), + high_mark = BadgeStat::HighMark.field(), + study_streak = BadgeStat::StudyStreak.field(), + )) + .bind(("usr", user.record())) + .await? + .check()?; + // `GROUP ALL` yields no row at all when nothing matched — that is the + // zero case, not a missing one. + let row = result.take::>(0)?.into_iter().next(); + // A vanished user row reads as all zeros, same as a fresh account. + let totals = result + .take::>(1)? + .into_iter() + .next() + .unwrap_or_default(); + Ok(ProfileStats { + totals, + pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), + // Floored at zero: a stint stamped by a wall clock that stepped + // backwards mid-session sums as negative time, and "you focused for + // minus five seconds" is never the truthful answer. New stints + // cannot go inverted (see [`PomodoroSession::finish`]); rows written + // before that guard still can, and this is what covers them. + pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), + courses, + classes, + }) +} + +/// The aggregate row of [`load`]. +#[derive(Debug, SurrealValue)] +struct PomodoroTotals { + sessions: i64, + focus_ms: i64, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn stats_are_zero_without_pomodoro_rows() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + + let stats = load(&db, &user, 3, 1).await.unwrap(); + // Derived counters: no rows is a true zero, never a null. + assert_eq!(stats.get_pomodoro_sessions(), 0); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + // The passed-in counts survive untouched. + assert_eq!(stats.get_courses(), 3); + assert_eq!(stats.get_classes(), 1); + // No user row at all — the lifetime counters still read as zeros. + assert_eq!(stats.get_totals().get_homework_submitted(), 0); + assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0); + } + + /// The second statement of the same query: the stored counters, straight off + /// the user row, with the columns an older row is missing read as zero. + #[tokio::test] + async fn lifetime_totals_ride_the_same_query() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + db.query(format!( + "CREATE $usr SET username = $name, password_hash = 'x', + {} = 4, {} = 3", + crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD, + crate::constant::EXAM_SAT_TOTAL_FIELD, + )) + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + + let totals = load(&db, &user, 0, 0).await.unwrap(); + let totals = totals.get_totals(); + assert_eq!(totals.get_homework_submitted(), 4); + assert_eq!(totals.get_exam_sat(), 3); + // Never written on this row: absent must read as 0, not as an error. + assert_eq!(totals.get_homework_on_time(), 0); + assert_eq!(totals.get_pomodoro_finished(), 0); + assert_eq!(totals.get_pomodoro_focus_ms(), 0); + } + + #[tokio::test] + async fn stats_count_finished_stints_only() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + let other = UserId::from_key(&ulid::Ulid::new().to_string()); + + // Two finished stints (1000 ms + 2500 ms), one still running, and one + // finished stint belonging to somebody else. + db.query( + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; + CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", + ) + .bind(("usr", user.record())) + .bind(("oth", other.record())) + .await + .unwrap() + .check() + .unwrap(); + + let stats = load(&db, &user, 0, 0).await.unwrap(); + assert_eq!(stats.get_pomodoro_sessions(), 2); + assert_eq!(stats.get_pomodoro_focus_ms(), 3500); + } + + #[tokio::test] + async fn focus_time_never_reads_negative() { + let db = crate::database::init_mem().await.unwrap(); + let user = UserId::from_key(&ulid::Ulid::new().to_string()); + + // One honest 1000 ms stint and one inverted row — what a backwards + // clock step left behind before `finish` grew its floor. The raw sum is + // -5000; the profile must still answer a duration, not an accusation. + db.query( + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", + ) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + + let stats = load(&db, &user, 0, 0).await.unwrap(); + // The stints still happened, so the count is honest at 2. + assert_eq!(stats.get_pomodoro_sessions(), 2); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + } +} diff --git a/src/domain/badge.rs b/src/domain/badge.rs index f75a6a3..f9fdfe6 100644 --- a/src/domain/badge.rs +++ b/src/domain/badge.rs @@ -3,7 +3,8 @@ //! //! Three properties hold here and nowhere else: //! -//! - **Auto-earned only.** No route awards a badge; [`sync`] is called after +//! - **Auto-earned only.** No route awards a badge; [`crate::db::badge::sync`] +//! is called after //! the writes that move a counter, and that is the only way a row appears. //! - **Permanent.** Nothing in this file deletes or revokes an award. A //! counter that later drops below the threshold — a submission withdrawn, @@ -16,16 +17,12 @@ use surrealdb::types::SurrealValue; use crate::constant::{ - BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, - LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, - POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, - STUDY_STREAK_LONGEST_FIELD, + BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, + HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, + MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, + POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STUDY_STREAK_LONGEST_FIELD, }; -use crate::database::Database; use crate::domain::timestamp::Timestamp; -use crate::domain::user::UserId; -use crate::error::AppError; /// The counter a badge family reads. One variant per column, and the enum is /// what ties a catalog line to a real number: a family added here cannot be @@ -166,54 +163,6 @@ impl BadgeStats { pub fn get_study_streak(&self) -> i64 { self.study_streak } - - /// Every counter off the user row, in one statement — a record lookup, not - /// a scan. - /// - /// Each projection is `(column ?? 0)`, parenthesized because `??` binds - /// loosely, and it is the whole stale-data story: the columns are - /// `option`, a row written before they existed carries none of them, - /// and absent must read as zero rather than as a null or an error. A user - /// row that is gone entirely reads as all zeros too — a badge sync is not - /// the place to discover a deleted account. - pub async fn load(user: &UserId, db: &Database) -> Result { - let mut result = db - .query(format!( - "SELECT ({homework_submitted} ?? 0) AS homework_submitted, - ({homework_on_time} ?? 0) AS homework_on_time, - ({exam_sat} ?? 0) AS exam_sat, - ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, - ({marks_given} ?? 0) AS marks_given, - ({lessons_held} ?? 0) AS lessons_held, - ({pool_approved} ?? 0) AS pool_approved, - ({pool_published} ?? 0) AS pool_published, - ({lessons_attended} ?? 0) AS lessons_attended, - ({high_mark} ?? 0) AS high_mark, - ({study_streak} ?? 0) AS study_streak - FROM $usr", - homework_submitted = BadgeStat::HomeworkSubmitted.field(), - homework_on_time = BadgeStat::HomeworkOnTime.field(), - exam_sat = BadgeStat::ExamSat.field(), - pomodoro_finished = BadgeStat::PomodoroFinished.field(), - pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), - marks_given = BadgeStat::MarksGiven.field(), - lessons_held = BadgeStat::LessonsHeld.field(), - pool_approved = BadgeStat::PoolApproved.field(), - pool_published = BadgeStat::PoolPublished.field(), - lessons_attended = BadgeStat::LessonsAttended.field(), - high_mark = BadgeStat::HighMark.field(), - study_streak = BadgeStat::StudyStreak.field(), - )) - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result - .take::>(0)? - .into_iter() - .next() - .unwrap_or_default()) - } } /// The ids of every badge `stats` has earned — the whole rule, and pure: no @@ -246,13 +195,6 @@ pub fn earned(stats: &BadgeStats) -> Vec<&'static str> { .collect() } -/// The record one (user, badge) pair always maps to, so a second [`sync`] -/// resolves onto the row the first one wrote instead of minting a duplicate. -/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide. -fn award_key(user: &UserId, badge: &str) -> String { - format!("{}_{badge}", user.key()) -} - /// One badge one user has earned, and when. #[derive(Debug, Clone, SurrealValue)] pub struct BadgeAward { @@ -268,148 +210,11 @@ impl BadgeAward { pub fn get_earned_at(&self) -> Timestamp { self.earned_at } - - /// Everything `user` has earned, oldest first. - /// - /// Filtered to the ids the catalog still holds: a badge retired from - /// `BADGES` stops being served without a data migration, and its rows stay - /// where they are in case the line comes back. - /// - /// The badge id breaks the tie, because one sync stamps every badge it - /// awards with the same millisecond and an arbitrary order there would - /// shuffle a student's shelf between reads. It is the record id's order - /// too — the key is `{user}_{badge}` and this reads one user — but spelled - /// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by - /// an idiom the selection does not carry ("Missing order idiom `id` in - /// statement selection"), and `id` is not a field of an award. - pub async fn list_for(user: &UserId, db: &Database) -> Result, AppError> { - let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); - let mut result = db - .query(format!( - "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} - WHERE user = $usr AND badge IN $ids - ORDER BY earned_at ASC, badge ASC LIMIT {}", - BADGES.len() - )) - .bind(("usr", user.record())) - .bind(("ids", ids)) - .await? - .check()?; - Ok(result.take::>(0)?) - } -} - -/// Write an award row for every badge `user` has now earned and does not -/// already hold. -/// -/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the -/// whole of the idempotency: the first call creates the row, and every later -/// call — with a later `$now` — matches a row that already has a stamp and -/// writes nothing at all. So the earned-at a student sees is when they first -/// crossed the line, not when the counter last moved. -/// -/// **Callers must log and ignore the error.** A badge is a decoration on top -/// of somebody's homework submission, exam sitting or pomodoro stint, and none -/// of those may fail because the decoration could not be written. The `Result` -/// is returned rather than swallowed here so the caller's log line names the -/// real cause; the next counter bump re-runs this and heals whatever was -/// missed, which is also why a lost write race needs no retry loop. -pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> { - let stats = BadgeStats::load(user, db).await?; - let earned = earned(&stats); - if earned.is_empty() { - return Ok(()); - } - let mut sql = String::new(); - for index in 0..earned.len() { - sql.push_str(&format!( - "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, - earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" - )); - } - let mut query = db - .query(sql) - .bind(("table", BADGE_AWARD_TABLE)) - .bind(("usr", user.record())) - .bind(("now", Timestamp::now())); - for (index, badge) in earned.iter().enumerate() { - query = query - .bind((format!("key{index}"), award_key(user, badge))) - .bind((format!("badge{index}"), badge.to_string())); - } - query.await?.check()?; - Ok(()) } #[cfg(test)] mod tests { use super::*; - use crate::constant::{STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD}; - - /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled - /// with the same `IF NOT EXISTS` guards the migration uses, so it is a - /// no-op once the real definitions land next to it. - async fn schema(db: &Database) { - db.query(format!( - "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option; - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option; - DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; - DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record; - DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; - DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option; - DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;" - )) - .await - .unwrap() - .check() - .unwrap(); - } - - /// A user row carrying `counters`, by column name. - async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { - let user = UserId::from_key(&ulid::Ulid::new().to_string()); - let sets: Vec = counters - .iter() - .map(|(field, value)| format!("{field} = {value}")) - .collect(); - let extra = if sets.is_empty() { - String::new() - } else { - format!(", {}", sets.join(", ")) - }; - db.query(format!( - "CREATE $usr SET username = $name, password_hash = 'x'{extra}" - )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); - user - } - - /// The stamps on the stored rows, oldest first. - async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> { - BadgeAward::list_for(user, db) - .await - .unwrap() - .into_iter() - .map(|award| (award.badge, award.earned_at.as_millis())) - .collect() - } /// The wire name and the column name are two names, not one. If a later /// edit points `as_str` back at `field`, this fails — which is the point: @@ -435,30 +240,6 @@ mod tests { } } - #[tokio::test] - async fn a_row_without_the_columns_loads_as_zeros() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - // The stale-data case: an account written before the counters existed - // carries none of them. And the harsher one — no row at all. - for user in [a_user(&[], &db).await, UserId::from_key("ghost")] { - let stats = BadgeStats::load(&user, &db).await.unwrap(); - assert_eq!(stats.get_homework_submitted(), 0); - assert_eq!(stats.get_homework_on_time(), 0); - assert_eq!(stats.get_exam_sat(), 0); - assert_eq!(stats.get_pomodoro_finished(), 0); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - assert_eq!(stats.get_marks_given(), 0); - assert_eq!(stats.get_lessons_held(), 0); - assert_eq!(stats.get_pool_approved(), 0); - assert_eq!(stats.get_pool_published(), 0); - assert_eq!(stats.get_lessons_attended(), 0); - assert_eq!(stats.get_high_mark(), 0); - assert_eq!(stats.get_study_streak(), 0); - assert!(earned(&stats).is_empty(), "zero earns nothing"); - } - } - #[tokio::test] async fn the_rule_takes_every_threshold_at_or_below_the_count() { let stats = BadgeStats { @@ -490,126 +271,4 @@ mod tests { ] ); } - - #[tokio::test] - async fn a_second_sync_does_not_move_the_stamp() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; - - sync(&user, &db).await.unwrap(); - let first = stamps(&user, &db).await; - assert_eq!(first.len(), 1, "{first:?}"); - assert_eq!(first[0].0, "homework_submitted_1"); - - // A later sync, provably at a later millisecond: the row must keep the - // instant the badge was *first* earned, and must not be doubled. - tokio::time::sleep(std::time::Duration::from_millis(5)).await; - sync(&user, &db).await.unwrap(); - assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); - } - - #[tokio::test] - async fn an_award_survives_a_counter_that_falls_back_below_it() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; - sync(&user, &db).await.unwrap(); - assert_eq!( - stamps(&user, &db).await.len(), - 2, - "1 and 10 are both earned" - ); - - // The submission is withdrawn and the counter comes back down. A badge - // records that it was done, so nothing here may take it away. - db.query(format!( - "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - assert!( - earned(&BadgeStats::load(&user, &db).await.unwrap()).is_empty(), - "the rule no longer holds…" - ); - sync(&user, &db).await.unwrap(); - let kept: Vec = stamps(&user, &db) - .await - .into_iter() - .map(|(badge, _)| badge) - .collect(); - assert_eq!( - kept, - vec!["homework_submitted_1", "homework_submitted_10"], - "…and the awards stand anyway" - ); - } - - #[tokio::test] - async fn a_badge_the_catalog_dropped_is_not_served() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await; - sync(&user, &db).await.unwrap(); - // The row a retired catalog line left behind: still stored, never - // served, and no migration deleted it. - db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1") - .bind(( - "id", - surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")), - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - - let served: Vec = stamps(&user, &db) - .await - .into_iter() - .map(|(badge, _)| badge) - .collect(); - assert_eq!(served, vec!["exam_sat_1"]); - let mut rows = db - .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) - .await - .unwrap(); - assert_eq!(rows.take::>(0).unwrap().len(), 2, "both stored"); - } - - /// One sync stamps every badge it writes with the same millisecond, so the - /// tie-break is what makes the order stable rather than incidental. - #[tokio::test] - async fn same_millisecond_awards_come_back_in_badge_order() { - let db = crate::database::init_mem().await.unwrap(); - schema(&db).await; - let user = a_user( - &[ - (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50), - (EXAM_SAT_TOTAL_FIELD, 1), - ], - &db, - ) - .await; - sync(&user, &db).await.unwrap(); - - let served = stamps(&user, &db).await; - let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect(); - assert_eq!( - ids, - vec![ - "exam_sat_1", - "homework_submitted_1", - "homework_submitted_10", - "homework_submitted_50" - ] - ); - assert!( - served.windows(2).all(|pair| pair[0].1 == pair[1].1), - "one sync stamps one instant: {served:?}" - ); - } } diff --git a/src/domain/builder.rs b/src/domain/builder.rs index ebd0cee..01a8883 100644 --- a/src/domain/builder.rs +++ b/src/domain/builder.rs @@ -12,12 +12,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use ulid::Ulid; -use crate::constant::SESSION_DURATION_DAYS; -use crate::database::Database; use crate::domain::session::SessionToken; use crate::domain::timestamp::Timestamp; -use crate::domain::user::{Password, PasswordHash, Username}; -use crate::error::AppError; +use crate::domain::user::{PasswordHash, Username}; pub const BUILDER_TABLE: &str = "builder"; pub const BUILDER_SESSION_TABLE: &str = "builder_session"; @@ -48,9 +45,9 @@ impl BuilderId { #[derive(Debug, Clone, SurrealValue)] pub struct Builder { - id: BuilderId, - username: Username, - password_hash: PasswordHash, + pub(crate) id: BuilderId, + pub(crate) username: Username, + pub(crate) password_hash: PasswordHash, } impl Builder { @@ -65,54 +62,6 @@ impl Builder { pub fn get_password_hash(&self) -> &PasswordHash { &self.password_hash } - - pub async fn find_by_username( - username: &str, - control: &Database, - ) -> Result, AppError> { - let mut result = control - .query("SELECT * FROM builder WHERE username = $u LIMIT 1") - .bind(("u", username.trim().to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - pub async fn read(id: &BuilderId, control: &Database) -> Result, AppError> { - Ok(control.select(id.record()).await?) - } - - /// Idempotent startup seed. An existing row is left exactly as it is — the - /// seed never rewrites a credential, so rotating `BUILDER_PASSWORD` in the - /// environment does not silently re-key a live account (delete the row to - /// re-seed). There is no role to promote here, so this cannot have - /// `ensure_admin`'s create-then-promote hole. - pub async fn ensure( - username: Username, - password: Password, - control: &Database, - ) -> Result<(), AppError> { - if Self::find_by_username(username.as_str(), control) - .await? - .is_some() - { - return Ok(()); - } - let builder = Builder { - id: BuilderId::generate(), - password_hash: password.hash_async().await?, - username, - }; - let created: Option = control - .create(builder.id.record()) - .content(builder.clone()) - .await?; - created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; - // The account name stays out of the event: exported log records must - // name no person (see `telemetry`). - tracing::info!("seeded the builder account named by BUILDER_USERNAME"); - Ok(()) - } } /// A builder's login session. [`crate::domain::session::Session`]'s shape @@ -120,30 +69,14 @@ impl Builder { /// are the same 64 hex chars. #[derive(Debug, Clone, SurrealValue)] pub struct BuilderSession { - id: RecordId, - builder: BuilderId, - token: SessionToken, - created_at: Timestamp, - expires_at: Timestamp, + pub(crate) id: RecordId, + pub(crate) builder: BuilderId, + pub(crate) token: SessionToken, + pub(crate) created_at: Timestamp, + pub(crate) expires_at: Timestamp, } impl BuilderSession { - pub async fn create( - builder: &BuilderId, - control: &Database, - ) -> Result { - let session = BuilderSession { - id: RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()), - builder: builder.clone(), - token: SessionToken::generate()?, - created_at: Timestamp::now(), - expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), - }; - let created: Option = - control.create(session.id.clone()).content(session).await?; - created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) - } - pub fn token(&self) -> &SessionToken { &self.token } @@ -155,98 +88,4 @@ impl BuilderSession { pub fn is_expired(&self) -> bool { self.expires_at.is_past() } - - pub async fn find_by_token( - token: &str, - control: &Database, - ) -> Result, AppError> { - let mut result = control - .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(result.take::>(0)?.into_iter().next()) - } - - pub async fn delete_by_token(token: &str, control: &Database) -> Result<(), AppError> { - control - .query("DELETE builder_session WHERE token = $tok") - .bind(("tok", token.to_string())) - .await? - .check()?; - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::tenant::Tenants; - - #[tokio::test] - async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { - let tenants = Tenants::new_mem().await.unwrap(); - let control = tenants.control(); - let name = Username::try_new("builder1").unwrap(); - Builder::ensure(name.clone(), Password::try_new("secret1").unwrap(), control) - .await - .unwrap(); - let first = Builder::find_by_username("builder1", control) - .await - .unwrap() - .expect("seeded"); - - // A second boot with a *different* password must leave the row alone: - // an environment edit is not a password reset. - Builder::ensure(name, Password::try_new("secret2").unwrap(), control) - .await - .unwrap(); - let again = Builder::find_by_username("builder1", control) - .await - .unwrap() - .expect("still there"); - assert_eq!(again.get_id(), first.get_id()); - assert_eq!( - again.get_password_hash().as_str(), - first.get_password_hash().as_str() - ); - } - - #[tokio::test] - async fn a_builder_session_round_trips_and_deletes() { - let tenants = Tenants::new_mem().await.unwrap(); - let control = tenants.control(); - Builder::ensure( - Username::try_new("builder1").unwrap(), - Password::try_new("secret1").unwrap(), - control, - ) - .await - .unwrap(); - let builder = Builder::find_by_username("builder1", control) - .await - .unwrap() - .unwrap(); - - let session = BuilderSession::create(builder.get_id(), control) - .await - .unwrap(); - let token = session.token().as_str().to_string(); - let found = BuilderSession::find_by_token(&token, control) - .await - .unwrap() - .expect("found by token"); - assert_eq!(found.builder(), builder.get_id()); - assert!(!found.is_expired()); - - BuilderSession::delete_by_token(&token, control) - .await - .unwrap(); - assert!( - BuilderSession::find_by_token(&token, control) - .await - .unwrap() - .is_none() - ); - } } diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 3d9a983..cfdc6f7 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -7,7 +7,6 @@ use crate::constant::{ STUDY_STREAK_LONGEST_FIELD, }; use crate::database::{Database, transaction_with_retry}; -use crate::domain::badge; use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; @@ -307,7 +306,7 @@ impl PomodoroSession { // A badge is a decoration on top of the stint: losing one to a // transient database error must never fail the finish, and the next // counter move re-runs this and heals it. - if let Err(err) = badge::sync(user, db).await { + if let Err(err) = crate::db::badge::sync(db, user).await { tracing::warn!("failed to sync badges for {}: {err}", user.key()); } Ok(saved) @@ -756,7 +755,7 @@ mod tests { 200 ); assert!( - badge::BadgeAward::list_for(&user, &db) + crate::db::badge::list_for(&db, &user) .await .unwrap() .is_empty(), @@ -827,9 +826,7 @@ mod tests { assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); // And the stat that sums these stays non-negative. - let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) - .await - .unwrap(); + let stats = crate::db::profile::load(&db, &user, 0, 0).await.unwrap(); assert_eq!(stats.get_pomodoro_sessions(), 1); assert_eq!(stats.get_pomodoro_focus_ms(), 0); } diff --git a/src/domain/profile.rs b/src/domain/profile.rs index 71ff2e8..2e0ff1d 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -4,11 +4,9 @@ use surrealdb::types::SurrealValue; use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; -use crate::database::Database; -use crate::domain::badge::{BadgeStat, BadgeStats}; +use crate::domain::badge::BadgeStats; use crate::domain::timestamp::Timestamp; -use crate::domain::user::UserId; -use crate::error::{AppError, ValidationError}; +use crate::error::ValidationError; use crate::validate::{validate_email, validate_optional, validate_phone, validate_required}; /// A person's given or family name. One type serves both fields — the `field` @@ -140,11 +138,11 @@ impl Bio { /// without touching a signature. #[derive(Debug, Clone, SurrealValue)] pub struct ProfileStats { - pomodoro_sessions: i64, - pomodoro_focus_ms: i64, - courses: i64, - classes: i64, - totals: BadgeStats, + pub(crate) pomodoro_sessions: i64, + pub(crate) pomodoro_focus_ms: i64, + pub(crate) courses: i64, + pub(crate) classes: i64, + pub(crate) totals: BadgeStats, } impl ProfileStats { @@ -170,91 +168,6 @@ impl ProfileStats { pub fn get_totals(&self) -> &BadgeStats { &self.totals } - - /// One round trip, and only one: `courses` and `classes` arrive from the - /// caller, which already holds them as the `total` of the paged class and - /// course readers it ran for the profile's own blocks — re-counting them - /// here would be two extra reads for numbers already in hand. - /// - /// The pomodoro aggregate rides the per-user index, so it is a lookup and - /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a - /// bare truthiness test would also drop a stint that finished at epoch. An - /// open stint contributes to neither the count nor the sum — unfinished - /// focus has no honest duration to add. - /// - /// The lifetime counters ride along as a second statement in the *same* - /// query rather than a [`BadgeStats::load`] call, which would be a second - /// round trip for one record lookup. It repeats that projection — `?? 0` - /// per column, because the columns are `option` and a row predating - /// them carries none — so the two must move together if the shape changes. - pub async fn load( - user: &UserId, - courses: i64, - classes: i64, - db: &Database, - ) -> Result { - let mut result = db - .query(format!( - "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms - FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; - SELECT ({homework_submitted} ?? 0) AS homework_submitted, - ({homework_on_time} ?? 0) AS homework_on_time, - ({exam_sat} ?? 0) AS exam_sat, - ({pomodoro_finished} ?? 0) AS pomodoro_finished, - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, - ({marks_given} ?? 0) AS marks_given, - ({lessons_held} ?? 0) AS lessons_held, - ({pool_approved} ?? 0) AS pool_approved, - ({pool_published} ?? 0) AS pool_published, - ({lessons_attended} ?? 0) AS lessons_attended, - ({high_mark} ?? 0) AS high_mark, - ({study_streak} ?? 0) AS study_streak - FROM $usr;", - homework_submitted = BadgeStat::HomeworkSubmitted.field(), - homework_on_time = BadgeStat::HomeworkOnTime.field(), - exam_sat = BadgeStat::ExamSat.field(), - pomodoro_finished = BadgeStat::PomodoroFinished.field(), - pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), - marks_given = BadgeStat::MarksGiven.field(), - lessons_held = BadgeStat::LessonsHeld.field(), - pool_approved = BadgeStat::PoolApproved.field(), - pool_published = BadgeStat::PoolPublished.field(), - lessons_attended = BadgeStat::LessonsAttended.field(), - high_mark = BadgeStat::HighMark.field(), - study_streak = BadgeStat::StudyStreak.field(), - )) - .bind(("usr", user.record())) - .await? - .check()?; - // `GROUP ALL` yields no row at all when nothing matched — that is the - // zero case, not a missing one. - let row = result.take::>(0)?.into_iter().next(); - // A vanished user row reads as all zeros, same as a fresh account. - let totals = result - .take::>(1)? - .into_iter() - .next() - .unwrap_or_default(); - Ok(ProfileStats { - totals, - pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), - // Floored at zero: a stint stamped by a wall clock that stepped - // backwards mid-session sums as negative time, and "you focused for - // minus five seconds" is never the truthful answer. New stints - // cannot go inverted (see [`PomodoroSession::finish`]); rows written - // before that guard still can, and this is what covers them. - pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), - courses, - classes, - }) - } -} - -/// The aggregate row of [`ProfileStats::load`]. -#[derive(Debug, SurrealValue)] -struct PomodoroTotals { - sessions: i64, - focus_ms: i64, } #[cfg(test)] @@ -342,100 +255,4 @@ mod tests { assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN)).is_ok()); assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN + 1)).is_err()); } - - #[tokio::test] - async fn stats_are_zero_without_pomodoro_rows() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::new().to_string()); - - let stats = ProfileStats::load(&user, 3, 1, &db).await.unwrap(); - // Derived counters: no rows is a true zero, never a null. - assert_eq!(stats.get_pomodoro_sessions(), 0); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - // The passed-in counts survive untouched. - assert_eq!(stats.get_courses(), 3); - assert_eq!(stats.get_classes(), 1); - // No user row at all — the lifetime counters still read as zeros. - assert_eq!(stats.get_totals().get_homework_submitted(), 0); - assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0); - } - - /// The second statement of the same query: the stored counters, straight off - /// the user row, with the columns an older row is missing read as zero. - #[tokio::test] - async fn lifetime_totals_ride_the_same_query() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::new().to_string()); - db.query(format!( - "CREATE $usr SET username = $name, password_hash = 'x', - {} = 4, {} = 3", - crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD, - crate::constant::EXAM_SAT_TOTAL_FIELD, - )) - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); - - let totals = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); - let totals = totals.get_totals(); - assert_eq!(totals.get_homework_submitted(), 4); - assert_eq!(totals.get_exam_sat(), 3); - // Never written on this row: absent must read as 0, not as an error. - assert_eq!(totals.get_homework_on_time(), 0); - assert_eq!(totals.get_pomodoro_finished(), 0); - assert_eq!(totals.get_pomodoro_focus_ms(), 0); - } - - #[tokio::test] - async fn stats_count_finished_stints_only() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::new().to_string()); - let other = UserId::from_key(&ulid::Ulid::new().to_string()); - - // Two finished stints (1000 ms + 2500 ms), one still running, and one - // finished stint belonging to somebody else. - db.query( - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; - CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", - ) - .bind(("usr", user.record())) - .bind(("oth", other.record())) - .await - .unwrap() - .check() - .unwrap(); - - let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); - assert_eq!(stats.get_pomodoro_sessions(), 2); - assert_eq!(stats.get_pomodoro_focus_ms(), 3500); - } - - #[tokio::test] - async fn focus_time_never_reads_negative() { - let db = crate::database::init_mem().await.unwrap(); - let user = UserId::from_key(&ulid::Ulid::new().to_string()); - - // One honest 1000 ms stint and one inverted row — what a backwards - // clock step left behind before `finish` grew its floor. The raw sum is - // -5000; the profile must still answer a duration, not an accusation. - db.query( - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", - ) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - - let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); - // The stints still happened, so the count is honest at 2. - assert_eq!(stats.get_pomodoro_sessions(), 2); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - } } diff --git a/src/domain/session_attendance.rs b/src/domain/session_attendance.rs index 57ced1c..e14b312 100644 --- a/src/domain/session_attendance.rs +++ b/src/domain/session_attendance.rs @@ -355,7 +355,6 @@ mod tests { use super::*; use crate::constant::DEFAULT_ATTENDANCE_STATUSES; use crate::database::init_mem; - use crate::domain::badge::BadgeStats; use crate::domain::course_session::SessionTopic; use crate::domain::role::Role; @@ -414,14 +413,17 @@ mod tests { /// The two counters as the badge rules read them, off the stored row. async fn attended(user: &UserId, db: &Database) -> i64 { - BadgeStats::load(user, db) + crate::db::badge::load(db, user) .await .unwrap() .get_lessons_attended() } async fn held(user: &UserId, db: &Database) -> i64 { - BadgeStats::load(user, db).await.unwrap().get_lessons_held() + crate::db::badge::load(db, user) + .await + .unwrap() + .get_lessons_held() } /// The whole transition table in one pass: an upsert may only move the diff --git a/src/service/badge.rs b/src/service/badge.rs new file mode 100644 index 0000000..7cc7842 --- /dev/null +++ b/src/service/badge.rs @@ -0,0 +1,22 @@ +//! Badge workflows: the reads and the award sync the web layer calls behind +//! counter-moving writes. The rules live in [`crate::domain::badge`] (pure) +//! and the queries in [`crate::db::badge`]; there is no lock and no +//! orchestration here — a badge is a decoration that never fails the write +//! it decorates, so every caller logs and swallows [`sync`]'s error. + +use crate::database::Database; +use crate::db::badge; +use crate::domain::badge::BadgeAward; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Everything `user` has earned, oldest first. +pub async fn list_for(db: &Database, user: &UserId) -> Result, AppError> { + badge::list_for(db, user).await +} + +/// Write an award row for every badge `user` has now earned and does not +/// already hold. +pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { + badge::sync(db, user).await +} diff --git a/src/service/builder.rs b/src/service/builder.rs new file mode 100644 index 0000000..9a49813 --- /dev/null +++ b/src/service/builder.rs @@ -0,0 +1,96 @@ +//! Builder workflows: the boot-time seed and the lookups the web layer +//! resolves cookies and logins with. The control-database queries live in +//! [`crate::db::builder`]; the school-provisioning routes never come through +//! here — they speak to [`crate::tenant::Tenants`] directly. + +use crate::database::Database; +use crate::db::builder; +use crate::domain::builder::{Builder, BuilderId, BuilderSession}; +use crate::domain::user::{Password, Username}; +use crate::error::AppError; + +/// Idempotent startup seed: guarantee an account with this username in the +/// control database. Missing → created. Already present → nothing to do (the +/// stored password stays whatever it is — the seed never rewrites a +/// credential, so rotating `BUILDER_PASSWORD` in the environment does not +/// silently re-key a live account; delete the row to re-seed). There is no +/// role to promote here, so this cannot have +/// [`crate::service::user::ensure_admin`]'s create-then-promote hole. +pub async fn ensure(db: &Database, username: Username, password: Password) -> Result<(), AppError> { + if builder::find_by_username(db, username.as_str()) + .await? + .is_some() + { + return Ok(()); + } + let builder = Builder { + id: BuilderId::generate(), + password_hash: password.hash_async().await?, + username, + }; + builder::create(db, builder).await?; + // The account name stays out of the event: exported log records must + // name no person (see `telemetry`). + tracing::info!("seeded the builder account named by BUILDER_USERNAME"); + Ok(()) +} + +/// The login lookup. Usernames are stored trimmed; callers trim the same way +/// so a padded attempt matches the canonical name. +pub async fn find_by_username(db: &Database, username: &str) -> Result, AppError> { + builder::find_by_username(db, username).await +} + +pub async fn read(db: &Database, id: &BuilderId) -> Result, AppError> { + builder::read(db, id).await +} + +pub async fn create_session( + db: &Database, + builder_id: &BuilderId, +) -> Result { + builder::create_session(db, builder_id).await +} + +pub async fn find_by_token(db: &Database, token: &str) -> Result, AppError> { + builder::find_by_token(db, token).await +} + +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { + builder::delete_by_token(db, token).await +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tenant::Tenants; + + #[tokio::test] + async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { + let tenants = Tenants::new_mem().await.unwrap(); + let control = tenants.control(); + let name = Username::try_new("builder1").unwrap(); + ensure(control, name.clone(), Password::try_new("secret1").unwrap()) + .await + .unwrap(); + let first = find_by_username(control, "builder1") + .await + .unwrap() + .expect("seeded"); + + // A second boot with a *different* password must leave the row alone: + // an environment edit is not a password reset. + ensure(control, name, Password::try_new("secret2").unwrap()) + .await + .unwrap(); + let again = find_by_username(control, "builder1") + .await + .unwrap() + .expect("still there"); + assert_eq!(again.get_id(), first.get_id()); + assert_eq!( + again.get_password_hash().as_str(), + first.get_password_hash().as_str() + ); + } +} diff --git a/src/service/exam_attempt.rs b/src/service/exam_attempt.rs index 604bd41..12a250c 100644 --- a/src/service/exam_attempt.rs +++ b/src/service/exam_attempt.rs @@ -6,7 +6,6 @@ use crate::constant::EXAM_SAT_TOTAL_FIELD; use crate::database::Database; use crate::db::cap; -use crate::domain::badge; use crate::domain::course::Course; use crate::domain::exam::{Exam, ExamId}; @@ -218,7 +217,7 @@ pub async fn start( { cap::Claimed::Made(created) => { // Only a moved counter can have crossed a threshold. - if first && let Err(err) = badge::sync(user, db).await { + if first && let Err(err) = crate::db::badge::sync(db, user).await { tracing::warn!("failed to sync badges for {}: {err}", user.key()); } Ok((created, true)) diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..5fa70ff 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -3,6 +3,8 @@ pub mod appointment; pub mod appointment_slot; +pub mod badge; +pub mod builder; pub mod class_blueprint; pub mod course; pub mod course_session; @@ -13,6 +15,7 @@ pub mod exam_question; pub mod meal_booking; pub mod note; pub mod payment_ledger; +pub mod profile; pub mod session; pub mod settings; pub mod user; diff --git a/src/service/profile.rs b/src/service/profile.rs new file mode 100644 index 0000000..4e7e438 --- /dev/null +++ b/src/service/profile.rs @@ -0,0 +1,20 @@ +//! Profile workflows: the aggregate stats read behind a profile response. +//! There is no decision and no lock here — the query itself is the whole +//! story, so this wraps [`crate::db::profile::load`] for the web layer. + +use crate::database::Database; +use crate::db::profile; +use crate::domain::profile::ProfileStats; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// One round trip for a profile's motivational counters; `courses` and +/// `classes` arrive from the caller's own paged reads. +pub async fn load( + db: &Database, + user: &UserId, + courses: i64, + classes: i64, +) -> Result { + profile::load(db, user, courses, classes).await +} diff --git a/src/web/auth.rs b/src/web/auth.rs index 6de3924..e3f157e 100644 --- a/src/web/auth.rs +++ b/src/web/auth.rs @@ -10,7 +10,6 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; -use crate::domain::builder::BuilderSession; use crate::domain::role::Role as DomainRole; use crate::domain::user::{Password, PasswordHash, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -242,7 +241,7 @@ async fn logout( // or suspended still clears below — logging out must never fail. if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { if prefix == BUILDER_COOKIE_PREFIX { - BuilderSession::delete_by_token(token, &st.db).await?; + crate::service::builder::delete_by_token(&st.db, token).await?; } else if let Ok(slug) = Slug::try_new(prefix) && let Ok(db) = st.tenants.get(&slug).await { diff --git a/src/web/builder.rs b/src/web/builder.rs index e188084..74ec340 100644 --- a/src/web/builder.rs +++ b/src/web/builder.rs @@ -26,7 +26,7 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::MAX_SCHOOL_NAME_LEN; -use crate::domain::builder::{Builder, BuilderSession}; +use crate::domain::builder::Builder; use crate::domain::role::Role; use crate::domain::user::{Password, PasswordHash, User, Username}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -257,23 +257,24 @@ async fn builder_login( ) -> Result<(CookieJar, Json), AppError> { let control = st.tenants.control(); let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; - let builder = match Builder::find_by_username(req.username.trim(), control).await? { - Some(builder) => { - if !builder.get_password_hash().verify_async(&password).await { + let builder = + match crate::service::builder::find_by_username(control, req.username.trim()).await? { + Some(builder) => { + if !builder.get_password_hash().verify_async(&password).await { + return Err(AppError::Unauthorized); + } + builder + } + None => { + // The same decoy hash `/auth/login` runs: a wrong name and a wrong + // password must cost the same, or the reply time enumerates the + // operator accounts. + PasswordHash::verify_decoy_async(&password).await; return Err(AppError::Unauthorized); } - builder - } - None => { - // The same decoy hash `/auth/login` runs: a wrong name and a wrong - // password must cost the same, or the reply time enumerates the - // operator accounts. - PasswordHash::verify_decoy_async(&password).await; - return Err(AppError::Unauthorized); - } - }; + }; - let session = BuilderSession::create(builder.get_id(), control).await?; + let session = crate::service::builder::create_session(control, builder.get_id()).await?; let cookie = session_cookie( format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()), st.cookie_secure, @@ -297,7 +298,7 @@ async fn builder_logout( .get("session") .and_then(|cookie| super::tenant_state::split_cookie(cookie.value())) { - BuilderSession::delete_by_token(token, st.tenants.control()).await?; + crate::service::builder::delete_by_token(st.tenants.control(), token).await?; } let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); Ok((jar, StatusCode::NO_CONTENT)) diff --git a/src/web/exams/mod.rs b/src/web/exams/mod.rs index 2569481..6cf2ea8 100644 --- a/src/web/exams/mod.rs +++ b/src/web/exams/mod.rs @@ -13,7 +13,6 @@ use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; use crate::domain::answer_image::AnswerImage; -use crate::domain::badge; use crate::domain::bank_question::{BankQuestion, BankQuestionId}; use crate::domain::bank_question_image::BankQuestionImage; @@ -622,7 +621,7 @@ async fn grade( // decoration on top of the mark: losing one to a transient database error // must never fail the grading, and the next counter move heals it. for person in [teacher.get_id(), &target] { - if let Err(err) = badge::sync(person, &st.db).await { + if let Err(err) = service::badge::sync(&st.db, person).await { tracing::warn!("failed to sync badges for {}: {err}", person.key()); } } diff --git a/src/web/extractor.rs b/src/web/extractor.rs index c9e2289..f2cac1d 100644 --- a/src/web/extractor.rs +++ b/src/web/extractor.rs @@ -3,7 +3,7 @@ use axum::http::request::Parts; use axum_extra::extract::CookieJar; use crate::database::Database; -use crate::domain::builder::{Builder, BuilderSession}; +use crate::domain::builder::Builder; use crate::domain::role::Role; use crate::domain::user::User; use crate::error::AppError; @@ -175,14 +175,14 @@ where } let control: Database = AppState::from_ref(state).tenants.control().clone(); - let session = BuilderSession::find_by_token(token, &control) + let session = crate::service::builder::find_by_token(&control, token) .await? .ok_or(AppError::Unauthorized)?; if session.is_expired() { return Err(AppError::Unauthorized); } Ok(RequireBuilder( - Builder::read(session.builder(), &control) + crate::service::builder::read(&control, session.builder()) .await? .ok_or(AppError::Unauthorized)?, )) diff --git a/src/web/homework.rs b/src/web/homework.rs index cc5f4b3..7685e44 100644 --- a/src/web/homework.rs +++ b/src/web/homework.rs @@ -18,7 +18,6 @@ use utoipa_axum::routes; use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; use crate::database::Database; -use crate::domain::badge; use crate::domain::course::{Course, CourseId}; use crate::domain::exam_result::Mark; @@ -837,7 +836,7 @@ async fn delete_submission( /// of the work, and losing one to a transient database error is not worth /// refusing a hand-in over — the next counter move re-runs this and heals it. async fn award_badges(user: &UserId, db: &Database) { - if let Err(err) = badge::sync(user, db).await { + if let Err(err) = service::badge::sync(db, user).await { tracing::warn!("failed to sync badges for {}: {err}", user.key()); } } diff --git a/src/web/questions.rs b/src/web/questions.rs index bbcd84a..5d33c3b 100644 --- a/src/web/questions.rs +++ b/src/web/questions.rs @@ -19,7 +19,6 @@ use utoipa_axum::router::OpenApiRouter; use utoipa_axum::routes; use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES}; -use crate::domain::badge; use crate::domain::pool_question::{ PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, }; @@ -394,7 +393,7 @@ async fn approve_question( // next counter move re-runs this and heals it. Two users, because the // transition credits the approver and the asker alike. for earner in [user.get_id(), question.get_asker()] { - if let Err(err) = badge::sync(earner, &st.db).await { + if let Err(err) = crate::service::badge::sync(&st.db, earner).await { tracing::warn!("failed to sync badges for {}: {err}", earner.key()); } } diff --git a/src/web/sessions.rs b/src/web/sessions.rs index 5533c5c..64d0e5d 100644 --- a/src/web/sessions.rs +++ b/src/web/sessions.rs @@ -11,7 +11,6 @@ use utoipa_axum::routes; use crate::database::Database; use crate::domain::attendance::AttendanceStatus; -use crate::domain::badge; use crate::domain::course::Course; use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; @@ -344,7 +343,7 @@ async fn mark_roll_call( // that failed, and knowing here whether the credit landed would mean // widening `mark`'s return type for nothing. for who in [&target, session.get_teacher()] { - if let Err(err) = badge::sync(who, &st.db).await { + if let Err(err) = service::badge::sync(&st.db, who).await { tracing::warn!("failed to sync badges for {}: {err}", who.key()); } } diff --git a/src/web/tenant_state.rs b/src/web/tenant_state.rs index 9671757..6ce9ec7 100644 --- a/src/web/tenant_state.rs +++ b/src/web/tenant_state.rs @@ -182,7 +182,6 @@ mod tests { use crate::database::init_mem_tenants; use crate::db::session; - use crate::domain::builder::{Builder, BuilderSession}; use crate::domain::user::{Password, Username}; use crate::tenant::DEMO_SLUG; use crate::web::{CurrentUser, RequireBuilder}; @@ -218,20 +217,21 @@ mod tests { let session = session::create(&school, user.get_id()).await.unwrap(); let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); - Builder::ensure( + crate::service::builder::ensure( + tenants.control(), Username::try_new("operator").unwrap(), Password::try_new("secret1").unwrap(), - tenants.control(), ) .await .unwrap(); - let builder = Builder::find_by_username("operator", tenants.control()) + let builder = crate::service::builder::find_by_username(tenants.control(), "operator") .await .unwrap() .unwrap(); - let builder_session = BuilderSession::create(builder.get_id(), tenants.control()) - .await - .unwrap(); + let builder_session = + crate::service::builder::create_session(tenants.control(), builder.get_id()) + .await + .unwrap(); let builder_cookie = format!("session=builder.{}", builder_session.token().as_str()); let state = AppState { diff --git a/src/web/users.rs b/src/web/users.rs index aaab134..a9fbc9d 100644 --- a/src/web/users.rs +++ b/src/web/users.rs @@ -174,14 +174,9 @@ async fn apply_preferences( let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; let language = merge_field(req.language.as_deref(), Language::try_from_str)?; let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; - let updated = crate::service::user::set_preferences( - db, - user.get_id(), - theme, - language, - palette_color, - ) - .await?; + let updated = + crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color) + .await?; Ok(UserResponse::new(&updated)) } @@ -602,8 +597,7 @@ async fn link_student( reason: "students can only be tied to a parent account", })); } - let Some(student) = - crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? + let Some(student) = crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? else { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", @@ -957,7 +951,7 @@ async fn profile_of( let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; // Both totals are the full counts, not the windowed ones — the blocks are a // preview, the stats are the truth. - let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?; + let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?; let badges = badges_of(st, id, &stats).await?; Ok(ProfileResponse { id: id.key().to_string(), @@ -1026,7 +1020,7 @@ async fn profile_of( /// callers log and swallow on purpose — leaves a gap, and that heals here on /// the next profile read of that account. /// -/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has +/// Nothing here revokes: [`crate::service::badge::sync`] only ever adds, so a counter that has /// since fallen back below its threshold leaves the badge standing. The sync's /// own error is logged and dropped, and the awards already read are served — /// a decoration may not fail the profile it decorates. @@ -1035,20 +1029,20 @@ async fn badges_of( user: &UserId, stats: &ProfileStats, ) -> Result, AppError> { - let awards = BadgeAward::list_for(user, &st.db).await?; + let awards = crate::service::badge::list_for(&st.db, user).await?; let complete = badge::earned(stats.get_totals()) .iter() .all(|id| awards.iter().any(|award| award.get_badge() == *id)); if complete { return Ok(awards); } - if let Err(err) = badge::sync(user, &st.db).await { + if let Err(err) = crate::service::badge::sync(&st.db, user).await { tracing::warn!("failed to sync badges for {}: {err}", user.key()); return Ok(awards); } // Re-read so the badge just healed appears on *this* response, stamp and // all, rather than only on the next one. - BadgeAward::list_for(user, &st.db).await + crate::service::badge::list_for(&st.db, user).await } /// The profile gate: any authenticated account reads any profile — except a @@ -1070,7 +1064,9 @@ async fn ensure_may_read_profile( async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result { let target = UserId::from_key(id); ensure_may_read_profile(caller, &target, &st.db).await?; - crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound) + crate::service::user::read(&st.db, &target) + .await? + .ok_or(AppError::NotFound) } /// The caller's own public profile — what everyone else sees of them. @@ -1165,7 +1161,15 @@ async fn upload_my_avatar( let file = ulid::Ulid::new().to_string(); store_blob(&st, &file, &upload.data, || async { - match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? { + match crate::service::user::set_avatar( + &st.db, + user.get_id(), + &file, + &upload.content_type, + size, + ) + .await? + { // Row written; the picture this one replaced comes off disk. Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), // The account went away mid-upload — the fresh blob is an orphan. diff --git a/tests/builder_api.rs b/tests/builder_api.rs index 5915c66..2496646 100644 --- a/tests/builder_api.rs +++ b/tests/builder_api.rs @@ -8,8 +8,8 @@ mod common; use axum::Router; use axum::http::StatusCode; use common::*; -use hezarfen_backend::domain::builder::Builder; use hezarfen_backend::domain::user::{Password, Username}; +use hezarfen_backend::service::builder; use hezarfen_backend::tenant::{DEMO_SLUG, Tenants}; use serde_json::{Value, json}; @@ -20,10 +20,10 @@ const BUILDER_PASS: &str = "secret1"; /// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path. async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) { let (app, db, tenants) = app_and_tenants().await; - Builder::ensure( + builder::ensure( + tenants.control(), Username::try_new(BUILDER_USER).unwrap(), Password::try_new(BUILDER_PASS).unwrap(), - tenants.control(), ) .await .expect("seed the builder"); @@ -1229,10 +1229,10 @@ async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { return; }; let app = deployment.app; - Builder::ensure( + builder::ensure( + deployment.tenants.control(), Username::try_new(BUILDER_USER).unwrap(), Password::try_new(BUILDER_PASS).unwrap(), - deployment.tenants.control(), ) .await .expect("seed the builder"); diff --git a/tests/e2e.rs b/tests/e2e.rs index a2c8d3e..45ad3a9 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -28,10 +28,10 @@ async fn spawn_server_with_ai(ai: Option) -> (St // The deployment's operator, seeded exactly as `main` does from // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable // over real TCP here too. - hezarfen_backend::domain::builder::Builder::ensure( + hezarfen_backend::service::builder::ensure( + tenants.control(), hezarfen_backend::domain::user::Username::try_new("operator").unwrap(), hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(), - tenants.control(), ) .await .expect("seed the builder"); diff --git a/tests/integration.rs b/tests/integration.rs index 65a4ac1..9ab7dd2 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -27951,10 +27951,10 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; let token_a = common::cookie_token(&a).to_string(); - hezarfen_backend::domain::builder::Builder::ensure( + hezarfen_backend::service::builder::ensure( + tenants.control(), Username::try_new("operator").unwrap(), Password::try_new("secret1").unwrap(), - tenants.control(), ) .await .expect("seed the builder"); @@ -28511,10 +28511,10 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { "the namespace holds exactly the two schools and the control database" ); - hezarfen_backend::domain::builder::Builder::ensure( + hezarfen_backend::service::builder::ensure( + d.tenants.control(), Username::try_new("operator").unwrap(), Password::try_new("secret1").unwrap(), - d.tenants.control(), ) .await .expect("seed the builder"); @@ -28824,7 +28824,7 @@ async fn a_disabled_module_refuses_its_websocket_upgrade() { // holds for *every* module, driven through the vendor's own surface, plus the // coverage test that fails when a future nest is mounted ungated. -use hezarfen_backend::domain::builder::Builder; +use hezarfen_backend::service::builder; const SWEEP_BUILDER_USER: &str = "operator"; const SWEEP_BUILDER_PASS: &str = "secret1"; @@ -28833,10 +28833,10 @@ const SWEEP_BUILDER_PASS: &str = "secret1"; /// modules by the same path production does (mirrors `tests/builder_api.rs`). async fn sweep_deployment() -> (axum::Router, hezarfen_backend::database::Database, Tenants) { let (app, db, tenants) = common::app_and_tenants().await; - Builder::ensure( + builder::ensure( + tenants.control(), Username::try_new(SWEEP_BUILDER_USER).unwrap(), Password::try_new(SWEEP_BUILDER_PASS).unwrap(), - tenants.control(), ) .await .expect("seed the builder");