forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

badge.rs215 lines, 8.7 KiBHistoryRawDownload
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
7use sqlx::AssertSqlSafe;
8
9use crate::constant::BADGE_AWARD_TABLE;
10use crate::database::Database;
11use crate::domain::badge::{BADGES, BadgeAward, BadgeStats};
12use crate::domain::timestamp::Timestamp;
13use crate::domain::user::UserId;
14use crate::error::AppError;
15
16/// Every counter off the user row, in one statement — a record lookup, not
17/// a scan.
18///
19/// The columns are `BIGINT NOT NULL DEFAULT 0`, so each reads as a true zero
20/// no matter when the row was written — the old `(column ?? 0)` projection
21/// existed because the old store stored absent counters as absent keys. A
22/// user row that is gone entirely reads as all zeros too — a badge sync is
23/// not the place to discover a deleted account.
24pub async fn load(db: &Database, user: &UserId) -> Result<BadgeStats, AppError> {
25 let stats = sqlx::query_as!(
26 BadgeStats,
27 r#"SELECT homework_submitted_total AS homework_submitted,
28 homework_on_time_total AS homework_on_time,
29 exam_sat_total AS exam_sat,
30 pomodoro_finished_total AS pomodoro_finished,
31 pomodoro_focus_ms_total AS pomodoro_focus_ms,
32 marks_given_total AS marks_given,
33 lessons_held_total AS lessons_held,
34 pool_approved_total AS pool_approved,
35 pool_published_total AS pool_published,
36 lessons_attended_total AS lessons_attended,
37 high_mark_total AS high_mark,
38 study_streak_longest AS study_streak
39 FROM app_user WHERE id = $1"#,
40 user.uuid()
41 )
42 .fetch_optional(db)
43 .await?;
44 Ok(stats.unwrap_or_default())
45}
46
47/// Everything `user` has earned, oldest first.
48///
49/// Filtered to the ids the catalog still holds: a badge retired from
50/// `BADGES` stops being served without a data migration, and its rows stay
51/// where they are in case the line comes back.
52///
53/// The badge id breaks the tie, because one sync stamps every badge it
54/// awards with the same millisecond and an arbitrary order there would
55/// shuffle a student's shelf between reads. It is the row's own key order
56/// too — the primary key is `(app_user, badge)` and this reads one user —
57/// but spelled as the projected column on purpose, because it is the
58/// *served* order, not an internal one.
59pub async fn list_for(db: &Database, user: &UserId) -> Result<Vec<BadgeAward>, AppError> {
60 let ids: Vec<String> = BADGES.iter().map(|(id, ..)| (*id).to_string()).collect();
61 let awards = sqlx::query_as!(
62 BadgeAward,
63 r#"SELECT badge,
64 earned_at AS "earned_at!: Timestamp"
65 FROM badge_award
66 WHERE app_user = $1 AND badge = ANY($2)
67 ORDER BY earned_at ASC, badge ASC
68 LIMIT $3"#,
69 user.uuid(),
70 &ids,
71 BADGES.len() as i64,
72 )
73 .fetch_all(db)
74 .await?;
75 Ok(awards)
76}
77
78/// Write an award row for every badge `user` has now earned and does not
79/// already hold.
80///
81/// The `WHERE earned_at IS NULL` arm of the conflict update is the whole of
82/// the idempotency: the first call inserts the row, and every later call —
83/// with a later `$now` — conflicts on the pair's primary key and matches a
84/// row that already has a stamp, writing nothing at all. So the earned-at a
85/// student sees is when they first crossed the line, not when the counter
86/// last moved.
87///
88/// Runtime-built SQL by the named exemption for this sync (the statement
89/// count is the earned list's length, decided by the pure rule). Each
90/// statement is fully bound — table name is a crate constant, badge ids are
91/// catalog constants, nothing client-shaped enters.
92///
93/// **Callers must log and ignore the error.** A badge is a decoration on top
94/// of somebody's homework submission, exam sitting or pomodoro stint, and none
95/// of those may fail because the decoration could not be written. The `Result`
96/// is returned rather than swallowed here so the caller's log line names the
97/// real cause; the next counter bump re-runs this and heals whatever was
98/// missed.
99pub async fn sync(db: &Database, user: &UserId) -> Result<(), AppError> {
100 let stats = load(db, user).await?;
101 let earned = crate::domain::badge::earned(&stats);
102 if earned.is_empty() {
103 return Ok(());
104 }
105 let now = Timestamp::now().as_millis();
106 for badge in earned {
107 sqlx::query(AssertSqlSafe(format!(
108 "INSERT INTO {BADGE_AWARD_TABLE} (app_user, badge, earned_at) \
109 VALUES ($1, $2, $3) \
110 ON CONFLICT (app_user, badge) DO UPDATE \
111 SET earned_at = badge_award.earned_at \
112 WHERE badge_award.earned_at IS NULL"
113 )))
114 .bind(user.uuid())
115 .bind(badge)
116 .bind(now)
117 .execute(db)
118 .await?;
119 }
120 Ok(())
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::constant::BADGE_AWARD_TABLE;
127 use crate::database::init_test_db;
128 use crate::domain::user::Username;
129
130 async fn a_user(username: &str, db: &Database) -> crate::domain::user::User {
131 crate::db::user::create(db, Username::try_new(username).unwrap(), None)
132 .await
133 .unwrap()
134 }
135
136 async fn count_awards(db: &Database, user: &UserId) -> i64 {
137 let (count,): (i64,) = sqlx::query_as(sqlx::AssertSqlSafe(format!(
138 "SELECT count(*) FROM {BADGE_AWARD_TABLE} WHERE app_user = $1"
139 )))
140 .bind(user.uuid())
141 .fetch_one(db)
142 .await
143 .unwrap();
144 count
145 }
146
147 #[tokio::test]
148 async fn load_defaults_every_counter_to_zero() {
149 let (db, _leases) = init_test_db().await;
150 let user = a_user("badge-sifir", &db).await;
151
152 let stats = load(&db, user.get_id()).await.unwrap();
153 assert_eq!(stats.get_homework_submitted(), 0);
154 assert_eq!(stats.get_pomodoro_focus_ms(), 0);
155 assert_eq!(stats.get_study_streak(), 0);
156
157 // A row that is gone entirely is all zeros, not an error.
158 let ghost = UserId::from_key("00000000-0000-0000-0000-000000000000");
159 let stats = load(&db, &ghost).await.unwrap();
160 assert_eq!(stats.get_homework_submitted(), 0);
161 }
162
163 #[tokio::test]
164 async fn sync_is_idempotent_and_keeps_the_first_stamp() {
165 let (db, _leases) = init_test_db().await;
166 let user = a_user("badge-ali", &db).await;
167
168 // Seed two submitted homeworks: enough for the first badge tier.
169 sqlx::query("UPDATE app_user SET homework_submitted_total = 2 WHERE id = $1")
170 .bind(user.get_id().uuid())
171 .execute(&db)
172 .await
173 .unwrap();
174
175 sync(&db, user.get_id()).await.unwrap();
176 let first = count_awards(&db, user.get_id()).await;
177 assert!(first > 0, "at least one badge crossed the line");
178 let shelf = list_for(&db, user.get_id()).await.unwrap();
179 let earned_at = shelf[0].get_earned_at();
180 // A second sync with the counter moved *further* writes nothing: the
181 // stamps are from the first crossing, and no row is duplicated.
182 sqlx::query("UPDATE app_user SET homework_submitted_total = 5 WHERE id = $1")
183 .bind(user.get_id().uuid())
184 .execute(&db)
185 .await
186 .unwrap();
187 sync(&db, user.get_id()).await.unwrap();
188 assert_eq!(count_awards(&db, user.get_id()).await, first);
189 let shelf_again = list_for(&db, user.get_id()).await.unwrap();
190 assert_eq!(shelf_again[0].get_earned_at(), earned_at);
191 assert_eq!(shelf_again.len(), shelf.len());
192 assert_eq!(shelf_again[0].get_badge(), shelf[0].get_badge());
193
194 // The shelf is filtered to badges the catalog still holds, oldest
195 // first with the badge id breaking same-millisecond ties.
196 for pair in shelf.windows(2) {
197 assert!(
198 pair[0].get_earned_at().as_millis() <= pair[1].get_earned_at().as_millis(),
199 "the shelf is ordered oldest first"
200 );
201 }
202 }
203
204 #[tokio::test]
205 async fn sync_writes_nothing_for_a_earned_nothing() {
206 let (db, _leases) = init_test_db().await;
207 let user = a_user("badge-bos", &db).await;
208 sync(&db, user.get_id()).await.unwrap();
209 assert_eq!(
210 count_awards(&db, user.get_id()).await,
211 0,
212 "zero counters earn zero badges"
213 );
214 }
215}