Split profile, badge, builder into domain/db/service layers
Browse files at this commit7f616c02dbe04b147612fe17c3d08a611314bdc8Parent: 387eb31- chore
- split profile, badge, builder into domain/db/service layers
28 changed files +918 -788
- src/constant.rs +1 -1
- src/database.rs +1 -2
- src/db/badge.rs +369 -0
- src/db/builder.rs +108 -0
- src/db/mod.rs +3 -0
- src/db/profile.rs +197 -0
- src/domain/badge.rs +6 -347
- src/domain/builder.rs +9 -170
- src/domain/pomodoro.rs +3 -6
- src/domain/profile.rs +7 -190
- src/domain/session_attendance.rs +5 -3
- src/service/badge.rs +22 -0
- src/service/builder.rs +96 -0
- src/service/exam_attempt.rs +1 -2
- src/service/mod.rs +3 -0
- src/service/profile.rs +20 -0
- src/web/auth.rs +1 -2
- src/web/builder.rs +17 -16
- src/web/exams/mod.rs +1 -2
- src/web/extractor.rs +3 -3
- src/web/homework.rs +1 -2
- src/web/questions.rs +1 -2
- src/web/sessions.rs +1 -2
- src/web/tenant_state.rs +7 -7
- src/web/users.rs +21 -17
- tests/builder_api.rs +5 -5
- tests/e2e.rs +2 -2
- tests/integration.rs +7 -7
src/constant.rsmodified+1 -1
| @@ -1090,7 +1090,7 @@ pub const HIGH_MARK_MIN: i64 = 90; | |||
| 1090 | /// award row stores one forever. So an id is never reused for a different | 1090 | /// award row stores one forever. So an id is never reused for a different |
| 1091 | /// meaning; retiring one is done by deleting the line, and the awards that | 1091 | /// meaning; retiring one is done by deleting the line, and the awards that |
| 1092 | /// carry it simply stop being served (no data migration — | 1092 | /// carry it simply stop being served (no data migration — |
| 1093 | -/// [`crate::domain::badge::BadgeAward::list_for`] filters to the live | 1093 | +/// [`crate::db::badge::list_for`] filters to the live |
| 1094 | /// catalog). | 1094 | /// catalog). |
| 1095 | pub const BADGES: [(&str, BadgeStat, i64); 34] = [ | 1095 | pub const BADGES: [(&str, BadgeStat, i64); 34] = [ |
| 1096 | ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), | 1096 | ("homework_submitted_1", BadgeStat::HomeworkSubmitted, 1), |
src/database.rsmodified+1 -2
| @@ -6,7 +6,6 @@ use surrealdb::opt::auth::Root; | |||
| 6 | 6 | ||
| 7 | use crate::config::Config; | 7 | use crate::config::Config; |
| 8 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; | 8 | use crate::constant::{CAP_WRITE_BACKOFF_MS, CAP_WRITE_TRIES, CHATBOT_PENDING_STALE_SECS}; |
| 9 | -use crate::domain::builder::Builder; | ||
| 10 | use crate::domain::timestamp::Timestamp; | 9 | use crate::domain::timestamp::Timestamp; |
| 11 | use crate::domain::user::{Password, Username}; | 10 | use crate::domain::user::{Password, Username}; |
| 12 | use crate::error::AppError; | 11 | use crate::error::AppError; |
| @@ -49,7 +48,7 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { | |||
| 49 | let db = std::sync::Arc::new(db); | 48 | let db = std::sync::Arc::new(db); |
| 50 | migrate_control(&db).await?; | 49 | migrate_control(&db).await?; |
| 51 | if let Some((username, password)) = builder { | 50 | if let Some((username, password)) = builder { |
| 52 | - Builder::ensure(username, password, &db).await?; | 51 | + crate::service::builder::ensure(&db, username, password).await?; |
| 53 | } | 52 | } |
| 54 | Ok(Tenants::new_remote(db, cfg)) | 53 | Ok(Tenants::new_remote(db, cfg)) |
| 55 | } | 54 | } |
src/db/badge.rsadded+369 -0
| @@ -0,0 +1,369 @@ | |||
| 1 | +//! The badge counters' reads and the award rows' writes: the lifetime-counter | ||
| 2 | +//! lookup off the user row, the shelf read, and the idempotent sync that | ||
| 3 | +//! mints an award per newly earned badge. The rule deciding *which* badges | ||
| 4 | +//! those are is [`crate::domain::badge::earned`] — pure, no I/O — and the | ||
| 5 | +//! service wrappers the web layer calls live in [`crate::service::badge`]. | ||
| 6 | + | ||
| 7 | +use crate::constant::{BADGE_AWARD_TABLE, BADGES}; | ||
| 8 | +use crate::database::Database; | ||
| 9 | +use crate::domain::badge::{BadgeAward, BadgeStats}; | ||
| 10 | +use crate::domain::timestamp::Timestamp; | ||
| 11 | +use crate::domain::user::UserId; | ||
| 12 | +use crate::error::AppError; | ||
| 13 | + | ||
| 14 | +/// Every counter off the user row, in one statement — a record lookup, not | ||
| 15 | +/// a scan. | ||
| 16 | +/// | ||
| 17 | +/// Each projection is `(column ?? 0)`, parenthesized because `??` binds | ||
| 18 | +/// loosely, and it is the whole stale-data story: the columns are | ||
| 19 | +/// `option<int>`, a row written before they existed carries none of them, | ||
| 20 | +/// and absent must read as zero rather than as a null or an error. A user | ||
| 21 | +/// row that is gone entirely reads as all zeros too — a badge sync is not | ||
| 22 | +/// the place to discover a deleted account. | ||
| 23 | +pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError> { | ||
| 24 | + let mut result = db | ||
| 25 | + .query(format!( | ||
| 26 | + "SELECT ({homework_submitted} ?? 0) AS homework_submitted, | ||
| 27 | + ({homework_on_time} ?? 0) AS homework_on_time, | ||
| 28 | + ({exam_sat} ?? 0) AS exam_sat, | ||
| 29 | + ({pomodoro_finished} ?? 0) AS pomodoro_finished, | ||
| 30 | + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, | ||
| 31 | + ({marks_given} ?? 0) AS marks_given, | ||
| 32 | + ({lessons_held} ?? 0) AS lessons_held, | ||
| 33 | + ({pool_approved} ?? 0) AS pool_approved, | ||
| 34 | + ({pool_published} ?? 0) AS pool_published, | ||
| 35 | + ({lessons_attended} ?? 0) AS lessons_attended, | ||
| 36 | + ({high_mark} ?? 0) AS high_mark, | ||
| 37 | + ({study_streak} ?? 0) AS study_streak | ||
| 38 | + FROM $usr", | ||
| 39 | + homework_submitted = crate::domain::badge::BadgeStat::HomeworkSubmitted.field(), | ||
| 40 | + homework_on_time = crate::domain::badge::BadgeStat::HomeworkOnTime.field(), | ||
| 41 | + exam_sat = crate::domain::badge::BadgeStat::ExamSat.field(), | ||
| 42 | + pomodoro_finished = crate::domain::badge::BadgeStat::PomodoroFinished.field(), | ||
| 43 | + pomodoro_focus_ms = crate::domain::badge::BadgeStat::PomodoroFocusMs.field(), | ||
| 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 | +} | ||
| 61 | + | ||
| 62 | +/// Everything `user` has earned, oldest first. | ||
| 63 | +/// | ||
| 64 | +/// Filtered to the ids the catalog still holds: a badge retired from | ||
| 65 | +/// `BADGES` stops being served without a data migration, and its rows stay | ||
| 66 | +/// where they are in case the line comes back. | ||
| 67 | +/// | ||
| 68 | +/// The badge id breaks the tie, because one sync stamps every badge it | ||
| 69 | +/// 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 order | ||
| 71 | +/// too — the key is `{user}_{badge}` and this reads one user — but spelled | ||
| 72 | +/// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by | ||
| 73 | +/// an idiom the selection does not carry ("Missing order idiom `id` in | ||
| 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> { | ||
| 76 | + let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); | ||
| 77 | + let mut result = db | ||
| 78 | + .query(format!( | ||
| 79 | + "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} | ||
| 80 | + WHERE user = $usr AND badge IN $ids | ||
| 81 | + ORDER BY earned_at ASC, badge ASC LIMIT {}", | ||
| 82 | + BADGES.len() | ||
| 83 | + )) | ||
| 84 | + .bind(("usr", user.record())) | ||
| 85 | + .bind(("ids", ids)) | ||
| 86 | + .await? | ||
| 87 | + .check()?; | ||
| 88 | + Ok(result.take::<Vec<BadgeAward>>(0)?) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// The record one (user, badge) pair always maps to, so a second [`sync`] | ||
| 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 | +} | ||
| 97 | + | ||
| 98 | +/// Write an award row for every badge `user` has now earned and does not | ||
| 99 | +/// already hold. | ||
| 100 | +/// | ||
| 101 | +/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the | ||
| 102 | +/// whole of the idempotency: the first call creates the row, and every later | ||
| 103 | +/// call — with a later `$now` — matches a row that already has a stamp and | ||
| 104 | +/// writes nothing at all. So the earned-at a student sees is when they first | ||
| 105 | +/// crossed the line, not when the counter last moved. | ||
| 106 | +/// | ||
| 107 | +/// **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 none | ||
| 109 | +/// 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 the | ||
| 111 | +/// 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. | ||
| 113 | +pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 114 | + let stats = load(db, user).await?; | ||
| 115 | + let earned = crate::domain::badge::earned(&stats); | ||
| 116 | + if earned.is_empty() { | ||
| 117 | + return Ok(()); | ||
| 118 | + } | ||
| 119 | + let mut sql = String::new(); | ||
| 120 | + for index in 0..earned.len() { | ||
| 121 | + sql.push_str(&format!( | ||
| 122 | + "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, | ||
| 123 | + earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" | ||
| 124 | + )); | ||
| 125 | + } | ||
| 126 | + let mut query = db | ||
| 127 | + .query(sql) | ||
| 128 | + .bind(("table", BADGE_AWARD_TABLE)) | ||
| 129 | + .bind(("usr", user.record())) | ||
| 130 | + .bind(("now", Timestamp::now())); | ||
| 131 | + for (index, badge) in earned.iter().enumerate() { | ||
| 132 | + query = query | ||
| 133 | + .bind((format!("key{index}"), award_key(user, badge))) | ||
| 134 | + .bind((format!("badge{index}"), badge.to_string())); | ||
| 135 | + } | ||
| 136 | + query.await?.check()?; | ||
| 137 | + Ok(()) | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +#[cfg(test)] | ||
| 141 | +mod tests { | ||
| 142 | + use super::{award_key, list_for, load, sync}; | ||
| 143 | + use crate::constant::{ | ||
| 144 | + BADGE_AWARD_TABLE, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, | ||
| 145 | + HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, | ||
| 146 | + LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, | ||
| 147 | + POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, | ||
| 148 | + STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, | ||
| 149 | + }; | ||
| 150 | + use crate::database::Database; | ||
| 151 | + use crate::domain::badge::earned; | ||
| 152 | + use crate::domain::user::UserId; | ||
| 153 | + | ||
| 154 | + /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled | ||
| 155 | + /// with the same `IF NOT EXISTS` guards the migration uses, so it is a | ||
| 156 | + /// no-op once the real definitions land next to it. | ||
| 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 | + .await | ||
| 180 | + .unwrap() | ||
| 181 | + .check() | ||
| 182 | + .unwrap(); | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + /// A user row carrying `counters`, by column name. | ||
| 186 | + async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { | ||
| 187 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 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 | + )) | ||
| 200 | + .bind(("usr", user.record())) | ||
| 201 | + .bind(("name", user.key().to_string())) | ||
| 202 | + .await | ||
| 203 | + .unwrap() | ||
| 204 | + .check() | ||
| 205 | + .unwrap(); | ||
| 206 | + user | ||
| 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 | + } | ||
| 223 | + | ||
| 224 | + #[tokio::test] | ||
| 225 | + async fn a_row_without_the_columns_loads_as_zeros() { | ||
| 226 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 227 | + schema(&db).await; | ||
| 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 | + } | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + #[tokio::test] | ||
| 249 | + async fn a_second_sync_does_not_move_the_stamp() { | ||
| 250 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 251 | + schema(&db).await; | ||
| 252 | + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; | ||
| 253 | + | ||
| 254 | + sync(&db, &user).await.unwrap(); | ||
| 255 | + let first = stamps(&user, &db).await; | ||
| 256 | + assert_eq!(first.len(), 1, "{first:?}"); | ||
| 257 | + assert_eq!(first[0].0, "homework_submitted_1"); | ||
| 258 | + | ||
| 259 | + // A later sync, provably at a later millisecond: the row must keep the | ||
| 260 | + // instant the badge was *first* earned, and must not be doubled. | ||
| 261 | + tokio::time::sleep(std::time::Duration::from_millis(5)).await; | ||
| 262 | + sync(&db, &user).await.unwrap(); | ||
| 263 | + assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + #[tokio::test] | ||
| 267 | + async fn an_award_survives_a_counter_that_falls_back_below_it() { | ||
| 268 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 269 | + schema(&db).await; | ||
| 270 | + let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; | ||
| 271 | + sync(&db, &user).await.unwrap(); | ||
| 272 | + assert_eq!( | ||
| 273 | + stamps(&user, &db).await.len(), | ||
| 274 | + 2, | ||
| 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 | + .await | ||
| 320 | + .unwrap() | ||
| 321 | + .check() | ||
| 322 | + .unwrap(); | ||
| 323 | + | ||
| 324 | + let served: Vec<String> = stamps(&user, &db) | ||
| 325 | + .await | ||
| 326 | + .into_iter() | ||
| 327 | + .map(|(badge, _)| badge) | ||
| 328 | + .collect(); | ||
| 329 | + assert_eq!(served, vec!["exam_sat_1"]); | ||
| 330 | + let mut rows = db | ||
| 331 | + .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) | ||
| 332 | + .await | ||
| 333 | + .unwrap(); | ||
| 334 | + assert_eq!(rows.take::<Vec<String>>(0).unwrap().len(), 2, "both stored"); | ||
| 335 | + } | ||
| 336 | + | ||
| 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] | ||
| 340 | + async fn same_millisecond_awards_come_back_in_badge_order() { | ||
| 341 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 342 | + schema(&db).await; | ||
| 343 | + let user = a_user( | ||
| 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!( | ||
| 356 | + ids, | ||
| 357 | + vec![ | ||
| 358 | + "exam_sat_1", | ||
| 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 | + ); | ||
| 368 | + } | ||
| 369 | +} | ||
src/db/builder.rsadded+108 -0
| @@ -0,0 +1,108 @@ | |||
| 1 | +//! The builder tables against the **control** database: the account lookup | ||
| 2 | +//! and row insert, and the login sessions keyed by cookie token. The | ||
| 3 | +//! credential newtypes are [`crate::domain::user`]'s; the seed workflow that | ||
| 4 | +//! decides whether an account exists is [`crate::service::builder::ensure`]. | ||
| 5 | + | ||
| 6 | +use surrealdb::types::RecordId; | ||
| 7 | +use ulid::Ulid; | ||
| 8 | + | ||
| 9 | +use crate::constant::SESSION_DURATION_DAYS; | ||
| 10 | +use crate::database::Database; | ||
| 11 | +use crate::domain::builder::{BUILDER_SESSION_TABLE, Builder, BuilderId, BuilderSession}; | ||
| 12 | +use crate::domain::session::SessionToken; | ||
| 13 | +use crate::domain::timestamp::Timestamp; | ||
| 14 | +use crate::error::AppError; | ||
| 15 | + | ||
| 16 | +pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Builder>, AppError> { | ||
| 17 | + let mut result = db | ||
| 18 | + .query("SELECT * FROM builder WHERE username = $u LIMIT 1") | ||
| 19 | + .bind(("u", username.trim().to_string())) | ||
| 20 | + .await? | ||
| 21 | + .check()?; | ||
| 22 | + Ok(result.take::<Vec<Builder>>(0)?.into_iter().next()) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppError> { | ||
| 26 | + Ok(db.select(id.record()).await?) | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/// The raw account insert behind [`crate::service::builder::ensure`]'s seed. | ||
| 30 | +pub async fn create(db: &Database, builder: Builder) -> Result<(), AppError> { | ||
| 31 | + let created: Option<Builder> = db | ||
| 32 | + .create(builder.get_id().record()) | ||
| 33 | + .content(builder.clone()) | ||
| 34 | + .await?; | ||
| 35 | + created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; | ||
| 36 | + Ok(()) | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// Mint and store one builder login session. | ||
| 40 | +pub async fn create_session( | ||
| 41 | + db: &Database, | ||
| 42 | + builder: &BuilderId, | ||
| 43 | +) -> Result<BuilderSession, AppError> { | ||
| 44 | + let key = RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()); | ||
| 45 | + let session = BuilderSession { | ||
| 46 | + id: key.clone(), | ||
| 47 | + builder: builder.clone(), | ||
| 48 | + token: SessionToken::generate()?, | ||
| 49 | + created_at: Timestamp::now(), | ||
| 50 | + expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), | ||
| 51 | + }; | ||
| 52 | + let created: Option<BuilderSession> = db.create(key).content(session).await?; | ||
| 53 | + created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<BuilderSession>, AppError> { | ||
| 57 | + let mut result = db | ||
| 58 | + .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") | ||
| 59 | + .bind(("tok", token.to_string())) | ||
| 60 | + .await? | ||
| 61 | + .check()?; | ||
| 62 | + Ok(result.take::<Vec<BuilderSession>>(0)?.into_iter().next()) | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { | ||
| 66 | + db.query("DELETE builder_session WHERE token = $tok") | ||
| 67 | + .bind(("tok", token.to_string())) | ||
| 68 | + .await? | ||
| 69 | + .check()?; | ||
| 70 | + Ok(()) | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +#[cfg(test)] | ||
| 74 | +mod tests { | ||
| 75 | + use super::{create_session, delete_by_token, find_by_token, find_by_username}; | ||
| 76 | + use crate::domain::user::{Password, Username}; | ||
| 77 | + use crate::service::builder; | ||
| 78 | + use crate::tenant::Tenants; | ||
| 79 | + | ||
| 80 | + #[tokio::test] | ||
| 81 | + async fn a_builder_session_round_trips_and_deletes() { | ||
| 82 | + let tenants = Tenants::new_mem().await.unwrap(); | ||
| 83 | + let control = tenants.control(); | ||
| 84 | + builder::ensure( | ||
| 85 | + control, | ||
| 86 | + Username::try_new("builder1").unwrap(), | ||
| 87 | + Password::try_new("secret1").unwrap(), | ||
| 88 | + ) | ||
| 89 | + .await | ||
| 90 | + .unwrap(); | ||
| 91 | + let builder = find_by_username(control, "builder1") | ||
| 92 | + .await | ||
| 93 | + .unwrap() | ||
| 94 | + .unwrap(); | ||
| 95 | + | ||
| 96 | + let session = create_session(control, builder.get_id()).await.unwrap(); | ||
| 97 | + let token = session.token().as_str().to_string(); | ||
| 98 | + let found = find_by_token(control, &token) | ||
| 99 | + .await | ||
| 100 | + .unwrap() | ||
| 101 | + .expect("found by token"); | ||
| 102 | + assert_eq!(found.builder(), builder.get_id()); | ||
| 103 | + assert!(!found.is_expired()); | ||
| 104 | + | ||
| 105 | + delete_by_token(control, &token).await.unwrap(); | ||
| 106 | + assert!(find_by_token(control, &token).await.unwrap().is_none()); | ||
| 107 | + } | ||
| 108 | +} | ||
src/db/mod.rsmodified+3 -0
| @@ -2,6 +2,8 @@ | |||
| 2 | 2 | ||
| 3 | pub mod appointment; | 3 | pub mod appointment; |
| 4 | pub mod appointment_slot; | 4 | pub mod appointment_slot; |
| 5 | +pub mod badge; | ||
| 6 | +pub mod builder; | ||
| 5 | pub mod cap; | 7 | pub mod cap; |
| 6 | pub mod class_blueprint; | 8 | pub mod class_blueprint; |
| 7 | pub mod course; | 9 | pub mod course; |
| @@ -15,6 +17,7 @@ pub mod meal_booking; | |||
| 15 | pub mod note; | 17 | pub mod note; |
| 16 | pub mod page; | 18 | pub mod page; |
| 17 | pub mod payment_ledger; | 19 | pub mod payment_ledger; |
| 20 | +pub mod profile; | ||
| 18 | pub mod session; | 21 | pub mod session; |
| 19 | pub mod settings; | 22 | pub mod settings; |
| 20 | pub mod user; | 23 | pub mod user; |
src/db/profile.rsadded+197 -0
| @@ -0,0 +1,197 @@ | |||
| 1 | +//! The profile's motivational stats: the one aggregate read behind a profile | ||
| 2 | +//! response. The counters themselves are [`crate::domain::profile`]'s; the | ||
| 3 | +//! auto-earned badge rules next door are [`crate::domain::badge`] (pure) and | ||
| 4 | +//! [`crate::db::badge`] (reads and writes). | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::domain::badge::{BadgeStat, BadgeStats}; | ||
| 8 | +use crate::domain::profile::ProfileStats; | ||
| 9 | +use crate::domain::user::UserId; | ||
| 10 | +use crate::error::AppError; | ||
| 11 | +use surrealdb::types::SurrealValue; | ||
| 12 | + | ||
| 13 | +/// 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 and | ||
| 15 | +/// course readers it ran for the profile's own blocks — re-counting them | ||
| 16 | +/// here would be two extra reads for numbers already in hand. | ||
| 17 | +/// | ||
| 18 | +/// 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: a | ||
| 20 | +/// bare truthiness test would also drop a stint that finished at epoch. An | ||
| 21 | +/// open stint contributes to neither the count nor the sum — unfinished | ||
| 22 | +/// focus has no honest duration to add. | ||
| 23 | +/// | ||
| 24 | +/// 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 second | ||
| 26 | +/// round trip for one record lookup. It repeats that projection — `?? 0` | ||
| 27 | +/// per column, because the columns are `option<int>` and a row predating | ||
| 28 | +/// them carries none — so the two must move together if the shape changes. | ||
| 29 | +pub async fn load( | ||
| 30 | + db: &Database, | ||
| 31 | + user: &UserId, | ||
| 32 | + courses: i64, | ||
| 33 | + classes: i64, | ||
| 34 | +) -> Result<ProfileStats, AppError> { | ||
| 35 | + let mut result = db | ||
| 36 | + .query(format!( | ||
| 37 | + "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms | ||
| 38 | + FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; | ||
| 39 | + SELECT ({homework_submitted} ?? 0) AS homework_submitted, | ||
| 40 | + ({homework_on_time} ?? 0) AS homework_on_time, | ||
| 41 | + ({exam_sat} ?? 0) AS exam_sat, | ||
| 42 | + ({pomodoro_finished} ?? 0) AS pomodoro_finished, | ||
| 43 | + ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, | ||
| 44 | + ({marks_given} ?? 0) AS marks_given, | ||
| 45 | + ({lessons_held} ?? 0) AS lessons_held, | ||
| 46 | + ({pool_approved} ?? 0) AS pool_approved, | ||
| 47 | + ({pool_published} ?? 0) AS pool_published, | ||
| 48 | + ({lessons_attended} ?? 0) AS lessons_attended, | ||
| 49 | + ({high_mark} ?? 0) AS high_mark, | ||
| 50 | + ({study_streak} ?? 0) AS study_streak | ||
| 51 | + FROM $usr;", | ||
| 52 | + homework_submitted = BadgeStat::HomeworkSubmitted.field(), | ||
| 53 | + homework_on_time = BadgeStat::HomeworkOnTime.field(), | ||
| 54 | + exam_sat = BadgeStat::ExamSat.field(), | ||
| 55 | + pomodoro_finished = BadgeStat::PomodoroFinished.field(), | ||
| 56 | + pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), | ||
| 57 | + marks_given = BadgeStat::MarksGiven.field(), | ||
| 58 | + lessons_held = BadgeStat::LessonsHeld.field(), | ||
| 59 | + pool_approved = BadgeStat::PoolApproved.field(), | ||
| 60 | + pool_published = BadgeStat::PoolPublished.field(), | ||
| 61 | + lessons_attended = BadgeStat::LessonsAttended.field(), | ||
| 62 | + high_mark = BadgeStat::HighMark.field(), | ||
| 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 { | ||
| 78 | + totals, | ||
| 79 | + pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), | ||
| 80 | + // Floored at zero: a stint stamped by a wall clock that stepped | ||
| 81 | + // backwards mid-session sums as negative time, and "you focused for | ||
| 82 | + // minus five seconds" is never the truthful answer. New stints | ||
| 83 | + // cannot go inverted (see [`PomodoroSession::finish`]); rows written | ||
| 84 | + // 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)), | ||
| 86 | + courses, | ||
| 87 | + classes, | ||
| 88 | + }) | ||
| 89 | +} | ||
| 90 | + | ||
| 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)] | ||
| 99 | +mod tests { | ||
| 100 | + use super::*; | ||
| 101 | + | ||
| 102 | + #[tokio::test] | ||
| 103 | + async fn stats_are_zero_without_pomodoro_rows() { | ||
| 104 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 105 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 106 | + | ||
| 107 | + let stats = load(&db, &user, 3, 1).await.unwrap(); | ||
| 108 | + // Derived counters: no rows is a true zero, never a null. | ||
| 109 | + assert_eq!(stats.get_pomodoro_sessions(), 0); | ||
| 110 | + assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 111 | + // The passed-in counts survive untouched. | ||
| 112 | + assert_eq!(stats.get_courses(), 3); | ||
| 113 | + assert_eq!(stats.get_classes(), 1); | ||
| 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 | + } | ||
| 118 | + | ||
| 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] | ||
| 122 | + async fn lifetime_totals_ride_the_same_query() { | ||
| 123 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 124 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 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 | + | ||
| 138 | + let totals = load(&db, &user, 0, 0).await.unwrap(); | ||
| 139 | + let totals = totals.get_totals(); | ||
| 140 | + assert_eq!(totals.get_homework_submitted(), 4); | ||
| 141 | + assert_eq!(totals.get_exam_sat(), 3); | ||
| 142 | + // Never written on this row: absent must read as 0, not as an error. | ||
| 143 | + assert_eq!(totals.get_homework_on_time(), 0); | ||
| 144 | + assert_eq!(totals.get_pomodoro_finished(), 0); | ||
| 145 | + assert_eq!(totals.get_pomodoro_focus_ms(), 0); | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + #[tokio::test] | ||
| 149 | + async fn stats_count_finished_stints_only() { | ||
| 150 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 151 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 152 | + let other = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 153 | + | ||
| 154 | + // Two finished stints (1000 ms + 2500 ms), one still running, and one | ||
| 155 | + // finished stint belonging to somebody else. | ||
| 156 | + db.query( | ||
| 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 | + ) | ||
| 162 | + .bind(("usr", user.record())) | ||
| 163 | + .bind(("oth", other.record())) | ||
| 164 | + .await | ||
| 165 | + .unwrap() | ||
| 166 | + .check() | ||
| 167 | + .unwrap(); | ||
| 168 | + | ||
| 169 | + let stats = load(&db, &user, 0, 0).await.unwrap(); | ||
| 170 | + assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 171 | + assert_eq!(stats.get_pomodoro_focus_ms(), 3500); | ||
| 172 | + } | ||
| 173 | + | ||
| 174 | + #[tokio::test] | ||
| 175 | + async fn focus_time_never_reads_negative() { | ||
| 176 | + let db = crate::database::init_mem().await.unwrap(); | ||
| 177 | + let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 178 | + | ||
| 179 | + // One honest 1000 ms stint and one inverted row — what a backwards | ||
| 180 | + // clock step left behind before `finish` grew its floor. The raw sum is | ||
| 181 | + // -5000; the profile must still answer a duration, not an accusation. | ||
| 182 | + db.query( | ||
| 183 | + "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; | ||
| 184 | + CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", | ||
| 185 | + ) | ||
| 186 | + .bind(("usr", user.record())) | ||
| 187 | + .await | ||
| 188 | + .unwrap() | ||
| 189 | + .check() | ||
| 190 | + .unwrap(); | ||
| 191 | + | ||
| 192 | + let stats = load(&db, &user, 0, 0).await.unwrap(); | ||
| 193 | + // The stints still happened, so the count is honest at 2. | ||
| 194 | + assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 195 | + assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 196 | + } | ||
| 197 | +} | ||
src/domain/badge.rsmodified+6 -347
| @@ -3,7 +3,8 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! Three properties hold here and nowhere else: | 4 | //! Three properties hold here and nowhere else: |
| 5 | //! | 5 | //! |
| 6 | -//! - **Auto-earned only.** No route awards a badge; [`sync`] is called after | 6 | +//! - **Auto-earned only.** No route awards a badge; [`crate::db::badge::sync`] |
| 7 | +//! is called after | ||
| 7 | //! the writes that move a counter, and that is the only way a row appears. | 8 | //! the writes that move a counter, and that is the only way a row appears. |
| 8 | //! - **Permanent.** Nothing in this file deletes or revokes an award. A | 9 | //! - **Permanent.** Nothing in this file deletes or revokes an award. A |
| 9 | //! counter that later drops below the threshold — a submission withdrawn, | 10 | //! counter that later drops below the threshold — a submission withdrawn, |
| @@ -16,16 +17,12 @@ | |||
| 16 | use surrealdb::types::SurrealValue; | 17 | use surrealdb::types::SurrealValue; |
| 17 | 18 | ||
| 18 | use crate::constant::{ | 19 | use crate::constant::{ |
| 19 | - BADGE_AWARD_TABLE, BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, | 20 | + BADGES, EXAM_SAT_TOTAL_FIELD, HIGH_MARK_TOTAL_FIELD, HOMEWORK_ON_TIME_TOTAL_FIELD, |
| 20 | - HOMEWORK_ON_TIME_TOTAL_FIELD, HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, | 21 | + HOMEWORK_SUBMITTED_TOTAL_FIELD, LESSONS_ATTENDED_TOTAL_FIELD, LESSONS_HELD_TOTAL_FIELD, |
| 21 | - LESSONS_HELD_TOTAL_FIELD, MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, | 22 | + MARKS_GIVEN_TOTAL_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, |
| 22 | - POMODORO_FOCUS_MS_TOTAL_FIELD, POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, | 23 | + POOL_APPROVED_TOTAL_FIELD, POOL_PUBLISHED_TOTAL_FIELD, STUDY_STREAK_LONGEST_FIELD, |
| 23 | - STUDY_STREAK_LONGEST_FIELD, | ||
| 24 | }; | 24 | }; |
| 25 | -use crate::database::Database; | ||
| 26 | use crate::domain::timestamp::Timestamp; | 25 | use crate::domain::timestamp::Timestamp; |
| 27 | -use crate::domain::user::UserId; | ||
| 28 | -use crate::error::AppError; | ||
| 29 | 26 | ||
| 30 | /// The counter a badge family reads. One variant per column, and the enum is | 27 | /// The counter a badge family reads. One variant per column, and the enum is |
| 31 | /// what ties a catalog line to a real number: a family added here cannot be | 28 | /// what ties a catalog line to a real number: a family added here cannot be |
| @@ -166,54 +163,6 @@ impl BadgeStats { | |||
| 166 | pub fn get_study_streak(&self) -> i64 { | 163 | pub fn get_study_streak(&self) -> i64 { |
| 167 | self.study_streak | 164 | self.study_streak |
| 168 | } | 165 | } |
| 169 | - | ||
| 170 | - /// Every counter off the user row, in one statement — a record lookup, not | ||
| 171 | - /// a scan. | ||
| 172 | - /// | ||
| 173 | - /// Each projection is `(column ?? 0)`, parenthesized because `??` binds | ||
| 174 | - /// loosely, and it is the whole stale-data story: the columns are | ||
| 175 | - /// `option<int>`, a row written before they existed carries none of them, | ||
| 176 | - /// and absent must read as zero rather than as a null or an error. A user | ||
| 177 | - /// row that is gone entirely reads as all zeros too — a badge sync is not | ||
| 178 | - /// the place to discover a deleted account. | ||
| 179 | - pub async fn load(user: &UserId, db: &Database) -> Result<BadgeStats, AppError> { | ||
| 180 | - let mut result = db | ||
| 181 | - .query(format!( | ||
| 182 | - "SELECT ({homework_submitted} ?? 0) AS homework_submitted, | ||
| 183 | - ({homework_on_time} ?? 0) AS homework_on_time, | ||
| 184 | - ({exam_sat} ?? 0) AS exam_sat, | ||
| 185 | - ({pomodoro_finished} ?? 0) AS pomodoro_finished, | ||
| 186 | - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, | ||
| 187 | - ({marks_given} ?? 0) AS marks_given, | ||
| 188 | - ({lessons_held} ?? 0) AS lessons_held, | ||
| 189 | - ({pool_approved} ?? 0) AS pool_approved, | ||
| 190 | - ({pool_published} ?? 0) AS pool_published, | ||
| 191 | - ({lessons_attended} ?? 0) AS lessons_attended, | ||
| 192 | - ({high_mark} ?? 0) AS high_mark, | ||
| 193 | - ({study_streak} ?? 0) AS study_streak | ||
| 194 | - FROM $usr", | ||
| 195 | - homework_submitted = BadgeStat::HomeworkSubmitted.field(), | ||
| 196 | - homework_on_time = BadgeStat::HomeworkOnTime.field(), | ||
| 197 | - exam_sat = BadgeStat::ExamSat.field(), | ||
| 198 | - pomodoro_finished = BadgeStat::PomodoroFinished.field(), | ||
| 199 | - pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), | ||
| 200 | - marks_given = BadgeStat::MarksGiven.field(), | ||
| 201 | - lessons_held = BadgeStat::LessonsHeld.field(), | ||
| 202 | - pool_approved = BadgeStat::PoolApproved.field(), | ||
| 203 | - pool_published = BadgeStat::PoolPublished.field(), | ||
| 204 | - lessons_attended = BadgeStat::LessonsAttended.field(), | ||
| 205 | - high_mark = BadgeStat::HighMark.field(), | ||
| 206 | - study_streak = BadgeStat::StudyStreak.field(), | ||
| 207 | - )) | ||
| 208 | - .bind(("usr", user.record())) | ||
| 209 | - .await? | ||
| 210 | - .check()?; | ||
| 211 | - Ok(result | ||
| 212 | - .take::<Vec<BadgeStats>>(0)? | ||
| 213 | - .into_iter() | ||
| 214 | - .next() | ||
| 215 | - .unwrap_or_default()) | ||
| 216 | - } | ||
| 217 | } | 166 | } |
| 218 | 167 | ||
| 219 | /// The ids of every badge `stats` has earned — the whole rule, and pure: no | 168 | /// 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> { | |||
| 246 | .collect() | 195 | .collect() |
| 247 | } | 196 | } |
| 248 | 197 | ||
| 249 | -/// The record one (user, badge) pair always maps to, so a second [`sync`] | ||
| 250 | -/// resolves onto the row the first one wrote instead of minting a duplicate. | ||
| 251 | -/// A user key is a ULID (alphanumeric), so `_` cannot make two pairs collide. | ||
| 252 | -fn award_key(user: &UserId, badge: &str) -> String { | ||
| 253 | - format!("{}_{badge}", user.key()) | ||
| 254 | -} | ||
| 255 | - | ||
| 256 | /// One badge one user has earned, and when. | 198 | /// One badge one user has earned, and when. |
| 257 | #[derive(Debug, Clone, SurrealValue)] | 199 | #[derive(Debug, Clone, SurrealValue)] |
| 258 | pub struct BadgeAward { | 200 | pub struct BadgeAward { |
| @@ -268,148 +210,11 @@ impl BadgeAward { | |||
| 268 | pub fn get_earned_at(&self) -> Timestamp { | 210 | pub fn get_earned_at(&self) -> Timestamp { |
| 269 | self.earned_at | 211 | self.earned_at |
| 270 | } | 212 | } |
| 271 | - | ||
| 272 | - /// Everything `user` has earned, oldest first. | ||
| 273 | - /// | ||
| 274 | - /// Filtered to the ids the catalog still holds: a badge retired from | ||
| 275 | - /// `BADGES` stops being served without a data migration, and its rows stay | ||
| 276 | - /// where they are in case the line comes back. | ||
| 277 | - /// | ||
| 278 | - /// The badge id breaks the tie, because one sync stamps every badge it | ||
| 279 | - /// awards with the same millisecond and an arbitrary order there would | ||
| 280 | - /// shuffle a student's shelf between reads. It is the record id's order | ||
| 281 | - /// too — the key is `{user}_{badge}` and this reads one user — but spelled | ||
| 282 | - /// as the projected column on purpose: SurrealDB 3.2.3 refuses to sort by | ||
| 283 | - /// an idiom the selection does not carry ("Missing order idiom `id` in | ||
| 284 | - /// statement selection"), and `id` is not a field of an award. | ||
| 285 | - pub async fn list_for(user: &UserId, db: &Database) -> Result<Vec<BadgeAward>, AppError> { | ||
| 286 | - let ids: Vec<&str> = BADGES.iter().map(|(id, ..)| *id).collect(); | ||
| 287 | - let mut result = db | ||
| 288 | - .query(format!( | ||
| 289 | - "SELECT badge, earned_at FROM {BADGE_AWARD_TABLE} | ||
| 290 | - WHERE user = $usr AND badge IN $ids | ||
| 291 | - ORDER BY earned_at ASC, badge ASC LIMIT {}", | ||
| 292 | - BADGES.len() | ||
| 293 | - )) | ||
| 294 | - .bind(("usr", user.record())) | ||
| 295 | - .bind(("ids", ids)) | ||
| 296 | - .await? | ||
| 297 | - .check()?; | ||
| 298 | - Ok(result.take::<Vec<BadgeAward>>(0)?) | ||
| 299 | - } | ||
| 300 | -} | ||
| 301 | - | ||
| 302 | -/// Write an award row for every badge `user` has now earned and does not | ||
| 303 | -/// already hold. | ||
| 304 | -/// | ||
| 305 | -/// The `WHERE earned_at = NONE` on an `UPSERT` of the pair's own key is the | ||
| 306 | -/// whole of the idempotency: the first call creates the row, and every later | ||
| 307 | -/// call — with a later `$now` — matches a row that already has a stamp and | ||
| 308 | -/// writes nothing at all. So the earned-at a student sees is when they first | ||
| 309 | -/// crossed the line, not when the counter last moved. | ||
| 310 | -/// | ||
| 311 | -/// **Callers must log and ignore the error.** A badge is a decoration on top | ||
| 312 | -/// of somebody's homework submission, exam sitting or pomodoro stint, and none | ||
| 313 | -/// of those may fail because the decoration could not be written. The `Result` | ||
| 314 | -/// is returned rather than swallowed here so the caller's log line names the | ||
| 315 | -/// real cause; the next counter bump re-runs this and heals whatever was | ||
| 316 | -/// missed, which is also why a lost write race needs no retry loop. | ||
| 317 | -pub async fn sync(user: &UserId, db: &Database) -> Result<(), AppError> { | ||
| 318 | - let stats = BadgeStats::load(user, db).await?; | ||
| 319 | - let earned = earned(&stats); | ||
| 320 | - if earned.is_empty() { | ||
| 321 | - return Ok(()); | ||
| 322 | - } | ||
| 323 | - let mut sql = String::new(); | ||
| 324 | - for index in 0..earned.len() { | ||
| 325 | - sql.push_str(&format!( | ||
| 326 | - "UPSERT type::record($table, $key{index}) SET user = $usr, badge = $badge{index}, | ||
| 327 | - earned_at = $now WHERE earned_at = NONE RETURN AFTER;\n" | ||
| 328 | - )); | ||
| 329 | - } | ||
| 330 | - let mut query = db | ||
| 331 | - .query(sql) | ||
| 332 | - .bind(("table", BADGE_AWARD_TABLE)) | ||
| 333 | - .bind(("usr", user.record())) | ||
| 334 | - .bind(("now", Timestamp::now())); | ||
| 335 | - for (index, badge) in earned.iter().enumerate() { | ||
| 336 | - query = query | ||
| 337 | - .bind((format!("key{index}"), award_key(user, badge))) | ||
| 338 | - .bind((format!("badge{index}"), badge.to_string())); | ||
| 339 | - } | ||
| 340 | - query.await?.check()?; | ||
| 341 | - Ok(()) | ||
| 342 | } | 213 | } |
| 343 | 214 | ||
| 344 | #[cfg(test)] | 215 | #[cfg(test)] |
| 345 | mod tests { | 216 | mod tests { |
| 346 | use super::*; | 217 | use super::*; |
| 347 | - use crate::constant::{STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD}; | ||
| 348 | - | ||
| 349 | - /// The schema these rows need, which `src/migration_sql.rs` owns. Spelled | ||
| 350 | - /// with the same `IF NOT EXISTS` guards the migration uses, so it is a | ||
| 351 | - /// no-op once the real definitions land next to it. | ||
| 352 | - async fn schema(db: &Database) { | ||
| 353 | - db.query(format!( | ||
| 354 | - "DEFINE FIELD IF NOT EXISTS {HOMEWORK_SUBMITTED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 355 | - DEFINE FIELD IF NOT EXISTS {HOMEWORK_ON_TIME_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 356 | - DEFINE FIELD IF NOT EXISTS {EXAM_SAT_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 357 | - DEFINE FIELD IF NOT EXISTS {POMODORO_FINISHED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 358 | - DEFINE FIELD IF NOT EXISTS {POMODORO_FOCUS_MS_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 359 | - DEFINE FIELD IF NOT EXISTS {MARKS_GIVEN_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 360 | - DEFINE FIELD IF NOT EXISTS {LESSONS_HELD_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 361 | - DEFINE FIELD IF NOT EXISTS {POOL_APPROVED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 362 | - DEFINE FIELD IF NOT EXISTS {POOL_PUBLISHED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 363 | - DEFINE FIELD IF NOT EXISTS {LESSONS_ATTENDED_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 364 | - DEFINE FIELD IF NOT EXISTS {HIGH_MARK_TOTAL_FIELD} ON user TYPE option<int>; | ||
| 365 | - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LONGEST_FIELD} ON user TYPE option<int>; | ||
| 366 | - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_CURRENT_FIELD} ON user TYPE option<int>; | ||
| 367 | - DEFINE FIELD IF NOT EXISTS {STUDY_STREAK_LAST_DAY_FIELD} ON user TYPE option<int>; | ||
| 368 | - DEFINE TABLE IF NOT EXISTS {BADGE_AWARD_TABLE} SCHEMAFULL; | ||
| 369 | - DEFINE FIELD IF NOT EXISTS user ON {BADGE_AWARD_TABLE} TYPE record<user>; | ||
| 370 | - DEFINE FIELD IF NOT EXISTS badge ON {BADGE_AWARD_TABLE} TYPE string; | ||
| 371 | - DEFINE FIELD IF NOT EXISTS earned_at ON {BADGE_AWARD_TABLE} TYPE option<int>; | ||
| 372 | - DEFINE INDEX IF NOT EXISTS badge_award_user ON {BADGE_AWARD_TABLE} FIELDS user;" | ||
| 373 | - )) | ||
| 374 | - .await | ||
| 375 | - .unwrap() | ||
| 376 | - .check() | ||
| 377 | - .unwrap(); | ||
| 378 | - } | ||
| 379 | - | ||
| 380 | - /// A user row carrying `counters`, by column name. | ||
| 381 | - async fn a_user(counters: &[(&str, i64)], db: &Database) -> UserId { | ||
| 382 | - let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 383 | - let sets: Vec<String> = counters | ||
| 384 | - .iter() | ||
| 385 | - .map(|(field, value)| format!("{field} = {value}")) | ||
| 386 | - .collect(); | ||
| 387 | - let extra = if sets.is_empty() { | ||
| 388 | - String::new() | ||
| 389 | - } else { | ||
| 390 | - format!(", {}", sets.join(", ")) | ||
| 391 | - }; | ||
| 392 | - db.query(format!( | ||
| 393 | - "CREATE $usr SET username = $name, password_hash = 'x'{extra}" | ||
| 394 | - )) | ||
| 395 | - .bind(("usr", user.record())) | ||
| 396 | - .bind(("name", user.key().to_string())) | ||
| 397 | - .await | ||
| 398 | - .unwrap() | ||
| 399 | - .check() | ||
| 400 | - .unwrap(); | ||
| 401 | - user | ||
| 402 | - } | ||
| 403 | - | ||
| 404 | - /// The stamps on the stored rows, oldest first. | ||
| 405 | - async fn stamps(user: &UserId, db: &Database) -> Vec<(String, i64)> { | ||
| 406 | - BadgeAward::list_for(user, db) | ||
| 407 | - .await | ||
| 408 | - .unwrap() | ||
| 409 | - .into_iter() | ||
| 410 | - .map(|award| (award.badge, award.earned_at.as_millis())) | ||
| 411 | - .collect() | ||
| 412 | - } | ||
| 413 | 218 | ||
| 414 | /// The wire name and the column name are two names, not one. If a later | 219 | /// The wire name and the column name are two names, not one. If a later |
| 415 | /// edit points `as_str` back at `field`, this fails — which is the point: | 220 | /// edit points `as_str` back at `field`, this fails — which is the point: |
| @@ -435,30 +240,6 @@ mod tests { | |||
| 435 | } | 240 | } |
| 436 | } | 241 | } |
| 437 | 242 | ||
| 438 | - #[tokio::test] | ||
| 439 | - async fn a_row_without_the_columns_loads_as_zeros() { | ||
| 440 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 441 | - schema(&db).await; | ||
| 442 | - // The stale-data case: an account written before the counters existed | ||
| 443 | - // carries none of them. And the harsher one — no row at all. | ||
| 444 | - for user in [a_user(&[], &db).await, UserId::from_key("ghost")] { | ||
| 445 | - let stats = BadgeStats::load(&user, &db).await.unwrap(); | ||
| 446 | - assert_eq!(stats.get_homework_submitted(), 0); | ||
| 447 | - assert_eq!(stats.get_homework_on_time(), 0); | ||
| 448 | - assert_eq!(stats.get_exam_sat(), 0); | ||
| 449 | - assert_eq!(stats.get_pomodoro_finished(), 0); | ||
| 450 | - assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 451 | - assert_eq!(stats.get_marks_given(), 0); | ||
| 452 | - assert_eq!(stats.get_lessons_held(), 0); | ||
| 453 | - assert_eq!(stats.get_pool_approved(), 0); | ||
| 454 | - assert_eq!(stats.get_pool_published(), 0); | ||
| 455 | - assert_eq!(stats.get_lessons_attended(), 0); | ||
| 456 | - assert_eq!(stats.get_high_mark(), 0); | ||
| 457 | - assert_eq!(stats.get_study_streak(), 0); | ||
| 458 | - assert!(earned(&stats).is_empty(), "zero earns nothing"); | ||
| 459 | - } | ||
| 460 | - } | ||
| 461 | - | ||
| 462 | #[tokio::test] | 243 | #[tokio::test] |
| 463 | async fn the_rule_takes_every_threshold_at_or_below_the_count() { | 244 | async fn the_rule_takes_every_threshold_at_or_below_the_count() { |
| 464 | let stats = BadgeStats { | 245 | let stats = BadgeStats { |
| @@ -490,126 +271,4 @@ mod tests { | |||
| 490 | ] | 271 | ] |
| 491 | ); | 272 | ); |
| 492 | } | 273 | } |
| 493 | - | ||
| 494 | - #[tokio::test] | ||
| 495 | - async fn a_second_sync_does_not_move_the_stamp() { | ||
| 496 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 497 | - schema(&db).await; | ||
| 498 | - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 1)], &db).await; | ||
| 499 | - | ||
| 500 | - sync(&user, &db).await.unwrap(); | ||
| 501 | - let first = stamps(&user, &db).await; | ||
| 502 | - assert_eq!(first.len(), 1, "{first:?}"); | ||
| 503 | - assert_eq!(first[0].0, "homework_submitted_1"); | ||
| 504 | - | ||
| 505 | - // A later sync, provably at a later millisecond: the row must keep the | ||
| 506 | - // instant the badge was *first* earned, and must not be doubled. | ||
| 507 | - tokio::time::sleep(std::time::Duration::from_millis(5)).await; | ||
| 508 | - sync(&user, &db).await.unwrap(); | ||
| 509 | - assert_eq!(stamps(&user, &db).await, first, "the stamp is frozen"); | ||
| 510 | - } | ||
| 511 | - | ||
| 512 | - #[tokio::test] | ||
| 513 | - async fn an_award_survives_a_counter_that_falls_back_below_it() { | ||
| 514 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 515 | - schema(&db).await; | ||
| 516 | - let user = a_user(&[(HOMEWORK_SUBMITTED_TOTAL_FIELD, 10)], &db).await; | ||
| 517 | - sync(&user, &db).await.unwrap(); | ||
| 518 | - assert_eq!( | ||
| 519 | - stamps(&user, &db).await.len(), | ||
| 520 | - 2, | ||
| 521 | - "1 and 10 are both earned" | ||
| 522 | - ); | ||
| 523 | - | ||
| 524 | - // The submission is withdrawn and the counter comes back down. A badge | ||
| 525 | - // records that it was done, so nothing here may take it away. | ||
| 526 | - db.query(format!( | ||
| 527 | - "UPDATE $usr SET {HOMEWORK_SUBMITTED_TOTAL_FIELD} = 0" | ||
| 528 | - )) | ||
| 529 | - .bind(("usr", user.record())) | ||
| 530 | - .await | ||
| 531 | - .unwrap() | ||
| 532 | - .check() | ||
| 533 | - .unwrap(); | ||
| 534 | - assert!( | ||
| 535 | - earned(&BadgeStats::load(&user, &db).await.unwrap()).is_empty(), | ||
| 536 | - "the rule no longer holds…" | ||
| 537 | - ); | ||
| 538 | - sync(&user, &db).await.unwrap(); | ||
| 539 | - let kept: Vec<String> = stamps(&user, &db) | ||
| 540 | - .await | ||
| 541 | - .into_iter() | ||
| 542 | - .map(|(badge, _)| badge) | ||
| 543 | - .collect(); | ||
| 544 | - assert_eq!( | ||
| 545 | - kept, | ||
| 546 | - vec!["homework_submitted_1", "homework_submitted_10"], | ||
| 547 | - "…and the awards stand anyway" | ||
| 548 | - ); | ||
| 549 | - } | ||
| 550 | - | ||
| 551 | - #[tokio::test] | ||
| 552 | - async fn a_badge_the_catalog_dropped_is_not_served() { | ||
| 553 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 554 | - schema(&db).await; | ||
| 555 | - let user = a_user(&[(EXAM_SAT_TOTAL_FIELD, 1)], &db).await; | ||
| 556 | - sync(&user, &db).await.unwrap(); | ||
| 557 | - // The row a retired catalog line left behind: still stored, never | ||
| 558 | - // served, and no migration deleted it. | ||
| 559 | - db.query("CREATE $id SET user = $usr, badge = 'exam_sat_3', earned_at = 1") | ||
| 560 | - .bind(( | ||
| 561 | - "id", | ||
| 562 | - surrealdb::types::RecordId::new(BADGE_AWARD_TABLE, award_key(&user, "exam_sat_3")), | ||
| 563 | - )) | ||
| 564 | - .bind(("usr", user.record())) | ||
| 565 | - .await | ||
| 566 | - .unwrap() | ||
| 567 | - .check() | ||
| 568 | - .unwrap(); | ||
| 569 | - | ||
| 570 | - let served: Vec<String> = stamps(&user, &db) | ||
| 571 | - .await | ||
| 572 | - .into_iter() | ||
| 573 | - .map(|(badge, _)| badge) | ||
| 574 | - .collect(); | ||
| 575 | - assert_eq!(served, vec!["exam_sat_1"]); | ||
| 576 | - let mut rows = db | ||
| 577 | - .query(format!("SELECT VALUE badge FROM {BADGE_AWARD_TABLE}")) | ||
| 578 | - .await | ||
| 579 | - .unwrap(); | ||
| 580 | - assert_eq!(rows.take::<Vec<String>>(0).unwrap().len(), 2, "both stored"); | ||
| 581 | - } | ||
| 582 | - | ||
| 583 | - /// One sync stamps every badge it writes with the same millisecond, so the | ||
| 584 | - /// tie-break is what makes the order stable rather than incidental. | ||
| 585 | - #[tokio::test] | ||
| 586 | - async fn same_millisecond_awards_come_back_in_badge_order() { | ||
| 587 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 588 | - schema(&db).await; | ||
| 589 | - let user = a_user( | ||
| 590 | - &[ | ||
| 591 | - (HOMEWORK_SUBMITTED_TOTAL_FIELD, 50), | ||
| 592 | - (EXAM_SAT_TOTAL_FIELD, 1), | ||
| 593 | - ], | ||
| 594 | - &db, | ||
| 595 | - ) | ||
| 596 | - .await; | ||
| 597 | - sync(&user, &db).await.unwrap(); | ||
| 598 | - | ||
| 599 | - let served = stamps(&user, &db).await; | ||
| 600 | - let ids: Vec<&str> = served.iter().map(|(badge, _)| badge.as_str()).collect(); | ||
| 601 | - assert_eq!( | ||
| 602 | - ids, | ||
| 603 | - vec![ | ||
| 604 | - "exam_sat_1", | ||
| 605 | - "homework_submitted_1", | ||
| 606 | - "homework_submitted_10", | ||
| 607 | - "homework_submitted_50" | ||
| 608 | - ] | ||
| 609 | - ); | ||
| 610 | - assert!( | ||
| 611 | - served.windows(2).all(|pair| pair[0].1 == pair[1].1), | ||
| 612 | - "one sync stamps one instant: {served:?}" | ||
| 613 | - ); | ||
| 614 | - } | ||
| 615 | } | 274 | } |
src/domain/builder.rsmodified+9 -170
| @@ -12,12 +12,9 @@ | |||
| 12 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; | 12 | use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; |
| 13 | use ulid::Ulid; | 13 | use ulid::Ulid; |
| 14 | 14 | ||
| 15 | -use crate::constant::SESSION_DURATION_DAYS; | ||
| 16 | -use crate::database::Database; | ||
| 17 | use crate::domain::session::SessionToken; | 15 | use crate::domain::session::SessionToken; |
| 18 | use crate::domain::timestamp::Timestamp; | 16 | use crate::domain::timestamp::Timestamp; |
| 19 | -use crate::domain::user::{Password, PasswordHash, Username}; | 17 | +use crate::domain::user::{PasswordHash, Username}; |
| 20 | -use crate::error::AppError; | ||
| 21 | 18 | ||
| 22 | pub const BUILDER_TABLE: &str = "builder"; | 19 | pub const BUILDER_TABLE: &str = "builder"; |
| 23 | pub const BUILDER_SESSION_TABLE: &str = "builder_session"; | 20 | pub const BUILDER_SESSION_TABLE: &str = "builder_session"; |
| @@ -48,9 +45,9 @@ impl BuilderId { | |||
| 48 | 45 | ||
| 49 | #[derive(Debug, Clone, SurrealValue)] | 46 | #[derive(Debug, Clone, SurrealValue)] |
| 50 | pub struct Builder { | 47 | pub struct Builder { |
| 51 | - id: BuilderId, | 48 | + pub(crate) id: BuilderId, |
| 52 | - username: Username, | 49 | + pub(crate) username: Username, |
| 53 | - password_hash: PasswordHash, | 50 | + pub(crate) password_hash: PasswordHash, |
| 54 | } | 51 | } |
| 55 | 52 | ||
| 56 | impl Builder { | 53 | impl Builder { |
| @@ -65,54 +62,6 @@ impl Builder { | |||
| 65 | pub fn get_password_hash(&self) -> &PasswordHash { | 62 | pub fn get_password_hash(&self) -> &PasswordHash { |
| 66 | &self.password_hash | 63 | &self.password_hash |
| 67 | } | 64 | } |
| 68 | - | ||
| 69 | - pub async fn find_by_username( | ||
| 70 | - username: &str, | ||
| 71 | - control: &Database, | ||
| 72 | - ) -> Result<Option<Builder>, AppError> { | ||
| 73 | - let mut result = control | ||
| 74 | - .query("SELECT * FROM builder WHERE username = $u LIMIT 1") | ||
| 75 | - .bind(("u", username.trim().to_string())) | ||
| 76 | - .await? | ||
| 77 | - .check()?; | ||
| 78 | - Ok(result.take::<Vec<Builder>>(0)?.into_iter().next()) | ||
| 79 | - } | ||
| 80 | - | ||
| 81 | - pub async fn read(id: &BuilderId, control: &Database) -> Result<Option<Builder>, AppError> { | ||
| 82 | - Ok(control.select(id.record()).await?) | ||
| 83 | - } | ||
| 84 | - | ||
| 85 | - /// Idempotent startup seed. An existing row is left exactly as it is — the | ||
| 86 | - /// seed never rewrites a credential, so rotating `BUILDER_PASSWORD` in the | ||
| 87 | - /// environment does not silently re-key a live account (delete the row to | ||
| 88 | - /// re-seed). There is no role to promote here, so this cannot have | ||
| 89 | - /// `ensure_admin`'s create-then-promote hole. | ||
| 90 | - pub async fn ensure( | ||
| 91 | - username: Username, | ||
| 92 | - password: Password, | ||
| 93 | - control: &Database, | ||
| 94 | - ) -> Result<(), AppError> { | ||
| 95 | - if Self::find_by_username(username.as_str(), control) | ||
| 96 | - .await? | ||
| 97 | - .is_some() | ||
| 98 | - { | ||
| 99 | - return Ok(()); | ||
| 100 | - } | ||
| 101 | - let builder = Builder { | ||
| 102 | - id: BuilderId::generate(), | ||
| 103 | - password_hash: password.hash_async().await?, | ||
| 104 | - username, | ||
| 105 | - }; | ||
| 106 | - let created: Option<Builder> = control | ||
| 107 | - .create(builder.id.record()) | ||
| 108 | - .content(builder.clone()) | ||
| 109 | - .await?; | ||
| 110 | - created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; | ||
| 111 | - // The account name stays out of the event: exported log records must | ||
| 112 | - // name no person (see `telemetry`). | ||
| 113 | - tracing::info!("seeded the builder account named by BUILDER_USERNAME"); | ||
| 114 | - Ok(()) | ||
| 115 | - } | ||
| 116 | } | 65 | } |
| 117 | 66 | ||
| 118 | /// A builder's login session. [`crate::domain::session::Session`]'s shape | 67 | /// A builder's login session. [`crate::domain::session::Session`]'s shape |
| @@ -120,30 +69,14 @@ impl Builder { | |||
| 120 | /// are the same 64 hex chars. | 69 | /// are the same 64 hex chars. |
| 121 | #[derive(Debug, Clone, SurrealValue)] | 70 | #[derive(Debug, Clone, SurrealValue)] |
| 122 | pub struct BuilderSession { | 71 | pub struct BuilderSession { |
| 123 | - id: RecordId, | 72 | + pub(crate) id: RecordId, |
| 124 | - builder: BuilderId, | 73 | + pub(crate) builder: BuilderId, |
| 125 | - token: SessionToken, | 74 | + pub(crate) token: SessionToken, |
| 126 | - created_at: Timestamp, | 75 | + pub(crate) created_at: Timestamp, |
| 127 | - expires_at: Timestamp, | 76 | + pub(crate) expires_at: Timestamp, |
| 128 | } | 77 | } |
| 129 | 78 | ||
| 130 | impl BuilderSession { | 79 | impl BuilderSession { |
| 131 | - pub async fn create( | ||
| 132 | - builder: &BuilderId, | ||
| 133 | - control: &Database, | ||
| 134 | - ) -> Result<BuilderSession, AppError> { | ||
| 135 | - let session = BuilderSession { | ||
| 136 | - id: RecordId::new(BUILDER_SESSION_TABLE, Ulid::new().to_string()), | ||
| 137 | - builder: builder.clone(), | ||
| 138 | - token: SessionToken::generate()?, | ||
| 139 | - created_at: Timestamp::now(), | ||
| 140 | - expires_at: Timestamp::in_days(SESSION_DURATION_DAYS), | ||
| 141 | - }; | ||
| 142 | - let created: Option<BuilderSession> = | ||
| 143 | - control.create(session.id.clone()).content(session).await?; | ||
| 144 | - created.ok_or_else(|| AppError::Internal("failed to create the builder session".into())) | ||
| 145 | - } | ||
| 146 | - | ||
| 147 | pub fn token(&self) -> &SessionToken { | 80 | pub fn token(&self) -> &SessionToken { |
| 148 | &self.token | 81 | &self.token |
| 149 | } | 82 | } |
| @@ -155,98 +88,4 @@ impl BuilderSession { | |||
| 155 | pub fn is_expired(&self) -> bool { | 88 | pub fn is_expired(&self) -> bool { |
| 156 | self.expires_at.is_past() | 89 | self.expires_at.is_past() |
| 157 | } | 90 | } |
| 158 | - | ||
| 159 | - pub async fn find_by_token( | ||
| 160 | - token: &str, | ||
| 161 | - control: &Database, | ||
| 162 | - ) -> Result<Option<BuilderSession>, AppError> { | ||
| 163 | - let mut result = control | ||
| 164 | - .query("SELECT * FROM builder_session WHERE token = $tok LIMIT 1") | ||
| 165 | - .bind(("tok", token.to_string())) | ||
| 166 | - .await? | ||
| 167 | - .check()?; | ||
| 168 | - Ok(result.take::<Vec<BuilderSession>>(0)?.into_iter().next()) | ||
| 169 | - } | ||
| 170 | - | ||
| 171 | - pub async fn delete_by_token(token: &str, control: &Database) -> Result<(), AppError> { | ||
| 172 | - control | ||
| 173 | - .query("DELETE builder_session WHERE token = $tok") | ||
| 174 | - .bind(("tok", token.to_string())) | ||
| 175 | - .await? | ||
| 176 | - .check()?; | ||
| 177 | - Ok(()) | ||
| 178 | - } | ||
| 179 | -} | ||
| 180 | - | ||
| 181 | -#[cfg(test)] | ||
| 182 | -mod tests { | ||
| 183 | - use super::*; | ||
| 184 | - use crate::tenant::Tenants; | ||
| 185 | - | ||
| 186 | - #[tokio::test] | ||
| 187 | - async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { | ||
| 188 | - let tenants = Tenants::new_mem().await.unwrap(); | ||
| 189 | - let control = tenants.control(); | ||
| 190 | - let name = Username::try_new("builder1").unwrap(); | ||
| 191 | - Builder::ensure(name.clone(), Password::try_new("secret1").unwrap(), control) | ||
| 192 | - .await | ||
| 193 | - .unwrap(); | ||
| 194 | - let first = Builder::find_by_username("builder1", control) | ||
| 195 | - .await | ||
| 196 | - .unwrap() | ||
| 197 | - .expect("seeded"); | ||
| 198 | - | ||
| 199 | - // A second boot with a *different* password must leave the row alone: | ||
| 200 | - // an environment edit is not a password reset. | ||
| 201 | - Builder::ensure(name, Password::try_new("secret2").unwrap(), control) | ||
| 202 | - .await | ||
| 203 | - .unwrap(); | ||
| 204 | - let again = Builder::find_by_username("builder1", control) | ||
| 205 | - .await | ||
| 206 | - .unwrap() | ||
| 207 | - .expect("still there"); | ||
| 208 | - assert_eq!(again.get_id(), first.get_id()); | ||
| 209 | - assert_eq!( | ||
| 210 | - again.get_password_hash().as_str(), | ||
| 211 | - first.get_password_hash().as_str() | ||
| 212 | - ); | ||
| 213 | - } | ||
| 214 | - | ||
| 215 | - #[tokio::test] | ||
| 216 | - async fn a_builder_session_round_trips_and_deletes() { | ||
| 217 | - let tenants = Tenants::new_mem().await.unwrap(); | ||
| 218 | - let control = tenants.control(); | ||
| 219 | - Builder::ensure( | ||
| 220 | - Username::try_new("builder1").unwrap(), | ||
| 221 | - Password::try_new("secret1").unwrap(), | ||
| 222 | - control, | ||
| 223 | - ) | ||
| 224 | - .await | ||
| 225 | - .unwrap(); | ||
| 226 | - let builder = Builder::find_by_username("builder1", control) | ||
| 227 | - .await | ||
| 228 | - .unwrap() | ||
| 229 | - .unwrap(); | ||
| 230 | - | ||
| 231 | - let session = BuilderSession::create(builder.get_id(), control) | ||
| 232 | - .await | ||
| 233 | - .unwrap(); | ||
| 234 | - let token = session.token().as_str().to_string(); | ||
| 235 | - let found = BuilderSession::find_by_token(&token, control) | ||
| 236 | - .await | ||
| 237 | - .unwrap() | ||
| 238 | - .expect("found by token"); | ||
| 239 | - assert_eq!(found.builder(), builder.get_id()); | ||
| 240 | - assert!(!found.is_expired()); | ||
| 241 | - | ||
| 242 | - BuilderSession::delete_by_token(&token, control) | ||
| 243 | - .await | ||
| 244 | - .unwrap(); | ||
| 245 | - assert!( | ||
| 246 | - BuilderSession::find_by_token(&token, control) | ||
| 247 | - .await | ||
| 248 | - .unwrap() | ||
| 249 | - .is_none() | ||
| 250 | - ); | ||
| 251 | - } | ||
| 252 | } | 91 | } |
src/domain/pomodoro.rsmodified+3 -6
| @@ -7,7 +7,6 @@ use crate::constant::{ | |||
| 7 | STUDY_STREAK_LONGEST_FIELD, | 7 | STUDY_STREAK_LONGEST_FIELD, |
| 8 | }; | 8 | }; |
| 9 | use crate::database::{Database, transaction_with_retry}; | 9 | use crate::database::{Database, transaction_with_retry}; |
| 10 | -use crate::domain::badge; | ||
| 11 | use crate::domain::monotonic_id::next_ulid; | 10 | use crate::domain::monotonic_id::next_ulid; |
| 12 | use crate::domain::timestamp::Timestamp; | 11 | use crate::domain::timestamp::Timestamp; |
| 13 | use crate::domain::user::UserId; | 12 | use crate::domain::user::UserId; |
| @@ -307,7 +306,7 @@ impl PomodoroSession { | |||
| 307 | // A badge is a decoration on top of the stint: losing one to a | 306 | // A badge is a decoration on top of the stint: losing one to a |
| 308 | // transient database error must never fail the finish, and the next | 307 | // transient database error must never fail the finish, and the next |
| 309 | // counter move re-runs this and heals it. | 308 | // counter move re-runs this and heals it. |
| 310 | - if let Err(err) = badge::sync(user, db).await { | 309 | + if let Err(err) = crate::db::badge::sync(db, user).await { |
| 311 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); | 310 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); |
| 312 | } | 311 | } |
| 313 | Ok(saved) | 312 | Ok(saved) |
| @@ -756,7 +755,7 @@ mod tests { | |||
| 756 | 200 | 755 | 200 |
| 757 | ); | 756 | ); |
| 758 | assert!( | 757 | assert!( |
| 759 | - badge::BadgeAward::list_for(&user, &db) | 758 | + crate::db::badge::list_for(&db, &user) |
| 760 | .await | 759 | .await |
| 761 | .unwrap() | 760 | .unwrap() |
| 762 | .is_empty(), | 761 | .is_empty(), |
| @@ -827,9 +826,7 @@ mod tests { | |||
| 827 | assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); | 826 | assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); |
| 828 | 827 | ||
| 829 | // And the stat that sums these stays non-negative. | 828 | // And the stat that sums these stays non-negative. |
| 830 | - let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) | 829 | + let stats = crate::db::profile::load(&db, &user, 0, 0).await.unwrap(); |
| 831 | - .await | ||
| 832 | - .unwrap(); | ||
| 833 | assert_eq!(stats.get_pomodoro_sessions(), 1); | 830 | assert_eq!(stats.get_pomodoro_sessions(), 1); |
| 834 | assert_eq!(stats.get_pomodoro_focus_ms(), 0); | 831 | assert_eq!(stats.get_pomodoro_focus_ms(), 0); |
| 835 | } | 832 | } |
src/domain/profile.rsmodified+7 -190
| @@ -4,11 +4,9 @@ | |||
| 4 | use surrealdb::types::SurrealValue; | 4 | use surrealdb::types::SurrealValue; |
| 5 | 5 | ||
| 6 | use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; | 6 | use crate::constant::{MAX_BIO_LEN, MAX_DISPLAY_NAME_LEN, MAX_NAME_LEN}; |
| 7 | -use crate::database::Database; | 7 | +use crate::domain::badge::BadgeStats; |
| 8 | -use crate::domain::badge::{BadgeStat, BadgeStats}; | ||
| 9 | use crate::domain::timestamp::Timestamp; | 8 | use crate::domain::timestamp::Timestamp; |
| 10 | -use crate::domain::user::UserId; | 9 | +use crate::error::ValidationError; |
| 11 | -use crate::error::{AppError, ValidationError}; | ||
| 12 | use crate::validate::{validate_email, validate_optional, validate_phone, validate_required}; | 10 | use crate::validate::{validate_email, validate_optional, validate_phone, validate_required}; |
| 13 | 11 | ||
| 14 | /// A person's given or family name. One type serves both fields — the `field` | 12 | /// A person's given or family name. One type serves both fields — the `field` |
| @@ -140,11 +138,11 @@ impl Bio { | |||
| 140 | /// without touching a signature. | 138 | /// without touching a signature. |
| 141 | #[derive(Debug, Clone, SurrealValue)] | 139 | #[derive(Debug, Clone, SurrealValue)] |
| 142 | pub struct ProfileStats { | 140 | pub struct ProfileStats { |
| 143 | - pomodoro_sessions: i64, | 141 | + pub(crate) pomodoro_sessions: i64, |
| 144 | - pomodoro_focus_ms: i64, | 142 | + pub(crate) pomodoro_focus_ms: i64, |
| 145 | - courses: i64, | 143 | + pub(crate) courses: i64, |
| 146 | - classes: i64, | 144 | + pub(crate) classes: i64, |
| 147 | - totals: BadgeStats, | 145 | + pub(crate) totals: BadgeStats, |
| 148 | } | 146 | } |
| 149 | 147 | ||
| 150 | impl ProfileStats { | 148 | impl ProfileStats { |
| @@ -170,91 +168,6 @@ impl ProfileStats { | |||
| 170 | pub fn get_totals(&self) -> &BadgeStats { | 168 | pub fn get_totals(&self) -> &BadgeStats { |
| 171 | &self.totals | 169 | &self.totals |
| 172 | } | 170 | } |
| 173 | - | ||
| 174 | - /// One round trip, and only one: `courses` and `classes` arrive from the | ||
| 175 | - /// caller, which already holds them as the `total` of the paged class and | ||
| 176 | - /// course readers it ran for the profile's own blocks — re-counting them | ||
| 177 | - /// here would be two extra reads for numbers already in hand. | ||
| 178 | - /// | ||
| 179 | - /// The pomodoro aggregate rides the per-user index, so it is a lookup and | ||
| 180 | - /// not a scan. `finished_at != NONE` is the filter because NONE is falsy: a | ||
| 181 | - /// bare truthiness test would also drop a stint that finished at epoch. An | ||
| 182 | - /// open stint contributes to neither the count nor the sum — unfinished | ||
| 183 | - /// focus has no honest duration to add. | ||
| 184 | - /// | ||
| 185 | - /// The lifetime counters ride along as a second statement in the *same* | ||
| 186 | - /// query rather than a [`BadgeStats::load`] call, which would be a second | ||
| 187 | - /// round trip for one record lookup. It repeats that projection — `?? 0` | ||
| 188 | - /// per column, because the columns are `option<int>` and a row predating | ||
| 189 | - /// them carries none — so the two must move together if the shape changes. | ||
| 190 | - pub async fn load( | ||
| 191 | - user: &UserId, | ||
| 192 | - courses: i64, | ||
| 193 | - classes: i64, | ||
| 194 | - db: &Database, | ||
| 195 | - ) -> Result<ProfileStats, AppError> { | ||
| 196 | - let mut result = db | ||
| 197 | - .query(format!( | ||
| 198 | - "SELECT count() AS sessions, math::sum(finished_at - started_at) AS focus_ms | ||
| 199 | - FROM pomodoro_session WHERE user = $usr AND finished_at != NONE GROUP ALL; | ||
| 200 | - SELECT ({homework_submitted} ?? 0) AS homework_submitted, | ||
| 201 | - ({homework_on_time} ?? 0) AS homework_on_time, | ||
| 202 | - ({exam_sat} ?? 0) AS exam_sat, | ||
| 203 | - ({pomodoro_finished} ?? 0) AS pomodoro_finished, | ||
| 204 | - ({pomodoro_focus_ms} ?? 0) AS pomodoro_focus_ms, | ||
| 205 | - ({marks_given} ?? 0) AS marks_given, | ||
| 206 | - ({lessons_held} ?? 0) AS lessons_held, | ||
| 207 | - ({pool_approved} ?? 0) AS pool_approved, | ||
| 208 | - ({pool_published} ?? 0) AS pool_published, | ||
| 209 | - ({lessons_attended} ?? 0) AS lessons_attended, | ||
| 210 | - ({high_mark} ?? 0) AS high_mark, | ||
| 211 | - ({study_streak} ?? 0) AS study_streak | ||
| 212 | - FROM $usr;", | ||
| 213 | - homework_submitted = BadgeStat::HomeworkSubmitted.field(), | ||
| 214 | - homework_on_time = BadgeStat::HomeworkOnTime.field(), | ||
| 215 | - exam_sat = BadgeStat::ExamSat.field(), | ||
| 216 | - pomodoro_finished = BadgeStat::PomodoroFinished.field(), | ||
| 217 | - pomodoro_focus_ms = BadgeStat::PomodoroFocusMs.field(), | ||
| 218 | - marks_given = BadgeStat::MarksGiven.field(), | ||
| 219 | - lessons_held = BadgeStat::LessonsHeld.field(), | ||
| 220 | - pool_approved = BadgeStat::PoolApproved.field(), | ||
| 221 | - pool_published = BadgeStat::PoolPublished.field(), | ||
| 222 | - lessons_attended = BadgeStat::LessonsAttended.field(), | ||
| 223 | - high_mark = BadgeStat::HighMark.field(), | ||
| 224 | - study_streak = BadgeStat::StudyStreak.field(), | ||
| 225 | - )) | ||
| 226 | - .bind(("usr", user.record())) | ||
| 227 | - .await? | ||
| 228 | - .check()?; | ||
| 229 | - // `GROUP ALL` yields no row at all when nothing matched — that is the | ||
| 230 | - // zero case, not a missing one. | ||
| 231 | - let row = result.take::<Vec<PomodoroTotals>>(0)?.into_iter().next(); | ||
| 232 | - // A vanished user row reads as all zeros, same as a fresh account. | ||
| 233 | - let totals = result | ||
| 234 | - .take::<Vec<BadgeStats>>(1)? | ||
| 235 | - .into_iter() | ||
| 236 | - .next() | ||
| 237 | - .unwrap_or_default(); | ||
| 238 | - Ok(ProfileStats { | ||
| 239 | - totals, | ||
| 240 | - pomodoro_sessions: row.as_ref().map_or(0, |totals| totals.sessions), | ||
| 241 | - // Floored at zero: a stint stamped by a wall clock that stepped | ||
| 242 | - // backwards mid-session sums as negative time, and "you focused for | ||
| 243 | - // minus five seconds" is never the truthful answer. New stints | ||
| 244 | - // cannot go inverted (see [`PomodoroSession::finish`]); rows written | ||
| 245 | - // before that guard still can, and this is what covers them. | ||
| 246 | - pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), | ||
| 247 | - courses, | ||
| 248 | - classes, | ||
| 249 | - }) | ||
| 250 | - } | ||
| 251 | -} | ||
| 252 | - | ||
| 253 | -/// The aggregate row of [`ProfileStats::load`]. | ||
| 254 | -#[derive(Debug, SurrealValue)] | ||
| 255 | -struct PomodoroTotals { | ||
| 256 | - sessions: i64, | ||
| 257 | - focus_ms: i64, | ||
| 258 | } | 171 | } |
| 259 | 172 | ||
| 260 | #[cfg(test)] | 173 | #[cfg(test)] |
| @@ -342,100 +255,4 @@ mod tests { | |||
| 342 | assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN)).is_ok()); | 255 | assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN)).is_ok()); |
| 343 | assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN + 1)).is_err()); | 256 | assert!(Bio::try_new(&"é".repeat(MAX_BIO_LEN + 1)).is_err()); |
| 344 | } | 257 | } |
| 345 | - | ||
| 346 | - #[tokio::test] | ||
| 347 | - async fn stats_are_zero_without_pomodoro_rows() { | ||
| 348 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 349 | - let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 350 | - | ||
| 351 | - let stats = ProfileStats::load(&user, 3, 1, &db).await.unwrap(); | ||
| 352 | - // Derived counters: no rows is a true zero, never a null. | ||
| 353 | - assert_eq!(stats.get_pomodoro_sessions(), 0); | ||
| 354 | - assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 355 | - // The passed-in counts survive untouched. | ||
| 356 | - assert_eq!(stats.get_courses(), 3); | ||
| 357 | - assert_eq!(stats.get_classes(), 1); | ||
| 358 | - // No user row at all — the lifetime counters still read as zeros. | ||
| 359 | - assert_eq!(stats.get_totals().get_homework_submitted(), 0); | ||
| 360 | - assert_eq!(stats.get_totals().get_pomodoro_focus_ms(), 0); | ||
| 361 | - } | ||
| 362 | - | ||
| 363 | - /// The second statement of the same query: the stored counters, straight off | ||
| 364 | - /// the user row, with the columns an older row is missing read as zero. | ||
| 365 | - #[tokio::test] | ||
| 366 | - async fn lifetime_totals_ride_the_same_query() { | ||
| 367 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 368 | - let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 369 | - db.query(format!( | ||
| 370 | - "CREATE $usr SET username = $name, password_hash = 'x', | ||
| 371 | - {} = 4, {} = 3", | ||
| 372 | - crate::constant::HOMEWORK_SUBMITTED_TOTAL_FIELD, | ||
| 373 | - crate::constant::EXAM_SAT_TOTAL_FIELD, | ||
| 374 | - )) | ||
| 375 | - .bind(("usr", user.record())) | ||
| 376 | - .bind(("name", user.key().to_string())) | ||
| 377 | - .await | ||
| 378 | - .unwrap() | ||
| 379 | - .check() | ||
| 380 | - .unwrap(); | ||
| 381 | - | ||
| 382 | - let totals = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); | ||
| 383 | - let totals = totals.get_totals(); | ||
| 384 | - assert_eq!(totals.get_homework_submitted(), 4); | ||
| 385 | - assert_eq!(totals.get_exam_sat(), 3); | ||
| 386 | - // Never written on this row: absent must read as 0, not as an error. | ||
| 387 | - assert_eq!(totals.get_homework_on_time(), 0); | ||
| 388 | - assert_eq!(totals.get_pomodoro_finished(), 0); | ||
| 389 | - assert_eq!(totals.get_pomodoro_focus_ms(), 0); | ||
| 390 | - } | ||
| 391 | - | ||
| 392 | - #[tokio::test] | ||
| 393 | - async fn stats_count_finished_stints_only() { | ||
| 394 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 395 | - let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 396 | - let other = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 397 | - | ||
| 398 | - // Two finished stints (1000 ms + 2500 ms), one still running, and one | ||
| 399 | - // finished stint belonging to somebody else. | ||
| 400 | - db.query( | ||
| 401 | - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; | ||
| 402 | - CREATE pomodoro_session CONTENT { user: $usr, started_at: 5000, finished_at: 7500 }; | ||
| 403 | - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000 }; | ||
| 404 | - CREATE pomodoro_session CONTENT { user: $oth, started_at: 0, finished_at: 60000 };", | ||
| 405 | - ) | ||
| 406 | - .bind(("usr", user.record())) | ||
| 407 | - .bind(("oth", other.record())) | ||
| 408 | - .await | ||
| 409 | - .unwrap() | ||
| 410 | - .check() | ||
| 411 | - .unwrap(); | ||
| 412 | - | ||
| 413 | - let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); | ||
| 414 | - assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 415 | - assert_eq!(stats.get_pomodoro_focus_ms(), 3500); | ||
| 416 | - } | ||
| 417 | - | ||
| 418 | - #[tokio::test] | ||
| 419 | - async fn focus_time_never_reads_negative() { | ||
| 420 | - let db = crate::database::init_mem().await.unwrap(); | ||
| 421 | - let user = UserId::from_key(&ulid::Ulid::new().to_string()); | ||
| 422 | - | ||
| 423 | - // One honest 1000 ms stint and one inverted row — what a backwards | ||
| 424 | - // clock step left behind before `finish` grew its floor. The raw sum is | ||
| 425 | - // -5000; the profile must still answer a duration, not an accusation. | ||
| 426 | - db.query( | ||
| 427 | - "CREATE pomodoro_session CONTENT { user: $usr, started_at: 1000, finished_at: 2000 }; | ||
| 428 | - CREATE pomodoro_session CONTENT { user: $usr, started_at: 9000, finished_at: 3000 };", | ||
| 429 | - ) | ||
| 430 | - .bind(("usr", user.record())) | ||
| 431 | - .await | ||
| 432 | - .unwrap() | ||
| 433 | - .check() | ||
| 434 | - .unwrap(); | ||
| 435 | - | ||
| 436 | - let stats = ProfileStats::load(&user, 0, 0, &db).await.unwrap(); | ||
| 437 | - // The stints still happened, so the count is honest at 2. | ||
| 438 | - assert_eq!(stats.get_pomodoro_sessions(), 2); | ||
| 439 | - assert_eq!(stats.get_pomodoro_focus_ms(), 0); | ||
| 440 | - } | ||
| 441 | } | 258 | } |
src/domain/session_attendance.rsmodified+5 -3
| @@ -355,7 +355,6 @@ mod tests { | |||
| 355 | use super::*; | 355 | use super::*; |
| 356 | use crate::constant::DEFAULT_ATTENDANCE_STATUSES; | 356 | use crate::constant::DEFAULT_ATTENDANCE_STATUSES; |
| 357 | use crate::database::init_mem; | 357 | use crate::database::init_mem; |
| 358 | - use crate::domain::badge::BadgeStats; | ||
| 359 | use crate::domain::course_session::SessionTopic; | 358 | use crate::domain::course_session::SessionTopic; |
| 360 | use crate::domain::role::Role; | 359 | use crate::domain::role::Role; |
| 361 | 360 | ||
| @@ -414,14 +413,17 @@ mod tests { | |||
| 414 | 413 | ||
| 415 | /// The two counters as the badge rules read them, off the stored row. | 414 | /// The two counters as the badge rules read them, off the stored row. |
| 416 | async fn attended(user: &UserId, db: &Database) -> i64 { | 415 | async fn attended(user: &UserId, db: &Database) -> i64 { |
| 417 | - BadgeStats::load(user, db) | 416 | + crate::db::badge::load(db, user) |
| 418 | .await | 417 | .await |
| 419 | .unwrap() | 418 | .unwrap() |
| 420 | .get_lessons_attended() | 419 | .get_lessons_attended() |
| 421 | } | 420 | } |
| 422 | 421 | ||
| 423 | async fn held(user: &UserId, db: &Database) -> i64 { | 422 | async fn held(user: &UserId, db: &Database) -> i64 { |
| 424 | - BadgeStats::load(user, db).await.unwrap().get_lessons_held() | 423 | + crate::db::badge::load(db, user) |
| 424 | + .await | ||
| 425 | + .unwrap() | ||
| 426 | + .get_lessons_held() | ||
| 425 | } | 427 | } |
| 426 | 428 | ||
| 427 | /// The whole transition table in one pass: an upsert may only move the | 429 | /// The whole transition table in one pass: an upsert may only move the |
src/service/badge.rsadded+22 -0
| @@ -0,0 +1,22 @@ | |||
| 1 | +//! Badge workflows: the reads and the award sync the web layer calls behind | ||
| 2 | +//! counter-moving writes. The rules live in [`crate::domain::badge`] (pure) | ||
| 3 | +//! and the queries in [`crate::db::badge`]; there is no lock and no | ||
| 4 | +//! orchestration here — a badge is a decoration that never fails the write | ||
| 5 | +//! it decorates, so every caller logs and swallows [`sync`]'s error. | ||
| 6 | + | ||
| 7 | +use crate::database::Database; | ||
| 8 | +use crate::db::badge; | ||
| 9 | +use crate::domain::badge::BadgeAward; | ||
| 10 | +use crate::domain::user::UserId; | ||
| 11 | +use crate::error::AppError; | ||
| 12 | + | ||
| 13 | +/// Everything `user` has earned, oldest first. | ||
| 14 | +pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> { | ||
| 15 | + badge::list_for(db, user).await | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +/// Write an award row for every badge `user` has now earned and does not | ||
| 19 | +/// already hold. | ||
| 20 | +pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> { | ||
| 21 | + badge::sync(db, user).await | ||
| 22 | +} | ||
src/service/builder.rsadded+96 -0
| @@ -0,0 +1,96 @@ | |||
| 1 | +//! Builder workflows: the boot-time seed and the lookups the web layer | ||
| 2 | +//! resolves cookies and logins with. The control-database queries live in | ||
| 3 | +//! [`crate::db::builder`]; the school-provisioning routes never come through | ||
| 4 | +//! here — they speak to [`crate::tenant::Tenants`] directly. | ||
| 5 | + | ||
| 6 | +use crate::database::Database; | ||
| 7 | +use crate::db::builder; | ||
| 8 | +use crate::domain::builder::{Builder, BuilderId, BuilderSession}; | ||
| 9 | +use crate::domain::user::{Password, Username}; | ||
| 10 | +use crate::error::AppError; | ||
| 11 | + | ||
| 12 | +/// Idempotent startup seed: guarantee an account with this username in the | ||
| 13 | +/// control database. Missing → created. Already present → nothing to do (the | ||
| 14 | +/// stored password stays whatever it is — the seed never rewrites a | ||
| 15 | +/// credential, so rotating `BUILDER_PASSWORD` in the environment does not | ||
| 16 | +/// silently re-key a live account; delete the row to re-seed). There is no | ||
| 17 | +/// role to promote here, so this cannot have | ||
| 18 | +/// [`crate::service::user::ensure_admin`]'s create-then-promote hole. | ||
| 19 | +pub async fn ensure(db: &Database, username: Username, password: Password) -> Result<(), AppError> { | ||
| 20 | + if builder::find_by_username(db, username.as_str()) | ||
| 21 | + .await? | ||
| 22 | + .is_some() | ||
| 23 | + { | ||
| 24 | + return Ok(()); | ||
| 25 | + } | ||
| 26 | + let builder = Builder { | ||
| 27 | + id: BuilderId::generate(), | ||
| 28 | + password_hash: password.hash_async().await?, | ||
| 29 | + username, | ||
| 30 | + }; | ||
| 31 | + builder::create(db, builder).await?; | ||
| 32 | + // The account name stays out of the event: exported log records must | ||
| 33 | + // name no person (see `telemetry`). | ||
| 34 | + tracing::info!("seeded the builder account named by BUILDER_USERNAME"); | ||
| 35 | + Ok(()) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The login lookup. Usernames are stored trimmed; callers trim the same way | ||
| 39 | +/// so a padded attempt matches the canonical name. | ||
| 40 | +pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Builder>, AppError> { | ||
| 41 | + builder::find_by_username(db, username).await | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +pub async fn read(db: &Database, id: &BuilderId) -> Result<Option<Builder>, AppError> { | ||
| 45 | + builder::read(db, id).await | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +pub async fn create_session( | ||
| 49 | + db: &Database, | ||
| 50 | + builder_id: &BuilderId, | ||
| 51 | +) -> Result<BuilderSession, AppError> { | ||
| 52 | + builder::create_session(db, builder_id).await | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +pub async fn find_by_token(db: &Database, token: &str) -> Result<Option<BuilderSession>, AppError> { | ||
| 56 | + builder::find_by_token(db, token).await | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +pub async fn delete_by_token(db: &Database, token: &str) -> Result<(), AppError> { | ||
| 60 | + builder::delete_by_token(db, token).await | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +#[cfg(test)] | ||
| 64 | +mod tests { | ||
| 65 | + use super::*; | ||
| 66 | + use crate::tenant::Tenants; | ||
| 67 | + | ||
| 68 | + #[tokio::test] | ||
| 69 | + async fn the_seed_is_idempotent_and_never_rewrites_a_credential() { | ||
| 70 | + let tenants = Tenants::new_mem().await.unwrap(); | ||
| 71 | + let control = tenants.control(); | ||
| 72 | + let name = Username::try_new("builder1").unwrap(); | ||
| 73 | + ensure(control, name.clone(), Password::try_new("secret1").unwrap()) | ||
| 74 | + .await | ||
| 75 | + .unwrap(); | ||
| 76 | + let first = find_by_username(control, "builder1") | ||
| 77 | + .await | ||
| 78 | + .unwrap() | ||
| 79 | + .expect("seeded"); | ||
| 80 | + | ||
| 81 | + // A second boot with a *different* password must leave the row alone: | ||
| 82 | + // an environment edit is not a password reset. | ||
| 83 | + ensure(control, name, Password::try_new("secret2").unwrap()) | ||
| 84 | + .await | ||
| 85 | + .unwrap(); | ||
| 86 | + let again = find_by_username(control, "builder1") | ||
| 87 | + .await | ||
| 88 | + .unwrap() | ||
| 89 | + .expect("still there"); | ||
| 90 | + assert_eq!(again.get_id(), first.get_id()); | ||
| 91 | + assert_eq!( | ||
| 92 | + again.get_password_hash().as_str(), | ||
| 93 | + first.get_password_hash().as_str() | ||
| 94 | + ); | ||
| 95 | + } | ||
| 96 | +} | ||
src/service/exam_attempt.rsmodified+1 -2
| @@ -6,7 +6,6 @@ | |||
| 6 | use crate::constant::EXAM_SAT_TOTAL_FIELD; | 6 | use crate::constant::EXAM_SAT_TOTAL_FIELD; |
| 7 | use crate::database::Database; | 7 | use crate::database::Database; |
| 8 | use crate::db::cap; | 8 | use crate::db::cap; |
| 9 | -use crate::domain::badge; | ||
| 10 | use crate::domain::course::Course; | 9 | use crate::domain::course::Course; |
| 11 | 10 | ||
| 12 | use crate::domain::exam::{Exam, ExamId}; | 11 | use crate::domain::exam::{Exam, ExamId}; |
| @@ -218,7 +217,7 @@ pub async fn start( | |||
| 218 | { | 217 | { |
| 219 | cap::Claimed::Made(created) => { | 218 | cap::Claimed::Made(created) => { |
| 220 | // Only a moved counter can have crossed a threshold. | 219 | // Only a moved counter can have crossed a threshold. |
| 221 | - if first && let Err(err) = badge::sync(user, db).await { | 220 | + if first && let Err(err) = crate::db::badge::sync(db, user).await { |
| 222 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); | 221 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); |
| 223 | } | 222 | } |
| 224 | Ok((created, true)) | 223 | Ok((created, true)) |
src/service/mod.rsmodified+3 -0
| @@ -3,6 +3,8 @@ | |||
| 3 | 3 | ||
| 4 | pub mod appointment; | 4 | pub mod appointment; |
| 5 | pub mod appointment_slot; | 5 | pub mod appointment_slot; |
| 6 | +pub mod badge; | ||
| 7 | +pub mod builder; | ||
| 6 | pub mod class_blueprint; | 8 | pub mod class_blueprint; |
| 7 | pub mod course; | 9 | pub mod course; |
| 8 | pub mod course_session; | 10 | pub mod course_session; |
| @@ -13,6 +15,7 @@ pub mod exam_question; | |||
| 13 | pub mod meal_booking; | 15 | pub mod meal_booking; |
| 14 | pub mod note; | 16 | pub mod note; |
| 15 | pub mod payment_ledger; | 17 | pub mod payment_ledger; |
| 18 | +pub mod profile; | ||
| 16 | pub mod session; | 19 | pub mod session; |
| 17 | pub mod settings; | 20 | pub mod settings; |
| 18 | pub mod user; | 21 | pub mod user; |
src/service/profile.rsadded+20 -0
| @@ -0,0 +1,20 @@ | |||
| 1 | +//! Profile workflows: the aggregate stats read behind a profile response. | ||
| 2 | +//! There is no decision and no lock here — the query itself is the whole | ||
| 3 | +//! story, so this wraps [`crate::db::profile::load`] for the web layer. | ||
| 4 | + | ||
| 5 | +use crate::database::Database; | ||
| 6 | +use crate::db::profile; | ||
| 7 | +use crate::domain::profile::ProfileStats; | ||
| 8 | +use crate::domain::user::UserId; | ||
| 9 | +use crate::error::AppError; | ||
| 10 | + | ||
| 11 | +/// One round trip for a profile's motivational counters; `courses` and | ||
| 12 | +/// `classes` arrive from the caller's own paged reads. | ||
| 13 | +pub async fn load( | ||
| 14 | + db: &Database, | ||
| 15 | + user: &UserId, | ||
| 16 | + courses: i64, | ||
| 17 | + classes: i64, | ||
| 18 | +) -> Result<ProfileStats, AppError> { | ||
| 19 | + profile::load(db, user, courses, classes).await | ||
| 20 | +} | ||
src/web/auth.rsmodified+1 -2
| @@ -10,7 +10,6 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 10 | use utoipa_axum::routes; | 10 | use utoipa_axum::routes; |
| 11 | 11 | ||
| 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; | 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; |
| 13 | -use crate::domain::builder::BuilderSession; | ||
| 14 | use crate::domain::role::Role as DomainRole; | 13 | use crate::domain::role::Role as DomainRole; |
| 15 | use crate::domain::user::{Password, PasswordHash, Username}; | 14 | use crate::domain::user::{Password, PasswordHash, Username}; |
| 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 15 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -242,7 +241,7 @@ async fn logout( | |||
| 242 | // or suspended still clears below — logging out must never fail. | 241 | // or suspended still clears below — logging out must never fail. |
| 243 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { | 242 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { |
| 244 | if prefix == BUILDER_COOKIE_PREFIX { | 243 | if prefix == BUILDER_COOKIE_PREFIX { |
| 245 | - BuilderSession::delete_by_token(token, &st.db).await?; | 244 | + crate::service::builder::delete_by_token(&st.db, token).await?; |
| 246 | } else if let Ok(slug) = Slug::try_new(prefix) | 245 | } else if let Ok(slug) = Slug::try_new(prefix) |
| 247 | && let Ok(db) = st.tenants.get(&slug).await | 246 | && let Ok(db) = st.tenants.get(&slug).await |
| 248 | { | 247 | { |
src/web/builder.rsmodified+17 -16
| @@ -26,7 +26,7 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 26 | use utoipa_axum::routes; | 26 | use utoipa_axum::routes; |
| 27 | 27 | ||
| 28 | use crate::constant::MAX_SCHOOL_NAME_LEN; | 28 | use crate::constant::MAX_SCHOOL_NAME_LEN; |
| 29 | -use crate::domain::builder::{Builder, BuilderSession}; | 29 | +use crate::domain::builder::Builder; |
| 30 | use crate::domain::role::Role; | 30 | use crate::domain::role::Role; |
| 31 | use crate::domain::user::{Password, PasswordHash, User, Username}; | 31 | use crate::domain::user::{Password, PasswordHash, User, Username}; |
| 32 | use crate::error::{AppError, ErrorResponse, ValidationError}; | 32 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| @@ -257,23 +257,24 @@ async fn builder_login( | |||
| 257 | ) -> Result<(CookieJar, Json<BuilderResponse>), AppError> { | 257 | ) -> Result<(CookieJar, Json<BuilderResponse>), AppError> { |
| 258 | let control = st.tenants.control(); | 258 | let control = st.tenants.control(); |
| 259 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; | 259 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 260 | - let builder = match Builder::find_by_username(req.username.trim(), control).await? { | 260 | + let builder = |
| 261 | - Some(builder) => { | 261 | + match crate::service::builder::find_by_username(control, req.username.trim()).await? { |
| 262 | - if !builder.get_password_hash().verify_async(&password).await { | 262 | + Some(builder) => { |
| 263 | + if !builder.get_password_hash().verify_async(&password).await { | ||
| 264 | + return Err(AppError::Unauthorized); | ||
| 265 | + } | ||
| 266 | + builder | ||
| 267 | + } | ||
| 268 | + None => { | ||
| 269 | + // The same decoy hash `/auth/login` runs: a wrong name and a wrong | ||
| 270 | + // password must cost the same, or the reply time enumerates the | ||
| 271 | + // operator accounts. | ||
| 272 | + PasswordHash::verify_decoy_async(&password).await; | ||
| 263 | return Err(AppError::Unauthorized); | 273 | return Err(AppError::Unauthorized); |
| 264 | } | 274 | } |
| 265 | - builder | 275 | + }; |
| 266 | - } | ||
| 267 | - None => { | ||
| 268 | - // The same decoy hash `/auth/login` runs: a wrong name and a wrong | ||
| 269 | - // password must cost the same, or the reply time enumerates the | ||
| 270 | - // operator accounts. | ||
| 271 | - PasswordHash::verify_decoy_async(&password).await; | ||
| 272 | - return Err(AppError::Unauthorized); | ||
| 273 | - } | ||
| 274 | - }; | ||
| 275 | 276 | ||
| 276 | - let session = BuilderSession::create(builder.get_id(), control).await?; | 277 | + let session = crate::service::builder::create_session(control, builder.get_id()).await?; |
| 277 | let cookie = session_cookie( | 278 | let cookie = session_cookie( |
| 278 | format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()), | 279 | format!("{BUILDER_COOKIE_PREFIX}.{}", session.token().as_str()), |
| 279 | st.cookie_secure, | 280 | st.cookie_secure, |
| @@ -297,7 +298,7 @@ async fn builder_logout( | |||
| 297 | .get("session") | 298 | .get("session") |
| 298 | .and_then(|cookie| super::tenant_state::split_cookie(cookie.value())) | 299 | .and_then(|cookie| super::tenant_state::split_cookie(cookie.value())) |
| 299 | { | 300 | { |
| 300 | - BuilderSession::delete_by_token(token, st.tenants.control()).await?; | 301 | + crate::service::builder::delete_by_token(st.tenants.control(), token).await?; |
| 301 | } | 302 | } |
| 302 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); | 303 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 303 | Ok((jar, StatusCode::NO_CONTENT)) | 304 | Ok((jar, StatusCode::NO_CONTENT)) |
src/web/exams/mod.rsmodified+1 -2
| @@ -13,7 +13,6 @@ use utoipa_axum::routes; | |||
| 13 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | 13 | use crate::constant::{MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 14 | use crate::database::Database; | 14 | use crate::database::Database; |
| 15 | use crate::domain::answer_image::AnswerImage; | 15 | use crate::domain::answer_image::AnswerImage; |
| 16 | -use crate::domain::badge; | ||
| 17 | use crate::domain::bank_question::{BankQuestion, BankQuestionId}; | 16 | use crate::domain::bank_question::{BankQuestion, BankQuestionId}; |
| 18 | use crate::domain::bank_question_image::BankQuestionImage; | 17 | use crate::domain::bank_question_image::BankQuestionImage; |
| 19 | 18 | ||
| @@ -622,7 +621,7 @@ async fn grade( | |||
| 622 | // decoration on top of the mark: losing one to a transient database error | 621 | // decoration on top of the mark: losing one to a transient database error |
| 623 | // must never fail the grading, and the next counter move heals it. | 622 | // must never fail the grading, and the next counter move heals it. |
| 624 | for person in [teacher.get_id(), &target] { | 623 | for person in [teacher.get_id(), &target] { |
| 625 | - if let Err(err) = badge::sync(person, &st.db).await { | 624 | + if let Err(err) = service::badge::sync(&st.db, person).await { |
| 626 | tracing::warn!("failed to sync badges for {}: {err}", person.key()); | 625 | tracing::warn!("failed to sync badges for {}: {err}", person.key()); |
| 627 | } | 626 | } |
| 628 | } | 627 | } |
src/web/extractor.rsmodified+3 -3
| @@ -3,7 +3,7 @@ use axum::http::request::Parts; | |||
| 3 | use axum_extra::extract::CookieJar; | 3 | use axum_extra::extract::CookieJar; |
| 4 | 4 | ||
| 5 | use crate::database::Database; | 5 | use crate::database::Database; |
| 6 | -use crate::domain::builder::{Builder, BuilderSession}; | 6 | +use crate::domain::builder::Builder; |
| 7 | use crate::domain::role::Role; | 7 | use crate::domain::role::Role; |
| 8 | use crate::domain::user::User; | 8 | use crate::domain::user::User; |
| 9 | use crate::error::AppError; | 9 | use crate::error::AppError; |
| @@ -175,14 +175,14 @@ where | |||
| 175 | } | 175 | } |
| 176 | 176 | ||
| 177 | let control: Database = AppState::from_ref(state).tenants.control().clone(); | 177 | let control: Database = AppState::from_ref(state).tenants.control().clone(); |
| 178 | - let session = BuilderSession::find_by_token(token, &control) | 178 | + let session = crate::service::builder::find_by_token(&control, token) |
| 179 | .await? | 179 | .await? |
| 180 | .ok_or(AppError::Unauthorized)?; | 180 | .ok_or(AppError::Unauthorized)?; |
| 181 | if session.is_expired() { | 181 | if session.is_expired() { |
| 182 | return Err(AppError::Unauthorized); | 182 | return Err(AppError::Unauthorized); |
| 183 | } | 183 | } |
| 184 | Ok(RequireBuilder( | 184 | Ok(RequireBuilder( |
| 185 | - Builder::read(session.builder(), &control) | 185 | + crate::service::builder::read(&control, session.builder()) |
| 186 | .await? | 186 | .await? |
| 187 | .ok_or(AppError::Unauthorized)?, | 187 | .ok_or(AppError::Unauthorized)?, |
| 188 | )) | 188 | )) |
src/web/homework.rsmodified+1 -2
| @@ -18,7 +18,6 @@ use utoipa_axum::routes; | |||
| 18 | 18 | ||
| 19 | use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; | 19 | use crate::constant::{MAX_HOMEWORK_ASSIGNED, MAX_MAX_FILE_BYTES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 20 | use crate::database::Database; | 20 | use crate::database::Database; |
| 21 | -use crate::domain::badge; | ||
| 22 | use crate::domain::course::{Course, CourseId}; | 21 | use crate::domain::course::{Course, CourseId}; |
| 23 | 22 | ||
| 24 | use crate::domain::exam_result::Mark; | 23 | use crate::domain::exam_result::Mark; |
| @@ -837,7 +836,7 @@ async fn delete_submission( | |||
| 837 | /// of the work, and losing one to a transient database error is not worth | 836 | /// of the work, and losing one to a transient database error is not worth |
| 838 | /// refusing a hand-in over — the next counter move re-runs this and heals it. | 837 | /// refusing a hand-in over — the next counter move re-runs this and heals it. |
| 839 | async fn award_badges(user: &UserId, db: &Database) { | 838 | async fn award_badges(user: &UserId, db: &Database) { |
| 840 | - if let Err(err) = badge::sync(user, db).await { | 839 | + if let Err(err) = service::badge::sync(db, user).await { |
| 841 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); | 840 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); |
| 842 | } | 841 | } |
| 843 | } | 842 | } |
src/web/questions.rsmodified+1 -2
| @@ -19,7 +19,6 @@ use utoipa_axum::router::OpenApiRouter; | |||
| 19 | use utoipa_axum::routes; | 19 | use utoipa_axum::routes; |
| 20 | 20 | ||
| 21 | use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES}; | 21 | use crate::constant::{MAX_MAX_FILE_BYTES, POOL_QUESTION_STATUSES, UPLOAD_BODY_OVERHEAD_BYTES}; |
| 22 | -use crate::domain::badge; | ||
| 23 | use crate::domain::pool_question::{ | 22 | use crate::domain::pool_question::{ |
| 24 | PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, | 23 | PoolQuestion, PoolQuestionBody, PoolQuestionId, PoolQuestionTitle, |
| 25 | }; | 24 | }; |
| @@ -394,7 +393,7 @@ async fn approve_question( | |||
| 394 | // next counter move re-runs this and heals it. Two users, because the | 393 | // next counter move re-runs this and heals it. Two users, because the |
| 395 | // transition credits the approver and the asker alike. | 394 | // transition credits the approver and the asker alike. |
| 396 | for earner in [user.get_id(), question.get_asker()] { | 395 | for earner in [user.get_id(), question.get_asker()] { |
| 397 | - if let Err(err) = badge::sync(earner, &st.db).await { | 396 | + if let Err(err) = crate::service::badge::sync(&st.db, earner).await { |
| 398 | tracing::warn!("failed to sync badges for {}: {err}", earner.key()); | 397 | tracing::warn!("failed to sync badges for {}: {err}", earner.key()); |
| 399 | } | 398 | } |
| 400 | } | 399 | } |
src/web/sessions.rsmodified+1 -2
| @@ -11,7 +11,6 @@ use utoipa_axum::routes; | |||
| 11 | 11 | ||
| 12 | use crate::database::Database; | 12 | use crate::database::Database; |
| 13 | use crate::domain::attendance::AttendanceStatus; | 13 | use crate::domain::attendance::AttendanceStatus; |
| 14 | -use crate::domain::badge; | ||
| 15 | use crate::domain::course::Course; | 14 | use crate::domain::course::Course; |
| 16 | use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; | 15 | use crate::domain::course_session::{CourseSession, CourseSessionId, SessionTopic}; |
| 17 | 16 | ||
| @@ -344,7 +343,7 @@ async fn mark_roll_call( | |||
| 344 | // that failed, and knowing here whether the credit landed would mean | 343 | // that failed, and knowing here whether the credit landed would mean |
| 345 | // widening `mark`'s return type for nothing. | 344 | // widening `mark`'s return type for nothing. |
| 346 | for who in [&target, session.get_teacher()] { | 345 | for who in [&target, session.get_teacher()] { |
| 347 | - if let Err(err) = badge::sync(who, &st.db).await { | 346 | + if let Err(err) = service::badge::sync(&st.db, who).await { |
| 348 | tracing::warn!("failed to sync badges for {}: {err}", who.key()); | 347 | tracing::warn!("failed to sync badges for {}: {err}", who.key()); |
| 349 | } | 348 | } |
| 350 | } | 349 | } |
src/web/tenant_state.rsmodified+7 -7
| @@ -182,7 +182,6 @@ mod tests { | |||
| 182 | 182 | ||
| 183 | use crate::database::init_mem_tenants; | 183 | use crate::database::init_mem_tenants; |
| 184 | use crate::db::session; | 184 | use crate::db::session; |
| 185 | - use crate::domain::builder::{Builder, BuilderSession}; | ||
| 186 | use crate::domain::user::{Password, Username}; | 185 | use crate::domain::user::{Password, Username}; |
| 187 | use crate::tenant::DEMO_SLUG; | 186 | use crate::tenant::DEMO_SLUG; |
| 188 | use crate::web::{CurrentUser, RequireBuilder}; | 187 | use crate::web::{CurrentUser, RequireBuilder}; |
| @@ -218,20 +217,21 @@ mod tests { | |||
| 218 | let session = session::create(&school, user.get_id()).await.unwrap(); | 217 | let session = session::create(&school, user.get_id()).await.unwrap(); |
| 219 | let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); | 218 | let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str()); |
| 220 | 219 | ||
| 221 | - Builder::ensure( | 220 | + crate::service::builder::ensure( |
| 221 | + tenants.control(), | ||
| 222 | Username::try_new("operator").unwrap(), | 222 | Username::try_new("operator").unwrap(), |
| 223 | Password::try_new("secret1").unwrap(), | 223 | Password::try_new("secret1").unwrap(), |
| 224 | - tenants.control(), | ||
| 225 | ) | 224 | ) |
| 226 | .await | 225 | .await |
| 227 | .unwrap(); | 226 | .unwrap(); |
| 228 | - let builder = Builder::find_by_username("operator", tenants.control()) | 227 | + let builder = crate::service::builder::find_by_username(tenants.control(), "operator") |
| 229 | .await | 228 | .await |
| 230 | .unwrap() | 229 | .unwrap() |
| 231 | .unwrap(); | 230 | .unwrap(); |
| 232 | - let builder_session = BuilderSession::create(builder.get_id(), tenants.control()) | 231 | + let builder_session = |
| 233 | - .await | 232 | + crate::service::builder::create_session(tenants.control(), builder.get_id()) |
| 234 | - .unwrap(); | 233 | + .await |
| 234 | + .unwrap(); | ||
| 235 | let builder_cookie = format!("session=builder.{}", builder_session.token().as_str()); | 235 | let builder_cookie = format!("session=builder.{}", builder_session.token().as_str()); |
| 236 | 236 | ||
| 237 | let state = AppState { | 237 | let state = AppState { |
src/web/users.rsmodified+21 -17
| @@ -174,14 +174,9 @@ async fn apply_preferences( | |||
| 174 | let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; | 174 | let theme = merge_field(req.theme.as_deref(), Theme::try_from_str)?; |
| 175 | let language = merge_field(req.language.as_deref(), Language::try_from_str)?; | 175 | let language = merge_field(req.language.as_deref(), Language::try_from_str)?; |
| 176 | let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; | 176 | let palette_color = merge_field(req.palette_color.as_deref(), PaletteColor::try_from_str)?; |
| 177 | - let updated = crate::service::user::set_preferences( | 177 | + let updated = |
| 178 | - db, | 178 | + crate::service::user::set_preferences(db, user.get_id(), theme, language, palette_color) |
| 179 | - user.get_id(), | 179 | + .await?; |
| 180 | - theme, | ||
| 181 | - language, | ||
| 182 | - palette_color, | ||
| 183 | - ) | ||
| 184 | - .await?; | ||
| 185 | Ok(UserResponse::new(&updated)) | 180 | Ok(UserResponse::new(&updated)) |
| 186 | } | 181 | } |
| 187 | 182 | ||
| @@ -602,8 +597,7 @@ async fn link_student( | |||
| 602 | reason: "students can only be tied to a parent account", | 597 | reason: "students can only be tied to a parent account", |
| 603 | })); | 598 | })); |
| 604 | } | 599 | } |
| 605 | - let Some(student) = | 600 | + let Some(student) = crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? |
| 606 | - crate::service::user::read(&st.db, &UserId::from_key(&req.user_id)).await? | ||
| 607 | else { | 601 | else { |
| 608 | return Err(AppError::Validation(ValidationError::Invalid { | 602 | return Err(AppError::Validation(ValidationError::Invalid { |
| 609 | field: "user_id", | 603 | field: "user_id", |
| @@ -957,7 +951,7 @@ async fn profile_of( | |||
| 957 | let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; | 951 | let classes = ClassGroup::list_by_ids(&class_ids, &st.db).await?; |
| 958 | // Both totals are the full counts, not the windowed ones — the blocks are a | 952 | // Both totals are the full counts, not the windowed ones — the blocks are a |
| 959 | // preview, the stats are the truth. | 953 | // preview, the stats are the truth. |
| 960 | - let stats = ProfileStats::load(id, course_total, class_total, &st.db).await?; | 954 | + let stats = crate::service::profile::load(&st.db, id, course_total, class_total).await?; |
| 961 | let badges = badges_of(st, id, &stats).await?; | 955 | let badges = badges_of(st, id, &stats).await?; |
| 962 | Ok(ProfileResponse { | 956 | Ok(ProfileResponse { |
| 963 | id: id.key().to_string(), | 957 | id: id.key().to_string(), |
| @@ -1026,7 +1020,7 @@ async fn profile_of( | |||
| 1026 | /// callers log and swallow on purpose — leaves a gap, and that heals here on | 1020 | /// callers log and swallow on purpose — leaves a gap, and that heals here on |
| 1027 | /// the next profile read of that account. | 1021 | /// the next profile read of that account. |
| 1028 | /// | 1022 | /// |
| 1029 | -/// Nothing here revokes: [`badge::sync`] only ever adds, so a counter that has | 1023 | +/// Nothing here revokes: [`crate::service::badge::sync`] only ever adds, so a counter that has |
| 1030 | /// since fallen back below its threshold leaves the badge standing. The sync's | 1024 | /// since fallen back below its threshold leaves the badge standing. The sync's |
| 1031 | /// own error is logged and dropped, and the awards already read are served — | 1025 | /// own error is logged and dropped, and the awards already read are served — |
| 1032 | /// a decoration may not fail the profile it decorates. | 1026 | /// a decoration may not fail the profile it decorates. |
| @@ -1035,20 +1029,20 @@ async fn badges_of( | |||
| 1035 | user: &UserId, | 1029 | user: &UserId, |
| 1036 | stats: &ProfileStats, | 1030 | stats: &ProfileStats, |
| 1037 | ) -> Result<Vec<BadgeAward>, AppError> { | 1031 | ) -> Result<Vec<BadgeAward>, AppError> { |
| 1038 | - let awards = BadgeAward::list_for(user, &st.db).await?; | 1032 | + let awards = crate::service::badge::list_for(&st.db, user).await?; |
| 1039 | let complete = badge::earned(stats.get_totals()) | 1033 | let complete = badge::earned(stats.get_totals()) |
| 1040 | .iter() | 1034 | .iter() |
| 1041 | .all(|id| awards.iter().any(|award| award.get_badge() == *id)); | 1035 | .all(|id| awards.iter().any(|award| award.get_badge() == *id)); |
| 1042 | if complete { | 1036 | if complete { |
| 1043 | return Ok(awards); | 1037 | return Ok(awards); |
| 1044 | } | 1038 | } |
| 1045 | - if let Err(err) = badge::sync(user, &st.db).await { | 1039 | + if let Err(err) = crate::service::badge::sync(&st.db, user).await { |
| 1046 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); | 1040 | tracing::warn!("failed to sync badges for {}: {err}", user.key()); |
| 1047 | return Ok(awards); | 1041 | return Ok(awards); |
| 1048 | } | 1042 | } |
| 1049 | // Re-read so the badge just healed appears on *this* response, stamp and | 1043 | // Re-read so the badge just healed appears on *this* response, stamp and |
| 1050 | // all, rather than only on the next one. | 1044 | // all, rather than only on the next one. |
| 1051 | - BadgeAward::list_for(user, &st.db).await | 1045 | + crate::service::badge::list_for(&st.db, user).await |
| 1052 | } | 1046 | } |
| 1053 | 1047 | ||
| 1054 | /// The profile gate: any authenticated account reads any profile — except a | 1048 | /// The profile gate: any authenticated account reads any profile — except a |
| @@ -1070,7 +1064,9 @@ async fn ensure_may_read_profile( | |||
| 1070 | async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> { | 1064 | async fn readable_profile_user(st: &AppState, caller: &User, id: &str) -> Result<User, AppError> { |
| 1071 | let target = UserId::from_key(id); | 1065 | let target = UserId::from_key(id); |
| 1072 | ensure_may_read_profile(caller, &target, &st.db).await?; | 1066 | ensure_may_read_profile(caller, &target, &st.db).await?; |
| 1073 | - crate::service::user::read(&st.db, &target).await?.ok_or(AppError::NotFound) | 1067 | + crate::service::user::read(&st.db, &target) |
| 1068 | + .await? | ||
| 1069 | + .ok_or(AppError::NotFound) | ||
| 1074 | } | 1070 | } |
| 1075 | 1071 | ||
| 1076 | /// The caller's own public profile — what everyone else sees of them. | 1072 | /// The caller's own public profile — what everyone else sees of them. |
| @@ -1165,7 +1161,15 @@ async fn upload_my_avatar( | |||
| 1165 | 1161 | ||
| 1166 | let file = ulid::Ulid::new().to_string(); | 1162 | let file = ulid::Ulid::new().to_string(); |
| 1167 | store_blob(&st, &file, &upload.data, || async { | 1163 | store_blob(&st, &file, &upload.data, || async { |
| 1168 | - match crate::service::user::set_avatar(&st.db, user.get_id(), &file, &upload.content_type, size).await? { | 1164 | + match crate::service::user::set_avatar( |
| 1165 | + &st.db, | ||
| 1166 | + user.get_id(), | ||
| 1167 | + &file, | ||
| 1168 | + &upload.content_type, | ||
| 1169 | + size, | ||
| 1170 | + ) | ||
| 1171 | + .await? | ||
| 1172 | + { | ||
| 1169 | // Row written; the picture this one replaced comes off disk. | 1173 | // Row written; the picture this one replaced comes off disk. |
| 1170 | Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), | 1174 | Some(before) => Ok(((), before.get_avatar_file().map(str::to_string))), |
| 1171 | // The account went away mid-upload — the fresh blob is an orphan. | 1175 | // The account went away mid-upload — the fresh blob is an orphan. |
tests/builder_api.rsmodified+5 -5
| @@ -8,8 +8,8 @@ mod common; | |||
| 8 | use axum::Router; | 8 | use axum::Router; |
| 9 | use axum::http::StatusCode; | 9 | use axum::http::StatusCode; |
| 10 | use common::*; | 10 | use common::*; |
| 11 | -use hezarfen_backend::domain::builder::Builder; | ||
| 12 | use hezarfen_backend::domain::user::{Password, Username}; | 11 | use hezarfen_backend::domain::user::{Password, Username}; |
| 12 | +use hezarfen_backend::service::builder; | ||
| 13 | use hezarfen_backend::tenant::{DEMO_SLUG, Tenants}; | 13 | use hezarfen_backend::tenant::{DEMO_SLUG, Tenants}; |
| 14 | use serde_json::{Value, json}; | 14 | use serde_json::{Value, json}; |
| 15 | 15 | ||
| @@ -20,10 +20,10 @@ const BUILDER_PASS: &str = "secret1"; | |||
| 20 | /// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path. | 20 | /// production's `BUILDER_USERNAME`/`BUILDER_PASSWORD` seed, by the same path. |
| 21 | async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) { | 21 | async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) { |
| 22 | let (app, db, tenants) = app_and_tenants().await; | 22 | let (app, db, tenants) = app_and_tenants().await; |
| 23 | - Builder::ensure( | 23 | + builder::ensure( |
| 24 | + tenants.control(), | ||
| 24 | Username::try_new(BUILDER_USER).unwrap(), | 25 | Username::try_new(BUILDER_USER).unwrap(), |
| 25 | Password::try_new(BUILDER_PASS).unwrap(), | 26 | Password::try_new(BUILDER_PASS).unwrap(), |
| 26 | - tenants.control(), | ||
| 27 | ) | 27 | ) |
| 28 | .await | 28 | .await |
| 29 | .expect("seed the builder"); | 29 | .expect("seed the builder"); |
| @@ -1229,10 +1229,10 @@ async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { | |||
| 1229 | return; | 1229 | return; |
| 1230 | }; | 1230 | }; |
| 1231 | let app = deployment.app; | 1231 | let app = deployment.app; |
| 1232 | - Builder::ensure( | 1232 | + builder::ensure( |
| 1233 | + deployment.tenants.control(), | ||
| 1233 | Username::try_new(BUILDER_USER).unwrap(), | 1234 | Username::try_new(BUILDER_USER).unwrap(), |
| 1234 | Password::try_new(BUILDER_PASS).unwrap(), | 1235 | Password::try_new(BUILDER_PASS).unwrap(), |
| 1235 | - deployment.tenants.control(), | ||
| 1236 | ) | 1236 | ) |
| 1237 | .await | 1237 | .await |
| 1238 | .expect("seed the builder"); | 1238 | .expect("seed the builder"); |
tests/e2e.rsmodified+2 -2
| @@ -28,10 +28,10 @@ async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (St | |||
| 28 | // The deployment's operator, seeded exactly as `main` does from | 28 | // The deployment's operator, seeded exactly as `main` does from |
| 29 | // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable | 29 | // `BUILDER_USERNAME`/`BUILDER_PASSWORD`, so the vendor surface is drivable |
| 30 | // over real TCP here too. | 30 | // over real TCP here too. |
| 31 | - hezarfen_backend::domain::builder::Builder::ensure( | 31 | + hezarfen_backend::service::builder::ensure( |
| 32 | + tenants.control(), | ||
| 32 | hezarfen_backend::domain::user::Username::try_new("operator").unwrap(), | 33 | hezarfen_backend::domain::user::Username::try_new("operator").unwrap(), |
| 33 | hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(), | 34 | hezarfen_backend::domain::user::Password::try_new("secret1").unwrap(), |
| 34 | - tenants.control(), | ||
| 35 | ) | 35 | ) |
| 36 | .await | 36 | .await |
| 37 | .expect("seed the builder"); | 37 | .expect("seed the builder"); |
tests/integration.rsmodified+7 -7
| @@ -27951,10 +27951,10 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t | |||
| 27951 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; | 27951 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 27952 | let token_a = common::cookie_token(&a).to_string(); | 27952 | let token_a = common::cookie_token(&a).to_string(); |
| 27953 | 27953 | ||
| 27954 | - hezarfen_backend::domain::builder::Builder::ensure( | 27954 | + hezarfen_backend::service::builder::ensure( |
| 27955 | + tenants.control(), | ||
| 27955 | Username::try_new("operator").unwrap(), | 27956 | Username::try_new("operator").unwrap(), |
| 27956 | Password::try_new("secret1").unwrap(), | 27957 | Password::try_new("secret1").unwrap(), |
| 27957 | - tenants.control(), | ||
| 27958 | ) | 27958 | ) |
| 27959 | .await | 27959 | .await |
| 27960 | .expect("seed the builder"); | 27960 | .expect("seed the builder"); |
| @@ -28511,10 +28511,10 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | |||
| 28511 | "the namespace holds exactly the two schools and the control database" | 28511 | "the namespace holds exactly the two schools and the control database" |
| 28512 | ); | 28512 | ); |
| 28513 | 28513 | ||
| 28514 | - hezarfen_backend::domain::builder::Builder::ensure( | 28514 | + hezarfen_backend::service::builder::ensure( |
| 28515 | + d.tenants.control(), | ||
| 28515 | Username::try_new("operator").unwrap(), | 28516 | Username::try_new("operator").unwrap(), |
| 28516 | Password::try_new("secret1").unwrap(), | 28517 | Password::try_new("secret1").unwrap(), |
| 28517 | - d.tenants.control(), | ||
| 28518 | ) | 28518 | ) |
| 28519 | .await | 28519 | .await |
| 28520 | .expect("seed the builder"); | 28520 | .expect("seed the builder"); |
| @@ -28824,7 +28824,7 @@ async fn a_disabled_module_refuses_its_websocket_upgrade() { | |||
| 28824 | // holds for *every* module, driven through the vendor's own surface, plus the | 28824 | // holds for *every* module, driven through the vendor's own surface, plus the |
| 28825 | // coverage test that fails when a future nest is mounted ungated. | 28825 | // coverage test that fails when a future nest is mounted ungated. |
| 28826 | 28826 | ||
| 28827 | -use hezarfen_backend::domain::builder::Builder; | 28827 | +use hezarfen_backend::service::builder; |
| 28828 | 28828 | ||
| 28829 | const SWEEP_BUILDER_USER: &str = "operator"; | 28829 | const SWEEP_BUILDER_USER: &str = "operator"; |
| 28830 | const SWEEP_BUILDER_PASS: &str = "secret1"; | 28830 | const SWEEP_BUILDER_PASS: &str = "secret1"; |
| @@ -28833,10 +28833,10 @@ const SWEEP_BUILDER_PASS: &str = "secret1"; | |||
| 28833 | /// modules by the same path production does (mirrors `tests/builder_api.rs`). | 28833 | /// modules by the same path production does (mirrors `tests/builder_api.rs`). |
| 28834 | async fn sweep_deployment() -> (axum::Router, hezarfen_backend::database::Database, Tenants) { | 28834 | async fn sweep_deployment() -> (axum::Router, hezarfen_backend::database::Database, Tenants) { |
| 28835 | let (app, db, tenants) = common::app_and_tenants().await; | 28835 | let (app, db, tenants) = common::app_and_tenants().await; |
| 28836 | - Builder::ensure( | 28836 | + builder::ensure( |
| 28837 | + tenants.control(), | ||
| 28837 | Username::try_new(SWEEP_BUILDER_USER).unwrap(), | 28838 | Username::try_new(SWEEP_BUILDER_USER).unwrap(), |
| 28838 | Password::try_new(SWEEP_BUILDER_PASS).unwrap(), | 28839 | Password::try_new(SWEEP_BUILDER_PASS).unwrap(), |
| 28839 | - tenants.control(), | ||
| 28840 | ) | 28840 | ) |
| 28841 | .await | 28841 | .await |
| 28842 | .expect("seed the builder"); | 28842 | .expect("seed the builder"); |