forge
Explore
Log in

Don't you dare go Hollow

Split pomodoro/work_entry/event into domain/db/service layers

Browse files at this commit

47eb0068ef7ba610f36a7a18b1c29a42e6ceaac8Ahmet Kaan GümüşParent: 387eb31
  • chore
    • split pomodoro/work_entry/event into domain/db/service layers
Show full message
🧹 chore: split pomodoro/work_entry/event into domain/db/service layers

18 changed files +1462 -1269

src/db/event.rsadded+288 -0
@@ -0,0 +1,288 @@
1+//! The `event` table: row reads and listings, the cascading delete, and the
2+//! audience's live membership resolution — the point check behind marking
3+//! ([`includes`]) and the who-missed report's backbone ([`members`]).
4+
5+use surrealdb::types::SurrealValue;
6+
7+use crate::database::{Database, transaction_with_retry};
8+use crate::db::field_update::FieldUpdate;
9+use crate::domain::class_member::{ClassMember, ClassMemberId};
10+use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
11+use crate::domain::registration::Registration;
12+use crate::domain::timestamp::{Timestamp, range_error};
13+use crate::domain::user::{User, UserId};
14+use crate::error::AppError;
15+
16+/// Is `user` in `audience`'s roster right now? The point check behind
17+/// marking — cheaper than resolving the whole roster when the target is
18+/// known. `event` must be the event this audience came from: the
19+/// registration kind resolves against that event's signup rows.
20+pub async fn includes(
21+ db: &Database,
22+ audience: &EventAudience,
23+ event: &EventId,
24+ user: &User,
25+) -> Result<bool, AppError> {
26+ match audience {
27+ EventAudience::School => Ok(true),
28+ EventAudience::Role { role } => Ok(user.get_role() == *role),
29+ EventAudience::Course { course } => {
30+ Ok(
31+ crate::db::enrollment::read_for_user(db, course, user.get_id())
32+ .await?
33+ .is_some(),
34+ )
35+ }
36+ // The (class, user) pair is the membership row's own id, so the
37+ // point check is a single select — no scan, no index needed.
38+ EventAudience::Class { class } => {
39+ let member: Option<ClassMember> = db
40+ .select(ClassMemberId::composite(class, user.get_id()).record())
41+ .await?;
42+ Ok(member.is_some())
43+ }
44+ EventAudience::Registration { .. } => {
45+ Ok(Registration::read_for_user(event, user.get_id(), db)
46+ .await?
47+ .is_some())
48+ }
49+ }
50+}
51+
52+/// `event`'s full roster, as it stands right now — the who-missed
53+/// report's backbone. Registered ids that no longer resolve to a user row
54+/// are kept; the caller degrades their display like any stale reference.
55+pub async fn members(
56+ db: &Database,
57+ audience: &EventAudience,
58+ event: &EventId,
59+) -> Result<Vec<UserId>, AppError> {
60+ match audience {
61+ EventAudience::School => Ok(crate::db::user::list_all(db, None, 0)
62+ .await?
63+ .0
64+ .iter()
65+ .map(|user| user.get_id().clone())
66+ .collect()),
67+ EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role)
68+ .await?
69+ .iter()
70+ .map(|user| user.get_id().clone())
71+ .collect()),
72+ EventAudience::Course { course } => {
73+ Ok(crate::db::enrollment::list_for_course(db, course, None, 0)
74+ .await?
75+ .0
76+ .iter()
77+ .map(|enrollment| enrollment.get_user().clone())
78+ .collect())
79+ }
80+ EventAudience::Class { class } => Ok(ClassMember::list_for_class(class, None, 0, db)
81+ .await?
82+ .0
83+ .iter()
84+ .map(|member| member.get_user().clone())
85+ .collect()),
86+ EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)
87+ .await?
88+ .iter()
89+ .map(|registration| registration.get_user().clone())
90+ .collect()),
91+ }
92+}
93+
94+pub async fn create(
95+ db: &Database,
96+ creator: &UserId,
97+ title: EventTitle,
98+ description: EventDescription,
99+ audience: EventAudience,
100+ starts_at: Option<Timestamp>,
101+ ends_at: Option<Timestamp>,
102+) -> Result<Event, AppError> {
103+ let event = Event {
104+ id: EventId::generate(),
105+ creator: creator.clone(),
106+ title,
107+ description,
108+ audience,
109+ starts_at,
110+ ends_at,
111+ };
112+ let created: Option<Event> = db.create(event.id.record()).content(event).await?;
113+ created.ok_or_else(|| AppError::Internal("failed to create event".into()))
114+}
115+
116+pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError> {
117+ Ok(db.select(id.record()).await?)
118+}
119+
120+pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
121+ let mut result = db
122+ .query("SELECT * FROM event ORDER BY id DESC")
123+ .await?
124+ .check()?;
125+ Ok(result.take::<Vec<Event>>(0)?)
126+}
127+
128+/// Request-scoped: the handler reads the event, then awaits the clock and a
129+/// course lookup before saving, holding no lock, so an omitted field
130+/// (`None`) is not written at all. Passing the snapshot's value back
131+/// instead would revert a concurrent edit of that field — scoping the `SET`
132+/// alone does not prevent that, the values have to come from the request.
133+/// The schedule columns are nullable, so they take the outer/inner
134+/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
135+pub async fn update(
136+ db: &Database,
137+ event: Event,
138+ title: Option<EventTitle>,
139+ description: Option<EventDescription>,
140+ audience: Option<EventAudience>,
141+ starts_at: Option<Option<Timestamp>>,
142+ ends_at: Option<Option<Timestamp>>,
143+) -> Result<Event, AppError> {
144+ FieldUpdate::new(event.id.record())
145+ .set("title", title)
146+ .set("description", description)
147+ .set("audience", audience)
148+ .set("starts_at", starts_at)
149+ .set("ends_at", ends_at)
150+ .ordered("starts_at", "ends_at", range_error())
151+ .run::<Event>(db)
152+ .await
153+}
154+
155+/// Delete the event and cascade-remove its attendance and signup rows.
156+///
157+/// Children first, and all of it in one transaction the way
158+/// [`crate::db::course::delete`] does it: run as two queries, a
159+/// registration or a mark that committed in between outlived its event —
160+/// an orphan no read path can ever reach and no delete can ever reclaim,
161+/// since every one of them is keyed on the event that is now gone.
162+///
163+/// Re-sent while the store answers "conflict, retry", the way
164+/// [`crate::db::course_session::delete`] is: now that
165+/// [`crate::domain::attendance::Attendance::mark`] writes the event row to
166+/// prove it exists, a mark landing in this window really does contend for
167+/// it — and without the retry the *delete* is the side that loses, turning
168+/// a race the store resolved correctly into a 500 (measured 4 rounds in 4).
169+/// Admissible: every statement is a `DELETE`, which can never answer
170+/// "already exists", and a lost round wrote nothing.
171+pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
172+ let (mut result, mut errors) = transaction_with_retry(
173+ db,
174+ "BEGIN TRANSACTION;
175+ DELETE attendance WHERE event = $ev;
176+ DELETE registration WHERE event = $ev;
177+ LET $gone = (DELETE $ev RETURN BEFORE);
178+ RETURN $gone;
179+ COMMIT TRANSACTION;",
180+ &[("ev".into(), event.id.record().into_value())],
181+ // No THROW of its own — an unconditional cascade.
182+ &[],
183+ )
184+ .await?;
185+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
186+ return Err(error.into());
187+ }
188+ // Read through the trailing `RETURN`, never a hand-counted slot.
189+ let slot = result.num_statements().saturating_sub(2);
190+ result
191+ .take::<Vec<Event>>(slot)?
192+ .into_iter()
193+ .next()
194+ .ok_or(AppError::NotFound)
195+}
196+
197+#[cfg(test)]
198+mod tests {
199+ use super::*;
200+ use crate::constant::REGISTRATION_FROZEN_GUARD;
201+ use crate::domain::class_group::ClassGroupId;
202+
203+ /// The forcing function behind the one rule with two spellings: the freeze
204+ /// this file decides in Rust ([`Event::registration_capacity`]) and
205+ /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which
206+ /// the role cascade (`service::user::set_role`) carries because it frees a demoted
207+ /// parent's seats inside a transaction and cannot call Rust from there.
208+ ///
209+ /// Every schedule shape is put to both, including the three the SQL is most
210+ /// likely to get wrong: the ends_at-only event (`??` must fall through to
211+ /// it), the boundary itself (closed *at* the instant, not after it — `>=` in
212+ /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound
213+ /// to that exact instant so the boundary is really exercised), and an event
214+ /// that takes no registrations at all, which Rust refuses one arm *earlier*
215+ /// — so the SQL must not report it frozen, or a stray row on it would be
216+ /// preserved forever instead of swept.
217+ #[tokio::test]
218+ async fn the_sql_freeze_guard_matches_the_rust_one() {
219+ let db = crate::database::init_mem().await.unwrap();
220+ let now = Timestamp::now().as_millis();
221+ let past = Some(Timestamp::from_millis(now - 60_000));
222+ let future = Some(Timestamp::from_millis(now + 3_600_000));
223+ let later = Some(Timestamp::from_millis(now + 7_200_000));
224+ let signup = EventAudience::Registration { capacity: None };
225+ let cases = [
226+ ("timeless", signup.clone(), None, None),
227+ ("deadline ahead", signup.clone(), None, future),
228+ ("deadline passed", signup.clone(), None, past),
229+ ("starts later", signup.clone(), future, later),
230+ ("already started", signup.clone(), past, None),
231+ ("started, ends later", signup.clone(), past, future),
232+ (
233+ "closing this instant",
234+ signup.clone(),
235+ Some(Timestamp::from_millis(now)),
236+ None,
237+ ),
238+ // No signup list to freeze: `registration_capacity` refuses these on
239+ // the audience, before it ever looks at the clock.
240+ ("started school event", EventAudience::School, past, None),
241+ (
242+ "started class event",
243+ EventAudience::Class {
244+ class: ClassGroupId::from_key("g1"),
245+ },
246+ past,
247+ None,
248+ ),
249+ ];
250+ for (name, audience, starts_at, ends_at) in cases {
251+ let event = create(
252+ &db,
253+ &UserId::from_key("teacher"),
254+ EventTitle::try_new(name).unwrap(),
255+ EventDescription::try_new("").unwrap(),
256+ audience,
257+ starts_at,
258+ ends_at,
259+ )
260+ .await
261+ .unwrap();
262+ let rust = matches!(
263+ event.registration_capacity(),
264+ Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
265+ );
266+ let mut result = db
267+ .query(format!(
268+ "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}"
269+ ))
270+ .bind(("ev", event.get_id().record()))
271+ .bind(("now", now))
272+ .await
273+ .unwrap()
274+ .check()
275+ .unwrap();
276+ let sql = !result
277+ .take::<Vec<surrealdb::types::RecordId>>(0)
278+ .unwrap()
279+ .is_empty();
280+ assert_eq!(
281+ sql, rust,
282+ "the SQL freeze guard and registration_capacity disagree on a \
283+ {name} event — the role cascade would rewrite a closed signup \
284+ list, or strand a seat on an open one"
285+ );
286+ }
287+ }
288+}
src/db/mod.rsmodified+3 -0
@@ -7,6 +7,7 @@ pub mod class_blueprint;
7 pub mod course;7 pub mod course;
8 pub mod course_session;8 pub mod course_session;
9 pub mod enrollment;9 pub mod enrollment;
10+pub mod event;
10 pub mod exam;11 pub mod exam;
11 pub mod exam_attempt;12 pub mod exam_attempt;
12 pub mod exam_question;13 pub mod exam_question;
@@ -15,6 +16,8 @@ pub mod meal_booking;
15 pub mod note;16 pub mod note;
16 pub mod page;17 pub mod page;
17 pub mod payment_ledger;18 pub mod payment_ledger;
19+pub mod pomodoro;
18 pub mod session;20 pub mod session;
19 pub mod settings;21 pub mod settings;
20 pub mod user;22 pub mod user;
23+pub mod work_entry;
src/db/pomodoro.rsadded+744 -0
@@ -0,0 +1,744 @@
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+
6+use surrealdb::types::SurrealValue;
7+
8+use crate::constant::{
9+ MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD,
10+ POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD,
11+ STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD,
12+};
13+use crate::database::{Database, transaction_with_retry};
14+use crate::domain::badge;
15+use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId};
16+use crate::domain::timestamp::Timestamp;
17+use crate::domain::user::UserId;
18+use crate::error::AppError;
19+
20+/// Start a session for `user`, stamped with the server clock. `UPSERT` on
21+/// the deterministic open id makes this atomic and always succeed: a
22+/// dangling unfinished session (the browser died mid-timer) is replaced —
23+/// it never counted, and blocking the next start behind it would only
24+/// punish the student for a crash.
25+pub async fn start(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
26+ let mut result = db
27+ .query("UPSERT $open CONTENT { user: $usr, started_at: $at }")
28+ .bind(("open", PomodoroSessionId::open_for(user).record()))
29+ .bind(("usr", user.record()))
30+ .bind(("at", Timestamp::now()))
31+ .await?
32+ .check()?;
33+ result
34+ .take::<Vec<PomodoroSession>>(0)?
35+ .into_iter()
36+ .next()
37+ .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into()))
38+}
39+
40+/// Close `user`'s running session: atomically take the open row and
41+/// re-file it under a ULID id, freeing the open slot for the next start.
42+/// Take and re-file share one transaction — a failed re-file rolls the
43+/// take back, so a session can never vanish half-closed. Of two racing
44+/// finishes exactly one receives the row (the other gets the conflict).
45+///
46+/// A lost round is re-sent rather than reported (`transaction_with_retry`):
47+/// the abort wrote nothing, so the whole cascade is safe to repeat, and the
48+/// `CREATE` cannot answer "already exists" on the way back — the table
49+/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
50+/// Only the guard's own `THROW` is a decision, and it stays a 409.
51+///
52+/// `finished_at` is floored at the row's own `started_at`. Both stamps come
53+/// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move
54+/// *backwards* mid-stint — so a close can legitimately read earlier than its
55+/// own start with nothing wrong on the client's side. Refusing it would lose
56+/// a real study session and leave the open slot wedged for a fault the
57+/// student did not cause; recording a zero-length stint keeps the session
58+/// count honest and its duration merely understated. Nothing downstream may
59+/// then read a negative duration (`ProfileStats::load` sums these).
60+///
61+/// The lifetime badge counters on the user row move in this same
62+/// transaction, so they can never count a stint the log does not hold (nor
63+/// miss one it does), and a retried round re-applies nothing — the abort
64+/// rolled the increment back with the rest. They are written field-scoped:
65+/// the row also carries admin-owned data (`role`), which a whole-row save
66+/// would silently revert. The clamped duration is the *same* expression the
67+/// `CREATE` stores (both read `$ms`), so the counter can never take a
68+/// negative summand and nothing downstream needs a floor. Only *finished*
69+/// stints reach here — an open row is a `pomodoro_session` row and nothing
70+/// else — and there is no student-facing delete for a stint, so neither
71+/// counter ever decrements.
72+///
73+/// They move only for a stint that **counts**, which is
74+/// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most
75+/// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this
76+/// is the farm [`crate::domain::pool_question::PoolQuestion::approve`]
77+/// argues about from the other end: finishing is self-service, one stint is
78+/// two requests and no second person, so a counter moved once per
79+/// round-trip is farmable — two hundred pairs inside the rate limit bought
80+/// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked.
81+/// Both stamps are the server's own clock, so the duration needs no
82+/// distrusting, only a floor.
83+///
84+/// The verdict is *stamped* on the closed row (`counted`), not re-derived
85+/// later: the thresholds are compiled in and will move, and a reader that
86+/// re-judged an old stint against today's numbers would answer something
87+/// other than what was credited. Nothing debits these counters today; the
88+/// stamp is what lets one be added without that asymmetry. A stint below
89+/// the bar is still recorded, still listed, and still sums into the log's
90+/// `total_focus_ms` — the rule bounds what *counts*, never what is kept.
91+///
92+/// The day quota is bucketed like the streak below (midnight UTC,
93+/// [`Timestamp::day_number`]) and rolls in its own statement ahead of the
94+/// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting
95+/// it, which resolves against the row as it was *before* the statement —
96+/// the same rule that forces the streak pair apart, used here on purpose. A
97+/// row that predates the two columns reads as no day at all (`?? -1`), so
98+/// the first finish after this deploy opens a fresh bucket and no backfill
99+/// is owed. The bucket write happens whether the stint counts or not; only
100+/// the `+ 1` sits behind the verdict.
101+///
102+/// The **study streak** rides the same transaction, and the same verdict: a
103+/// study day is a UTC calendar day on which a stint *counted*, so a day
104+/// bought with one instant round-trip is not a day studied (midnight UTC, like every
105+/// other day calculation here — no timezone is stored anywhere): the same
106+/// day again changes nothing, the next day extends the run, any other gap
107+/// starts a new one at 1. It is written as **two** statements, not one:
108+/// every field reference on the right-hand side of a `SET` resolves
109+/// against the row as it was *before* that statement, so a single
110+/// `SET current = …, longest = math::max([longest, current])` would take
111+/// the *old* `current` and lag one write behind forever (probed on a real
112+/// 3.2.3 server: day two left `current = 2, longest = 1`). Across
113+/// statements *inside a transaction* the read does see the prior write, so
114+/// the pair is correct and still atomic. Absent columns are read through
115+/// `?? 0` (and `?? -1` for the day — a sentinel no real day number
116+/// reaches), because `math::max` errors outright on a `NONE` argument and
117+/// every account older than these columns carries none of them.
118+///
119+/// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two
120+/// lines up: a plain `UPDATE` hands back an array, so a user row that is
121+/// missing (a `record<user>` column checks only the table of the id) simply
122+/// yields nothing to index and the second statement matches no row either.
123+/// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero
124+/// rows; it errors on *many* — but a `null` is a shape the read then has to
125+/// special-case, so the file's existing idiom wins.
126+///
127+/// No `cap::counter_lock` is taken, deliberately. The pair cannot tear:
128+/// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts
129+/// a rival that touched the row in between — `transaction_with_retry` then
130+/// re-sends the whole round. And `longest` is written as
131+/// `max(longest, current)`, which cannot come down under *any*
132+/// interleaving, so even a torn pair could only under-count `current`,
133+/// never lower the high-water mark the badges read. The lock would only
134+/// serialize this process's writers (its other job, keeping the in-memory
135+/// test engine deterministic, is moot here — these tests are sequential).
136+/// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent
137+/// finishes for one user left `current = 60, longest = 60` with no
138+/// anomaly; a rival write forced *between* the two statements (a `sleep`
139+/// wedged into the batch) aborted the whole cascade with a write conflict,
140+/// wrote nothing, and left the rival's value standing.
141+///
142+/// Streaks begin at this deploy: nothing reconstructs history from the
143+/// stint log, so every account starts with no streak columns and its first
144+/// finish sets a run of 1.
145+pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
146+ let done = Timestamp::now();
147+ let (mut result, mut errors) = transaction_with_retry(
148+ db,
149+ &format!(
150+ "BEGIN TRANSACTION;
151+ LET $before = (DELETE $open RETURN BEFORE);
152+ IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }};
153+ LET $end = math::max([$before[0].started_at, $done]);
154+ LET $ms = $end - $before[0].started_at;
155+ LET $bucket = (UPDATE $usr SET
156+ {POMODORO_COUNTED_TODAY_FIELD} =
157+ IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day
158+ THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END,
159+ {POMODORO_COUNTED_DAY_FIELD} = $day
160+ RETURN AFTER);
161+ LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS})
162+ AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0)
163+ < {MAX_COUNTED_POMODORO_PER_DAY});
164+ IF $counted {{
165+ UPDATE $usr SET
166+ {POMODORO_FINISHED_TOTAL_FIELD} =
167+ ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1,
168+ {POMODORO_FOCUS_MS_TOTAL_FIELD} =
169+ ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms,
170+ {POMODORO_COUNTED_TODAY_FIELD} =
171+ ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1;
172+ LET $streak = (UPDATE $usr SET
173+ {STUDY_STREAK_CURRENT_FIELD} =
174+ IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day
175+ THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0)
176+ ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1)
177+ THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1)
178+ ELSE 1 END,
179+ {STUDY_STREAK_LAST_DAY_FIELD} = $day
180+ RETURN AFTER);
181+ UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([
182+ ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
183+ ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)])
184+ }};
185+ CREATE $closed CONTENT {{
186+ user: $before[0].user,
187+ started_at: $before[0].started_at,
188+ finished_at: $end,
189+ counted: $counted,
190+ }};
191+ COMMIT TRANSACTION;"
192+ ),
193+ &[
194+ (
195+ "open".into(),
196+ PomodoroSessionId::open_for(user).record().into_value(),
197+ ),
198+ ("usr".into(), user.record().into_value()),
199+ (
200+ "closed".into(),
201+ PomodoroSessionId::generate().record().into_value(),
202+ ),
203+ ("done".into(), done.into_value()),
204+ ("day".into(), done.day_number().into_value()),
205+ ],
206+ &["no_pomodoro_running"],
207+ )
208+ .await?;
209+ // An aborted transaction errors *every* slot, most with a generic
210+ // "not executed" — only the THROW's own slot names the reason, so scan
211+ // them all for the marker instead of trusting the first.
212+ if errors
213+ .values()
214+ .any(|error| error.to_string().contains("no_pomodoro_running"))
215+ {
216+ return Err(AppError::Conflict("no pomodoro session running"));
217+ }
218+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
219+ return Err(error.into());
220+ }
221+ // The `CREATE` is deliberately kept the last statement before `COMMIT`
222+ // (the counter `UPDATE` sits ahead of it — same transaction, so the
223+ // order is free), which is what lets its slot follow the statement
224+ // count instead of a hand-kept number: `num_statements` counts `BEGIN`
225+ // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a
226+ // hand-kept slot caused.
227+ let slot = result.num_statements().saturating_sub(2);
228+ let saved: Option<PomodoroSession> = result
229+ .take::<Vec<PomodoroSession>>(slot)?
230+ .into_iter()
231+ .next();
232+ let saved =
233+ saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?;
234+ // A badge is a decoration on top of the stint: losing one to a
235+ // transient database error must never fail the finish, and the next
236+ // counter move re-runs this and heals it.
237+ if let Err(err) = badge::sync(user, db).await {
238+ tracing::warn!("failed to sync badges for {}: {err}", user.key());
239+ }
240+ Ok(saved)
241+}
242+
243+/// Every session of `user`, newest first — the running one (if any)
244+/// included. Ordered by `started_at`, never by id alone: the open entry's
245+/// `open_` key doesn't sort with the ULIDs, so id order would misplace it.
246+/// The `id` tie-break behind it only ever separates two *finished* stints
247+/// sharing a `started_at` — there is one running row per user, so it can
248+/// never tie with itself.
249+pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {
250+ let mut result = db
251+ .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC")
252+ .bind(("usr", user.record()))
253+ .await?
254+ .check()?;
255+ Ok(result.take::<Vec<PomodoroSession>>(0)?)
256+}
257+
258+#[cfg(test)]
259+mod tests {
260+ use ulid::Ulid;
261+
262+ use super::*;
263+ use crate::database;
264+
265+ /// A real `user` row: the counters land with `UPDATE`, which only ever
266+ /// touches a record that exists, so a fabricated id would silently store
267+ /// nothing. The tests above need no row — they read only the stint log.
268+ async fn a_user(db: &Database) -> UserId {
269+ let user = UserId::from_key(&Ulid::new().to_string());
270+ db.query("CREATE $usr SET username = $name, password_hash = 'x'")
271+ .bind(("usr", user.record()))
272+ .bind(("name", user.key().to_string()))
273+ .await
274+ .unwrap()
275+ .check()
276+ .unwrap();
277+ user
278+ }
279+
280+ /// `(finished_total, focus_ms_total)` re-read from the store — never off
281+ /// what `finish` returned, which proves nothing about what was written.
282+ async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
283+ let mut result = db
284+ .query(format!(
285+ "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0),
286+ ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr"
287+ ))
288+ .bind(("usr", user.record()))
289+ .await
290+ .unwrap()
291+ .check()
292+ .unwrap();
293+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
294+ let row = rows.into_iter().next().expect("the user row");
295+ (row[0], row[1])
296+ }
297+
298+ /// `(current, longest, last_day)` re-read from the store.
299+ async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
300+ let mut result = db
301+ .query(format!(
302+ "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0),
303+ ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
304+ ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr"
305+ ))
306+ .bind(("usr", user.record()))
307+ .await
308+ .unwrap()
309+ .check()
310+ .unwrap();
311+ let rows: Vec<Vec<i64>> = result.take(0).unwrap();
312+ let row = rows.into_iter().next().expect("the user row");
313+ (row[0], row[1], row[2])
314+ }
315+
316+ /// Age *both* day buckets by `days`, so the next finish lands that many
317+ /// days later on the calendar — the streak's and the day quota's, since
318+ /// they are the same calendar and a test that moved one would be asserting
319+ /// against a day the other has never heard of. The day is injected into the
320+ /// stored state rather than into the clock, which keeps `Timestamp::now`
321+ /// the sole clock read and the test free of sleeping.
322+ ///
323+ /// Known flake, left as-is: every caller assumes the UTC day does not turn
324+ /// over mid-test — a crossing between two stints shifts the real day under
325+ /// the injected one and reddens the run. That is one ~ms-wide window per
326+ /// day (~5e-6 per run), and the alternative is a clock seam in production
327+ /// code to serve a test. Re-run before believing a failure that only ever
328+ /// happens near midnight UTC.
329+ async fn age_by_days(user: &UserId, db: &Database, days: i64) {
330+ db.query(format!(
331+ "UPDATE $usr SET
332+ {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days,
333+ {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days"
334+ ))
335+ .bind(("usr", user.record()))
336+ .bind(("days", days))
337+ .await
338+ .unwrap()
339+ .check()
340+ .unwrap();
341+ }
342+
343+ /// Open a stint that has already been running for `ms` — the stamp the
344+ /// close measures against, injected instead of slept through.
345+ ///
346+ /// One `UPSERT`, not `start` followed by a backdate: the concurrent test
347+ /// races four of these onto the same open row, and a separate backdate can
348+ /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a
349+ /// zero-length stint and reddening the run for no defect. Same statement
350+ /// `start` runs, one clock read earlier.
351+ async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {
352+ db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }")
353+ .bind(("open", PomodoroSessionId::open_for(user).record()))
354+ .bind(("usr", user.record()))
355+ .bind(("at", Timestamp::now().as_millis() - ms))
356+ .await?
357+ .check()?;
358+ Ok(())
359+ }
360+
361+ /// Start and close one stint that counts: exactly the minimum on the clock,
362+ /// so every streak assertion below is about the day and not the duration.
363+ async fn one_stint(user: &UserId, db: &Database) {
364+ start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap();
365+ finish(db, user).await.unwrap();
366+ }
367+
368+ #[tokio::test]
369+ async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
370+ let db = database::init_mem().await.unwrap();
371+ let user = a_user(&db).await;
372+ // The stale-data case: a row that predates all three columns reads as
373+ // no streak at all, and its first finish opens a run of one.
374+ assert_eq!(streak(&user, &db).await, (0, 0, -1));
375+
376+ one_stint(&user, &db).await;
377+ let today = Timestamp::now().day_number();
378+ assert_eq!(streak(&user, &db).await, (1, 1, today));
379+
380+ // A second stint the same day is not a second day.
381+ one_stint(&user, &db).await;
382+ assert_eq!(streak(&user, &db).await, (1, 1, today));
383+
384+ // Days N+1 and N+2.
385+ for day in 2..=3 {
386+ age_by_days(&user, &db, 1).await;
387+ one_stint(&user, &db).await;
388+ assert_eq!(streak(&user, &db).await, (day, day, today));
389+ }
390+ }
391+
392+ #[tokio::test]
393+ async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
394+ let db = database::init_mem().await.unwrap();
395+ let user = a_user(&db).await;
396+
397+ one_stint(&user, &db).await;
398+ age_by_days(&user, &db, 1).await;
399+ one_stint(&user, &db).await;
400+ assert_eq!(streak(&user, &db).await.0, 2);
401+
402+ // Skip a day: the run restarts at one, the longest stays where it got.
403+ age_by_days(&user, &db, 2).await;
404+ one_stint(&user, &db).await;
405+ let (current, longest, _) = streak(&user, &db).await;
406+ assert_eq!((current, longest), (1, 2));
407+
408+ // A backwards day (a clock stepped back over a boundary) is a gap too,
409+ // and still cannot lower the mark.
410+ age_by_days(&user, &db, -5).await;
411+ one_stint(&user, &db).await;
412+ assert_eq!(
413+ streak(&user, &db).await,
414+ (1, 2, Timestamp::now().day_number())
415+ );
416+ }
417+
418+ /// The transaction boundary itself, on a real server: the streak pair and
419+ /// the counters must commit with the stint or not at all, under real
420+ /// contention on one user row.
421+ ///
422+ /// Multi-threaded and off the embedded engine for the reason
423+ /// [`crate::db::cap`] spells out: the in-memory engine does not
424+ /// conflict-check two concurrent writes to one record, so it would answer
425+ /// `Ok` to a write it dropped and *forge* the integrity failure this test
426+ /// exists to catch.
427+ ///
428+ /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT`
429+ /// pair from the batch turns all 20 rounds red. A `THROW` then errors only
430+ /// its own statement, so the losers of the open-row race run the rest of
431+ /// the cascade anyway — they bump the counters for a stint they never
432+ /// closed and `CREATE` a session row out of an empty `$before`, which comes
433+ /// back as `500 … Expected record, got none` (the `errors` assertion below
434+ /// fires first; `finished_total` running ahead of the `Ok` finishes is the
435+ /// same wound one statement later). What it does *not* pin is the
436+ /// streak arithmetic under concurrency: same-day finishes all compute the
437+ /// same value, so that stays green either way — it is
438+ /// `max(longest, current)` that makes that robust, not the isolation.
439+ ///
440+ /// The shape of the contention, measured rather than assumed: four racers
441+ /// per round is four `start`s collapsing onto *one* open row (the id is
442+ /// deterministic per user), so typically exactly one `finish` commits and
443+ /// three lose the `DELETE` and abort their whole cascade — 20 finishes and
444+ /// 60 conflicts over 20 rounds, measured. That is the contention: the
445+ /// losers' cascades are live against the same user row, which is precisely
446+ /// what must leave nothing behind. Two commits in one round are possible
447+ /// (a racer scheduled entirely after another's finish frees the slot) and
448+ /// the assertions allow it — the day count is per round, not per stint.
449+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
450+ #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
451+ async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
452+ let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await;
453+ let user = a_user(&db).await;
454+ let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
455+ let mut last_error = String::new();
456+ for round in 1..=20 {
457+ let racers: Vec<_> = (0..4)
458+ .map(|_| {
459+ let (user, db) = (user.clone(), db.clone());
460+ tokio::spawn(async move {
461+ // Aged past the minimum, so whichever racer wins the
462+ // open row closes a stint that *counts* — a fresh
463+ // `start` here would hand the winner a zero-length
464+ // stint, which now moves nothing and would leave this
465+ // test asserting against an untouched counter.
466+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?;
467+ finish(&db, &user).await
468+ })
469+ })
470+ .collect();
471+ let mut won = 0;
472+ for racer in racers {
473+ match racer.await.unwrap() {
474+ Ok(_) => won += 1,
475+ // Losing the open row is the correct answer for a racer
476+ // whose stint someone else closed; only `Db` is a defect.
477+ Err(AppError::Conflict(_)) => conflicts += 1,
478+ Err(err) => {
479+ errors += 1;
480+ last_error = format!("{err:?}");
481+ }
482+ }
483+ }
484+ finished += won;
485+ // One day per round, however many stints landed in it, and the
486+ // mark never lags the run in progress.
487+ let (current, longest, _) = streak(&user, &db).await;
488+ assert_eq!(
489+ (current, longest),
490+ (round, round),
491+ "round {round} counted {won} finishes as {current} days"
492+ );
493+ age_by_days(&user, &db, 1).await;
494+ }
495+ // The atomicity claim: the counter counts exactly the stints that were
496+ // closed, never a loser's aborted round.
497+ let (counted, _) = counters(&user, &db).await;
498+ eprintln!(
499+ "PomodoroSession::finish raced: {finished} finishes over 20 days, \
500+ {conflicts} rivals refused, {errors} 500s"
501+ );
502+ assert_eq!(
503+ errors, 0,
504+ "a raced finish must conflict, not 500: {last_error}"
505+ );
506+ assert_eq!(
507+ counted, finished,
508+ "the counter counted {counted} stints for {finished} finishes"
509+ );
510+ assert!(
511+ conflicts > 0,
512+ "every racer won its own round, so no cascade was ever aborted mid-flight \
513+ and this run proves nothing about the transaction boundary"
514+ );
515+ }
516+
517+ #[tokio::test]
518+ async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
519+ let db = database::init_mem().await.unwrap();
520+ let user = a_user(&db).await;
521+ assert_eq!(counters(&user, &db).await, (0, 0));
522+
523+ // An open stint is not a finished one: neither counter moves until it
524+ // closes.
525+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
526+ .await
527+ .unwrap();
528+ assert_eq!(counters(&user, &db).await, (0, 0));
529+
530+ let mut focus_ms = 0;
531+ for _ in 0..2 {
532+ let closed = finish(&db, &user).await.unwrap();
533+ focus_ms +=
534+ closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis();
535+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
536+ .await
537+ .unwrap();
538+ }
539+ // Three starts, two finishes — the third is still running.
540+ assert_eq!(counters(&user, &db).await, (2, focus_ms));
541+ }
542+
543+ #[tokio::test]
544+ async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
545+ let db = database::init_mem().await.unwrap();
546+ let user = a_user(&db).await;
547+
548+ start(&db, &user).await.unwrap();
549+ db.query("UPDATE $open SET started_at = $future")
550+ .bind(("open", PomodoroSessionId::open_for(&user).record()))
551+ .bind(("future", Timestamp::now().as_millis() + 3_600_000))
552+ .await
553+ .unwrap()
554+ .check()
555+ .unwrap();
556+
557+ // The clamp holds: zero milliseconds, never a negative — and a stint
558+ // measuring zero is below the minimum, so it moves neither counter.
559+ let closed = finish(&db, &user).await.unwrap();
560+ assert_eq!(closed.get_counted(), Some(false));
561+ assert_eq!(counters(&user, &db).await, (0, 0));
562+ }
563+
564+ /// The minimum, from both sides. A round-trip is not a study session, and
565+ /// the boundary is inclusive (`>=`) — a stint of exactly the minimum
566+ /// counts, which is the side these assertions pin.
567+ ///
568+ /// The near miss is a whole minute short, not one millisecond: `finish`
569+ /// reads its own clock *after* the stint is opened, so a stint aged to
570+ /// exactly one millisecond under the bar crosses it by the time the close
571+ /// measures it (measured — that assertion failed on the first run). A
572+ /// millisecond-exact probe would need a clock seam in production code, and
573+ /// what matters here is the four orders of magnitude between a scripted
574+ /// pair and a study session, not the last millisecond.
575+ #[tokio::test]
576+ async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {
577+ let db = database::init_mem().await.unwrap();
578+ let user = a_user(&db).await;
579+
580+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)
581+ .await
582+ .unwrap();
583+ let short = finish(&db, &user).await.unwrap();
584+ assert_eq!(short.get_counted(), Some(false));
585+ assert_eq!(counters(&user, &db).await, (0, 0));
586+ // Not a study day either — and no streak column was even opened.
587+ assert_eq!(streak(&user, &db).await, (0, 0, -1));
588+ // But it happened, and the log says so.
589+ let log = list_for_user(&db, &user).await.unwrap();
590+ assert_eq!(log.len(), 1);
591+ assert_eq!(log[0].get_finished_at(), short.get_finished_at());
592+
593+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
594+ .await
595+ .unwrap();
596+ let counted = finish(&db, &user).await.unwrap();
597+ assert_eq!(counted.get_counted(), Some(true));
598+ let (finished, focus_ms) = counters(&user, &db).await;
599+ // The counter took the *same* duration the row stores, not a second
600+ // reading of the clock.
601+ assert_eq!(
602+ (finished, focus_ms),
603+ (
604+ 1,
605+ counted.get_finished_at().unwrap().as_millis()
606+ - counted.get_started_at().as_millis()
607+ )
608+ );
609+ assert_eq!(streak(&user, &db).await.0, 1);
610+ assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 2);
611+ }
612+
613+ /// The day quota: it stops the counter, it never stops the log, and it
614+ /// rolls at midnight UTC.
615+ #[tokio::test]
616+ async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() {
617+ let db = database::init_mem().await.unwrap();
618+ let user = a_user(&db).await;
619+
620+ for _ in 0..MAX_COUNTED_POMODORO_PER_DAY {
621+ one_stint(&user, &db).await;
622+ }
623+ let (finished, focus_ms) = counters(&user, &db).await;
624+ assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY);
625+
626+ // Past the quota: recorded, listed, worth nothing — neither stint count
627+ // nor focus milliseconds.
628+ for _ in 0..3 {
629+ start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
630+ .await
631+ .unwrap();
632+ let over = finish(&db, &user).await.unwrap();
633+ assert_eq!(over.get_counted(), Some(false));
634+ }
635+ assert_eq!(counters(&user, &db).await, (finished, focus_ms));
636+ assert_eq!(
637+ list_for_user(&db, &user).await.unwrap().len() as i64,
638+ MAX_COUNTED_POMODORO_PER_DAY + 3
639+ );
640+ // The quota is a day's, not a lifetime's.
641+ age_by_days(&user, &db, 1).await;
642+ one_stint(&user, &db).await;
643+ assert_eq!(
644+ counters(&user, &db).await.0,
645+ MAX_COUNTED_POMODORO_PER_DAY + 1
646+ );
647+ }
648+
649+ /// The farm, run: `start`/`finish` in a loop is two requests a round with
650+ /// no second person in it, which used to move `pomodoro_finished_total` one
651+ /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`,
652+ /// and a badge is never taken back.
653+ #[tokio::test]
654+ async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {
655+ let db = database::init_mem().await.unwrap();
656+ let user = a_user(&db).await;
657+
658+ for _ in 0..200 {
659+ start(&db, &user).await.unwrap();
660+ finish(&db, &user).await.unwrap();
661+ }
662+ assert_eq!(counters(&user, &db).await, (0, 0));
663+ assert_eq!(streak(&user, &db).await, (0, 0, -1));
664+ // Every one of them is still the student's own history.
665+ assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 200);
666+ assert!(
667+ badge::BadgeAward::list_for(&user, &db)
668+ .await
669+ .unwrap()
670+ .is_empty(),
671+ "the farm minted a permanent badge"
672+ );
673+
674+ // And paying the minimum for each one only buys the day's quota.
675+ for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) {
676+ one_stint(&user, &db).await;
677+ }
678+ assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY);
679+ }
680+
681+ #[tokio::test]
682+ async fn restart_replaces_the_open_session_and_finish_closes_it() {
683+ let db = database::init_mem().await.unwrap();
684+ // A `record<user>` column checks the table of the id, not row
685+ // existence — a fabricated id keeps this test free of user ceremony.
686+ let user = UserId::from_key(&Ulid::new().to_string());
687+
688+ // Nothing running yet — finishing conflicts.
689+ assert!(matches!(
690+ finish(&db, &user).await,
691+ Err(AppError::Conflict(_))
692+ ));
693+
694+ let first = start(&db, &user).await.unwrap();
695+ assert!(first.get_finished_at().is_none());
696+ assert_eq!(first.get_id().key(), format!("open_{}", user.key()));
697+
698+ // A restart replaces the dangling session: still one row, fresh clock.
699+ let second = start(&db, &user).await.unwrap();
700+ assert!(second.get_started_at() >= first.get_started_at());
701+ let sessions = list_for_user(&db, &user).await.unwrap();
702+ assert_eq!(sessions.len(), 1);
703+
704+ let closed = finish(&db, &user).await.unwrap();
705+ assert!(closed.get_finished_at().unwrap() >= closed.get_started_at());
706+
707+ // The open slot is free again; a stray second finish conflicts.
708+ assert!(matches!(
709+ finish(&db, &user).await,
710+ Err(AppError::Conflict(_))
711+ ));
712+ start(&db, &user).await.unwrap();
713+ let sessions = list_for_user(&db, &user).await.unwrap();
714+ assert_eq!(sessions.len(), 2);
715+ }
716+
717+ #[tokio::test]
718+ async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {
719+ let db = database::init_mem().await.unwrap();
720+ let user = UserId::from_key(&Ulid::new().to_string());
721+
722+ start(&db, &user).await.unwrap();
723+ // Stand in for the NTP step: push the running stint's start an hour
724+ // ahead, so the server clock `finish` reads is *behind* it.
725+ db.query("UPDATE $open SET started_at = $future")
726+ .bind(("open", PomodoroSessionId::open_for(&user).record()))
727+ .bind(("future", Timestamp::now().as_millis() + 3_600_000))
728+ .await
729+ .unwrap()
730+ .check()
731+ .unwrap();
732+
733+ let closed = finish(&db, &user).await.unwrap();
734+ let started = closed.get_started_at().as_millis();
735+ assert_eq!(closed.get_finished_at().unwrap().as_millis(), started);
736+
737+ // And the stat that sums these stays non-negative.
738+ let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db)
739+ .await
740+ .unwrap();
741+ assert_eq!(stats.get_pomodoro_sessions(), 1);
742+ assert_eq!(stats.get_pomodoro_focus_ms(), 0);
743+ }
744+}
src/db/work_entry.rsadded+183 -0
@@ -0,0 +1,183 @@
1+//! The `work_entry` table: the open-slot check-in/check-out pair, the
2+//! newest-first log, and manager corrections guarded by the stored order.
3+
4+use surrealdb::types::SurrealValue;
5+
6+use crate::database::{Database, transaction_with_retry};
7+use crate::db::field_update::FieldUpdate;
8+use crate::db::page::PagedList;
9+use crate::domain::timestamp::Timestamp;
10+use crate::domain::user::UserId;
11+use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
12+use crate::error::AppError;
13+
14+/// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE`
15+/// on the deterministic open id makes this atomic: if an open entry
16+/// already exists the insert is skipped (empty result) and the caller gets
17+/// a conflict — two racing check-ins can never create two open rows or
18+/// reset a running clock.
19+pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
20+ let entry = WorkEntry {
21+ id: WorkEntryId::open_for(user),
22+ user: user.clone(),
23+ check_in: Timestamp::now(),
24+ check_out: None,
25+ };
26+ let mut result = db
27+ .query("INSERT IGNORE INTO work_entry $entry")
28+ .bind(("entry", entry))
29+ .await?
30+ .check()?;
31+ result
32+ .take::<Vec<WorkEntry>>(0)?
33+ .into_iter()
34+ .next()
35+ .ok_or(AppError::Conflict("already checked in — check out first"))
36+}
37+
38+/// Close `user`'s open stint: atomically take the open row and re-file it
39+/// under a ULID id, freeing the open slot for the next check-in. Take and
40+/// re-file share one transaction — a failed re-file rolls the take back,
41+/// so a stint can never vanish half-closed. Of two racing check-outs
42+/// exactly one receives the row (the other gets the conflict).
43+///
44+/// A lost round is re-sent rather than reported (`transaction_with_retry`):
45+/// the abort wrote nothing, so the whole cascade is safe to repeat, and the
46+/// `CREATE` cannot answer "already exists" on the way back — the table
47+/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
48+/// Only the guard's own `THROW` is a decision, and it stays a 409.
49+pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
50+ let (mut result, mut errors) = transaction_with_retry(
51+ db,
52+ "BEGIN TRANSACTION;
53+ LET $before = (DELETE $open RETURN BEFORE);
54+ IF array::len($before) = 0 { THROW 'not_checked_in' };
55+ CREATE $closed CONTENT {
56+ user: $before[0].user,
57+ check_in: $before[0].check_in,
58+ check_out: $out,
59+ };
60+ COMMIT TRANSACTION;",
61+ &[
62+ (
63+ "open".into(),
64+ WorkEntryId::open_for(user).record().into_value(),
65+ ),
66+ (
67+ "closed".into(),
68+ WorkEntryId::generate().record().into_value(),
69+ ),
70+ ("out".into(), Timestamp::now().into_value()),
71+ ],
72+ &["not_checked_in"],
73+ )
74+ .await?;
75+ // An aborted transaction errors *every* slot, most with a generic
76+ // "not executed" — only the THROW's own slot names the reason, so scan
77+ // them all for the marker instead of trusting the first.
78+ if errors
79+ .values()
80+ .any(|error| error.to_string().contains("not_checked_in"))
81+ {
82+ return Err(AppError::Conflict("not checked in"));
83+ }
84+ if let Some(error) = errors.drain().map(|(_, error)| error).next() {
85+ return Err(error.into());
86+ }
87+ // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3.
88+ let saved: Option<WorkEntry> = result.take::<Vec<WorkEntry>>(3)?.into_iter().next();
89+ saved.ok_or_else(|| AppError::Internal("failed to close work entry".into()))
90+}
91+
92+pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
93+ Ok(db.select(id.record()).await?)
94+}
95+
96+/// Every stint of `user`, newest first — the open one (if any) included.
97+/// Ordered by `check_in`, never by id alone: the open entry's `open_` key
98+/// doesn't sort with the ULIDs, so id order would misplace it. The `id`
99+/// tie-break behind it only ever separates two *closed* stints sharing a
100+/// `check_in` — there is one open row per user, so it can never tie with
101+/// itself — and that is what keeps offset paging from skipping a row.
102+pub async fn list_for_user(
103+ db: &Database,
104+ user: &UserId,
105+ limit: Option<i64>,
106+ offset: i64,
107+) -> Result<(Vec<WorkEntry>, i64), AppError> {
108+ PagedList::new(
109+ "work_entry WHERE user = $usr",
110+ "ORDER BY check_in DESC, id DESC",
111+ )
112+ .bind("usr", user.record())
113+ .run(limit, offset, db)
114+ .await
115+}
116+
117+/// Persist corrected instants (manager fix-ups on closed entries; the web
118+/// layer validates ordering and rejects open entries).
119+/// `None` = the correction left that instant out, so it is not written at
120+/// all — the stint's `user` and `check_in`/`check_out` stamps are never
121+/// replayed from a struct the handler read before its validation awaits.
122+/// `check_out` is never cleared here: an open stint is refused upstream, so
123+/// "absent" and "null" both mean keep.
124+pub async fn update(
125+ db: &Database,
126+ entry: WorkEntry,
127+ check_in: Option<Timestamp>,
128+ check_out: Option<Timestamp>,
129+) -> Result<WorkEntry, AppError> {
130+ FieldUpdate::new(entry.get_id().record())
131+ .set("check_in", check_in)
132+ .set("check_out", check_out)
133+ // Same race closer as the schedule ranges, with this table's own
134+ // field names and message: a correction of one instant is only
135+ // written while it still orders against the other as *stored*.
136+ .ordered("check_in", "check_out", out_before_in_error())
137+ .run::<WorkEntry>(db)
138+ .await
139+}
140+
141+pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
142+ Ok(db.delete(id.record()).await?)
143+}
144+
145+#[cfg(test)]
146+mod tests {
147+ use ulid::Ulid;
148+
149+ use super::*;
150+ use crate::database;
151+
152+ #[tokio::test]
153+ async fn check_in_is_exclusive_until_check_out() {
154+ let db = database::init_mem().await.unwrap();
155+ // A `record<user>` column checks the table of the id, not row
156+ // existence — a fabricated id keeps this test free of user ceremony.
157+ let user = UserId::from_key(&Ulid::new().to_string());
158+
159+ let open = check_in(&db, &user).await.unwrap();
160+ assert!(open.is_open());
161+ assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
162+
163+ // Second check-in must not create a second stint or reset the clock.
164+ let dup = check_in(&db, &user).await;
165+ assert!(matches!(dup, Err(AppError::Conflict(_))));
166+ let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
167+ assert_eq!(entries.len(), 1);
168+ assert_eq!(entries[0].get_check_in(), open.get_check_in());
169+
170+ let closed = check_out(&db, &user).await.unwrap();
171+ assert!(!closed.is_open());
172+ assert!(closed.get_check_out().unwrap() >= closed.get_check_in());
173+
174+ // The open slot is free again; a stray second check-out conflicts.
175+ assert!(matches!(
176+ check_out(&db, &user).await,
177+ Err(AppError::Conflict(_))
178+ ));
179+ check_in(&db, &user).await.unwrap();
180+ let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
181+ assert_eq!(entries.len(), 2);
182+ }
183+}
src/domain/attendance.rsmodified+7 -7
@@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD};3 use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD};
4 use crate::database::{Database, transaction_with_retry};4 use crate::database::{Database, transaction_with_retry};
5-use crate::domain::event::EventId;
6 use crate::db::page::PagedList;5 use crate::db::page::PagedList;
6+use crate::domain::event::EventId;
7 use crate::domain::user::UserId;7 use crate::domain::user::UserId;
8 use crate::error::{AppError, ValidationError};8 use crate::error::{AppError, ValidationError};
9 9
@@ -234,7 +234,7 @@ mod tests {
234 /// The session twin's race, one table over234 /// The session twin's race, one table over
235 /// ([`crate::domain::session_attendance::SessionAttendance`]): a235 /// ([`crate::domain::session_attendance::SessionAttendance`]): a
236 /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and236 /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and
237- /// [`Event::delete`] sweeps its attendance rows before removing the row, so237+ /// [`crate::db::event::delete`] sweeps its attendance rows before removing the row, so
238 /// the `SLEEP` lands exactly between the sweep and the commit — the window238 /// the `SLEEP` lands exactly between the sweep and the commit — the window
239 /// where a bare upsert wrote a mark nothing would ever sweep again.239 /// where a bare upsert wrote a mark nothing would ever sweep again.
240 ///240 ///
@@ -246,7 +246,7 @@ mod tests {
246 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]246 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
247 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]247 #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
248 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {248 async fn a_mark_written_inside_a_delete_never_outlives_the_event() {
249- use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle};249+ use crate::domain::event::{EventAudience, EventDescription, EventTitle};
250 let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;250 let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await;
251 db.query(251 db.query(
252 "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \252 "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \
@@ -263,21 +263,21 @@ mod tests {
263 let marker = UserId::from_key("t");263 let marker = UserId::from_key("t");
264 let (mut swept, mut orphans) = (0, 0);264 let (mut swept, mut orphans) = (0, 0);
265 for round in 0..4 {265 for round in 0..4 {
266- let event = Event::create(266+ let event = crate::db::event::create(
267+ &db,
267 &marker,268 &marker,
268 EventTitle::try_new("gezi").unwrap(),269 EventTitle::try_new("gezi").unwrap(),
269 EventDescription::try_new("").unwrap(),270 EventDescription::try_new("").unwrap(),
270 EventAudience::School,271 EventAudience::School,
271 None,272 None,
272 None,273 None,
273- &db,
274 )274 )
275 .await275 .await
276 .unwrap();276 .unwrap();
277 let id = event.get_id().clone();277 let id = event.get_id().clone();
278 let drop_it = {278 let drop_it = {
279 let db = db.clone();279 let db = db.clone();
280- tokio::spawn(async move { event.delete(&db).await })280+ tokio::spawn(async move { crate::db::event::delete(&db, event).await })
281 };281 };
282 // The mark starts inside the held window: the sweep has run and the282 // The mark starts inside the held window: the sweep has run and the
283 // event row is gone but uncommitted.283 // event row is gone but uncommitted.
@@ -297,7 +297,7 @@ mod tests {
297 );297 );
298 298
299 // Stored state is the whole verdict; a return value is not evidence.299 // Stored state is the whole verdict; a return value is not evidence.
300- if Event::read(&id, &db).await.unwrap().is_none() {300+ if crate::db::event::read(&db, &id).await.unwrap().is_none() {
301 swept += 1;301 swept += 1;
302 orphans += Attendance::list_for_event(&id, None, 0, &db)302 orphans += Attendance::list_for_event(&id, None, 0, &db)
303 .await303 .await
src/domain/event.rsmodified+10 -281
@@ -3,16 +3,12 @@
3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};3 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value};
4 4
5 use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};5 use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN};
6-use crate::database::{Database, transaction_with_retry};
7-use crate::db::field_update::FieldUpdate;
8 use crate::domain::class_group::ClassGroupId;6 use crate::domain::class_group::ClassGroupId;
9-use crate::domain::class_member::{ClassMember, ClassMemberId};
10 use crate::domain::course::CourseId;7 use crate::domain::course::CourseId;
11 use crate::domain::monotonic_id::next_ulid;8 use crate::domain::monotonic_id::next_ulid;
12-use crate::domain::registration::Registration;
13 use crate::domain::role::Role;9 use crate::domain::role::Role;
14-use crate::domain::timestamp::{Timestamp, range_error};10+use crate::domain::timestamp::Timestamp;
15-use crate::domain::user::{User, UserId};11+use crate::domain::user::UserId;
16 use crate::error::{AppError, ValidationError};12 use crate::error::{AppError, ValidationError};
17 use crate::validate::{validate_optional, validate_required};13 use crate::validate::{validate_optional, validate_required};
18 14
@@ -21,7 +17,7 @@ pub struct EventId(RecordId);
21 17
22 impl EventId {18 impl EventId {
23 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:19 /// Minted from the process-wide monotonic generator, not `Ulid::new()`:
24- /// events list `id DESC` (newest first, [`Event::list_all`]),20+ /// events list `id DESC` (newest first, [`crate::db::event::list_all`]),
25 /// and a random low half scrambles rows minted in the same millisecond.21 /// and a random low half scrambles rows minted in the same millisecond.
26 pub fn generate() -> Self {22 pub fn generate() -> Self {
27 Self(RecordId::new(EVENT_TABLE, next_ulid().to_string()))23 Self(RecordId::new(EVENT_TABLE, next_ulid().to_string()))
@@ -105,91 +101,15 @@ pub enum EventAudience {
105 Registration { capacity: Option<i64> },101 Registration { capacity: Option<i64> },
106 }102 }
107 103
108-impl EventAudience {
109- /// Is `user` in `event`'s roster right now? The point check behind
110- /// marking — cheaper than resolving the whole roster when the target is
111- /// known. `event` must be the event this audience came from: the
112- /// registration kind resolves against that event's signup rows.
113- pub async fn includes(
114- &self,
115- event: &EventId,
116- user: &User,
117- db: &Database,
118- ) -> Result<bool, AppError> {
119- match self {
120- EventAudience::School => Ok(true),
121- EventAudience::Role { role } => Ok(user.get_role() == *role),
122- EventAudience::Course { course } => {
123- Ok(
124- crate::db::enrollment::read_for_user(db, course, user.get_id())
125- .await?
126- .is_some(),
127- )
128- }
129- // The (class, user) pair is the membership row's own id, so the
130- // point check is a single select — no scan, no index needed.
131- EventAudience::Class { class } => {
132- let member: Option<ClassMember> = db
133- .select(ClassMemberId::composite(class, user.get_id()).record())
134- .await?;
135- Ok(member.is_some())
136- }
137- EventAudience::Registration { .. } => {
138- Ok(Registration::read_for_user(event, user.get_id(), db)
139- .await?
140- .is_some())
141- }
142- }
143- }
144-
145- /// `event`'s full roster, as it stands right now — the who-missed
146- /// report's backbone. Registered ids that no longer resolve to a user row
147- /// are kept; the caller degrades their display like any stale reference.
148- pub async fn members(&self, event: &EventId, db: &Database) -> Result<Vec<UserId>, AppError> {
149- match self {
150- EventAudience::School => Ok(crate::db::user::list_all(db, None, 0)
151- .await?
152- .0
153- .iter()
154- .map(|user| user.get_id().clone())
155- .collect()),
156- EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role)
157- .await?
158- .iter()
159- .map(|user| user.get_id().clone())
160- .collect()),
161- EventAudience::Course { course } => {
162- Ok(crate::db::enrollment::list_for_course(db, course, None, 0)
163- .await?
164- .0
165- .iter()
166- .map(|enrollment| enrollment.get_user().clone())
167- .collect())
168- }
169- EventAudience::Class { class } => Ok(ClassMember::list_for_class(class, None, 0, db)
170- .await?
171- .0
172- .iter()
173- .map(|member| member.get_user().clone())
174- .collect()),
175- EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db)
176- .await?
177- .iter()
178- .map(|registration| registration.get_user().clone())
179- .collect()),
180- }
181- }
182-}
183-
184 #[derive(Debug, Clone, SurrealValue)]104 #[derive(Debug, Clone, SurrealValue)]
185 pub struct Event {105 pub struct Event {
186- id: EventId,106+ pub(crate) id: EventId,
187- creator: UserId,107+ pub(crate) creator: UserId,
188- title: EventTitle,108+ pub(crate) title: EventTitle,
189- description: EventDescription,109+ pub(crate) description: EventDescription,
190- audience: EventAudience,110+ pub(crate) audience: EventAudience,
191- starts_at: Option<Timestamp>,111+ pub(crate) starts_at: Option<Timestamp>,
192- ends_at: Option<Timestamp>,112+ pub(crate) ends_at: Option<Timestamp>,
193 }113 }
194 114
195 impl Event {115 impl Event {
@@ -247,203 +167,12 @@ impl Event {
247 }167 }
248 Ok(*capacity)168 Ok(*capacity)
249 }169 }
250-
251- pub async fn create(
252- creator: &UserId,
253- title: EventTitle,
254- description: EventDescription,
255- audience: EventAudience,
256- starts_at: Option<Timestamp>,
257- ends_at: Option<Timestamp>,
258- db: &Database,
259- ) -> Result<Event, AppError> {
260- let event = Event {
261- id: EventId::generate(),
262- creator: creator.clone(),
263- title,
264- description,
265- audience,
266- starts_at,
267- ends_at,
268- };
269- let created: Option<Event> = db.create(event.id.record()).content(event).await?;
270- created.ok_or_else(|| AppError::Internal("failed to create event".into()))
271- }
272-
273- pub async fn read(id: &EventId, db: &Database) -> Result<Option<Event>, AppError> {
274- Ok(db.select(id.record()).await?)
275- }
276-
277- pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
278- let mut result = db
279- .query("SELECT * FROM event ORDER BY id DESC")
280- .await?
281- .check()?;
282- Ok(result.take::<Vec<Event>>(0)?)
283- }
284-
285- /// Request-scoped: the handler reads the event, then awaits the clock and a
286- /// course lookup before saving, holding no lock, so an omitted field
287- /// (`None`) is not written at all. Passing the snapshot's value back
288- /// instead would revert a concurrent edit of that field — scoping the `SET`
289- /// alone does not prevent that, the values have to come from the request.
290- /// The schedule columns are nullable, so they take the outer/inner
291- /// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
292- pub async fn update(
293- self,
294- title: Option<EventTitle>,
295- description: Option<EventDescription>,
296- audience: Option<EventAudience>,
297- starts_at: Option<Option<Timestamp>>,
298- ends_at: Option<Option<Timestamp>>,
299- db: &Database,
300- ) -> Result<Event, AppError> {
301- FieldUpdate::new(self.id.record())
302- .set("title", title)
303- .set("description", description)
304- .set("audience", audience)
305- .set("starts_at", starts_at)
306- .set("ends_at", ends_at)
307- .ordered("starts_at", "ends_at", range_error())
308- .run::<Event>(db)
309- .await
310- }
311-
312- /// Delete the event and cascade-remove its attendance and signup rows.
313- ///
314- /// Children first, and all of it in one transaction the way
315- /// [`crate::db::course::delete`] does it: run as two queries, a
316- /// registration or a mark that committed in between outlived its event —
317- /// an orphan no read path can ever reach and no delete can ever reclaim,
318- /// since every one of them is keyed on the event that is now gone.
319- ///
320- /// Re-sent while the store answers "conflict, retry", the way
321- /// [`crate::db::course_session::delete`] is: now that
322- /// [`crate::domain::attendance::Attendance::mark`] writes the event row to
323- /// prove it exists, a mark landing in this window really does contend for
324- /// it — and without the retry the *delete* is the side that loses, turning
325- /// a race the store resolved correctly into a 500 (measured 4 rounds in 4).
326- /// Admissible: every statement is a `DELETE`, which can never answer
327- /// "already exists", and a lost round wrote nothing.
328- pub async fn delete(self, db: &Database) -> Result<Event, AppError> {
329- let (mut result, mut errors) = transaction_with_retry(
330- db,
331- "BEGIN TRANSACTION;
332- DELETE attendance WHERE event = $ev;
333- DELETE registration WHERE event = $ev;
334- LET $gone = (DELETE $ev RETURN BEFORE);
335- RETURN $gone;
336- COMMIT TRANSACTION;",
337- &[("ev".into(), self.id.record().into_value())],
338- // No THROW of its own — an unconditional cascade.
339- &[],
340- )
341- .await?;
342- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
343- return Err(error.into());
344- }
345- // Read through the trailing `RETURN`, never a hand-counted slot.
346- let slot = result.num_statements().saturating_sub(2);
347- result
348- .take::<Vec<Event>>(slot)?
349- .into_iter()
350- .next()
351- .ok_or(AppError::NotFound)
352- }
353 }170 }
354 171
355 #[cfg(test)]172 #[cfg(test)]
356 mod tests {173 mod tests {
357 use super::*;174 use super::*;
358 175
359- /// The forcing function behind the one rule with two spellings: the freeze
360- /// this file decides in Rust ([`Event::registration_capacity`]) and
361- /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which
362- /// the role cascade (`service::user::set_role`) carries because it frees a demoted
363- /// parent's seats inside a transaction and cannot call Rust from there.
364- ///
365- /// Every schedule shape is put to both, including the three the SQL is most
366- /// likely to get wrong: the ends_at-only event (`??` must fall through to
367- /// it), the boundary itself (closed *at* the instant, not after it — `>=` in
368- /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound
369- /// to that exact instant so the boundary is really exercised), and an event
370- /// that takes no registrations at all, which Rust refuses one arm *earlier*
371- /// — so the SQL must not report it frozen, or a stray row on it would be
372- /// preserved forever instead of swept.
373- #[tokio::test]
374- async fn the_sql_freeze_guard_matches_the_rust_one() {
375- use crate::constant::REGISTRATION_FROZEN_GUARD;
376-
377- let db = crate::database::init_mem().await.unwrap();
378- let now = Timestamp::now().as_millis();
379- let past = Some(Timestamp::from_millis(now - 60_000));
380- let future = Some(Timestamp::from_millis(now + 3_600_000));
381- let later = Some(Timestamp::from_millis(now + 7_200_000));
382- let signup = EventAudience::Registration { capacity: None };
383- let cases = [
384- ("timeless", signup.clone(), None, None),
385- ("deadline ahead", signup.clone(), None, future),
386- ("deadline passed", signup.clone(), None, past),
387- ("starts later", signup.clone(), future, later),
388- ("already started", signup.clone(), past, None),
389- ("started, ends later", signup.clone(), past, future),
390- (
391- "closing this instant",
392- signup.clone(),
393- Some(Timestamp::from_millis(now)),
394- None,
395- ),
396- // No signup list to freeze: `registration_capacity` refuses these on
397- // the audience, before it ever looks at the clock.
398- ("started school event", EventAudience::School, past, None),
399- (
400- "started class event",
401- EventAudience::Class {
402- class: ClassGroupId::from_key("g1"),
403- },
404- past,
405- None,
406- ),
407- ];
408- for (name, audience, starts_at, ends_at) in cases {
409- let event = Event::create(
410- &UserId::from_key("teacher"),
411- EventTitle::try_new(name).unwrap(),
412- EventDescription::try_new("").unwrap(),
413- audience,
414- starts_at,
415- ends_at,
416- &db,
417- )
418- .await
419- .unwrap();
420- let rust = matches!(
421- event.registration_capacity(),
422- Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
423- );
424- let mut result = db
425- .query(format!(
426- "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}"
427- ))
428- .bind(("ev", event.get_id().record()))
429- .bind(("now", now))
430- .await
431- .unwrap()
432- .check()
433- .unwrap();
434- let sql = !result
435- .take::<Vec<surrealdb::types::RecordId>>(0)
436- .unwrap()
437- .is_empty();
438- assert_eq!(
439- sql, rust,
440- "the SQL freeze guard and registration_capacity disagree on a \
441- {name} event — the role cascade would rewrite a closed signup \
442- list, or strand a seat on an open one"
443- );
444- }
445- }
446-
447 #[tokio::test]176 #[tokio::test]
448 async fn title_is_required() {177 async fn title_is_required() {
449 assert!(EventTitle::try_new("standup").is_ok());178 assert!(EventTitle::try_new("standup").is_ok());
src/domain/pomodoro.rsmodified+5 -756
@@ -1,17 +1,9 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3-use crate::constant::{3+use crate::constant::POMODORO_SESSION_TABLE;
4- MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD,
5- POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD,
6- POMODORO_SESSION_TABLE, STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD,
7- STUDY_STREAK_LONGEST_FIELD,
8-};
9-use crate::database::{Database, transaction_with_retry};
10-use crate::domain::badge;
11 use crate::domain::monotonic_id::next_ulid;4 use crate::domain::monotonic_id::next_ulid;
12 use crate::domain::timestamp::Timestamp;5 use crate::domain::timestamp::Timestamp;
13 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
14-use crate::error::AppError;
15 7
16 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]8 #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)]
17 pub struct PomodoroSessionId(RecordId);9 pub struct PomodoroSessionId(RecordId);
@@ -83,754 +75,11 @@ impl PomodoroSession {
83 self.finished_at75 self.finished_at
84 }76 }
85 77
86- /// Whether this stint moved the lifetime counters, as [`Self::finish`]78+ /// Whether this stint moved the lifetime counters, as
87- /// judged it. `None` while it is still running — and on any stint closed79+ /// [`crate::db::pomodoro::finish`] judged it. `None` while it is still
88- /// before the rule existed, which cannot honestly be given a verdict now.80+ /// running — and on any stint closed before the rule existed, which
81+ /// cannot honestly be given a verdict now.
89 pub fn get_counted(&self) -> Option<bool> {82 pub fn get_counted(&self) -> Option<bool> {
90 self.counted83 self.counted
91 }84 }
92-
93- /// Start a session for `user`, stamped with the server clock. `UPSERT` on
94- /// the deterministic open id makes this atomic and always succeed: a
95- /// dangling unfinished session (the browser died mid-timer) is replaced —
96- /// it never counted, and blocking the next start behind it would only
97- /// punish the student for a crash.
98- pub async fn start(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> {
99- let mut result = db
100- .query("UPSERT $open CONTENT { user: $usr, started_at: $at }")
101- .bind(("open", PomodoroSessionId::open_for(user).record()))
102- .bind(("usr", user.record()))
103- .bind(("at", Timestamp::now()))
104- .await?
105- .check()?;
106- result
107- .take::<Vec<PomodoroSession>>(0)?
108- .into_iter()
109- .next()
110- .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into()))
111- }
112-
113- /// Close `user`'s running session: atomically take the open row and
114- /// re-file it under a ULID id, freeing the open slot for the next start.
115- /// Take and re-file share one transaction — a failed re-file rolls the
116- /// take back, so a session can never vanish half-closed. Of two racing
117- /// finishes exactly one receives the row (the other gets the conflict).
118- ///
119- /// A lost round is re-sent rather than reported (`transaction_with_retry`):
120- /// the abort wrote nothing, so the whole cascade is safe to repeat, and the
121- /// `CREATE` cannot answer "already exists" on the way back — the table
122- /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
123- /// Only the guard's own `THROW` is a decision, and it stays a 409.
124- ///
125- /// `finished_at` is floored at the row's own `started_at`. Both stamps come
126- /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move
127- /// *backwards* mid-stint — so a close can legitimately read earlier than its
128- /// own start with nothing wrong on the client's side. Refusing it would lose
129- /// a real study session and leave the open slot wedged for a fault the
130- /// student did not cause; recording a zero-length stint keeps the session
131- /// count honest and its duration merely understated. Nothing downstream may
132- /// then read a negative duration (`ProfileStats::load` sums these).
133- ///
134- /// The lifetime badge counters on the user row move in this same
135- /// transaction, so they can never count a stint the log does not hold (nor
136- /// miss one it does), and a retried round re-applies nothing — the abort
137- /// rolled the increment back with the rest. They are written field-scoped:
138- /// the row also carries admin-owned data (`role`), which a whole-row save
139- /// would silently revert. The clamped duration is the *same* expression the
140- /// `CREATE` stores (both read `$ms`), so the counter can never take a
141- /// negative summand and nothing downstream needs a floor. Only *finished*
142- /// stints reach here — an open row is a `pomodoro_session` row and nothing
143- /// else — and there is no student-facing delete for a stint, so neither
144- /// counter ever decrements.
145- ///
146- /// They move only for a stint that **counts**, which is
147- /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most
148- /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this
149- /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`]
150- /// argues about from the other end: finishing is self-service, one stint is
151- /// two requests and no second person, so a counter moved once per
152- /// round-trip is farmable — two hundred pairs inside the rate limit bought
153- /// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked.
154- /// Both stamps are the server's own clock, so the duration needs no
155- /// distrusting, only a floor.
156- ///
157- /// The verdict is *stamped* on the closed row (`counted`), not re-derived
158- /// later: the thresholds are compiled in and will move, and a reader that
159- /// re-judged an old stint against today's numbers would answer something
160- /// other than what was credited. Nothing debits these counters today; the
161- /// stamp is what lets one be added without that asymmetry. A stint below
162- /// the bar is still recorded, still listed, and still sums into the log's
163- /// `total_focus_ms` — the rule bounds what *counts*, never what is kept.
164- ///
165- /// The day quota is bucketed like the streak below (midnight UTC,
166- /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the
167- /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting
168- /// it, which resolves against the row as it was *before* the statement —
169- /// the same rule that forces the streak pair apart, used here on purpose. A
170- /// row that predates the two columns reads as no day at all (`?? -1`), so
171- /// the first finish after this deploy opens a fresh bucket and no backfill
172- /// is owed. The bucket write happens whether the stint counts or not; only
173- /// the `+ 1` sits behind the verdict.
174- ///
175- /// The **study streak** rides the same transaction, and the same verdict: a
176- /// study day is a UTC calendar day on which a stint *counted*, so a day
177- /// bought with one instant round-trip is not a day studied (midnight UTC, like every
178- /// other day calculation here — no timezone is stored anywhere): the same
179- /// day again changes nothing, the next day extends the run, any other gap
180- /// starts a new one at 1. It is written as **two** statements, not one:
181- /// every field reference on the right-hand side of a `SET` resolves
182- /// against the row as it was *before* that statement, so a single
183- /// `SET current = …, longest = math::max([longest, current])` would take
184- /// the *old* `current` and lag one write behind forever (probed on a real
185- /// 3.2.3 server: day two left `current = 2, longest = 1`). Across
186- /// statements *inside a transaction* the read does see the prior write, so
187- /// the pair is correct and still atomic. Absent columns are read through
188- /// `?? 0` (and `?? -1` for the day — a sentinel no real day number
189- /// reaches), because `math::max` errors outright on a `NONE` argument and
190- /// every account older than these columns carries none of them.
191- ///
192- /// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two
193- /// lines up: a plain `UPDATE` hands back an array, so a user row that is
194- /// missing (a `record<user>` column checks only the table of the id) simply
195- /// yields nothing to index and the second statement matches no row either.
196- /// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero
197- /// rows; it errors on *many* — but a `null` is a shape the read then has to
198- /// special-case, so the file's existing idiom wins.
199- ///
200- /// No `cap::counter_lock` is taken, deliberately. The pair cannot tear:
201- /// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts
202- /// a rival that touched the row in between — `transaction_with_retry` then
203- /// re-sends the whole round. And `longest` is written as
204- /// `max(longest, current)`, which cannot come down under *any*
205- /// interleaving, so even a torn pair could only under-count `current`,
206- /// never lower the high-water mark the badges read. The lock would only
207- /// serialize this process's writers (its other job, keeping the in-memory
208- /// test engine deterministic, is moot here — these tests are sequential).
209- /// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent
210- /// finishes for one user left `current = 60, longest = 60` with no
211- /// anomaly; a rival write forced *between* the two statements (a `sleep`
212- /// wedged into the batch) aborted the whole cascade with a write conflict,
213- /// wrote nothing, and left the rival's value standing.
214- ///
215- /// Streaks begin at this deploy: nothing reconstructs history from the
216- /// stint log, so every account starts with no streak columns and its first
217- /// finish sets a run of 1.
218- pub async fn finish(user: &UserId, db: &Database) -> Result<PomodoroSession, AppError> {
219- let done = Timestamp::now();
220- let (mut result, mut errors) = transaction_with_retry(
221- db,
222- &format!(
223- "BEGIN TRANSACTION;
224- LET $before = (DELETE $open RETURN BEFORE);
225- IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }};
226- LET $end = math::max([$before[0].started_at, $done]);
227- LET $ms = $end - $before[0].started_at;
228- LET $bucket = (UPDATE $usr SET
229- {POMODORO_COUNTED_TODAY_FIELD} =
230- IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day
231- THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END,
232- {POMODORO_COUNTED_DAY_FIELD} = $day
233- RETURN AFTER);
234- LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS})
235- AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0)
236- < {MAX_COUNTED_POMODORO_PER_DAY});
237- IF $counted {{
238- UPDATE $usr SET
239- {POMODORO_FINISHED_TOTAL_FIELD} =
240- ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1,
241- {POMODORO_FOCUS_MS_TOTAL_FIELD} =
242- ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms,
243- {POMODORO_COUNTED_TODAY_FIELD} =
244- ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1;
245- LET $streak = (UPDATE $usr SET
246- {STUDY_STREAK_CURRENT_FIELD} =
247- IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day
248- THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0)
249- ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1)
250- THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1)
251- ELSE 1 END,
252- {STUDY_STREAK_LAST_DAY_FIELD} = $day
253- RETURN AFTER);
254- UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([
255- ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
256- ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)])
257- }};
258- CREATE $closed CONTENT {{
259- user: $before[0].user,
260- started_at: $before[0].started_at,
261- finished_at: $end,
262- counted: $counted,
263- }};
264- COMMIT TRANSACTION;"
265- ),
266- &[
267- (
268- "open".into(),
269- PomodoroSessionId::open_for(user).record().into_value(),
270- ),
271- ("usr".into(), user.record().into_value()),
272- (
273- "closed".into(),
274- PomodoroSessionId::generate().record().into_value(),
275- ),
276- ("done".into(), done.into_value()),
277- ("day".into(), done.day_number().into_value()),
278- ],
279- &["no_pomodoro_running"],
280- )
281- .await?;
282- // An aborted transaction errors *every* slot, most with a generic
283- // "not executed" — only the THROW's own slot names the reason, so scan
284- // them all for the marker instead of trusting the first.
285- if errors
286- .values()
287- .any(|error| error.to_string().contains("no_pomodoro_running"))
288- {
289- return Err(AppError::Conflict("no pomodoro session running"));
290- }
291- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
292- return Err(error.into());
293- }
294- // The `CREATE` is deliberately kept the last statement before `COMMIT`
295- // (the counter `UPDATE` sits ahead of it — same transaction, so the
296- // order is free), which is what lets its slot follow the statement
297- // count instead of a hand-kept number: `num_statements` counts `BEGIN`
298- // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a
299- // hand-kept slot caused.
300- let slot = result.num_statements().saturating_sub(2);
301- let saved: Option<PomodoroSession> = result
302- .take::<Vec<PomodoroSession>>(slot)?
303- .into_iter()
304- .next();
305- let saved =
306- saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?;
307- // 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
309- // counter move re-runs this and heals it.
310- if let Err(err) = badge::sync(user, db).await {
311- tracing::warn!("failed to sync badges for {}: {err}", user.key());
312- }
313- Ok(saved)
314- }
315-
316- /// Every session of `user`, newest first — the running one (if any)
317- /// included. Ordered by `started_at`, never by id alone: the open entry's
318- /// `open_` key doesn't sort with the ULIDs, so id order would misplace it.
319- /// The `id` tie-break behind it only ever separates two *finished* stints
320- /// sharing a `started_at` — there is one running row per user, so it can
321- /// never tie with itself.
322- pub async fn list_for_user(
323- user: &UserId,
324- db: &Database,
325- ) -> Result<Vec<PomodoroSession>, AppError> {
326- let mut result = db
327- .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC")
328- .bind(("usr", user.record()))
329- .await?
330- .check()?;
331- Ok(result.take::<Vec<PomodoroSession>>(0)?)
332- }
333-}
334-
335-#[cfg(test)]
336-mod tests {
337- use ulid::Ulid;
338-
339- use super::*;
340- use crate::database;
341-
342- /// A real `user` row: the counters land with `UPDATE`, which only ever
343- /// touches a record that exists, so a fabricated id would silently store
344- /// nothing. The tests above need no row — they read only the stint log.
345- async fn a_user(db: &Database) -> UserId {
346- let user = UserId::from_key(&Ulid::new().to_string());
347- db.query("CREATE $usr SET username = $name, password_hash = 'x'")
348- .bind(("usr", user.record()))
349- .bind(("name", user.key().to_string()))
350- .await
351- .unwrap()
352- .check()
353- .unwrap();
354- user
355- }
356-
357- /// `(finished_total, focus_ms_total)` re-read from the store — never off
358- /// what `finish` returned, which proves nothing about what was written.
359- async fn counters(user: &UserId, db: &Database) -> (i64, i64) {
360- let mut result = db
361- .query(format!(
362- "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0),
363- ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr"
364- ))
365- .bind(("usr", user.record()))
366- .await
367- .unwrap()
368- .check()
369- .unwrap();
370- let rows: Vec<Vec<i64>> = result.take(0).unwrap();
371- let row = rows.into_iter().next().expect("the user row");
372- (row[0], row[1])
373- }
374-
375- /// `(current, longest, last_day)` re-read from the store.
376- async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) {
377- let mut result = db
378- .query(format!(
379- "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0),
380- ({STUDY_STREAK_LONGEST_FIELD} ?? 0),
381- ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr"
382- ))
383- .bind(("usr", user.record()))
384- .await
385- .unwrap()
386- .check()
387- .unwrap();
388- let rows: Vec<Vec<i64>> = result.take(0).unwrap();
389- let row = rows.into_iter().next().expect("the user row");
390- (row[0], row[1], row[2])
391- }
392-
393- /// Age *both* day buckets by `days`, so the next finish lands that many
394- /// days later on the calendar — the streak's and the day quota's, since
395- /// they are the same calendar and a test that moved one would be asserting
396- /// against a day the other has never heard of. The day is injected into the
397- /// stored state rather than into the clock, which keeps `Timestamp::now`
398- /// the sole clock read and the test free of sleeping.
399- ///
400- /// Known flake, left as-is: every caller assumes the UTC day does not turn
401- /// over mid-test — a crossing between two stints shifts the real day under
402- /// the injected one and reddens the run. That is one ~ms-wide window per
403- /// day (~5e-6 per run), and the alternative is a clock seam in production
404- /// code to serve a test. Re-run before believing a failure that only ever
405- /// happens near midnight UTC.
406- async fn age_by_days(user: &UserId, db: &Database, days: i64) {
407- db.query(format!(
408- "UPDATE $usr SET
409- {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days,
410- {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days"
411- ))
412- .bind(("usr", user.record()))
413- .bind(("days", days))
414- .await
415- .unwrap()
416- .check()
417- .unwrap();
418- }
419-
420- /// Open a stint that has already been running for `ms` — the stamp the
421- /// close measures against, injected instead of slept through.
422- ///
423- /// One `UPSERT`, not `start` followed by a backdate: the concurrent test
424- /// races four of these onto the same open row, and a separate backdate can
425- /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a
426- /// zero-length stint and reddening the run for no defect. Same statement
427- /// `start` runs, one clock read earlier.
428- async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> {
429- db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }")
430- .bind(("open", PomodoroSessionId::open_for(user).record()))
431- .bind(("usr", user.record()))
432- .bind(("at", Timestamp::now().as_millis() - ms))
433- .await?
434- .check()?;
435- Ok(())
436- }
437-
438- /// Start and close one stint that counts: exactly the minimum on the clock,
439- /// so every streak assertion below is about the day and not the duration.
440- async fn one_stint(user: &UserId, db: &Database) {
441- start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap();
442- PomodoroSession::finish(user, db).await.unwrap();
443- }
444-
445- #[tokio::test]
446- async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() {
447- let db = database::init_mem().await.unwrap();
448- let user = a_user(&db).await;
449- // The stale-data case: a row that predates all three columns reads as
450- // no streak at all, and its first finish opens a run of one.
451- assert_eq!(streak(&user, &db).await, (0, 0, -1));
452-
453- one_stint(&user, &db).await;
454- let today = Timestamp::now().day_number();
455- assert_eq!(streak(&user, &db).await, (1, 1, today));
456-
457- // A second stint the same day is not a second day.
458- one_stint(&user, &db).await;
459- assert_eq!(streak(&user, &db).await, (1, 1, today));
460-
461- // Days N+1 and N+2.
462- for day in 2..=3 {
463- age_by_days(&user, &db, 1).await;
464- one_stint(&user, &db).await;
465- assert_eq!(streak(&user, &db).await, (day, day, today));
466- }
467- }
468-
469- #[tokio::test]
470- async fn a_gap_resets_the_run_but_never_the_high_water_mark() {
471- let db = database::init_mem().await.unwrap();
472- let user = a_user(&db).await;
473-
474- one_stint(&user, &db).await;
475- age_by_days(&user, &db, 1).await;
476- one_stint(&user, &db).await;
477- assert_eq!(streak(&user, &db).await.0, 2);
478-
479- // Skip a day: the run restarts at one, the longest stays where it got.
480- age_by_days(&user, &db, 2).await;
481- one_stint(&user, &db).await;
482- let (current, longest, _) = streak(&user, &db).await;
483- assert_eq!((current, longest), (1, 2));
484-
485- // A backwards day (a clock stepped back over a boundary) is a gap too,
486- // and still cannot lower the mark.
487- age_by_days(&user, &db, -5).await;
488- one_stint(&user, &db).await;
489- assert_eq!(
490- streak(&user, &db).await,
491- (1, 2, Timestamp::now().day_number())
492- );
493- }
494-
495- /// The transaction boundary itself, on a real server: the streak pair and
496- /// the counters must commit with the stint or not at all, under real
497- /// contention on one user row.
498- ///
499- /// Multi-threaded and off the embedded engine for the reason
500- /// [`crate::db::cap`] spells out: the in-memory engine does not
501- /// conflict-check two concurrent writes to one record, so it would answer
502- /// `Ok` to a write it dropped and *forge* the integrity failure this test
503- /// exists to catch.
504- ///
505- /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT`
506- /// pair from the batch turns all 20 rounds red. A `THROW` then errors only
507- /// its own statement, so the losers of the open-row race run the rest of
508- /// the cascade anyway — they bump the counters for a stint they never
509- /// closed and `CREATE` a session row out of an empty `$before`, which comes
510- /// back as `500 … Expected record, got none` (the `errors` assertion below
511- /// fires first; `finished_total` running ahead of the `Ok` finishes is the
512- /// same wound one statement later). What it does *not* pin is the
513- /// streak arithmetic under concurrency: same-day finishes all compute the
514- /// same value, so that stays green either way — it is
515- /// `max(longest, current)` that makes that robust, not the isolation.
516- ///
517- /// The shape of the contention, measured rather than assumed: four racers
518- /// per round is four `start`s collapsing onto *one* open row (the id is
519- /// deterministic per user), so typically exactly one `finish` commits and
520- /// three lose the `DELETE` and abort their whole cascade — 20 finishes and
521- /// 60 conflicts over 20 rounds, measured. That is the contention: the
522- /// losers' cascades are live against the same user row, which is precisely
523- /// what must leave nothing behind. Two commits in one round are possible
524- /// (a racer scheduled entirely after another's finish frees the slot) and
525- /// the assertions allow it — the day count is per round, not per stint.
526- #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
527- #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"]
528- async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() {
529- let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await;
530- let user = a_user(&db).await;
531- let (mut finished, mut conflicts, mut errors) = (0, 0, 0);
532- let mut last_error = String::new();
533- for round in 1..=20 {
534- let racers: Vec<_> = (0..4)
535- .map(|_| {
536- let (user, db) = (user.clone(), db.clone());
537- tokio::spawn(async move {
538- // Aged past the minimum, so whichever racer wins the
539- // open row closes a stint that *counts* — a fresh
540- // `start` here would hand the winner a zero-length
541- // stint, which now moves nothing and would leave this
542- // test asserting against an untouched counter.
543- start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?;
544- PomodoroSession::finish(&user, &db).await
545- })
546- })
547- .collect();
548- let mut won = 0;
549- for racer in racers {
550- match racer.await.unwrap() {
551- Ok(_) => won += 1,
552- // Losing the open row is the correct answer for a racer
553- // whose stint someone else closed; only `Db` is a defect.
554- Err(AppError::Conflict(_)) => conflicts += 1,
555- Err(err) => {
556- errors += 1;
557- last_error = format!("{err:?}");
558- }
559- }
560- }
561- finished += won;
562- // One day per round, however many stints landed in it, and the
563- // mark never lags the run in progress.
564- let (current, longest, _) = streak(&user, &db).await;
565- assert_eq!(
566- (current, longest),
567- (round, round),
568- "round {round} counted {won} finishes as {current} days"
569- );
570- age_by_days(&user, &db, 1).await;
571- }
572- // The atomicity claim: the counter counts exactly the stints that were
573- // closed, never a loser's aborted round.
574- let (counted, _) = counters(&user, &db).await;
575- eprintln!(
576- "PomodoroSession::finish raced: {finished} finishes over 20 days, \
577- {conflicts} rivals refused, {errors} 500s"
578- );
579- assert_eq!(
580- errors, 0,
581- "a raced finish must conflict, not 500: {last_error}"
582- );
583- assert_eq!(
584- counted, finished,
585- "the counter counted {counted} stints for {finished} finishes"
586- );
587- assert!(
588- conflicts > 0,
589- "every racer won its own round, so no cascade was ever aborted mid-flight \
590- and this run proves nothing about the transaction boundary"
591- );
592- }
593-
594- #[tokio::test]
595- async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() {
596- let db = database::init_mem().await.unwrap();
597- let user = a_user(&db).await;
598- assert_eq!(counters(&user, &db).await, (0, 0));
599-
600- // An open stint is not a finished one: neither counter moves until it
601- // closes.
602- start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
603- .await
604- .unwrap();
605- assert_eq!(counters(&user, &db).await, (0, 0));
606-
607- let mut focus_ms = 0;
608- for _ in 0..2 {
609- let closed = PomodoroSession::finish(&user, &db).await.unwrap();
610- focus_ms +=
611- closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis();
612- start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
613- .await
614- .unwrap();
615- }
616- // Three starts, two finishes — the third is still running.
617- assert_eq!(counters(&user, &db).await, (2, focus_ms));
618- }
619-
620- #[tokio::test]
621- async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() {
622- let db = database::init_mem().await.unwrap();
623- let user = a_user(&db).await;
624-
625- PomodoroSession::start(&user, &db).await.unwrap();
626- db.query("UPDATE $open SET started_at = $future")
627- .bind(("open", PomodoroSessionId::open_for(&user).record()))
628- .bind(("future", Timestamp::now().as_millis() + 3_600_000))
629- .await
630- .unwrap()
631- .check()
632- .unwrap();
633-
634- // The clamp holds: zero milliseconds, never a negative — and a stint
635- // measuring zero is below the minimum, so it moves neither counter.
636- let closed = PomodoroSession::finish(&user, &db).await.unwrap();
637- assert_eq!(closed.get_counted(), Some(false));
638- assert_eq!(counters(&user, &db).await, (0, 0));
639- }
640-
641- /// The minimum, from both sides. A round-trip is not a study session, and
642- /// the boundary is inclusive (`>=`) — a stint of exactly the minimum
643- /// counts, which is the side these assertions pin.
644- ///
645- /// The near miss is a whole minute short, not one millisecond: `finish`
646- /// reads its own clock *after* the stint is opened, so a stint aged to
647- /// exactly one millisecond under the bar crosses it by the time the close
648- /// measures it (measured — that assertion failed on the first run). A
649- /// millisecond-exact probe would need a clock seam in production code, and
650- /// what matters here is the four orders of magnitude between a scripted
651- /// pair and a study session, not the last millisecond.
652- #[tokio::test]
653- async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() {
654- let db = database::init_mem().await.unwrap();
655- let user = a_user(&db).await;
656-
657- start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000)
658- .await
659- .unwrap();
660- let short = PomodoroSession::finish(&user, &db).await.unwrap();
661- assert_eq!(short.get_counted(), Some(false));
662- assert_eq!(counters(&user, &db).await, (0, 0));
663- // Not a study day either — and no streak column was even opened.
664- assert_eq!(streak(&user, &db).await, (0, 0, -1));
665- // But it happened, and the log says so.
666- let log = PomodoroSession::list_for_user(&user, &db).await.unwrap();
667- assert_eq!(log.len(), 1);
668- assert_eq!(log[0].get_finished_at(), short.get_finished_at());
669-
670- start_aged(&user, &db, MIN_COUNTED_POMODORO_MS)
671- .await
672- .unwrap();
673- let counted = PomodoroSession::finish(&user, &db).await.unwrap();
674- assert_eq!(counted.get_counted(), Some(true));
675- let (finished, focus_ms) = counters(&user, &db).await;
676- // The counter took the *same* duration the row stores, not a second
677- // reading of the clock.
678- assert_eq!(
679- (finished, focus_ms),
680- (
681- 1,
682- counted.get_finished_at().unwrap().as_millis()
683- - counted.get_started_at().as_millis()
684- )
685- );
686- assert_eq!(streak(&user, &db).await.0, 1);
687- assert_eq!(
688- PomodoroSession::list_for_user(&user, &db)
689- .await
690- .unwrap()
691- .len(),
692- 2
693- );
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 = database::init_mem().await.unwrap();
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 = PomodoroSession::finish(&user, &db).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- PomodoroSession::list_for_user(&user, &db)
721- .await
722- .unwrap()
723- .len() as i64,
724- MAX_COUNTED_POMODORO_PER_DAY + 3
725- );
726- // The quota is a day's, not a lifetime's.
727- age_by_days(&user, &db, 1).await;
728- one_stint(&user, &db).await;
729- assert_eq!(
730- counters(&user, &db).await.0,
731- MAX_COUNTED_POMODORO_PER_DAY + 1
732- );
733- }
734-
735- /// The farm, run: `start`/`finish` in a loop is two requests a round with
736- /// no second person in it, which used to move `pomodoro_finished_total` one
737- /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`,
738- /// and a badge is never taken back.
739- #[tokio::test]
740- async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() {
741- let db = database::init_mem().await.unwrap();
742- let user = a_user(&db).await;
743-
744- for _ in 0..200 {
745- PomodoroSession::start(&user, &db).await.unwrap();
746- PomodoroSession::finish(&user, &db).await.unwrap();
747- }
748- assert_eq!(counters(&user, &db).await, (0, 0));
749- assert_eq!(streak(&user, &db).await, (0, 0, -1));
750- // Every one of them is still the student's own history.
751- assert_eq!(
752- PomodoroSession::list_for_user(&user, &db)
753- .await
754- .unwrap()
755- .len(),
756- 200
757- );
758- assert!(
759- badge::BadgeAward::list_for(&user, &db)
760- .await
761- .unwrap()
762- .is_empty(),
763- "the farm minted a permanent badge"
764- );
765-
766- // And paying the minimum for each one only buys the day's quota.
767- for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) {
768- one_stint(&user, &db).await;
769- }
770- assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY);
771- }
772-
773- #[tokio::test]
774- async fn restart_replaces_the_open_session_and_finish_closes_it() {
775- let db = database::init_mem().await.unwrap();
776- // A `record<user>` column checks the table of the id, not row
777- // existence — a fabricated id keeps this test free of user ceremony.
778- let user = UserId::from_key(&Ulid::new().to_string());
779-
780- // Nothing running yet — finishing conflicts.
781- assert!(matches!(
782- PomodoroSession::finish(&user, &db).await,
783- Err(AppError::Conflict(_))
784- ));
785-
786- let first = PomodoroSession::start(&user, &db).await.unwrap();
787- assert!(first.get_finished_at().is_none());
788- assert_eq!(first.get_id().key(), format!("open_{}", user.key()));
789-
790- // A restart replaces the dangling session: still one row, fresh clock.
791- let second = PomodoroSession::start(&user, &db).await.unwrap();
792- assert!(second.get_started_at() >= first.get_started_at());
793- let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap();
794- assert_eq!(sessions.len(), 1);
795-
796- let closed = PomodoroSession::finish(&user, &db).await.unwrap();
797- assert!(closed.get_finished_at().unwrap() >= closed.get_started_at());
798-
799- // The open slot is free again; a stray second finish conflicts.
800- assert!(matches!(
801- PomodoroSession::finish(&user, &db).await,
802- Err(AppError::Conflict(_))
803- ));
804- PomodoroSession::start(&user, &db).await.unwrap();
805- let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap();
806- assert_eq!(sessions.len(), 2);
807- }
808-
809- #[tokio::test]
810- async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() {
811- let db = database::init_mem().await.unwrap();
812- let user = UserId::from_key(&Ulid::new().to_string());
813-
814- PomodoroSession::start(&user, &db).await.unwrap();
815- // Stand in for the NTP step: push the running stint's start an hour
816- // ahead, so the server clock `finish` reads is *behind* it.
817- db.query("UPDATE $open SET started_at = $future")
818- .bind(("open", PomodoroSessionId::open_for(&user).record()))
819- .bind(("future", Timestamp::now().as_millis() + 3_600_000))
820- .await
821- .unwrap()
822- .check()
823- .unwrap();
824-
825- let closed = PomodoroSession::finish(&user, &db).await.unwrap();
826- let started = closed.get_started_at().as_millis();
827- assert_eq!(closed.get_finished_at().unwrap().as_millis(), started);
828-
829- // And the stat that sums these stays non-negative.
830- let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db)
831- .await
832- .unwrap();
833- assert_eq!(stats.get_pomodoro_sessions(), 1);
834- assert_eq!(stats.get_pomodoro_focus_ms(), 0);
835- }
836 }85 }
src/domain/profile.rsmodified+1 -1
@@ -241,7 +241,7 @@ impl ProfileStats {
241 // Floored at zero: a stint stamped by a wall clock that stepped241 // Floored at zero: a stint stamped by a wall clock that stepped
242 // backwards mid-session sums as negative time, and "you focused for242 // backwards mid-session sums as negative time, and "you focused for
243 // minus five seconds" is never the truthful answer. New stints243 // minus five seconds" is never the truthful answer. New stints
244- // cannot go inverted (see [`PomodoroSession::finish`]); rows written244+ // cannot go inverted (see [`crate::db::pomodoro::finish`]); rows written
245 // before that guard still can, and this is what covers them.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)),246 pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)),
247 courses,247 courses,
src/domain/registration.rsmodified+3 -3
@@ -3,7 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
3 use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};3 use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE};
4 use crate::database::Database;4 use crate::database::Database;
5 use crate::db::cap;5 use crate::db::cap;
6-use crate::domain::event::{Event, EventId};6+use crate::domain::event::EventId;
7 use crate::domain::role::Role;7 use crate::domain::role::Role;
8 use crate::domain::user::UserId;8 use crate::domain::user::UserId;
9 use crate::error::AppError;9 use crate::error::AppError;
@@ -94,7 +94,7 @@ impl Registration {
94 }94 }
95 // Read for its refusals only — the audience kind and the closing time.95 // Read for its refusals only — the audience kind and the closing time.
96 // The seat count itself is re-read by the claim.96 // The seat count itself is re-read by the claim.
97- Event::read(event, db)97+ crate::db::event::read(db, event)
98 .await?98 .await?
99 .ok_or(AppError::NotFound)?99 .ok_or(AppError::NotFound)?
100 .registration_capacity()?;100 .registration_capacity()?;
@@ -131,7 +131,7 @@ impl Registration {
131 // the holder fell to parent while this ran — the conditional writes131 // the holder fell to parent while this ran — the conditional writes
132 // match nothing (or throw) either way, and only this path pays for132 // match nothing (or throw) either way, and only this path pays for
133 // the reads that tell them apart.133 // the reads that tell them apart.
134- cap::Claimed::Full => match Event::read(event, db).await? {134+ cap::Claimed::Full => match crate::db::event::read(db, event).await? {
135 None => Err(AppError::NotFound),135 None => Err(AppError::NotFound),
136 Some(_) => match crate::db::user::read(db, user).await? {136 Some(_) => match crate::db::user::read(db, user).await? {
137 Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(137 Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden(
src/domain/work_entry.rsmodified+4 -178
@@ -1,10 +1,7 @@
1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};1 use surrealdb::types::{RecordId, RecordIdKey, SurrealValue};
2 2
3 use crate::constant::WORK_ENTRY_TABLE;3 use crate::constant::WORK_ENTRY_TABLE;
4-use crate::database::{Database, transaction_with_retry};
5-use crate::db::field_update::FieldUpdate;
6 use crate::domain::monotonic_id::next_ulid;4 use crate::domain::monotonic_id::next_ulid;
7-use crate::db::page::PagedList;
8 use crate::domain::timestamp::Timestamp;5 use crate::domain::timestamp::Timestamp;
9 use crate::domain::user::UserId;6 use crate::domain::user::UserId;
10 use crate::error::{AppError, ValidationError};7 use crate::error::{AppError, ValidationError};
@@ -65,10 +62,10 @@ impl WorkEntryId {
65 /// through an explicit endpoint instead).62 /// through an explicit endpoint instead).
66 #[derive(Debug, Clone, SurrealValue)]63 #[derive(Debug, Clone, SurrealValue)]
67 pub struct WorkEntry {64 pub struct WorkEntry {
68- id: WorkEntryId,65+ pub(crate) id: WorkEntryId,
69- user: UserId,66+ pub(crate) user: UserId,
70- check_in: Timestamp,67+ pub(crate) check_in: Timestamp,
71- check_out: Option<Timestamp>,68+ pub(crate) check_out: Option<Timestamp>,
72 }69 }
73 70
74 impl WorkEntry {71 impl WorkEntry {
@@ -91,175 +88,4 @@ impl WorkEntry {
91 pub fn is_open(&self) -> bool {88 pub fn is_open(&self) -> bool {
92 self.check_out.is_none()89 self.check_out.is_none()
93 }90 }
94-
95- /// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE`
96- /// on the deterministic open id makes this atomic: if an open entry
97- /// already exists the insert is skipped (empty result) and the caller gets
98- /// a conflict — two racing check-ins can never create two open rows or
99- /// reset a running clock.
100- pub async fn check_in(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> {
101- let entry = WorkEntry {
102- id: WorkEntryId::open_for(user),
103- user: user.clone(),
104- check_in: Timestamp::now(),
105- check_out: None,
106- };
107- let mut result = db
108- .query("INSERT IGNORE INTO work_entry $entry")
109- .bind(("entry", entry))
110- .await?
111- .check()?;
112- result
113- .take::<Vec<WorkEntry>>(0)?
114- .into_iter()
115- .next()
116- .ok_or(AppError::Conflict("already checked in — check out first"))
117- }
118-
119- /// Close `user`'s open stint: atomically take the open row and re-file it
120- /// under a ULID id, freeing the open slot for the next check-in. Take and
121- /// re-file share one transaction — a failed re-file rolls the take back,
122- /// so a stint can never vanish half-closed. Of two racing check-outs
123- /// exactly one receives the row (the other gets the conflict).
124- ///
125- /// A lost round is re-sent rather than reported (`transaction_with_retry`):
126- /// the abort wrote nothing, so the whole cascade is safe to repeat, and the
127- /// `CREATE` cannot answer "already exists" on the way back — the table
128- /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
129- /// Only the guard's own `THROW` is a decision, and it stays a 409.
130- pub async fn check_out(user: &UserId, db: &Database) -> Result<WorkEntry, AppError> {
131- let (mut result, mut errors) = transaction_with_retry(
132- db,
133- "BEGIN TRANSACTION;
134- LET $before = (DELETE $open RETURN BEFORE);
135- IF array::len($before) = 0 { THROW 'not_checked_in' };
136- CREATE $closed CONTENT {
137- user: $before[0].user,
138- check_in: $before[0].check_in,
139- check_out: $out,
140- };
141- COMMIT TRANSACTION;",
142- &[
143- (
144- "open".into(),
145- WorkEntryId::open_for(user).record().into_value(),
146- ),
147- (
148- "closed".into(),
149- WorkEntryId::generate().record().into_value(),
150- ),
151- ("out".into(), Timestamp::now().into_value()),
152- ],
153- &["not_checked_in"],
154- )
155- .await?;
156- // An aborted transaction errors *every* slot, most with a generic
157- // "not executed" — only the THROW's own slot names the reason, so scan
158- // them all for the marker instead of trusting the first.
159- if errors
160- .values()
161- .any(|error| error.to_string().contains("not_checked_in"))
162- {
163- return Err(AppError::Conflict("not checked in"));
164- }
165- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
166- return Err(error.into());
167- }
168- // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3.
169- let saved: Option<WorkEntry> = result.take::<Vec<WorkEntry>>(3)?.into_iter().next();
170- saved.ok_or_else(|| AppError::Internal("failed to close work entry".into()))
171- }
172-
173- pub async fn read(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> {
174- Ok(db.select(id.record()).await?)
175- }
176-
177- /// Every stint of `user`, newest first — the open one (if any) included.
178- /// Ordered by `check_in`, never by id alone: the open entry's `open_` key
179- /// doesn't sort with the ULIDs, so id order would misplace it. The `id`
180- /// tie-break behind it only ever separates two *closed* stints sharing a
181- /// `check_in` — there is one open row per user, so it can never tie with
182- /// itself — and that is what keeps offset paging from skipping a row.
183- pub async fn list_for_user(
184- user: &UserId,
185- limit: Option<i64>,
186- offset: i64,
187- db: &Database,
188- ) -> Result<(Vec<WorkEntry>, i64), AppError> {
189- PagedList::new(
190- "work_entry WHERE user = $usr",
191- "ORDER BY check_in DESC, id DESC",
192- )
193- .bind("usr", user.record())
194- .run(limit, offset, db)
195- .await
196- }
197-
198- /// Persist corrected instants (manager fix-ups on closed entries; the web
199- /// layer validates ordering and rejects open entries).
200- /// `None` = the correction left that instant out, so it is not written at
201- /// all — the stint's `user` and `check_in`/`check_out` stamps are never
202- /// replayed from a struct the handler read before its validation awaits.
203- /// `check_out` is never cleared here: an open stint is refused upstream, so
204- /// "absent" and "null" both mean keep.
205- pub async fn update(
206- self,
207- check_in: Option<Timestamp>,
208- check_out: Option<Timestamp>,
209- db: &Database,
210- ) -> Result<WorkEntry, AppError> {
211- FieldUpdate::new(self.id.record())
212- .set("check_in", check_in)
213- .set("check_out", check_out)
214- // Same race closer as the schedule ranges, with this table's own
215- // field names and message: a correction of one instant is only
216- // written while it still orders against the other as *stored*.
217- .ordered("check_in", "check_out", out_before_in_error())
218- .run::<WorkEntry>(db)
219- .await
220- }
221-
222- pub async fn remove(id: &WorkEntryId, db: &Database) -> Result<Option<WorkEntry>, AppError> {
223- Ok(db.delete(id.record()).await?)
224- }
225-}
226-
227-#[cfg(test)]
228-mod tests {
229- use ulid::Ulid;
230-
231- use super::*;
232- use crate::database;
233-
234- #[tokio::test]
235- async fn check_in_is_exclusive_until_check_out() {
236- let db = database::init_mem().await.unwrap();
237- // A `record<user>` column checks the table of the id, not row
238- // existence — a fabricated id keeps this test free of user ceremony.
239- let user = UserId::from_key(&Ulid::new().to_string());
240-
241- let open = WorkEntry::check_in(&user, &db).await.unwrap();
242- assert!(open.is_open());
243- assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
244-
245- // Second check-in must not create a second stint or reset the clock.
246- let dup = WorkEntry::check_in(&user, &db).await;
247- assert!(matches!(dup, Err(AppError::Conflict(_))));
248- let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap();
249- assert_eq!(entries.len(), 1);
250- assert_eq!(entries[0].get_check_in(), open.get_check_in());
251-
252- let closed = WorkEntry::check_out(&user, &db).await.unwrap();
253- assert!(!closed.is_open());
254- assert!(closed.get_check_out().unwrap() >= closed.get_check_in());
255-
256- // The open slot is free again; a stray second check-out conflicts.
257- assert!(matches!(
258- WorkEntry::check_out(&user, &db).await,
259- Err(AppError::Conflict(_))
260- ));
261- WorkEntry::check_in(&user, &db).await.unwrap();
262- let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap();
263- assert_eq!(entries.len(), 2);
264- }
265 }91 }
src/service/event.rsadded+82 -0
@@ -0,0 +1,82 @@
1+//! Event surfacing: the calendar's create/read/update/delete and the
2+//! audience's live membership resolution. The queries live in
3+//! [`crate::db::event`]; there is no workflow of this domain's own — every
4+//! write is a single atomic statement or transaction, and the freeze rule
5+//! the signup flow leans on is the pure
6+//! [`crate::domain::event::Event::registration_capacity`].
7+
8+use crate::database::Database;
9+use crate::db::event;
10+use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle};
11+use crate::domain::timestamp::Timestamp;
12+use crate::domain::user::{User, UserId};
13+use crate::error::AppError;
14+
15+pub async fn create(
16+ db: &Database,
17+ creator: &UserId,
18+ title: EventTitle,
19+ description: EventDescription,
20+ audience: EventAudience,
21+ starts_at: Option<Timestamp>,
22+ ends_at: Option<Timestamp>,
23+) -> Result<Event, AppError> {
24+ event::create(
25+ db,
26+ creator,
27+ title,
28+ description,
29+ audience,
30+ starts_at,
31+ ends_at,
32+ )
33+ .await
34+}
35+
36+pub async fn read(db: &Database, id: &EventId) -> Result<Option<Event>, AppError> {
37+ event::read(db, id).await
38+}
39+
40+/// Every event, newest first.
41+pub async fn list_all(db: &Database) -> Result<Vec<Event>, AppError> {
42+ event::list_all(db).await
43+}
44+
45+/// Only what the request carried is written: an omitted field (`None`) is
46+/// not stored at all. The schedule columns take the set-or-clear spelling.
47+pub async fn update(
48+ db: &Database,
49+ event: Event,
50+ title: Option<EventTitle>,
51+ description: Option<EventDescription>,
52+ audience: Option<EventAudience>,
53+ starts_at: Option<Option<Timestamp>>,
54+ ends_at: Option<Option<Timestamp>>,
55+) -> Result<Event, AppError> {
56+ event::update(db, event, title, description, audience, starts_at, ends_at).await
57+}
58+
59+/// Delete the event and cascade its attendance and signup rows.
60+pub async fn delete(db: &Database, event: Event) -> Result<Event, AppError> {
61+ event::delete(db, event).await
62+}
63+
64+/// Is `user` in the event's audience roster right now — the point check
65+/// behind marking.
66+pub async fn includes(
67+ db: &Database,
68+ audience: &EventAudience,
69+ event: &EventId,
70+ user: &User,
71+) -> Result<bool, AppError> {
72+ event::includes(db, audience, event, user).await
73+}
74+
75+/// The event's full expected-attendee roster, resolved live.
76+pub async fn members(
77+ db: &Database,
78+ audience: &EventAudience,
79+ event: &EventId,
80+) -> Result<Vec<UserId>, AppError> {
81+ event::members(db, audience, event).await
82+}
src/service/mod.rsmodified+3 -0
@@ -7,12 +7,15 @@ pub mod class_blueprint;
7 pub mod course;7 pub mod course;
8 pub mod course_session;8 pub mod course_session;
9 pub mod enrollment;9 pub mod enrollment;
10+pub mod event;
10 pub mod exam;11 pub mod exam;
11 pub mod exam_attempt;12 pub mod exam_attempt;
12 pub mod exam_question;13 pub mod exam_question;
13 pub mod meal_booking;14 pub mod meal_booking;
14 pub mod note;15 pub mod note;
15 pub mod payment_ledger;16 pub mod payment_ledger;
17+pub mod pomodoro;
16 pub mod session;18 pub mod session;
17 pub mod settings;19 pub mod settings;
18 pub mod user;20 pub mod user;
21+pub mod work_entry;
src/service/pomodoro.rsadded+25 -0
@@ -0,0 +1,25 @@
1+//! Pomodoro surfacing: the start/finish pair and the log the timer drives.
2+//! The queries live in [`crate::db::pomodoro`]; the counting verdict, the
3+//! lifetime counters, and the study streak are decided inside `finish`'s
4+//! single transaction there — there is no workflow of this domain's own.
5+
6+use crate::database::Database;
7+use crate::db::pomodoro;
8+use crate::domain::pomodoro::PomodoroSession;
9+use crate::domain::user::UserId;
10+use crate::error::AppError;
11+
12+pub async fn start(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
13+ pomodoro::start(db, user).await
14+}
15+
16+/// Close the running session (`409` when none runs); the returned row
17+/// carries the `counted` verdict.
18+pub async fn finish(db: &Database, user: &UserId) -> Result<PomodoroSession, AppError> {
19+ pomodoro::finish(db, user).await
20+}
21+
22+/// Every session of `user`, newest first — the running one included.
23+pub async fn list_for_user(db: &Database, user: &UserId) -> Result<Vec<PomodoroSession>, AppError> {
24+ pomodoro::list_for_user(db, user).await
25+}
src/service/work_entry.rsadded+51 -0
@@ -0,0 +1,51 @@
1+//! Work-log surfacing: the check-in/check-out pair, the staff log, and the
2+//! manager corrections. The queries live in
3+//! [`crate::db::work_entry`] — both transitions are single atomic writes on
4+//! the deterministic open id (`INSERT IGNORE` in, take-and-refile out), so
5+//! this domain has no workflow of its own.
6+
7+use crate::database::Database;
8+use crate::db::work_entry;
9+use crate::domain::timestamp::Timestamp;
10+use crate::domain::user::UserId;
11+use crate::domain::work_entry::WorkEntry;
12+use crate::domain::work_entry::WorkEntryId;
13+use crate::error::AppError;
14+
15+/// Check in (`409` while already checked in).
16+pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
17+ work_entry::check_in(db, user).await
18+}
19+
20+/// Check out (`409` when not checked in).
21+pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
22+ work_entry::check_out(db, user).await
23+}
24+
25+pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
26+ work_entry::read(db, id).await
27+}
28+
29+/// Every stint of `user`, newest first — the open one included.
30+pub async fn list_for_user(
31+ db: &Database,
32+ user: &UserId,
33+ limit: Option<i64>,
34+ offset: i64,
35+) -> Result<(Vec<WorkEntry>, i64), AppError> {
36+ work_entry::list_for_user(db, user, limit, offset).await
37+}
38+
39+/// Persist corrected instants on a closed entry; `None` keeps the field.
40+pub async fn update(
41+ db: &Database,
42+ entry: WorkEntry,
43+ check_in: Option<Timestamp>,
44+ check_out: Option<Timestamp>,
45+) -> Result<WorkEntry, AppError> {
46+ work_entry::update(db, entry, check_in, check_out).await
47+}
48+
49+pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
50+ work_entry::remove(db, id).await
51+}
src/web/boards.rsmodified+6 -6
@@ -35,7 +35,7 @@ use crate::domain::board_stroke::BoardStroke;
35 use crate::domain::class_group::{ClassGroup, ClassGroupId};35 use crate::domain::class_group::{ClassGroup, ClassGroupId};
36 use crate::domain::class_member::ClassMember;36 use crate::domain::class_member::ClassMember;
37 use crate::domain::course::CourseId;37 use crate::domain::course::CourseId;
38-use crate::domain::event::{Event, EventId};38+use crate::domain::event::EventId;
39 use crate::domain::role::Role;39 use crate::domain::role::Role;
40 use crate::domain::user::{User, UserId};40 use crate::domain::user::{User, UserId};
41 use crate::error::{AppError, ErrorResponse, ValidationError};41 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -767,13 +767,13 @@ impl InviteSource {
767 "requires teacher role or higher to invite an event's roster",767 "requires teacher role or higher to invite an event's roster",
768 ));768 ));
769 }769 }
770- let event = Event::read(&EventId::from_key(&event), db).await?.ok_or(770+ let event = crate::service::event::read(db, &EventId::from_key(&event))
771- AppError::Validation(ValidationError::Invalid {771+ .await?
772+ .ok_or(AppError::Validation(ValidationError::Invalid {
772 field: "event",773 field: "event",
773 reason: "no such event",774 reason: "no such event",
774- }),775+ }))?;
775- )?;776+ crate::service::event::members(db, event.get_audience(), event.get_id()).await
776- event.get_audience().members(event.get_id(), db).await
777 }777 }
778 }778 }
779 }779 }
src/web/events.rsmodified+32 -25
@@ -289,14 +289,14 @@ async fn create_event(
289 check_not_past("starts_at", starts_at)?;289 check_not_past("starts_at", starts_at)?;
290 check_not_past("ends_at", ends_at)?;290 check_not_past("ends_at", ends_at)?;
291 check_time_range(starts_at, ends_at)?;291 check_time_range(starts_at, ends_at)?;
292- let event = Event::create(292+ let event = service::event::create(
293+ &st.db,
293 user.get_id(),294 user.get_id(),
294 title,295 title,
295 description,296 description,
296 audience,297 audience,
297 starts_at,298 starts_at,
298 ends_at,299 ends_at,
299- &st.db,
300 )300 )
301 .await?;301 .await?;
302 Ok((StatusCode::CREATED, Json(EventResponse::new(&event))))302 Ok((StatusCode::CREATED, Json(EventResponse::new(&event))))
@@ -329,7 +329,7 @@ async fn list_events(
329 Query(page): Query<PageParams>,329 Query(page): Query<PageParams>,
330 ) -> Result<Json<Page<EventResponse>>, AppError> {330 ) -> Result<Json<Page<EventResponse>>, AppError> {
331 let (limit, offset) = page.resolve()?;331 let (limit, offset) = page.resolve()?;
332- let events = window.apply(Event::list_all(&st.db).await?)?;332+ let events = window.apply(service::event::list_all(&st.db).await?)?;
333 let total = events.len() as i64;333 let total = events.len() as i64;
334 // Paged in the web layer: `WindowParams` filters and re-orders in Rust.334 // Paged in the web layer: `WindowParams` filters and re-orders in Rust.
335 let items = paginate(&events, limit, offset)335 let items = paginate(&events, limit, offset)
@@ -357,7 +357,7 @@ async fn get_event(
357 _user: CurrentUser,357 _user: CurrentUser,
358 Path(id): Path<String>,358 Path(id): Path<String>,
359 ) -> Result<Json<EventResponse>, AppError> {359 ) -> Result<Json<EventResponse>, AppError> {
360- let event = Event::read(&EventId::from_key(&id), &st.db)360+ let event = service::event::read(&st.db, &EventId::from_key(&id))
361 .await?361 .await?
362 .ok_or(AppError::NotFound)?;362 .ok_or(AppError::NotFound)?;
363 Ok(Json(EventResponse::new(&event)))363 Ok(Json(EventResponse::new(&event)))
@@ -398,7 +398,7 @@ async fn update_event(
398 .starts_at398 .starts_at
399 .map(|update| update.map(Timestamp::from_millis));399 .map(|update| update.map(Timestamp::from_millis));
400 let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));400 let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis));
401- let event = Event::read(&EventId::from_key(&id), &st.db)401+ let event = service::event::read(&st.db, &EventId::from_key(&id))
402 .await?402 .await?
403 .ok_or(AppError::NotFound)?;403 .ok_or(AppError::NotFound)?;
404 if !can_manage(&event, &user) {404 if !can_manage(&event, &user) {
@@ -432,16 +432,23 @@ async fn update_event(
432 }432 }
433 // The range CHECK needs both ends: whichever the request omitted comes433 // The range CHECK needs both ends: whichever the request omitted comes
434 // from the stored row. Read for the check only — the omitted side is434 // from the stored row. Read for the check only — the omitted side is
435- // never written back. Pre-flight only: `Event::update` re-makes this check435+ // never written back. Pre-flight only: the UPDATE's own `WHERE` re-makes
436- // in the UPDATE's `WHERE`, so a concurrent move of the omitted end loses.436+ // this check, so a concurrent move of the omitted end loses.
437 check_time_range(437 check_time_range(
438 starts_at.unwrap_or_else(|| event.get_starts_at()),438 starts_at.unwrap_or_else(|| event.get_starts_at()),
439 ends_at.unwrap_or_else(|| event.get_ends_at()),439 ends_at.unwrap_or_else(|| event.get_ends_at()),
440 )?;440 )?;
441 441
442- let updated = event442+ let updated = service::event::update(
443- .update(title, description, audience, starts_at, ends_at, &st.db)443+ &st.db,
444- .await?;444+ event,
445+ title,
446+ description,
447+ audience,
448+ starts_at,
449+ ends_at,
450+ )
451+ .await?;
445 Ok(Json(EventResponse::new(&updated)))452 Ok(Json(EventResponse::new(&updated)))
446 }453 }
447 454
@@ -465,7 +472,7 @@ async fn delete_event(
465 RequireTeacher(user): RequireTeacher,472 RequireTeacher(user): RequireTeacher,
466 Path(id): Path<String>,473 Path(id): Path<String>,
467 ) -> Result<StatusCode, AppError> {474 ) -> Result<StatusCode, AppError> {
468- let event = Event::read(&EventId::from_key(&id), &st.db)475+ let event = service::event::read(&st.db, &EventId::from_key(&id))
469 .await?476 .await?
470 .ok_or(AppError::NotFound)?;477 .ok_or(AppError::NotFound)?;
471 if !can_manage(&event, &user) {478 if !can_manage(&event, &user) {
@@ -473,7 +480,7 @@ async fn delete_event(
473 "only the creator or a manager/admin can delete this event",480 "only the creator or a manager/admin can delete this event",
474 ));481 ));
475 }482 }
476- event.delete(&st.db).await?;483+ service::event::delete(&st.db, event).await?;
477 Ok(StatusCode::NO_CONTENT)484 Ok(StatusCode::NO_CONTENT)
478 }485 }
479 486
@@ -505,7 +512,7 @@ async fn mark(
505 Json(req): Json<MarkAttendance>,512 Json(req): Json<MarkAttendance>,
506 ) -> Result<Json<AttendanceResponse>, AppError> {513 ) -> Result<Json<AttendanceResponse>, AppError> {
507 let event_id = EventId::from_key(&id);514 let event_id = EventId::from_key(&id);
508- let event = Event::read(&event_id, &st.db)515+ let event = service::event::read(&st.db, &event_id)
509 .await?516 .await?
510 .ok_or(AppError::NotFound)?;517 .ok_or(AppError::NotFound)?;
511 518
@@ -526,10 +533,7 @@ async fn mark(
526 533
527 // Only expected attendees can be marked. The marker needn't be in the534 // Only expected attendees can be marked. The marker needn't be in the
528 // audience — a teacher takes roll of a student-targeted event.535 // audience — a teacher takes roll of a student-targeted event.
529- if !event536+ if !service::event::includes(&st.db, event.get_audience(), event.get_id(), &target_user).await?
530- .get_audience()
531- .includes(event.get_id(), &target_user, &st.db)
532- .await?
533 {537 {
534 return Err(AppError::Validation(ValidationError::Invalid {538 return Err(AppError::Validation(ValidationError::Invalid {
535 field: "user_id",539 field: "user_id",
@@ -569,7 +573,7 @@ async fn list_attendance(
569 let (limit, offset) = page.resolve()?;573 let (limit, offset) = page.resolve()?;
570 let event_id = EventId::from_key(&id);574 let event_id = EventId::from_key(&id);
571 // Event must exist — a missing event is a 404, not an empty roster.575 // Event must exist — a missing event is a 404, not an empty roster.
572- Event::read(&event_id, &st.db)576+ service::event::read(&st.db, &event_id)
573 .await?577 .await?
574 .ok_or(AppError::NotFound)?;578 .ok_or(AppError::NotFound)?;
575 let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?;579 let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?;
@@ -661,11 +665,11 @@ async fn roster(
661 ) -> Result<Json<Page<RosterEntry>>, AppError> {665 ) -> Result<Json<Page<RosterEntry>>, AppError> {
662 let (limit, offset) = page.resolve()?;666 let (limit, offset) = page.resolve()?;
663 let event_id = EventId::from_key(&id);667 let event_id = EventId::from_key(&id);
664- let event = Event::read(&event_id, &st.db)668+ let event = service::event::read(&st.db, &event_id)
665 .await?669 .await?
666 .ok_or(AppError::NotFound)?;670 .ok_or(AppError::NotFound)?;
667 671
668- let mut members = event.get_audience().members(event.get_id(), &st.db).await?;672+ let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?;
669 // ULID keys sort by creation instant — a stable order keeps pages coherent.673 // ULID keys sort by creation instant — a stable order keeps pages coherent.
670 members.sort_by(|a, b| a.key().cmp(b.key()));674 members.sort_by(|a, b| a.key().cmp(b.key()));
671 let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?;675 let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?;
@@ -748,7 +752,7 @@ async fn register(
748 Json(req): Json<RegisterUser>,752 Json(req): Json<RegisterUser>,
749 ) -> Result<Json<RegistrationResponse>, AppError> {753 ) -> Result<Json<RegistrationResponse>, AppError> {
750 let event_id = EventId::from_key(&id);754 let event_id = EventId::from_key(&id);
751- let event = Event::read(&event_id, &st.db)755+ let event = service::event::read(&st.db, &event_id)
752 .await?756 .await?
753 .ok_or(AppError::NotFound)?;757 .ok_or(AppError::NotFound)?;
754 // Fast-fail gate; the authoritative re-check runs inside758 // Fast-fail gate; the authoritative re-check runs inside
@@ -822,7 +826,7 @@ async fn unregister(
822 Path((id, target)): Path<(String, String)>,826 Path((id, target)): Path<(String, String)>,
823 ) -> Result<StatusCode, AppError> {827 ) -> Result<StatusCode, AppError> {
824 let event_id = EventId::from_key(&id);828 let event_id = EventId::from_key(&id);
825- let event = Event::read(&event_id, &st.db)829+ let event = service::event::read(&st.db, &event_id)
826 .await?830 .await?
827 .ok_or(AppError::NotFound)?;831 .ok_or(AppError::NotFound)?;
828 event.registration_capacity()?;832 event.registration_capacity()?;
@@ -868,7 +872,10 @@ mod tests {
868 let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash)872 let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash)
869 .await873 .await
870 .unwrap();874 .unwrap();
871- crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0875+ crate::service::user::set_role(db, user.get_id(), role)
876+ .await
877+ .unwrap()
878+ .0
872 }879 }
873 880
874 /// `can_manage` is only reached behind `RequireTeacher` today, so this is881 /// `can_manage` is only reached behind `RequireTeacher` today, so this is
@@ -878,14 +885,14 @@ mod tests {
878 async fn demoted_event_creator_loses_management() {885 async fn demoted_event_creator_loses_management() {
879 let db = init_mem().await.unwrap();886 let db = init_mem().await.unwrap();
880 let creator = user("ogretmen", Role::Teacher, &db).await;887 let creator = user("ogretmen", Role::Teacher, &db).await;
881- let event = Event::create(888+ let event = service::event::create(
889+ &db,
882 creator.get_id(),890 creator.get_id(),
883 EventTitle::try_new("Gezi").unwrap(),891 EventTitle::try_new("Gezi").unwrap(),
884 EventDescription::try_new("").unwrap(),892 EventDescription::try_new("").unwrap(),
885 EventAudience::School,893 EventAudience::School,
886 None,894 None,
887 None,895 None,
888- &db,
889 )896 )
890 .await897 .await
891 .unwrap();898 .unwrap();
src/web/pomodoro.rsmodified+5 -4
@@ -11,6 +11,7 @@ use crate::domain::pomodoro::PomodoroSession;
11 use crate::domain::role::Role;11 use crate::domain::role::Role;
12 use crate::domain::user::{User, UserId};12 use crate::domain::user::{User, UserId};
13 use crate::error::{AppError, ErrorResponse};13 use crate::error::{AppError, ErrorResponse};
14+use crate::service::pomodoro;
14 use crate::state::AppState;15 use crate::state::AppState;
15 16
16 use super::{CurrentUser, PageParams, ensure_can_observe, paginate};17 use super::{CurrentUser, PageParams, ensure_can_observe, paginate};
@@ -137,7 +138,7 @@ async fn start(
137 CurrentUser(user): CurrentUser,138 CurrentUser(user): CurrentUser,
138 ) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> {139 ) -> Result<(StatusCode, Json<PomodoroResponse>), AppError> {
139 ensure_student(&user)?;140 ensure_student(&user)?;
140- let session = PomodoroSession::start(user.get_id(), &st.db).await?;141+ let session = pomodoro::start(&st.db, user.get_id()).await?;
141 Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session))))142 Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session))))
142 }143 }
143 144
@@ -168,7 +169,7 @@ async fn finish(
168 State(st): State<AppState>,169 State(st): State<AppState>,
169 CurrentUser(user): CurrentUser,170 CurrentUser(user): CurrentUser,
170 ) -> Result<Json<PomodoroResponse>, AppError> {171 ) -> Result<Json<PomodoroResponse>, AppError> {
171- let session = PomodoroSession::finish(user.get_id(), &st.db).await?;172+ let session = pomodoro::finish(&st.db, user.get_id()).await?;
172 Ok(Json(PomodoroResponse::new(&session)))173 Ok(Json(PomodoroResponse::new(&session)))
173 }174 }
174 175
@@ -194,7 +195,7 @@ async fn my_pomodoro(
194 Query(page): Query<PageParams>,195 Query(page): Query<PageParams>,
195 ) -> Result<Json<PomodoroLog>, AppError> {196 ) -> Result<Json<PomodoroLog>, AppError> {
196 let (limit, offset) = page.resolve()?;197 let (limit, offset) = page.resolve()?;
197- let sessions = PomodoroSession::list_for_user(user.get_id(), &st.db).await?;198+ let sessions = pomodoro::list_for_user(&st.db, user.get_id()).await?;
198 Ok(Json(PomodoroLog::new(&sessions, limit, offset)))199 Ok(Json(PomodoroLog::new(&sessions, limit, offset)))
199 }200 }
200 201
@@ -228,6 +229,6 @@ async fn user_pomodoro(
228 crate::service::user::read(&st.db, &target)229 crate::service::user::read(&st.db, &target)
229 .await?230 .await?
230 .ok_or(AppError::NotFound)?;231 .ok_or(AppError::NotFound)?;
231- let sessions = PomodoroSession::list_for_user(&target, &st.db).await?;232+ let sessions = pomodoro::list_for_user(&st.db, &target).await?;
232 Ok(Json(PomodoroLog::new(&sessions, limit, offset)))233 Ok(Json(PomodoroLog::new(&sessions, limit, offset)))
233 }234 }
src/web/work.rsmodified+10 -8
@@ -11,6 +11,7 @@ use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;11 use crate::domain::user::UserId;
12 use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};12 use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
13 use crate::error::{AppError, ErrorResponse};13 use crate::error::{AppError, ErrorResponse};
14+use crate::service::work_entry;
14 use crate::state::AppState;15 use crate::state::AppState;
15 16
16 use super::{Page, PageParams, RequireManager, RequireTeacher};17 use super::{Page, PageParams, RequireManager, RequireTeacher};
@@ -79,7 +80,7 @@ async fn check_in(
79 State(st): State<AppState>,80 State(st): State<AppState>,
80 RequireTeacher(user): RequireTeacher,81 RequireTeacher(user): RequireTeacher,
81 ) -> Result<(StatusCode, Json<WorkEntryResponse>), AppError> {82 ) -> Result<(StatusCode, Json<WorkEntryResponse>), AppError> {
82- let entry = WorkEntry::check_in(user.get_id(), &st.db).await?;83+ let entry = work_entry::check_in(&st.db, user.get_id()).await?;
83 Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry))))84 Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry))))
84 }85 }
85 86
@@ -101,7 +102,7 @@ async fn check_out(
101 State(st): State<AppState>,102 State(st): State<AppState>,
102 RequireTeacher(user): RequireTeacher,103 RequireTeacher(user): RequireTeacher,
103 ) -> Result<Json<WorkEntryResponse>, AppError> {104 ) -> Result<Json<WorkEntryResponse>, AppError> {
104- let entry = WorkEntry::check_out(user.get_id(), &st.db).await?;105+ let entry = work_entry::check_out(&st.db, user.get_id()).await?;
105 Ok(Json(WorkEntryResponse::new(&entry)))106 Ok(Json(WorkEntryResponse::new(&entry)))
106 }107 }
107 108
@@ -128,7 +129,7 @@ async fn my_work(
128 Query(page): Query<PageParams>,129 Query(page): Query<PageParams>,
129 ) -> Result<Json<Page<WorkEntryResponse>>, AppError> {130 ) -> Result<Json<Page<WorkEntryResponse>>, AppError> {
130 let (limit, offset) = page.resolve()?;131 let (limit, offset) = page.resolve()?;
131- let (entries, total) = WorkEntry::list_for_user(user.get_id(), limit, offset, &st.db).await?;132+ let (entries, total) = work_entry::list_for_user(&st.db, user.get_id(), limit, offset).await?;
132 let items = entries.iter().map(WorkEntryResponse::new).collect();133 let items = entries.iter().map(WorkEntryResponse::new).collect();
133 Ok(Json(Page::new(items, total, limit, offset)))134 Ok(Json(Page::new(items, total, limit, offset)))
134 }135 }
@@ -162,7 +163,7 @@ async fn user_work(
162 crate::service::user::read(&st.db, &target)163 crate::service::user::read(&st.db, &target)
163 .await?164 .await?
164 .ok_or(AppError::NotFound)?;165 .ok_or(AppError::NotFound)?;
165- let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?;166+ let (entries, total) = work_entry::list_for_user(&st.db, &target, limit, offset).await?;
166 let items = entries.iter().map(WorkEntryResponse::new).collect();167 let items = entries.iter().map(WorkEntryResponse::new).collect();
167 Ok(Json(Page::new(items, total, limit, offset)))168 Ok(Json(Page::new(items, total, limit, offset)))
168 }169 }
@@ -194,7 +195,7 @@ async fn update_entry(
194 ) -> Result<Json<WorkEntryResponse>, AppError> {195 ) -> Result<Json<WorkEntryResponse>, AppError> {
195 let check_in = req.check_in.map(Timestamp::from_millis);196 let check_in = req.check_in.map(Timestamp::from_millis);
196 let check_out = req.check_out.map(Timestamp::from_millis);197 let check_out = req.check_out.map(Timestamp::from_millis);
197- let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db)198+ let entry = work_entry::read(&st.db, &WorkEntryId::from_key(&id))
198 .await?199 .await?
199 .ok_or(AppError::NotFound)?;200 .ok_or(AppError::NotFound)?;
200 let Some(current_out) = entry.get_check_out() else {201 let Some(current_out) = entry.get_check_out() else {
@@ -205,12 +206,13 @@ async fn update_entry(
205 206
206 // The side the correction left out is only *read* for the ordering check —207 // The side the correction left out is only *read* for the ordering check —
207 // it is never written back, so a concurrent correction of it survives.208 // it is never written back, so a concurrent correction of it survives.
208- // Pre-flight only: `WorkEntry::update` re-makes this in the UPDATE's `WHERE`.209+ // Pre-flight only: the UPDATE's `WHERE` re-makes this check against the
210+ // stored row.
209 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {211 if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) {
210 return Err(out_before_in_error());212 return Err(out_before_in_error());
211 }213 }
212 214
213- let updated = entry.update(check_in, check_out, &st.db).await?;215+ let updated = work_entry::update(&st.db, entry, check_in, check_out).await?;
214 Ok(Json(WorkEntryResponse::new(&updated)))216 Ok(Json(WorkEntryResponse::new(&updated)))
215 }217 }
216 218
@@ -233,7 +235,7 @@ async fn delete_entry(
233 _manager: RequireManager,235 _manager: RequireManager,
234 Path(id): Path<String>,236 Path(id): Path<String>,
235 ) -> Result<StatusCode, AppError> {237 ) -> Result<StatusCode, AppError> {
236- let removed = WorkEntry::remove(&WorkEntryId::from_key(&id), &st.db).await?;238+ let removed = work_entry::remove(&st.db, &WorkEntryId::from_key(&id)).await?;
237 if removed.is_none() {239 if removed.is_none() {
238 return Err(AppError::NotFound);240 return Err(AppError::NotFound);
239 }241 }