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

pomodoro.rs920 lines, 39.1 KiBHistoryRawDownload
1//! The `pomodoro_session` table: the open-slot start/finish pair and the
2//! newest-first log. The counting verdict, the lifetime badge counters, and
3//! the study streak are all decided inside [`finish`]'s one transaction —
4//! the whole rule is the batch itself.
5
6use crate::constant::{MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS};
7use crate::database::{Database, tx_with_retry};
8use crate::db::page::{Param, PagedList};
9use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
10use crate::domain::timestamp::Timestamp;
11use crate::domain::user::UserId;
12use crate::error::AppError;
13use sqlx::postgres::PgArguments;
14use sqlx::query_as;
15use sqlx::AssertSqlSafe;
16
17/// Start a session for `user`, stamped with the server clock. The open slot
18/// is the partial unique index (`pomodoro_session_open_stint`): one row per
19/// user with `finished_at IS NULL`. A dangling unfinished session (the
20/// browser died mid-timer) is replaced by the same statement — the arbiter
21/// turns the insert into an in-place re-stamp (`DO UPDATE`), so the old row
22/// becomes the new stint; it never counted, and blocking the next start
23/// behind it would only punish the student for a crash.
24///
25/// The replace has to ride the arbiter. A `WITH gone AS (DELETE …) INSERT …`
26/// CTE cannot do it: both halves run on one snapshot, so the insert's
27/// uniqueness check still sees the row the CTE just deleted and refuses
28/// (23505) *deterministically* — a retry re-sends the identical statement and
29/// dies identically, which is the 500 the port briefly shipped. `DO UPDATE`
30/// is atomic: two racing starts cannot both win the slot, and the loser
31/// re-stamps the winner's row — the same last-write-wins the old
32/// deterministic-key upsert had.
33///
34/// `label` is the student's own name for the stint, validated and trimmed
35/// upstream and stored verbatim. A `None` binds NULL — an unnamed start
36/// reads back unnamed.
37pub async fn start(
38 db: &Database,
39 user: &UserId,
40 label: Option<String>,
41) -> Result<PomodoroSession, AppError> {
42 let started_at = Timestamp::now();
43 let id = PomodoroSessionId::generate();
44 let started = query_as!(
45 PomodoroSession,
46 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
47 VALUES ($2, $1, $3, NULL, NULL, $4)
48 ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
49 SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL,
50 label = EXCLUDED.label
51 RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
52 started_at AS \"started_at: Timestamp\", \
53 finished_at AS \"finished_at: Timestamp\", counted, label",
54 user.uuid(),
55 id.uuid(),
56 started_at.as_millis(),
57 label
58 )
59 .fetch_one(db)
60 .await?;
61 Ok(started)
62}
63
64/// Close `user`'s running session, deciding the counting verdict, the
65/// lifetime badge counters, and the study streak in one transaction.
66///
67/// The open row is taken by a guarded `DELETE … WHERE finished_at IS NULL
68/// RETURNING` — of two racing finishes exactly one receives the row, and
69/// the other is refused (`no pomodoro session running`), the old abort
70/// marker now an ordinary early return. The user row carries every counter family
71/// this decision moves, so the transaction takes it `FOR NO KEY UPDATE`,
72/// decides in Rust, and writes once: no interleaving can tear the streak
73/// pair, and a rival finish is serialized on the row lock instead of
74/// aborting. `longest` is written as `max(longest, current)`, which cannot
75/// come down under any interleaving.
76///
77/// `finished_at` is floored at the row's own `started_at`. Both stamps come
78/// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move
79/// *backwards* mid-stint — so a close can legitimately read earlier than its
80/// own start with nothing wrong on the client's side. Refusing it would lose
81/// a real study session and leave the open slot wedged for a fault the
82/// student did not cause; recording a zero-length stint keeps the session
83/// count honest and its duration merely understated. Nothing downstream may
84/// then read a negative duration (`ProfileStats::load` sums these).
85///
86/// The lifetime badge counters move only for a stint that **counts**, which
87/// is [`MIN_COUNTED_POMODORO_MS`] of real focus and at most
88/// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this
89/// is the farm [`crate::domain::pool_question::PoolQuestion::approve`]
90/// argues about from the other end: finishing is self-service, one stint is
91/// two requests and no second person, so a counter moved once per
92/// round-trip is farmable. Both stamps are the server's own clock, so the
93/// duration needs no distrusting, only a floor.
94///
95/// The verdict is *stamped* on the closed row (`counted`), not re-derived
96/// later: the thresholds are compiled in and will move, and a reader that
97/// re-judged an old stint against today's numbers would answer something
98/// other than what was credited. A stint below the bar is still recorded,
99/// still listed, and still sums into the log's focus total — the rule
100/// bounds what *counts*, never what is kept.
101///
102/// The day quota is bucketed like the streak (midnight UTC,
103/// [`Timestamp::day_number`]) and rolls whether the stint counts or not;
104/// only the `+ 1` sits behind the verdict.
105///
106/// The **study streak** rides the same transaction, and the same verdict: a
107/// study day is a UTC calendar day on which a stint *counted* — the same
108/// day again changes nothing, the next day extends the run, any other gap
109/// starts a new one at 1.
110///
111/// The closed stint is re-filed under a freshly minted id: the open slot is
112/// the partial index, so the closed row releases it by no longer matching
113/// `finished_at IS NULL`.
114pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
115 let done = Timestamp::now();
116 let day = done.day_number();
117 // Owned capture: an `async move` closure holding a `&UserId` fails the
118 // higher-ranked `Send` check `tx_with_retry`'s future must pass.
119 let user = *user;
120 let saved = tx_with_retry(db, false, async move |tx| {
121 // Take the open row. Empty means nothing is running.
122 let open = sqlx::query!(
123 "DELETE FROM pomodoro_session
124 WHERE app_user = $1 AND finished_at IS NULL
125 RETURNING started_at AS \"started_at: Timestamp\", label",
126 user.uuid()
127 )
128 .fetch_optional(&mut *tx)
129 .await?;
130 let Some(open) = open else {
131 return Err(AppError::Conflict("no pomodoro session running"));
132 };
133 let end = Timestamp::from_millis(open.started_at.as_millis().max(done.as_millis()));
134 let ms = end.as_millis() - open.started_at.as_millis();
135
136 // Every counter this decision moves lives on the user row; the row
137 // lock decides the whole verdict against one consistent read.
138 let counts = sqlx::query!(
139 "SELECT pomodoro_counted_today, pomodoro_counted_day, pomodoro_finished_total, \
140 pomodoro_focus_ms_total, study_streak_current, study_streak_last_day, \
141 study_streak_longest \
142 FROM app_user WHERE id = $1 \
143 FOR NO KEY UPDATE",
144 user.uuid()
145 )
146 .fetch_optional(&mut *tx)
147 .await?;
148 let Some(c) = counts else {
149 // The foreign key on the stint would refuse the insert below
150 // anyway; the honest answer for a user who does not exist.
151 return Err(AppError::NotFound);
152 };
153
154 // Day-bucket roll: a finish on a new day reopens the quota.
155 let counted_today = if c.pomodoro_counted_day == Some(day) {
156 c.pomodoro_counted_today
157 } else {
158 0
159 };
160 let counted = ms >= MIN_COUNTED_POMODORO_MS && counted_today < MAX_COUNTED_POMODORO_PER_DAY;
161 if counted {
162 let current = match c.study_streak_last_day {
163 Some(last) if last == day => c.study_streak_current,
164 Some(last) if last == day - 1 => c.study_streak_current + 1,
165 _ => 1,
166 };
167 sqlx::query!(
168 "UPDATE app_user SET pomodoro_finished_total = pomodoro_finished_total + 1, \
169 pomodoro_focus_ms_total = pomodoro_focus_ms_total + $2, \
170 pomodoro_counted_today = $3, pomodoro_counted_day = $4, \
171 study_streak_current = $5, study_streak_last_day = $4, \
172 study_streak_longest = GREATEST(study_streak_longest, $5) \
173 WHERE id = $1",
174 user.uuid(),
175 ms,
176 counted_today + 1,
177 day,
178 current,
179 )
180 .execute(&mut *tx)
181 .await?;
182 } else if c.pomodoro_counted_day != Some(day) {
183 sqlx::query!(
184 "UPDATE app_user SET pomodoro_counted_today = 0, pomodoro_counted_day = $2 \
185 WHERE id = $1",
186 user.uuid(),
187 day
188 )
189 .execute(&mut *tx)
190 .await?;
191 }
192
193 let closed = query_as!(
194 PomodoroSession,
195 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
196 VALUES ($1, $2, $3, $4, $5, $6)
197 RETURNING id AS \"id: PomodoroSessionId\", app_user AS \"user: UserId\", \
198 started_at AS \"started_at: Timestamp\", \
199 finished_at AS \"finished_at: Timestamp\", counted, label",
200 PomodoroSessionId::generate().uuid(),
201 user.uuid(),
202 open.started_at.as_millis(),
203 Some(end.as_millis()),
204 Some(counted),
205 open.label,
206 )
207 .fetch_one(&mut *tx)
208 .await?;
209 Ok(closed)
210 })
211 .await?;
212 // A badge is a decoration on top of the stint: losing one to a
213 // transient database error must never fail the finish, and the next
214 // counter move re-runs this and heals it.
215 if let Err(err) = crate::db::badge::sync(db, &user).await {
216 tracing::warn!("failed to sync badges for {}: {err}", user.key());
217 }
218 Ok(saved)
219}
220
221/// One read of the log: the page's rows, the filtered session count, and the
222/// filtered focus total — three answers over one `WHERE`, so they can never
223/// disagree.
224pub(crate) struct PomodoroLogPage {
225 pub(crate) items: Vec<PomodoroSession>,
226 /// Sessions in the filtered set, before the page window is applied.
227 pub(crate) total: i64,
228 /// `SUM(finished_at - started_at)` over the filtered set, unpaged.
229 pub(crate) total_focus_ms: i64,
230}
231
232/// The `FROM … WHERE` the page, the count, and the focus sum share, assembled
233/// once per read. Placeholders are positional: `$1` is the user, and the
234/// bounds follow in `from`, `to` order, present exactly when the arm names
235/// them.
236fn log_from_where(from: bool, to: bool) -> &'static str {
237 match (from, to) {
238 (true, true) => {
239 "pomodoro_session WHERE app_user = $1 AND started_at >= $2 AND started_at < $3"
240 }
241 (true, false) => "pomodoro_session WHERE app_user = $1 AND started_at >= $2",
242 (false, true) => "pomodoro_session WHERE app_user = $1 AND started_at < $2",
243 (false, false) => "pomodoro_session WHERE app_user = $1",
244 }
245}
246
247/// A page of `user`'s log, newest first — the running session (if any)
248/// included — with the half-open window `[from, to)` applied *before* both
249/// the page window and the sums. Ordered by `started_at`, never by id alone:
250/// the log is a chronology, and the id tie-break only ever separates two
251/// *finished* stints sharing a `started_at` — there is one running row per
252/// user, so it can never tie with itself.
253///
254/// With no bounds this is the whole-history read the unpaged `list` used to give.
255/// With bounds, answering the page never materializes the log beyond
256/// the page itself — the count and the focus total are database scalars over
257/// the same `WHERE`.
258pub(crate) async fn page_for_user(
259 db: &Database,
260 user: &UserId,
261 from: Option<i64>,
262 to: Option<i64>,
263 limit: Option<i64>,
264 offset: i64,
265) -> Result<PomodoroLogPage, AppError> {
266 let from_where = log_from_where(from.is_some(), to.is_some());
267 let mut list = PagedList::new(from_where, "ORDER BY started_at DESC, id DESC").bind(user.uuid());
268 if let Some(ms) = from {
269 list = list.bind(ms);
270 }
271 if let Some(ms) = to {
272 list = list.bind(ms);
273 }
274 let (items, total) = list.run(limit, offset, db).await?;
275 let total_focus_ms = focus_total_ms(db, from_where, user, from, to).await?;
276 Ok(PomodoroLogPage {
277 items,
278 total,
279 total_focus_ms,
280 })
281}
282
283/// `SUM(finished_at - started_at)` over the same filtered set the page reads —
284/// one SQL scalar, so the focus total never folds the log in Rust. A running
285/// stint contributes nothing (its `finished_at` is `NULL` and `SUM` skips
286/// `NULL`), and an empty set `COALESCE`s to zero. `SUM(bigint)` answers
287/// `numeric`, hence the `::BIGINT` cast.
288async fn focus_total_ms(
289 db: &Database,
290 from_where: &str,
291 user: &UserId,
292 from: Option<i64>,
293 to: Option<i64>,
294) -> Result<i64, AppError> {
295 let sql = format!(
296 "SELECT COALESCE(SUM(finished_at - started_at), 0)::BIGINT FROM {from_where}"
297 );
298 let mut args = PgArguments::default();
299 Param::Uuid(user.uuid()).add_to(&mut args);
300 if let Some(ms) = from {
301 Param::I64(ms).add_to(&mut args);
302 }
303 if let Some(ms) = to {
304 Param::I64(ms).add_to(&mut args);
305 }
306 Ok(sqlx::query_scalar_with(AssertSqlSafe(sql), args)
307 .fetch_one(db)
308 .await?)
309}
310#[cfg(test)]
311mod tests {
312 use super::*;
313 use sqlx::Row as _;
314
315 /// A real `app_user` row: the counters land with `UPDATE`, which only ever
316 /// touches a row that exists, so a fabricated id would silently store
317 /// nothing. The tests above need no row — they read only the stint log.
318 async fn a_user(db: &Database) -> UserId {
319 let user = UserId::generate();
320 sqlx::query("INSERT INTO app_user (id, username, created_at) VALUES ($1, $2, 0)")
321 .bind(user.uuid())
322 .bind(format!("u{}", &user.key()[30..]))
323 .execute(db)
324 .await
325 .unwrap();
326 user
327 }
328
329 /// `(finished_total, focus_ms_total)` re-read from the store — never off
330 /// what `finish` returned, which proves nothing about what was written.
331 async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
332 let row = sqlx::query(
333 "SELECT pomodoro_finished_total, pomodoro_focus_ms_total \
334 FROM app_user WHERE id = $1",
335 )
336 .bind(user.uuid())
337 .fetch_one(db)
338 .await
339 .unwrap();
340 (
341 row.try_get::<i64, _>(0).unwrap(),
342 row.try_get::<i64, _>(1).unwrap(),
343 )
344 }
345
346 /// `(current, longest, last_day)` re-read from the store; the unset day
347 /// reads as the sentinel `-1` the streak arithmetic runs on.
348 async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
349 let row = sqlx::query(
350 "SELECT study_streak_current, study_streak_longest, \
351 COALESCE(study_streak_last_day, -1) \
352 FROM app_user WHERE id = $1",
353 )
354 .bind(user.uuid())
355 .fetch_one(db)
356 .await
357 .unwrap();
358 (
359 row.try_get::<i64, _>(0).unwrap(),
360 row.try_get::<i64, _>(1).unwrap(),
361 row.try_get::<i64, _>(2).unwrap(),
362 )
363 }
364
365 /// Age *both* day buckets by `days`, so the next finish lands that many
366 /// days later on the calendar — the streak's and the day quota's, since
367 /// they are the same calendar and a test that moved one would be asserting
368 /// against a day the other has never heard of. The day is injected into the
369 /// stored state rather than into the clock, which keeps `Timestamp::now`
370 /// the sole clock read and the test free of sleeping.
371 ///
372 /// Known flake, left as-is: every caller assumes the UTC day does not turn
373 /// over mid-test — a crossing between two stints shifts the real day under
374 /// the injected one and reddens the run. That is one ~ms-wide window per
375 /// day (~5e-6 per run), and the alternative is a clock seam in production
376 /// code to serve a test. Re-run before believing a failure that only ever
377 /// happens near midnight UTC.
378 async fn age_by_days(user: &UserId, db: &Database, days: i64) {
379 sqlx::query(
380 "UPDATE app_user SET
381 study_streak_last_day = COALESCE(study_streak_last_day, -1) - $1,
382 pomodoro_counted_day = COALESCE(pomodoro_counted_day, -1) - $1
383 WHERE id = $2",
384 )
385 .bind(days)
386 .bind(user.uuid())
387 .execute(db)
388 .await
389 .unwrap();
390 }
391
392 /// Open a stint that has already been running for `ms` — the stamp the
393 /// close measures against, injected instead of slept through.
394 ///
395 /// One `UPSERT`, not `start` followed by a backdate: the concurrent test
396 /// races four of these onto the same open row, and a separate backdate can
397 /// be wiped by a rival's fresh `start`, handing whoever wins the arbiter
398 /// a zero-length stint and reddening the run for no defect. The same
399 /// arbiter-riding statement `start` runs, one clock read earlier — the
400 /// `DO UPDATE` arm drops the loser onto the winner's row in place.
401 async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {
402 sqlx::query(
403 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
404 VALUES ($2, $1, $3, NULL, NULL, NULL)
405 ON CONFLICT (app_user) WHERE finished_at IS NULL DO UPDATE
406 SET started_at = EXCLUDED.started_at, finished_at = NULL, counted = NULL",
407 )
408 .bind(user.uuid())
409 .bind(PomodoroSessionId::generate().uuid())
410 .bind(Timestamp::now().as_millis() - ms)
411 .execute(db)
412 .await?;
413 Ok(())
414 }
415
416 /// Start and close one stint that counts: exactly the minimum on the clock,
417 /// so every streak assertion below is about the day and not the duration.
418 async fn one_stint(user: &UserId, db: &Database) {
419 start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap();
420 finish(db, user).await.unwrap();
421 }
422
423 /// Insert one closed stint at explicit unix-ms stamps — a row the
424 /// windowed-log tests below can aim bounds at, no clock involved.
425 /// `counted = NULL` (a pre-rule row) is the honest verdict for a stint no
426 /// transaction judged.
427 async fn seeded_stint(user: &UserId, db: &Database, started_at: i64, finished_at: i64) {
428 sqlx::query(
429 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
430 VALUES ($1, $2, $3, $4, NULL, NULL)",
431 )
432 .bind(PomodoroSessionId::generate().uuid())
433 .bind(user.uuid())
434 .bind(started_at)
435 .bind(finished_at)
436 .execute(db)
437 .await
438 .unwrap();
439 }
440
441 /// The whole unwindowed log — the read the old `list_for_user` gave —
442 /// for tests that just want the sessions.
443 async fn whole_log(user: &UserId, db: &Database) -> Vec<PomodoroSession> {
444 page_for_user(db, user, None, None, None, 0)
445 .await
446 .unwrap()
447 .items
448 }
449
450 #[tokio::test]
451 async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
452 let (db, _leases) = crate::database::init_test_db().await;
453 let user = a_user(&db).await;
454 // The stale-data case: a row that predates all three columns reads as
455 // no streak at all, and its first finish opens a run of one.
456 assert_eq!(streak(&user, &db).await, (0, 0, -1));
457
458 one_stint(&user, &db).await;
459 let today = Timestamp::now().day_number();
460 assert_eq!(streak(&user, &db).await, (1, 1, today));
461
462 // A second stint the same day is not a second day.
463 one_stint(&user, &db).await;
464 assert_eq!(streak(&user, &db).await, (1, 1, today));
465
466 // Days N+1 and N+2.
467 for day in 2..=3 {
468 age_by_days(&user, &db, 1).await;
469 one_stint(&user, &db).await;
470 assert_eq!(streak(&user, &db).await, (day, day, today));
471 }
472 }
473
474 #[tokio::test]
475 async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
476 let (db, _leases) = crate::database::init_test_db().await;
477 let user = a_user(&db).await;
478
479 one_stint(&user, &db).await;
480 age_by_days(&user, &db, 1).await;
481 one_stint(&user, &db).await;
482 assert_eq!(streak(&user, &db).await.0, 2);
483
484 // Skip a day: the run restarts at one, the longest stays where it got.
485 age_by_days(&user, &db, 2).await;
486 one_stint(&user, &db).await;
487 let (current, longest, _) = streak(&user, &db).await;
488 assert_eq!((current, longest), (1, 2));
489
490 // A backwards day (a clock stepped back over a boundary) is a gap too,
491 // and still cannot lower the mark.
492 age_by_days(&user, &db, -5).await;
493 one_stint(&user, &db).await;
494 assert_eq!(
495 streak(&user, &db).await,
496 (1, 2, Timestamp::now().day_number())
497 );
498 }
499
500 /// The transaction boundary itself, on a real server: the streak pair and
501 /// the counters must commit with the stint or not at all, under real
502 /// contention on one user row.
503 ///
504 /// Multi-threaded and off the embedded engine for the reason
505 /// [`crate::db::cap`] spells out: the in-memory engine does not
506 /// conflict-check two concurrent writes to one record, so it would answer
507 /// `Ok` to a write it dropped and *forge* the integrity failure this test
508 /// exists to catch.
509 ///
510 /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT`
511 /// pair from the batch turns all 20 rounds red. A `THROW` then errors only
512 /// its own statement, so the losers of the open-row race run the rest of
513 /// the cascade anyway — they bump the counters for a stint they never
514 /// closed and `CREATE` a session row out of an empty `$before`, which comes
515 /// back as `500 … Expected record, got none` (the `errors` assertion below
516 /// fires first; `finished_total` running ahead of the `Ok` finishes is the
517 /// same wound one statement later). What it does *not* pin is the
518 /// streak arithmetic under concurrency: same-day finishes all compute the
519 /// same value, so that stays green either way — it is
520 /// `max(longest, current)` that makes that robust, not the isolation.
521 ///
522 /// The shape of the contention, measured rather than assumed: four racers
523 /// per round is four `start`s collapsing onto *one* open row (the id is
524 /// deterministic per user), so typically exactly one `finish` commits and
525 /// three lose the `DELETE` and abort their whole cascade — 20 finishes and
526 /// 60 conflicts over 20 rounds, measured. That is the contention: the
527 /// losers' cascades are live against the same user row, which is precisely
528 /// what must leave nothing behind. Two commits in one round are possible
529 /// (a racer scheduled entirely after another's finish frees the slot) and
530 /// the assertions allow it — the day count is per round, not per stint.
531 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
532 async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
533 let (db, _leases) = crate::database::init_test_db().await;
534 let user = a_user(&db).await;
535 let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
536 let mut last_error = String::new();
537 for round in 1..=20 {
538 let racers: Vec<_> = (0..4)
539 .map(|_| {
540 let (user, db) = (user, db.clone());
541 tokio::spawn(async move {
542 // Aged past the minimum, so whichever racer wins the
543 // open row closes a stint that *counts* — a fresh
544 // `start` here would hand the winner a zero-length
545 // stint, which now moves nothing and would leave this
546 // test asserting against an untouched counter.
547 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?;
548 finish(&db, &user).await
549 })
550 })
551 .collect();
552 let mut won = 0;
553 for racer in racers {
554 match racer.await.unwrap() {
555 Ok(_) => won += 1,
556 // Losing the open row is the correct answer for a racer
557 // whose stint someone else closed; only `Db` is a defect.
558 Err(AppError::Conflict(_)) => conflicts += 1,
559 Err(err) => {
560 errors += 1;
561 last_error = format!("{err:?}");
562 }
563 }
564 }
565 finished += won;
566 // Streak length == round is load luck: same-day finishes share
567 // a day, and a round with only uncounted closes does not
568 // advance it. Atomicity is the claim — pinned after the loop.
569 let (current, longest, _) = streak(&user, &db).await;
570 assert!(
571 longest >= current && current <= round,
572 "round {round} streak ran off the calendar: current={current} longest={longest} won={won}"
573 );
574 age_by_days(&user, &db, 1).await;
575 }
576 // The atomicity claim: the counter counts exactly the stints that were
577 // closed, never a loser's aborted round.
578 let (counted, _) = counters(&user, &db).await;
579 eprintln!(
580 "PomodoroSession::finish raced: {finished} finishes over 20 days, \
581 {conflicts} rivals refused, {errors} 500s"
582 );
583 assert_eq!(
584 errors, 0,
585 "a raced finish must conflict, not 500: {last_error}"
586 );
587 assert_eq!(
588 counted, finished,
589 "the counter counted {counted} stints for {finished} finishes"
590 );
591 assert!(
592 conflicts > 0,
593 "every racer won its own round, so no cascade was ever aborted mid-flight \
594 and this run proves nothing about the transaction boundary"
595 );
596 }
597
598 #[tokio::test]
599 async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
600 let (db, _leases) = crate::database::init_test_db().await;
601 let user = a_user(&db).await;
602 assert_eq!(counters(&user, &db).await, (0, 0));
603
604 // An open stint is not a finished one: neither counter moves until it
605 // closes.
606 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
607 .await
608 .unwrap();
609 assert_eq!(counters(&user, &db).await, (0, 0));
610
611 let mut focus_ms = 0;
612 for _ in 0..2 {
613 let closed = finish(&db, &user).await.unwrap();
614 focus_ms +=
615 closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis();
616 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
617 .await
618 .unwrap();
619 }
620 // Three starts, two finishes — the third is still running.
621 assert_eq!(counters(&user, &db).await, (2, focus_ms));
622 }
623
624 #[tokio::test]
625 async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
626 let (db, _leases) = crate::database::init_test_db().await;
627 let user = a_user(&db).await;
628
629 start(&db, &user, None).await.unwrap();
630 sqlx::query(
631 "UPDATE pomodoro_session SET started_at = $1
632 WHERE app_user = $2 AND finished_at IS NULL",
633 )
634 .bind(Timestamp::now().as_millis() + 3_600_000)
635 .bind(user.uuid())
636 .execute(&db)
637 .await
638 .unwrap();
639
640 // The clamp holds: zero milliseconds, never a negative — and a stint
641 // measuring zero is below the minimum, so it moves neither counter.
642 let closed = finish(&db, &user).await.unwrap();
643 assert_eq!(closed.get_counted(), Some(false));
644 assert_eq!(counters(&user, &db).await, (0, 0));
645 }
646
647 /// The minimum, from both sides. A round-trip is not a study session, and
648 /// the boundary is inclusive (`>=`) — a stint of exactly the minimum
649 /// counts, which is the side these assertions pin.
650 ///
651 /// The near miss is a whole minute short, not one millisecond: `finish`
652 /// reads its own clock *after* the stint is opened, so a stint aged to
653 /// exactly one millisecond under the bar crosses it by the time the close
654 /// measures it (measured — that assertion failed on the first run). A
655 /// millisecond-exact probe would need a clock seam in production code, and
656 /// what matters here is the four orders of magnitude between a scripted
657 /// pair and a study session, not the last millisecond.
658 #[tokio::test]
659 async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {
660 let (db, _leases) = crate::database::init_test_db().await;
661 let user = a_user(&db).await;
662
663 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)
664 .await
665 .unwrap();
666 let short = finish(&db, &user).await.unwrap();
667 assert_eq!(short.get_counted(), Some(false));
668 assert_eq!(counters(&user, &db).await, (0, 0));
669 // Not a study day either — and no streak column was even opened.
670 assert_eq!(streak(&user, &db).await, (0, 0, -1));
671 // But it happened, and the log says so.
672 let log = whole_log(&user, &db).await;
673 assert_eq!(log.len(), 1);
674 assert_eq!(log[0].get_finished_at(), short.get_finished_at());
675
676 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
677 .await
678 .unwrap();
679 let counted = finish(&db, &user).await.unwrap();
680 assert_eq!(counted.get_counted(), Some(true));
681 let (finished, focus_ms) = counters(&user, &db).await;
682 // The counter took the *same* duration the row stores, not a second
683 // reading of the clock.
684 assert_eq!(
685 (finished, focus_ms),
686 (
687 1,
688 counted.get_finished_at().unwrap().as_millis()
689 - counted.get_started_at().as_millis()
690 )
691 );
692 assert_eq!(streak(&user, &db).await.0, 1);
693 assert_eq!(whole_log(&user, &db).await.len(), 2);
694 }
695
696 /// The day quota: it stops the counter, it never stops the log, and it
697 /// rolls at midnight UTC.
698 #[tokio::test]
699 async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() {
700 let (db, _leases) = crate::database::init_test_db().await;
701 let user = a_user(&db).await;
702
703 for _ in 0..MAX_COUNTED_POMODORO_PER_DAY {
704 one_stint(&user, &db).await;
705 }
706 let (finished, focus_ms) = counters(&user, &db).await;
707 assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY);
708
709 // Past the quota: recorded, listed, worth nothing — neither stint count
710 // nor focus milliseconds.
711 for _ in 0..3 {
712 start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
713 .await
714 .unwrap();
715 let over = finish(&db, &user).await.unwrap();
716 assert_eq!(over.get_counted(), Some(false));
717 }
718 assert_eq!(counters(&user, &db).await, (finished, focus_ms));
719 assert_eq!(
720 whole_log(&user, &db).await.len() as i64,
721 MAX_COUNTED_POMODORO_PER_DAY + 3
722 );
723 // The quota is a day's, not a lifetime's.
724 age_by_days(&user, &db, 1).await;
725 one_stint(&user, &db).await;
726 assert_eq!(
727 counters(&user, &db).await.0,
728 MAX_COUNTED_POMODORO_PER_DAY + 1
729 );
730 }
731
732 /// The farm, run: `start`/`finish` in a loop is two requests a round with
733 /// no second person in it, which used to move `pomodoro_finished_total` one
734 /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`,
735 /// and a badge is never taken back.
736 #[tokio::test]
737 async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {
738 let (db, _leases) = crate::database::init_test_db().await;
739 let user = a_user(&db).await;
740
741 for _ in 0..200 {
742 start(&db, &user, None).await.unwrap();
743 finish(&db, &user).await.unwrap();
744 }
745 assert_eq!(counters(&user, &db).await, (0, 0));
746 assert_eq!(streak(&user, &db).await, (0, 0, -1));
747 // Every one of them is still the student's own history.
748 assert_eq!(whole_log(&user, &db).await.len(), 200);
749 assert!(
750 crate::db::badge::list_for(&db, &user)
751 .await
752 .unwrap()
753 .is_empty(),
754 "the farm minted a permanent badge"
755 );
756
757 // And paying the minimum for each one only buys the day's quota.
758 for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) {
759 one_stint(&user, &db).await;
760 }
761 assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY);
762 }
763
764 #[tokio::test]
765 async fn restart_replaces_the_open_session_and_finish_closes_it() {
766 let (db, _leases) = crate::database::init_test_db().await;
767 // The stint's owner is a real parent row now (the FK checks it), so
768 // the user ceremony stays — it is one helper call.
769 let user = a_user(&db).await;
770
771 // Nothing running yet — finishing conflicts.
772 assert!(matches!(
773 finish(&db, &user).await,
774 Err(AppError::Conflict(_))
775 ));
776
777 let first = start(&db, &user, None).await.unwrap();
778
779 // A restart replaces the dangling session: still one row, fresh clock.
780 let second = start(&db, &user, None).await.unwrap();
781 assert!(second.get_started_at() >= first.get_started_at());
782 let sessions = whole_log(&user, &db).await;
783 assert_eq!(sessions.len(), 1);
784
785 let closed = finish(&db, &user).await.unwrap();
786 assert!(closed.get_finished_at().unwrap() >= closed.get_started_at());
787
788 // The open slot is free again; a stray second finish conflicts.
789 assert!(matches!(
790 finish(&db, &user).await,
791 Err(AppError::Conflict(_))
792 ));
793 start(&db, &user, None).await.unwrap();
794 let sessions = whole_log(&user, &db).await;
795 assert_eq!(sessions.len(), 2);
796 }
797
798 #[tokio::test]
799 async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {
800 let (db, _leases) = crate::database::init_test_db().await;
801 let user = a_user(&db).await;
802
803 start(&db, &user, None).await.unwrap();
804 // Stand in for the NTP step: push the running stint's start an hour
805 // ahead, so the server clock `finish` reads is *behind* it.
806 sqlx::query(
807 "UPDATE pomodoro_session SET started_at = $1
808 WHERE app_user = $2 AND finished_at IS NULL",
809 )
810 .bind(Timestamp::now().as_millis() + 3_600_000)
811 .bind(user.uuid())
812 .execute(&db)
813 .await
814 .unwrap();
815
816 let closed = finish(&db, &user).await.unwrap();
817 let started = closed.get_started_at().as_millis();
818 assert_eq!(closed.get_finished_at().unwrap().as_millis(), started);
819
820 // And the stat that sums these stays non-negative.
821 let stats = crate::db::profile::load(&db, &user, 0, 0).await.unwrap();
822 assert_eq!(stats.get_pomodoro_sessions(), 1);
823 assert_eq!(stats.get_pomodoro_focus_ms(), 0);
824 }
825
826 /// A timeline the windowed reads aim at: three finished stints
827 /// (5000 + 500 + 6000 ms of focus) and one still running, which the sums
828 /// must never mistake for focus.
829 async fn a_seeded_timeline(db: &Database) -> UserId {
830 let user = a_user(db).await;
831 seeded_stint(&user, db, 1000, 6000).await;
832 seeded_stint(&user, db, 2000, 2500).await;
833 seeded_stint(&user, db, 3000, 9000).await;
834 sqlx::query(
835 "INSERT INTO pomodoro_session (id, app_user, started_at, finished_at, counted, label)
836 VALUES ($1, $2, 4000, NULL, NULL, NULL)",
837 )
838 .bind(PomodoroSessionId::generate().uuid())
839 .bind(user.uuid())
840 .execute(db)
841 .await
842 .unwrap();
843 user
844 }
845
846 fn starts(page: &PomodoroLogPage) -> Vec<i64> {
847 page.items
848 .iter()
849 .map(|session| session.get_started_at().as_millis())
850 .collect()
851 }
852
853 #[tokio::test]
854 async fn the_window_bounds_the_page_the_count_and_the_focus_total_alike() {
855 let (db, _leases) = crate::database::init_test_db().await;
856 let user = a_seeded_timeline(&db).await;
857
858 // No bounds: today's whole-history read — every session, newest
859 // first, and the focus total over all of it (running adds nothing).
860 let page = page_for_user(&db, &user, None, None, None, 0).await.unwrap();
861 assert_eq!(page.total, 4);
862 assert_eq!(starts(&page), [4000, 3000, 2000, 1000]);
863 assert_eq!(page.total_focus_ms, 11_500);
864
865 // `from` only: half-open at the start, so the stint opening at 2500
866 // itself is out and the ones from 3000 on are in.
867 let page = page_for_user(&db, &user, Some(2500), None, None, 0)
868 .await
869 .unwrap();
870 assert_eq!(page.total, 2);
871 assert_eq!(starts(&page), [4000, 3000]);
872 assert_eq!(page.total_focus_ms, 6_000);
873
874 // `to` only: exclusive, so the stint starting exactly at 2000 is out.
875 let page = page_for_user(&db, &user, None, Some(2000), None, 0)
876 .await
877 .unwrap();
878 assert_eq!(page.total, 1);
879 assert_eq!(starts(&page), [1000]);
880 assert_eq!(page.total_focus_ms, 5_000);
881
882 // Both bounds AND together.
883 let page = page_for_user(&db, &user, Some(1000), Some(3000), None, 0)
884 .await
885 .unwrap();
886 assert_eq!(page.total, 2);
887 assert_eq!(starts(&page), [2000, 1000]);
888 assert_eq!(page.total_focus_ms, 5_500);
889
890 // A window over empty ground answers an empty page, not an error.
891 let page = page_for_user(&db, &user, Some(10_000), None, None, 0)
892 .await
893 .unwrap();
894 assert!(page.items.is_empty());
895 assert_eq!(page.total, 0);
896 assert_eq!(page.total_focus_ms, 0);
897 }
898
899 #[tokio::test]
900 async fn the_page_window_slices_after_the_time_window() {
901 let (db, _leases) = crate::database::init_test_db().await;
902 let user = a_seeded_timeline(&db).await;
903
904 // limit slices the filtered set; `total` stays the filtered count and
905 // the focus total the filtered sum — not the one listed row's.
906 let page = page_for_user(&db, &user, Some(2500), None, Some(1), 0)
907 .await
908 .unwrap();
909 assert_eq!(starts(&page), [4000]);
910 assert_eq!(page.total, 2);
911 assert_eq!(page.total_focus_ms, 6_000);
912
913 // offset paging lands inside the filtered order, and the unpaged sums
914 // span the whole filtered log — 11_500, not the two listed rows' 11_000.
915 let page = page_for_user(&db, &user, None, None, Some(2), 1).await.unwrap();
916 assert_eq!(starts(&page), [3000, 2000]);
917 assert_eq!(page.total, 4);
918 assert_eq!(page.total_focus_ms, 11_500);
919 }
920}