diff --git a/src/db/event.rs b/src/db/event.rs new file mode 100644 index 0000000..971bdca --- /dev/null +++ b/src/db/event.rs @@ -0,0 +1,288 @@ +//! The `event` table: row reads and listings, the cascading delete, and the +//! audience's live membership resolution — the point check behind marking +//! ([`includes`]) and the who-missed report's backbone ([`members`]). + +use surrealdb::types::SurrealValue; + +use crate::database::{Database, transaction_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::domain::class_member::{ClassMember, ClassMemberId}; +use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; +use crate::domain::registration::Registration; +use crate::domain::timestamp::{Timestamp, range_error}; +use crate::domain::user::{User, UserId}; +use crate::error::AppError; + +/// Is `user` in `audience`'s roster right now? The point check behind +/// marking — cheaper than resolving the whole roster when the target is +/// known. `event` must be the event this audience came from: the +/// registration kind resolves against that event's signup rows. +pub async fn includes( + db: &Database, + audience: &EventAudience, + event: &EventId, + user: &User, +) -> Result { + match audience { + EventAudience::School => Ok(true), + EventAudience::Role { role } => Ok(user.get_role() == *role), + EventAudience::Course { course } => { + Ok( + crate::db::enrollment::read_for_user(db, course, user.get_id()) + .await? + .is_some(), + ) + } + // The (class, user) pair is the membership row's own id, so the + // point check is a single select — no scan, no index needed. + EventAudience::Class { class } => { + let member: Option = db + .select(ClassMemberId::composite(class, user.get_id()).record()) + .await?; + Ok(member.is_some()) + } + EventAudience::Registration { .. } => { + Ok(Registration::read_for_user(event, user.get_id(), db) + .await? + .is_some()) + } + } +} + +/// `event`'s full roster, as it stands right now — the who-missed +/// report's backbone. Registered ids that no longer resolve to a user row +/// are kept; the caller degrades their display like any stale reference. +pub async fn members( + db: &Database, + audience: &EventAudience, + event: &EventId, +) -> Result, AppError> { + match audience { + EventAudience::School => Ok(crate::db::user::list_all(db, None, 0) + .await? + .0 + .iter() + .map(|user| user.get_id().clone()) + .collect()), + EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role) + .await? + .iter() + .map(|user| user.get_id().clone()) + .collect()), + EventAudience::Course { course } => { + Ok(crate::db::enrollment::list_for_course(db, course, None, 0) + .await? + .0 + .iter() + .map(|enrollment| enrollment.get_user().clone()) + .collect()) + } + EventAudience::Class { class } => Ok(ClassMember::list_for_class(class, None, 0, db) + .await? + .0 + .iter() + .map(|member| member.get_user().clone()) + .collect()), + EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) + .await? + .iter() + .map(|registration| registration.get_user().clone()) + .collect()), + } +} + +pub async fn create( + db: &Database, + creator: &UserId, + title: EventTitle, + description: EventDescription, + audience: EventAudience, + starts_at: Option, + ends_at: Option, +) -> Result { + let event = Event { + id: EventId::generate(), + creator: creator.clone(), + title, + description, + audience, + starts_at, + ends_at, + }; + let created: Option = db.create(event.id.record()).content(event).await?; + created.ok_or_else(|| AppError::Internal("failed to create event".into())) +} + +pub async fn read(db: &Database, id: &EventId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +pub async fn list_all(db: &Database) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM event ORDER BY id DESC") + .await? + .check()?; + Ok(result.take::>(0)?) +} + +/// Request-scoped: the handler reads the event, then awaits the clock and a +/// course lookup before saving, holding no lock, so an omitted field +/// (`None`) is not written at all. Passing the snapshot's value back +/// instead would revert a concurrent edit of that field — scoping the `SET` +/// alone does not prevent that, the values have to come from the request. +/// The schedule columns are nullable, so they take the outer/inner +/// `Option>`: `None` = omitted (keep), `Some(None)` = clear. +pub async fn update( + db: &Database, + event: Event, + title: Option, + description: Option, + audience: Option, + starts_at: Option>, + ends_at: Option>, +) -> Result { + FieldUpdate::new(event.id.record()) + .set("title", title) + .set("description", description) + .set("audience", audience) + .set("starts_at", starts_at) + .set("ends_at", ends_at) + .ordered("starts_at", "ends_at", range_error()) + .run::(db) + .await +} + +/// Delete the event and cascade-remove its attendance and signup rows. +/// +/// Children first, and all of it in one transaction the way +/// [`crate::db::course::delete`] does it: run as two queries, a +/// registration or a mark that committed in between outlived its event — +/// an orphan no read path can ever reach and no delete can ever reclaim, +/// since every one of them is keyed on the event that is now gone. +/// +/// Re-sent while the store answers "conflict, retry", the way +/// [`crate::db::course_session::delete`] is: now that +/// [`crate::domain::attendance::Attendance::mark`] writes the event row to +/// prove it exists, a mark landing in this window really does contend for +/// it — and without the retry the *delete* is the side that loses, turning +/// a race the store resolved correctly into a 500 (measured 4 rounds in 4). +/// Admissible: every statement is a `DELETE`, which can never answer +/// "already exists", and a lost round wrote nothing. +pub async fn delete(db: &Database, event: Event) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + DELETE attendance WHERE event = $ev; + DELETE registration WHERE event = $ev; + LET $gone = (DELETE $ev RETURN BEFORE); + RETURN $gone; + COMMIT TRANSACTION;", + &[("ev".into(), event.id.record().into_value())], + // No THROW of its own — an unconditional cascade. + &[], + ) + .await?; + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Read through the trailing `RETURN`, never a hand-counted slot. + let slot = result.num_statements().saturating_sub(2); + result + .take::>(slot)? + .into_iter() + .next() + .ok_or(AppError::NotFound) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::constant::REGISTRATION_FROZEN_GUARD; + use crate::domain::class_group::ClassGroupId; + + /// The forcing function behind the one rule with two spellings: the freeze + /// this file decides in Rust ([`Event::registration_capacity`]) and + /// [`REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which + /// the role cascade (`service::user::set_role`) carries because it frees a demoted + /// parent's seats inside a transaction and cannot call Rust from there. + /// + /// Every schedule shape is put to both, including the three the SQL is most + /// likely to get wrong: the ends_at-only event (`??` must fall through to + /// it), the boundary itself (closed *at* the instant, not after it — `>=` in + /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound + /// to that exact instant so the boundary is really exercised), and an event + /// that takes no registrations at all, which Rust refuses one arm *earlier* + /// — so the SQL must not report it frozen, or a stray row on it would be + /// preserved forever instead of swept. + #[tokio::test] + async fn the_sql_freeze_guard_matches_the_rust_one() { + let db = crate::database::init_mem().await.unwrap(); + let now = Timestamp::now().as_millis(); + let past = Some(Timestamp::from_millis(now - 60_000)); + let future = Some(Timestamp::from_millis(now + 3_600_000)); + let later = Some(Timestamp::from_millis(now + 7_200_000)); + let signup = EventAudience::Registration { capacity: None }; + let cases = [ + ("timeless", signup.clone(), None, None), + ("deadline ahead", signup.clone(), None, future), + ("deadline passed", signup.clone(), None, past), + ("starts later", signup.clone(), future, later), + ("already started", signup.clone(), past, None), + ("started, ends later", signup.clone(), past, future), + ( + "closing this instant", + signup.clone(), + Some(Timestamp::from_millis(now)), + None, + ), + // No signup list to freeze: `registration_capacity` refuses these on + // the audience, before it ever looks at the clock. + ("started school event", EventAudience::School, past, None), + ( + "started class event", + EventAudience::Class { + class: ClassGroupId::from_key("g1"), + }, + past, + None, + ), + ]; + for (name, audience, starts_at, ends_at) in cases { + let event = create( + &db, + &UserId::from_key("teacher"), + EventTitle::try_new(name).unwrap(), + EventDescription::try_new("").unwrap(), + audience, + starts_at, + ends_at, + ) + .await + .unwrap(); + let rust = matches!( + event.registration_capacity(), + Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) + ); + let mut result = db + .query(format!( + "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}" + )) + .bind(("ev", event.get_id().record())) + .bind(("now", now)) + .await + .unwrap() + .check() + .unwrap(); + let sql = !result + .take::>(0) + .unwrap() + .is_empty(); + assert_eq!( + sql, rust, + "the SQL freeze guard and registration_capacity disagree on a \ + {name} event — the role cascade would rewrite a closed signup \ + list, or strand a seat on an open one" + ); + } + } +} diff --git a/src/db/mod.rs b/src/db/mod.rs index e164f1b..d283d68 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -7,6 +7,7 @@ pub mod class_blueprint; pub mod course; pub mod course_session; pub mod enrollment; +pub mod event; pub mod exam; pub mod exam_attempt; pub mod exam_question; @@ -15,6 +16,8 @@ pub mod meal_booking; pub mod note; pub mod page; pub mod payment_ledger; +pub mod pomodoro; pub mod session; pub mod settings; pub mod user; +pub mod work_entry; diff --git a/src/db/pomodoro.rs b/src/db/pomodoro.rs new file mode 100644 index 0000000..fda849f --- /dev/null +++ b/src/db/pomodoro.rs @@ -0,0 +1,744 @@ +//! The `pomodoro_session` table: the open-slot start/finish pair and the +//! newest-first log. The counting verdict, the lifetime badge counters, and +//! the study streak are all decided inside [`finish`]'s one transaction — +//! the whole rule is the batch itself. + +use surrealdb::types::SurrealValue; + +use crate::constant::{ + MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD, + POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, + STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, STUDY_STREAK_LONGEST_FIELD, +}; +use crate::database::{Database, transaction_with_retry}; +use crate::domain::badge; +use crate::domain::pomodoro::{PomodoroSession, PomodoroSessionId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::error::AppError; + +/// Start a session for `user`, stamped with the server clock. `UPSERT` on +/// the deterministic open id makes this atomic and always succeed: a +/// dangling unfinished session (the browser died mid-timer) is replaced — +/// it never counted, and blocking the next start behind it would only +/// punish the student for a crash. +pub async fn start(db: &Database, user: &UserId) -> Result { + let mut result = db + .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") + .bind(("open", PomodoroSessionId::open_for(user).record())) + .bind(("usr", user.record())) + .bind(("at", Timestamp::now())) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into())) +} + +/// Close `user`'s running session: atomically take the open row and +/// re-file it under a ULID id, freeing the open slot for the next start. +/// Take and re-file share one transaction — a failed re-file rolls the +/// take back, so a session can never vanish half-closed. Of two racing +/// finishes exactly one receives the row (the other gets the conflict). +/// +/// A lost round is re-sent rather than reported (`transaction_with_retry`): +/// the abort wrote nothing, so the whole cascade is safe to repeat, and the +/// `CREATE` cannot answer "already exists" on the way back — the table +/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. +/// Only the guard's own `THROW` is a decision, and it stays a 409. +/// +/// `finished_at` is floored at the row's own `started_at`. Both stamps come +/// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move +/// *backwards* mid-stint — so a close can legitimately read earlier than its +/// own start with nothing wrong on the client's side. Refusing it would lose +/// a real study session and leave the open slot wedged for a fault the +/// student did not cause; recording a zero-length stint keeps the session +/// count honest and its duration merely understated. Nothing downstream may +/// then read a negative duration (`ProfileStats::load` sums these). +/// +/// The lifetime badge counters on the user row move in this same +/// transaction, so they can never count a stint the log does not hold (nor +/// miss one it does), and a retried round re-applies nothing — the abort +/// rolled the increment back with the rest. They are written field-scoped: +/// the row also carries admin-owned data (`role`), which a whole-row save +/// would silently revert. The clamped duration is the *same* expression the +/// `CREATE` stores (both read `$ms`), so the counter can never take a +/// negative summand and nothing downstream needs a floor. Only *finished* +/// stints reach here — an open row is a `pomodoro_session` row and nothing +/// else — and there is no student-facing delete for a stint, so neither +/// counter ever decrements. +/// +/// They move only for a stint that **counts**, which is +/// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most +/// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this +/// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] +/// argues about from the other end: finishing is self-service, one stint is +/// two requests and no second person, so a counter moved once per +/// round-trip is farmable — two hundred pairs inside the rate limit bought +/// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked. +/// Both stamps are the server's own clock, so the duration needs no +/// distrusting, only a floor. +/// +/// The verdict is *stamped* on the closed row (`counted`), not re-derived +/// later: the thresholds are compiled in and will move, and a reader that +/// re-judged an old stint against today's numbers would answer something +/// other than what was credited. Nothing debits these counters today; the +/// stamp is what lets one be added without that asymmetry. A stint below +/// the bar is still recorded, still listed, and still sums into the log's +/// `total_focus_ms` — the rule bounds what *counts*, never what is kept. +/// +/// The day quota is bucketed like the streak below (midnight UTC, +/// [`Timestamp::day_number`]) and rolls in its own statement ahead of the +/// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting +/// it, which resolves against the row as it was *before* the statement — +/// the same rule that forces the streak pair apart, used here on purpose. A +/// row that predates the two columns reads as no day at all (`?? -1`), so +/// the first finish after this deploy opens a fresh bucket and no backfill +/// is owed. The bucket write happens whether the stint counts or not; only +/// the `+ 1` sits behind the verdict. +/// +/// The **study streak** rides the same transaction, and the same verdict: a +/// study day is a UTC calendar day on which a stint *counted*, so a day +/// bought with one instant round-trip is not a day studied (midnight UTC, like every +/// other day calculation here — no timezone is stored anywhere): the same +/// day again changes nothing, the next day extends the run, any other gap +/// starts a new one at 1. It is written as **two** statements, not one: +/// every field reference on the right-hand side of a `SET` resolves +/// against the row as it was *before* that statement, so a single +/// `SET current = …, longest = math::max([longest, current])` would take +/// the *old* `current` and lag one write behind forever (probed on a real +/// 3.2.3 server: day two left `current = 2, longest = 1`). Across +/// statements *inside a transaction* the read does see the prior write, so +/// the pair is correct and still atomic. Absent columns are read through +/// `?? 0` (and `?? -1` for the day — a sentinel no real day number +/// reaches), because `math::max` errors outright on a `NONE` argument and +/// every account older than these columns carries none of them. +/// +/// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two +/// lines up: a plain `UPDATE` hands back an array, so a user row that is +/// missing (a `record` column checks only the table of the id) simply +/// yields nothing to index and the second statement matches no row either. +/// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero +/// rows; it errors on *many* — but a `null` is a shape the read then has to +/// special-case, so the file's existing idiom wins. +/// +/// No `cap::counter_lock` is taken, deliberately. The pair cannot tear: +/// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts +/// a rival that touched the row in between — `transaction_with_retry` then +/// re-sends the whole round. And `longest` is written as +/// `max(longest, current)`, which cannot come down under *any* +/// interleaving, so even a torn pair could only under-count `current`, +/// never lower the high-water mark the badges read. The lock would only +/// serialize this process's writers (its other job, keeping the in-memory +/// test engine deterministic, is moot here — these tests are sequential). +/// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent +/// finishes for one user left `current = 60, longest = 60` with no +/// anomaly; a rival write forced *between* the two statements (a `sleep` +/// wedged into the batch) aborted the whole cascade with a write conflict, +/// wrote nothing, and left the rival's value standing. +/// +/// Streaks begin at this deploy: nothing reconstructs history from the +/// stint log, so every account starts with no streak columns and its first +/// finish sets a run of 1. +pub async fn finish(db: &Database, user: &UserId) -> Result { + let done = Timestamp::now(); + let (mut result, mut errors) = transaction_with_retry( + db, + &format!( + "BEGIN TRANSACTION; + LET $before = (DELETE $open RETURN BEFORE); + IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; + LET $end = math::max([$before[0].started_at, $done]); + LET $ms = $end - $before[0].started_at; + LET $bucket = (UPDATE $usr SET + {POMODORO_COUNTED_TODAY_FIELD} = + IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day + THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END, + {POMODORO_COUNTED_DAY_FIELD} = $day + RETURN AFTER); + LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS}) + AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0) + < {MAX_COUNTED_POMODORO_PER_DAY}); + IF $counted {{ + UPDATE $usr SET + {POMODORO_FINISHED_TOTAL_FIELD} = + ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, + {POMODORO_FOCUS_MS_TOTAL_FIELD} = + ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms, + {POMODORO_COUNTED_TODAY_FIELD} = + ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1; + LET $streak = (UPDATE $usr SET + {STUDY_STREAK_CURRENT_FIELD} = + IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day + THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) + ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) + THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) + ELSE 1 END, + {STUDY_STREAK_LAST_DAY_FIELD} = $day + RETURN AFTER); + UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), + ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]) + }}; + CREATE $closed CONTENT {{ + user: $before[0].user, + started_at: $before[0].started_at, + finished_at: $end, + counted: $counted, + }}; + COMMIT TRANSACTION;" + ), + &[ + ( + "open".into(), + PomodoroSessionId::open_for(user).record().into_value(), + ), + ("usr".into(), user.record().into_value()), + ( + "closed".into(), + PomodoroSessionId::generate().record().into_value(), + ), + ("done".into(), done.into_value()), + ("day".into(), done.day_number().into_value()), + ], + &["no_pomodoro_running"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the THROW's own slot names the reason, so scan + // them all for the marker instead of trusting the first. + if errors + .values() + .any(|error| error.to_string().contains("no_pomodoro_running")) + { + return Err(AppError::Conflict("no pomodoro session running")); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // The `CREATE` is deliberately kept the last statement before `COMMIT` + // (the counter `UPDATE` sits ahead of it — same transaction, so the + // order is free), which is what lets its slot follow the statement + // count instead of a hand-kept number: `num_statements` counts `BEGIN` + // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a + // hand-kept slot caused. + let slot = result.num_statements().saturating_sub(2); + let saved: Option = result + .take::>(slot)? + .into_iter() + .next(); + let saved = + saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?; + // A badge is a decoration on top of the stint: losing one to a + // transient database error must never fail the finish, and the next + // counter move re-runs this and heals it. + if let Err(err) = badge::sync(user, db).await { + tracing::warn!("failed to sync badges for {}: {err}", user.key()); + } + Ok(saved) +} + +/// Every session of `user`, newest first — the running one (if any) +/// included. Ordered by `started_at`, never by id alone: the open entry's +/// `open_` key doesn't sort with the ULIDs, so id order would misplace it. +/// The `id` tie-break behind it only ever separates two *finished* stints +/// sharing a `started_at` — there is one running row per user, so it can +/// never tie with itself. +pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { + let mut result = db + .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC") + .bind(("usr", user.record())) + .await? + .check()?; + Ok(result.take::>(0)?) +} + +#[cfg(test)] +mod tests { + use ulid::Ulid; + + use super::*; + use crate::database; + + /// A real `user` row: the counters land with `UPDATE`, which only ever + /// touches a record that exists, so a fabricated id would silently store + /// nothing. The tests above need no row — they read only the stint log. + async fn a_user(db: &Database) -> UserId { + let user = UserId::from_key(&Ulid::new().to_string()); + db.query("CREATE $usr SET username = $name, password_hash = 'x'") + .bind(("usr", user.record())) + .bind(("name", user.key().to_string())) + .await + .unwrap() + .check() + .unwrap(); + user + } + + /// `(finished_total, focus_ms_total)` re-read from the store — never off + /// what `finish` returned, which proves nothing about what was written. + async fn counters(user: &UserId, db: &Database) -> (i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0), + ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + let row = rows.into_iter().next().expect("the user row"); + (row[0], row[1]) + } + + /// `(current, longest, last_day)` re-read from the store. + async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) { + let mut result = db + .query(format!( + "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0), + ({STUDY_STREAK_LONGEST_FIELD} ?? 0), + ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr" + )) + .bind(("usr", user.record())) + .await + .unwrap() + .check() + .unwrap(); + let rows: Vec> = result.take(0).unwrap(); + let row = rows.into_iter().next().expect("the user row"); + (row[0], row[1], row[2]) + } + + /// Age *both* day buckets by `days`, so the next finish lands that many + /// days later on the calendar — the streak's and the day quota's, since + /// they are the same calendar and a test that moved one would be asserting + /// against a day the other has never heard of. The day is injected into the + /// stored state rather than into the clock, which keeps `Timestamp::now` + /// the sole clock read and the test free of sleeping. + /// + /// Known flake, left as-is: every caller assumes the UTC day does not turn + /// over mid-test — a crossing between two stints shifts the real day under + /// the injected one and reddens the run. That is one ~ms-wide window per + /// day (~5e-6 per run), and the alternative is a clock seam in production + /// code to serve a test. Re-run before believing a failure that only ever + /// happens near midnight UTC. + async fn age_by_days(user: &UserId, db: &Database, days: i64) { + db.query(format!( + "UPDATE $usr SET + {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, + {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" + )) + .bind(("usr", user.record())) + .bind(("days", days)) + .await + .unwrap() + .check() + .unwrap(); + } + + /// Open a stint that has already been running for `ms` — the stamp the + /// close measures against, injected instead of slept through. + /// + /// One `UPSERT`, not `start` followed by a backdate: the concurrent test + /// races four of these onto the same open row, and a separate backdate can + /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a + /// zero-length stint and reddening the run for no defect. Same statement + /// `start` runs, one clock read earlier. + async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { + db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }") + .bind(("open", PomodoroSessionId::open_for(user).record())) + .bind(("usr", user.record())) + .bind(("at", Timestamp::now().as_millis() - ms)) + .await? + .check()?; + Ok(()) + } + + /// Start and close one stint that counts: exactly the minimum on the clock, + /// so every streak assertion below is about the day and not the duration. + async fn one_stint(user: &UserId, db: &Database) { + start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap(); + finish(db, user).await.unwrap(); + } + + #[tokio::test] + async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + // The stale-data case: a row that predates all three columns reads as + // no streak at all, and its first finish opens a run of one. + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + + one_stint(&user, &db).await; + let today = Timestamp::now().day_number(); + assert_eq!(streak(&user, &db).await, (1, 1, today)); + + // A second stint the same day is not a second day. + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await, (1, 1, today)); + + // Days N+1 and N+2. + for day in 2..=3 { + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await, (day, day, today)); + } + } + + #[tokio::test] + async fn a_gap_resets_the_run_but_never_the_high_water_mark() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + one_stint(&user, &db).await; + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!(streak(&user, &db).await.0, 2); + + // Skip a day: the run restarts at one, the longest stays where it got. + age_by_days(&user, &db, 2).await; + one_stint(&user, &db).await; + let (current, longest, _) = streak(&user, &db).await; + assert_eq!((current, longest), (1, 2)); + + // A backwards day (a clock stepped back over a boundary) is a gap too, + // and still cannot lower the mark. + age_by_days(&user, &db, -5).await; + one_stint(&user, &db).await; + assert_eq!( + streak(&user, &db).await, + (1, 2, Timestamp::now().day_number()) + ); + } + + /// The transaction boundary itself, on a real server: the streak pair and + /// the counters must commit with the stint or not at all, under real + /// contention on one user row. + /// + /// Multi-threaded and off the embedded engine for the reason + /// [`crate::db::cap`] spells out: the in-memory engine does not + /// conflict-check two concurrent writes to one record, so it would answer + /// `Ok` to a write it dropped and *forge* the integrity failure this test + /// exists to catch. + /// + /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT` + /// pair from the batch turns all 20 rounds red. A `THROW` then errors only + /// its own statement, so the losers of the open-row race run the rest of + /// the cascade anyway — they bump the counters for a stint they never + /// closed and `CREATE` a session row out of an empty `$before`, which comes + /// back as `500 … Expected record, got none` (the `errors` assertion below + /// fires first; `finished_total` running ahead of the `Ok` finishes is the + /// same wound one statement later). What it does *not* pin is the + /// streak arithmetic under concurrency: same-day finishes all compute the + /// same value, so that stays green either way — it is + /// `max(longest, current)` that makes that robust, not the isolation. + /// + /// The shape of the contention, measured rather than assumed: four racers + /// per round is four `start`s collapsing onto *one* open row (the id is + /// deterministic per user), so typically exactly one `finish` commits and + /// three lose the `DELETE` and abort their whole cascade — 20 finishes and + /// 60 conflicts over 20 rounds, measured. That is the contention: the + /// losers' cascades are live against the same user row, which is precisely + /// what must leave nothing behind. Two commits in one round are possible + /// (a racer scheduled entirely after another's finish frees the slot) and + /// the assertions allow it — the day count is per round, not per stint. + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] + #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] + async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { + let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await; + let user = a_user(&db).await; + let (mut finished, mut conflicts, mut errors) = (0, 0, 0); + let mut last_error = String::new(); + for round in 1..=20 { + let racers: Vec<_> = (0..4) + .map(|_| { + let (user, db) = (user.clone(), db.clone()); + tokio::spawn(async move { + // Aged past the minimum, so whichever racer wins the + // open row closes a stint that *counts* — a fresh + // `start` here would hand the winner a zero-length + // stint, which now moves nothing and would leave this + // test asserting against an untouched counter. + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?; + finish(&db, &user).await + }) + }) + .collect(); + let mut won = 0; + for racer in racers { + match racer.await.unwrap() { + Ok(_) => won += 1, + // Losing the open row is the correct answer for a racer + // whose stint someone else closed; only `Db` is a defect. + Err(AppError::Conflict(_)) => conflicts += 1, + Err(err) => { + errors += 1; + last_error = format!("{err:?}"); + } + } + } + finished += won; + // One day per round, however many stints landed in it, and the + // mark never lags the run in progress. + let (current, longest, _) = streak(&user, &db).await; + assert_eq!( + (current, longest), + (round, round), + "round {round} counted {won} finishes as {current} days" + ); + age_by_days(&user, &db, 1).await; + } + // The atomicity claim: the counter counts exactly the stints that were + // closed, never a loser's aborted round. + let (counted, _) = counters(&user, &db).await; + eprintln!( + "PomodoroSession::finish raced: {finished} finishes over 20 days, \ + {conflicts} rivals refused, {errors} 500s" + ); + assert_eq!( + errors, 0, + "a raced finish must conflict, not 500: {last_error}" + ); + assert_eq!( + counted, finished, + "the counter counted {counted} stints for {finished} finishes" + ); + assert!( + conflicts > 0, + "every racer won its own round, so no cascade was ever aborted mid-flight \ + and this run proves nothing about the transaction boundary" + ); + } + + #[tokio::test] + async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + assert_eq!(counters(&user, &db).await, (0, 0)); + + // An open stint is not a finished one: neither counter moves until it + // closes. + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + assert_eq!(counters(&user, &db).await, (0, 0)); + + let mut focus_ms = 0; + for _ in 0..2 { + let closed = finish(&db, &user).await.unwrap(); + focus_ms += + closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + } + // Three starts, two finishes — the third is still running. + assert_eq!(counters(&user, &db).await, (2, focus_ms)); + } + + #[tokio::test] + async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + start(&db, &user).await.unwrap(); + db.query("UPDATE $open SET started_at = $future") + .bind(("open", PomodoroSessionId::open_for(&user).record())) + .bind(("future", Timestamp::now().as_millis() + 3_600_000)) + .await + .unwrap() + .check() + .unwrap(); + + // The clamp holds: zero milliseconds, never a negative — and a stint + // measuring zero is below the minimum, so it moves neither counter. + let closed = finish(&db, &user).await.unwrap(); + assert_eq!(closed.get_counted(), Some(false)); + assert_eq!(counters(&user, &db).await, (0, 0)); + } + + /// The minimum, from both sides. A round-trip is not a study session, and + /// the boundary is inclusive (`>=`) — a stint of exactly the minimum + /// counts, which is the side these assertions pin. + /// + /// The near miss is a whole minute short, not one millisecond: `finish` + /// reads its own clock *after* the stint is opened, so a stint aged to + /// exactly one millisecond under the bar crosses it by the time the close + /// measures it (measured — that assertion failed on the first run). A + /// millisecond-exact probe would need a clock seam in production code, and + /// what matters here is the four orders of magnitude between a scripted + /// pair and a study session, not the last millisecond. + #[tokio::test] + async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) + .await + .unwrap(); + let short = finish(&db, &user).await.unwrap(); + assert_eq!(short.get_counted(), Some(false)); + assert_eq!(counters(&user, &db).await, (0, 0)); + // Not a study day either — and no streak column was even opened. + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + // But it happened, and the log says so. + let log = list_for_user(&db, &user).await.unwrap(); + assert_eq!(log.len(), 1); + assert_eq!(log[0].get_finished_at(), short.get_finished_at()); + + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + let counted = finish(&db, &user).await.unwrap(); + assert_eq!(counted.get_counted(), Some(true)); + let (finished, focus_ms) = counters(&user, &db).await; + // The counter took the *same* duration the row stores, not a second + // reading of the clock. + assert_eq!( + (finished, focus_ms), + ( + 1, + counted.get_finished_at().unwrap().as_millis() + - counted.get_started_at().as_millis() + ) + ); + assert_eq!(streak(&user, &db).await.0, 1); + assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 2); + } + + /// The day quota: it stops the counter, it never stops the log, and it + /// rolls at midnight UTC. + #[tokio::test] + async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { + one_stint(&user, &db).await; + } + let (finished, focus_ms) = counters(&user, &db).await; + assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY); + + // Past the quota: recorded, listed, worth nothing — neither stint count + // nor focus milliseconds. + for _ in 0..3 { + start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) + .await + .unwrap(); + let over = finish(&db, &user).await.unwrap(); + assert_eq!(over.get_counted(), Some(false)); + } + assert_eq!(counters(&user, &db).await, (finished, focus_ms)); + assert_eq!( + list_for_user(&db, &user).await.unwrap().len() as i64, + MAX_COUNTED_POMODORO_PER_DAY + 3 + ); + // The quota is a day's, not a lifetime's. + age_by_days(&user, &db, 1).await; + one_stint(&user, &db).await; + assert_eq!( + counters(&user, &db).await.0, + MAX_COUNTED_POMODORO_PER_DAY + 1 + ); + } + + /// The farm, run: `start`/`finish` in a loop is two requests a round with + /// no second person in it, which used to move `pomodoro_finished_total` one + /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`, + /// and a badge is never taken back. + #[tokio::test] + async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { + let db = database::init_mem().await.unwrap(); + let user = a_user(&db).await; + + for _ in 0..200 { + start(&db, &user).await.unwrap(); + finish(&db, &user).await.unwrap(); + } + assert_eq!(counters(&user, &db).await, (0, 0)); + assert_eq!(streak(&user, &db).await, (0, 0, -1)); + // Every one of them is still the student's own history. + assert_eq!(list_for_user(&db, &user).await.unwrap().len(), 200); + assert!( + badge::BadgeAward::list_for(&user, &db) + .await + .unwrap() + .is_empty(), + "the farm minted a permanent badge" + ); + + // And paying the minimum for each one only buys the day's quota. + for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) { + one_stint(&user, &db).await; + } + assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY); + } + + #[tokio::test] + async fn restart_replaces_the_open_session_and_finish_closes_it() { + let db = database::init_mem().await.unwrap(); + // A `record` column checks the table of the id, not row + // existence — a fabricated id keeps this test free of user ceremony. + let user = UserId::from_key(&Ulid::new().to_string()); + + // Nothing running yet — finishing conflicts. + assert!(matches!( + finish(&db, &user).await, + Err(AppError::Conflict(_)) + )); + + let first = start(&db, &user).await.unwrap(); + assert!(first.get_finished_at().is_none()); + assert_eq!(first.get_id().key(), format!("open_{}", user.key())); + + // A restart replaces the dangling session: still one row, fresh clock. + let second = start(&db, &user).await.unwrap(); + assert!(second.get_started_at() >= first.get_started_at()); + let sessions = list_for_user(&db, &user).await.unwrap(); + assert_eq!(sessions.len(), 1); + + let closed = finish(&db, &user).await.unwrap(); + assert!(closed.get_finished_at().unwrap() >= closed.get_started_at()); + + // The open slot is free again; a stray second finish conflicts. + assert!(matches!( + finish(&db, &user).await, + Err(AppError::Conflict(_)) + )); + start(&db, &user).await.unwrap(); + let sessions = list_for_user(&db, &user).await.unwrap(); + assert_eq!(sessions.len(), 2); + } + + #[tokio::test] + async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { + let db = database::init_mem().await.unwrap(); + let user = UserId::from_key(&Ulid::new().to_string()); + + start(&db, &user).await.unwrap(); + // Stand in for the NTP step: push the running stint's start an hour + // ahead, so the server clock `finish` reads is *behind* it. + db.query("UPDATE $open SET started_at = $future") + .bind(("open", PomodoroSessionId::open_for(&user).record())) + .bind(("future", Timestamp::now().as_millis() + 3_600_000)) + .await + .unwrap() + .check() + .unwrap(); + + let closed = finish(&db, &user).await.unwrap(); + let started = closed.get_started_at().as_millis(); + assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); + + // And the stat that sums these stays non-negative. + let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) + .await + .unwrap(); + assert_eq!(stats.get_pomodoro_sessions(), 1); + assert_eq!(stats.get_pomodoro_focus_ms(), 0); + } +} diff --git a/src/db/work_entry.rs b/src/db/work_entry.rs new file mode 100644 index 0000000..94a0f78 --- /dev/null +++ b/src/db/work_entry.rs @@ -0,0 +1,183 @@ +//! The `work_entry` table: the open-slot check-in/check-out pair, the +//! newest-first log, and manager corrections guarded by the stored order. + +use surrealdb::types::SurrealValue; + +use crate::database::{Database, transaction_with_retry}; +use crate::db::field_update::FieldUpdate; +use crate::db::page::PagedList; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; +use crate::error::AppError; + +/// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE` +/// on the deterministic open id makes this atomic: if an open entry +/// already exists the insert is skipped (empty result) and the caller gets +/// a conflict — two racing check-ins can never create two open rows or +/// reset a running clock. +pub async fn check_in(db: &Database, user: &UserId) -> Result { + let entry = WorkEntry { + id: WorkEntryId::open_for(user), + user: user.clone(), + check_in: Timestamp::now(), + check_out: None, + }; + let mut result = db + .query("INSERT IGNORE INTO work_entry $entry") + .bind(("entry", entry)) + .await? + .check()?; + result + .take::>(0)? + .into_iter() + .next() + .ok_or(AppError::Conflict("already checked in — check out first")) +} + +/// Close `user`'s open stint: atomically take the open row and re-file it +/// under a ULID id, freeing the open slot for the next check-in. Take and +/// re-file share one transaction — a failed re-file rolls the take back, +/// so a stint can never vanish half-closed. Of two racing check-outs +/// exactly one receives the row (the other gets the conflict). +/// +/// A lost round is re-sent rather than reported (`transaction_with_retry`): +/// the abort wrote nothing, so the whole cascade is safe to repeat, and the +/// `CREATE` cannot answer "already exists" on the way back — the table +/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. +/// Only the guard's own `THROW` is a decision, and it stays a 409. +pub async fn check_out(db: &Database, user: &UserId) -> Result { + let (mut result, mut errors) = transaction_with_retry( + db, + "BEGIN TRANSACTION; + LET $before = (DELETE $open RETURN BEFORE); + IF array::len($before) = 0 { THROW 'not_checked_in' }; + CREATE $closed CONTENT { + user: $before[0].user, + check_in: $before[0].check_in, + check_out: $out, + }; + COMMIT TRANSACTION;", + &[ + ( + "open".into(), + WorkEntryId::open_for(user).record().into_value(), + ), + ( + "closed".into(), + WorkEntryId::generate().record().into_value(), + ), + ("out".into(), Timestamp::now().into_value()), + ], + &["not_checked_in"], + ) + .await?; + // An aborted transaction errors *every* slot, most with a generic + // "not executed" — only the THROW's own slot names the reason, so scan + // them all for the marker instead of trusting the first. + if errors + .values() + .any(|error| error.to_string().contains("not_checked_in")) + { + return Err(AppError::Conflict("not checked in")); + } + if let Some(error) = errors.drain().map(|(_, error)| error).next() { + return Err(error.into()); + } + // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. + let saved: Option = result.take::>(3)?.into_iter().next(); + saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) +} + +pub async fn read(db: &Database, id: &WorkEntryId) -> Result, AppError> { + Ok(db.select(id.record()).await?) +} + +/// Every stint of `user`, newest first — the open one (if any) included. +/// Ordered by `check_in`, never by id alone: the open entry's `open_` key +/// doesn't sort with the ULIDs, so id order would misplace it. The `id` +/// tie-break behind it only ever separates two *closed* stints sharing a +/// `check_in` — there is one open row per user, so it can never tie with +/// itself — and that is what keeps offset paging from skipping a row. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + PagedList::new( + "work_entry WHERE user = $usr", + "ORDER BY check_in DESC, id DESC", + ) + .bind("usr", user.record()) + .run(limit, offset, db) + .await +} + +/// Persist corrected instants (manager fix-ups on closed entries; the web +/// layer validates ordering and rejects open entries). +/// `None` = the correction left that instant out, so it is not written at +/// all — the stint's `user` and `check_in`/`check_out` stamps are never +/// replayed from a struct the handler read before its validation awaits. +/// `check_out` is never cleared here: an open stint is refused upstream, so +/// "absent" and "null" both mean keep. +pub async fn update( + db: &Database, + entry: WorkEntry, + check_in: Option, + check_out: Option, +) -> Result { + FieldUpdate::new(entry.get_id().record()) + .set("check_in", check_in) + .set("check_out", check_out) + // Same race closer as the schedule ranges, with this table's own + // field names and message: a correction of one instant is only + // written while it still orders against the other as *stored*. + .ordered("check_in", "check_out", out_before_in_error()) + .run::(db) + .await +} + +pub async fn remove(db: &Database, id: &WorkEntryId) -> Result, AppError> { + Ok(db.delete(id.record()).await?) +} + +#[cfg(test)] +mod tests { + use ulid::Ulid; + + use super::*; + use crate::database; + + #[tokio::test] + async fn check_in_is_exclusive_until_check_out() { + let db = database::init_mem().await.unwrap(); + // A `record` column checks the table of the id, not row + // existence — a fabricated id keeps this test free of user ceremony. + let user = UserId::from_key(&Ulid::new().to_string()); + + let open = check_in(&db, &user).await.unwrap(); + assert!(open.is_open()); + assert_eq!(open.get_id().key(), format!("open_{}", user.key())); + + // Second check-in must not create a second stint or reset the clock. + let dup = check_in(&db, &user).await; + assert!(matches!(dup, Err(AppError::Conflict(_)))); + let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap(); + assert_eq!(entries.len(), 1); + assert_eq!(entries[0].get_check_in(), open.get_check_in()); + + let closed = check_out(&db, &user).await.unwrap(); + assert!(!closed.is_open()); + assert!(closed.get_check_out().unwrap() >= closed.get_check_in()); + + // The open slot is free again; a stray second check-out conflicts. + assert!(matches!( + check_out(&db, &user).await, + Err(AppError::Conflict(_)) + )); + check_in(&db, &user).await.unwrap(); + let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap(); + assert_eq!(entries.len(), 2); + } +} diff --git a/src/domain/attendance.rs b/src/domain/attendance.rs index 9950f5a..3dc2688 100644 --- a/src/domain/attendance.rs +++ b/src/domain/attendance.rs @@ -2,8 +2,8 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{ATTENDANCE_TABLE, REGISTRATION_COUNT_FIELD}; use crate::database::{Database, transaction_with_retry}; -use crate::domain::event::EventId; use crate::db::page::PagedList; +use crate::domain::event::EventId; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -234,7 +234,7 @@ mod tests { /// The session twin's race, one table over /// ([`crate::domain::session_attendance::SessionAttendance`]): a /// `DEFINE EVENT` on `event` fires inside the delete's own transaction, and - /// [`Event::delete`] sweeps its attendance rows before removing the row, so + /// [`crate::db::event::delete`] sweeps its attendance rows before removing the row, so /// the `SLEEP` lands exactly between the sweep and the commit — the window /// where a bare upsert wrote a mark nothing would ever sweep again. /// @@ -246,7 +246,7 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] async fn a_mark_written_inside_a_delete_never_outlives_the_event() { - use crate::domain::event::{Event, EventAudience, EventDescription, EventTitle}; + use crate::domain::event::{EventAudience, EventDescription, EventTitle}; let (db, _serialized) = crate::database::init_test_server("event_attendance_race").await; db.query( "DEFINE EVENT hold_the_window ON TABLE event WHEN $event = 'DELETE' \ @@ -263,21 +263,21 @@ mod tests { let marker = UserId::from_key("t"); let (mut swept, mut orphans) = (0, 0); for round in 0..4 { - let event = Event::create( + let event = crate::db::event::create( + &db, &marker, EventTitle::try_new("gezi").unwrap(), EventDescription::try_new("").unwrap(), EventAudience::School, None, None, - &db, ) .await .unwrap(); let id = event.get_id().clone(); let drop_it = { let db = db.clone(); - tokio::spawn(async move { event.delete(&db).await }) + tokio::spawn(async move { crate::db::event::delete(&db, event).await }) }; // The mark starts inside the held window: the sweep has run and the // event row is gone but uncommitted. @@ -297,7 +297,7 @@ mod tests { ); // Stored state is the whole verdict; a return value is not evidence. - if Event::read(&id, &db).await.unwrap().is_none() { + if crate::db::event::read(&db, &id).await.unwrap().is_none() { swept += 1; orphans += Attendance::list_for_event(&id, None, 0, &db) .await diff --git a/src/domain/event.rs b/src/domain/event.rs index 2094333..d771440 100644 --- a/src/domain/event.rs +++ b/src/domain/event.rs @@ -3,16 +3,12 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue, Value}; use crate::constant::{EVENT_TABLE, MAX_EVENT_DESCRIPTION_LEN, MAX_EVENT_TITLE_LEN}; -use crate::database::{Database, transaction_with_retry}; -use crate::db::field_update::FieldUpdate; use crate::domain::class_group::ClassGroupId; -use crate::domain::class_member::{ClassMember, ClassMemberId}; use crate::domain::course::CourseId; use crate::domain::monotonic_id::next_ulid; -use crate::domain::registration::Registration; use crate::domain::role::Role; -use crate::domain::timestamp::{Timestamp, range_error}; -use crate::domain::user::{User, UserId}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; use crate::validate::{validate_optional, validate_required}; @@ -21,7 +17,7 @@ pub struct EventId(RecordId); impl EventId { /// Minted from the process-wide monotonic generator, not `Ulid::new()`: - /// events list `id DESC` (newest first, [`Event::list_all`]), + /// events list `id DESC` (newest first, [`crate::db::event::list_all`]), /// and a random low half scrambles rows minted in the same millisecond. pub fn generate() -> Self { Self(RecordId::new(EVENT_TABLE, next_ulid().to_string())) @@ -105,91 +101,15 @@ pub enum EventAudience { Registration { capacity: Option }, } -impl EventAudience { - /// Is `user` in `event`'s roster right now? The point check behind - /// marking — cheaper than resolving the whole roster when the target is - /// known. `event` must be the event this audience came from: the - /// registration kind resolves against that event's signup rows. - pub async fn includes( - &self, - event: &EventId, - user: &User, - db: &Database, - ) -> Result { - match self { - EventAudience::School => Ok(true), - EventAudience::Role { role } => Ok(user.get_role() == *role), - EventAudience::Course { course } => { - Ok( - crate::db::enrollment::read_for_user(db, course, user.get_id()) - .await? - .is_some(), - ) - } - // The (class, user) pair is the membership row's own id, so the - // point check is a single select — no scan, no index needed. - EventAudience::Class { class } => { - let member: Option = db - .select(ClassMemberId::composite(class, user.get_id()).record()) - .await?; - Ok(member.is_some()) - } - EventAudience::Registration { .. } => { - Ok(Registration::read_for_user(event, user.get_id(), db) - .await? - .is_some()) - } - } - } - - /// `event`'s full roster, as it stands right now — the who-missed - /// report's backbone. Registered ids that no longer resolve to a user row - /// are kept; the caller degrades their display like any stale reference. - pub async fn members(&self, event: &EventId, db: &Database) -> Result, AppError> { - match self { - EventAudience::School => Ok(crate::db::user::list_all(db, None, 0) - .await? - .0 - .iter() - .map(|user| user.get_id().clone()) - .collect()), - EventAudience::Role { role } => Ok(crate::db::user::list_by_role(db, *role) - .await? - .iter() - .map(|user| user.get_id().clone()) - .collect()), - EventAudience::Course { course } => { - Ok(crate::db::enrollment::list_for_course(db, course, None, 0) - .await? - .0 - .iter() - .map(|enrollment| enrollment.get_user().clone()) - .collect()) - } - EventAudience::Class { class } => Ok(ClassMember::list_for_class(class, None, 0, db) - .await? - .0 - .iter() - .map(|member| member.get_user().clone()) - .collect()), - EventAudience::Registration { .. } => Ok(Registration::list_for_event(event, db) - .await? - .iter() - .map(|registration| registration.get_user().clone()) - .collect()), - } - } -} - #[derive(Debug, Clone, SurrealValue)] pub struct Event { - id: EventId, - creator: UserId, - title: EventTitle, - description: EventDescription, - audience: EventAudience, - starts_at: Option, - ends_at: Option, + pub(crate) id: EventId, + pub(crate) creator: UserId, + pub(crate) title: EventTitle, + pub(crate) description: EventDescription, + pub(crate) audience: EventAudience, + pub(crate) starts_at: Option, + pub(crate) ends_at: Option, } impl Event { @@ -247,203 +167,12 @@ impl Event { } Ok(*capacity) } - - pub async fn create( - creator: &UserId, - title: EventTitle, - description: EventDescription, - audience: EventAudience, - starts_at: Option, - ends_at: Option, - db: &Database, - ) -> Result { - let event = Event { - id: EventId::generate(), - creator: creator.clone(), - title, - description, - audience, - starts_at, - ends_at, - }; - let created: Option = db.create(event.id.record()).content(event).await?; - created.ok_or_else(|| AppError::Internal("failed to create event".into())) - } - - pub async fn read(id: &EventId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - pub async fn list_all(db: &Database) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM event ORDER BY id DESC") - .await? - .check()?; - Ok(result.take::>(0)?) - } - - /// Request-scoped: the handler reads the event, then awaits the clock and a - /// course lookup before saving, holding no lock, so an omitted field - /// (`None`) is not written at all. Passing the snapshot's value back - /// instead would revert a concurrent edit of that field — scoping the `SET` - /// alone does not prevent that, the values have to come from the request. - /// The schedule columns are nullable, so they take the outer/inner - /// `Option>`: `None` = omitted (keep), `Some(None)` = clear. - pub async fn update( - self, - title: Option, - description: Option, - audience: Option, - starts_at: Option>, - ends_at: Option>, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("title", title) - .set("description", description) - .set("audience", audience) - .set("starts_at", starts_at) - .set("ends_at", ends_at) - .ordered("starts_at", "ends_at", range_error()) - .run::(db) - .await - } - - /// Delete the event and cascade-remove its attendance and signup rows. - /// - /// Children first, and all of it in one transaction the way - /// [`crate::db::course::delete`] does it: run as two queries, a - /// registration or a mark that committed in between outlived its event — - /// an orphan no read path can ever reach and no delete can ever reclaim, - /// since every one of them is keyed on the event that is now gone. - /// - /// Re-sent while the store answers "conflict, retry", the way - /// [`crate::db::course_session::delete`] is: now that - /// [`crate::domain::attendance::Attendance::mark`] writes the event row to - /// prove it exists, a mark landing in this window really does contend for - /// it — and without the retry the *delete* is the side that loses, turning - /// a race the store resolved correctly into a 500 (measured 4 rounds in 4). - /// Admissible: every statement is a `DELETE`, which can never answer - /// "already exists", and a lost round wrote nothing. - pub async fn delete(self, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - DELETE attendance WHERE event = $ev; - DELETE registration WHERE event = $ev; - LET $gone = (DELETE $ev RETURN BEFORE); - RETURN $gone; - COMMIT TRANSACTION;", - &[("ev".into(), self.id.record().into_value())], - // No THROW of its own — an unconditional cascade. - &[], - ) - .await?; - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Read through the trailing `RETURN`, never a hand-counted slot. - let slot = result.num_statements().saturating_sub(2); - result - .take::>(slot)? - .into_iter() - .next() - .ok_or(AppError::NotFound) - } } #[cfg(test)] mod tests { use super::*; - /// The forcing function behind the one rule with two spellings: the freeze - /// this file decides in Rust ([`Event::registration_capacity`]) and - /// [`crate::constant::REGISTRATION_FROZEN_GUARD`], its SurrealQL copy, which - /// the role cascade (`service::user::set_role`) carries because it frees a demoted - /// parent's seats inside a transaction and cannot call Rust from there. - /// - /// Every schedule shape is put to both, including the three the SQL is most - /// likely to get wrong: the ends_at-only event (`??` must fall through to - /// it), the boundary itself (closed *at* the instant, not after it — `>=` in - /// Rust, `<=` in SQL, and the two read opposite ways round; `$now` is bound - /// to that exact instant so the boundary is really exercised), and an event - /// that takes no registrations at all, which Rust refuses one arm *earlier* - /// — so the SQL must not report it frozen, or a stray row on it would be - /// preserved forever instead of swept. - #[tokio::test] - async fn the_sql_freeze_guard_matches_the_rust_one() { - use crate::constant::REGISTRATION_FROZEN_GUARD; - - let db = crate::database::init_mem().await.unwrap(); - let now = Timestamp::now().as_millis(); - let past = Some(Timestamp::from_millis(now - 60_000)); - let future = Some(Timestamp::from_millis(now + 3_600_000)); - let later = Some(Timestamp::from_millis(now + 7_200_000)); - let signup = EventAudience::Registration { capacity: None }; - let cases = [ - ("timeless", signup.clone(), None, None), - ("deadline ahead", signup.clone(), None, future), - ("deadline passed", signup.clone(), None, past), - ("starts later", signup.clone(), future, later), - ("already started", signup.clone(), past, None), - ("started, ends later", signup.clone(), past, future), - ( - "closing this instant", - signup.clone(), - Some(Timestamp::from_millis(now)), - None, - ), - // No signup list to freeze: `registration_capacity` refuses these on - // the audience, before it ever looks at the clock. - ("started school event", EventAudience::School, past, None), - ( - "started class event", - EventAudience::Class { - class: ClassGroupId::from_key("g1"), - }, - past, - None, - ), - ]; - for (name, audience, starts_at, ends_at) in cases { - let event = Event::create( - &UserId::from_key("teacher"), - EventTitle::try_new(name).unwrap(), - EventDescription::try_new("").unwrap(), - audience, - starts_at, - ends_at, - &db, - ) - .await - .unwrap(); - let rust = matches!( - event.registration_capacity(), - Err(AppError::Conflict(_) | AppError::ConflictOwned(_)) - ); - let mut result = db - .query(format!( - "SELECT VALUE id FROM $ev WHERE {REGISTRATION_FROZEN_GUARD}" - )) - .bind(("ev", event.get_id().record())) - .bind(("now", now)) - .await - .unwrap() - .check() - .unwrap(); - let sql = !result - .take::>(0) - .unwrap() - .is_empty(); - assert_eq!( - sql, rust, - "the SQL freeze guard and registration_capacity disagree on a \ - {name} event — the role cascade would rewrite a closed signup \ - list, or strand a seat on an open one" - ); - } - } - #[tokio::test] async fn title_is_required() { assert!(EventTitle::try_new("standup").is_ok()); diff --git a/src/domain/pomodoro.rs b/src/domain/pomodoro.rs index 3d9a983..5c2192a 100644 --- a/src/domain/pomodoro.rs +++ b/src/domain/pomodoro.rs @@ -1,17 +1,9 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; -use crate::constant::{ - MAX_COUNTED_POMODORO_PER_DAY, MIN_COUNTED_POMODORO_MS, POMODORO_COUNTED_DAY_FIELD, - POMODORO_COUNTED_TODAY_FIELD, POMODORO_FINISHED_TOTAL_FIELD, POMODORO_FOCUS_MS_TOTAL_FIELD, - POMODORO_SESSION_TABLE, STUDY_STREAK_CURRENT_FIELD, STUDY_STREAK_LAST_DAY_FIELD, - STUDY_STREAK_LONGEST_FIELD, -}; -use crate::database::{Database, transaction_with_retry}; -use crate::domain::badge; +use crate::constant::POMODORO_SESSION_TABLE; use crate::domain::monotonic_id::next_ulid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; -use crate::error::AppError; #[derive(Debug, Clone, PartialEq, Eq, SurrealValue)] pub struct PomodoroSessionId(RecordId); @@ -83,754 +75,11 @@ impl PomodoroSession { self.finished_at } - /// Whether this stint moved the lifetime counters, as [`Self::finish`] - /// judged it. `None` while it is still running — and on any stint closed - /// before the rule existed, which cannot honestly be given a verdict now. + /// Whether this stint moved the lifetime counters, as + /// [`crate::db::pomodoro::finish`] judged it. `None` while it is still + /// running — and on any stint closed before the rule existed, which + /// cannot honestly be given a verdict now. pub fn get_counted(&self) -> Option { self.counted } - - /// Start a session for `user`, stamped with the server clock. `UPSERT` on - /// the deterministic open id makes this atomic and always succeed: a - /// dangling unfinished session (the browser died mid-timer) is replaced — - /// it never counted, and blocking the next start behind it would only - /// punish the student for a crash. - pub async fn start(user: &UserId, db: &Database) -> Result { - let mut result = db - .query("UPSERT $open CONTENT { user: $usr, started_at: $at }") - .bind(("open", PomodoroSessionId::open_for(user).record())) - .bind(("usr", user.record())) - .bind(("at", Timestamp::now())) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or_else(|| AppError::Internal("failed to start pomodoro session".into())) - } - - /// Close `user`'s running session: atomically take the open row and - /// re-file it under a ULID id, freeing the open slot for the next start. - /// Take and re-file share one transaction — a failed re-file rolls the - /// take back, so a session can never vanish half-closed. Of two racing - /// finishes exactly one receives the row (the other gets the conflict). - /// - /// A lost round is re-sent rather than reported (`transaction_with_retry`): - /// the abort wrote nothing, so the whole cascade is safe to repeat, and the - /// `CREATE` cannot answer "already exists" on the way back — the table - /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. - /// Only the guard's own `THROW` is a decision, and it stays a 409. - /// - /// `finished_at` is floored at the row's own `started_at`. Both stamps come - /// from [`Timestamp::now`], i.e. the wall clock, which an NTP step can move - /// *backwards* mid-stint — so a close can legitimately read earlier than its - /// own start with nothing wrong on the client's side. Refusing it would lose - /// a real study session and leave the open slot wedged for a fault the - /// student did not cause; recording a zero-length stint keeps the session - /// count honest and its duration merely understated. Nothing downstream may - /// then read a negative duration (`ProfileStats::load` sums these). - /// - /// The lifetime badge counters on the user row move in this same - /// transaction, so they can never count a stint the log does not hold (nor - /// miss one it does), and a retried round re-applies nothing — the abort - /// rolled the increment back with the rest. They are written field-scoped: - /// the row also carries admin-owned data (`role`), which a whole-row save - /// would silently revert. The clamped duration is the *same* expression the - /// `CREATE` stores (both read `$ms`), so the counter can never take a - /// negative summand and nothing downstream needs a floor. Only *finished* - /// stints reach here — an open row is a `pomodoro_session` row and nothing - /// else — and there is no student-facing delete for a stint, so neither - /// counter ever decrements. - /// - /// They move only for a stint that **counts**, which is - /// [`MIN_COUNTED_POMODORO_MS`] of real focus and at most - /// [`MAX_COUNTED_POMODORO_PER_DAY`] of them per UTC day. Without that this - /// is the farm [`crate::domain::pool_question::PoolQuestion::approve`] - /// argues about from the other end: finishing is self-service, one stint is - /// two requests and no second person, so a counter moved once per - /// round-trip is farmable — two hundred pairs inside the rate limit bought - /// `pomodoro_finished_200` in ninety seconds, and a badge is never revoked. - /// Both stamps are the server's own clock, so the duration needs no - /// distrusting, only a floor. - /// - /// The verdict is *stamped* on the closed row (`counted`), not re-derived - /// later: the thresholds are compiled in and will move, and a reader that - /// re-judged an old stint against today's numbers would answer something - /// other than what was credited. Nothing debits these counters today; the - /// stamp is what lets one be added without that asymmetry. A stint below - /// the bar is still recorded, still listed, and still sums into the log's - /// `total_focus_ms` — the rule bounds what *counts*, never what is kept. - /// - /// The day quota is bucketed like the streak below (midnight UTC, - /// [`Timestamp::day_number`]) and rolls in its own statement ahead of the - /// verdict: that `UPDATE` reads `pomodoro_counted_day` while also setting - /// it, which resolves against the row as it was *before* the statement — - /// the same rule that forces the streak pair apart, used here on purpose. A - /// row that predates the two columns reads as no day at all (`?? -1`), so - /// the first finish after this deploy opens a fresh bucket and no backfill - /// is owed. The bucket write happens whether the stint counts or not; only - /// the `+ 1` sits behind the verdict. - /// - /// The **study streak** rides the same transaction, and the same verdict: a - /// study day is a UTC calendar day on which a stint *counted*, so a day - /// bought with one instant round-trip is not a day studied (midnight UTC, like every - /// other day calculation here — no timezone is stored anywhere): the same - /// day again changes nothing, the next day extends the run, any other gap - /// starts a new one at 1. It is written as **two** statements, not one: - /// every field reference on the right-hand side of a `SET` resolves - /// against the row as it was *before* that statement, so a single - /// `SET current = …, longest = math::max([longest, current])` would take - /// the *old* `current` and lag one write behind forever (probed on a real - /// 3.2.3 server: day two left `current = 2, longest = 1`). Across - /// statements *inside a transaction* the read does see the prior write, so - /// the pair is correct and still atomic. Absent columns are read through - /// `?? 0` (and `?? -1` for the day — a sentinel no real day number - /// reaches), because `math::max` errors outright on a `NONE` argument and - /// every account older than these columns carries none of them. - /// - /// The read-back is `$streak[0].…`, the same shape `$before[0]` uses two - /// lines up: a plain `UPDATE` hands back an array, so a user row that is - /// missing (a `record` column checks only the table of the id) simply - /// yields nothing to index and the second statement matches no row either. - /// `UPDATE ONLY` would work too — it answers `null`, not an error, on zero - /// rows; it errors on *many* — but a `null` is a shape the read then has to - /// special-case, so the file's existing idiom wins. - /// - /// No `cap::counter_lock` is taken, deliberately. The pair cannot tear: - /// both statements sit inside one `BEGIN…COMMIT`, and a real server aborts - /// a rival that touched the row in between — `transaction_with_retry` then - /// re-sends the whole round. And `longest` is written as - /// `max(longest, current)`, which cannot come down under *any* - /// interleaving, so even a torn pair could only under-count `current`, - /// never lower the high-water mark the badges read. The lock would only - /// serialize this process's writers (its other job, keeping the in-memory - /// test engine deterministic, is moot here — these tests are sequential). - /// Probed on a real 3.2.3 server, 2026-08-04: 60 rounds of 4 concurrent - /// finishes for one user left `current = 60, longest = 60` with no - /// anomaly; a rival write forced *between* the two statements (a `sleep` - /// wedged into the batch) aborted the whole cascade with a write conflict, - /// wrote nothing, and left the rival's value standing. - /// - /// Streaks begin at this deploy: nothing reconstructs history from the - /// stint log, so every account starts with no streak columns and its first - /// finish sets a run of 1. - pub async fn finish(user: &UserId, db: &Database) -> Result { - let done = Timestamp::now(); - let (mut result, mut errors) = transaction_with_retry( - db, - &format!( - "BEGIN TRANSACTION; - LET $before = (DELETE $open RETURN BEFORE); - IF array::len($before) = 0 {{ THROW 'no_pomodoro_running' }}; - LET $end = math::max([$before[0].started_at, $done]); - LET $ms = $end - $before[0].started_at; - LET $bucket = (UPDATE $usr SET - {POMODORO_COUNTED_TODAY_FIELD} = - IF ({POMODORO_COUNTED_DAY_FIELD} ?? -1) == $day - THEN ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) ELSE 0 END, - {POMODORO_COUNTED_DAY_FIELD} = $day - RETURN AFTER); - LET $counted = ($ms >= {MIN_COUNTED_POMODORO_MS}) - AND (($bucket[0].{POMODORO_COUNTED_TODAY_FIELD} ?? 0) - < {MAX_COUNTED_POMODORO_PER_DAY}); - IF $counted {{ - UPDATE $usr SET - {POMODORO_FINISHED_TOTAL_FIELD} = - ({POMODORO_FINISHED_TOTAL_FIELD} ?? 0) + 1, - {POMODORO_FOCUS_MS_TOTAL_FIELD} = - ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0) + $ms, - {POMODORO_COUNTED_TODAY_FIELD} = - ({POMODORO_COUNTED_TODAY_FIELD} ?? 0) + 1; - LET $streak = (UPDATE $usr SET - {STUDY_STREAK_CURRENT_FIELD} = - IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == $day - THEN ({STUDY_STREAK_CURRENT_FIELD} ?? 0) - ELSE IF ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1) == ($day - 1) - THEN (({STUDY_STREAK_CURRENT_FIELD} ?? 0) + 1) - ELSE 1 END, - {STUDY_STREAK_LAST_DAY_FIELD} = $day - RETURN AFTER); - UPDATE $usr SET {STUDY_STREAK_LONGEST_FIELD} = math::max([ - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), - ($streak[0].{STUDY_STREAK_CURRENT_FIELD} ?? 0)]) - }}; - CREATE $closed CONTENT {{ - user: $before[0].user, - started_at: $before[0].started_at, - finished_at: $end, - counted: $counted, - }}; - COMMIT TRANSACTION;" - ), - &[ - ( - "open".into(), - PomodoroSessionId::open_for(user).record().into_value(), - ), - ("usr".into(), user.record().into_value()), - ( - "closed".into(), - PomodoroSessionId::generate().record().into_value(), - ), - ("done".into(), done.into_value()), - ("day".into(), done.day_number().into_value()), - ], - &["no_pomodoro_running"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the THROW's own slot names the reason, so scan - // them all for the marker instead of trusting the first. - if errors - .values() - .any(|error| error.to_string().contains("no_pomodoro_running")) - { - return Err(AppError::Conflict("no pomodoro session running")); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // The `CREATE` is deliberately kept the last statement before `COMMIT` - // (the counter `UPDATE` sits ahead of it — same transaction, so the - // order is free), which is what lets its slot follow the statement - // count instead of a hand-kept number: `num_statements` counts `BEGIN` - // and `COMMIT` too, hence -2. See `ExamResult::record` for the bug a - // hand-kept slot caused. - let slot = result.num_statements().saturating_sub(2); - let saved: Option = result - .take::>(slot)? - .into_iter() - .next(); - let saved = - saved.ok_or_else(|| AppError::Internal("failed to close pomodoro session".into()))?; - // A badge is a decoration on top of the stint: losing one to a - // transient database error must never fail the finish, and the next - // counter move re-runs this and heals it. - if let Err(err) = badge::sync(user, db).await { - tracing::warn!("failed to sync badges for {}: {err}", user.key()); - } - Ok(saved) - } - - /// Every session of `user`, newest first — the running one (if any) - /// included. Ordered by `started_at`, never by id alone: the open entry's - /// `open_` key doesn't sort with the ULIDs, so id order would misplace it. - /// The `id` tie-break behind it only ever separates two *finished* stints - /// sharing a `started_at` — there is one running row per user, so it can - /// never tie with itself. - pub async fn list_for_user( - user: &UserId, - db: &Database, - ) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM pomodoro_session WHERE user = $usr ORDER BY started_at DESC, id DESC") - .bind(("usr", user.record())) - .await? - .check()?; - Ok(result.take::>(0)?) - } -} - -#[cfg(test)] -mod tests { - use ulid::Ulid; - - use super::*; - use crate::database; - - /// A real `user` row: the counters land with `UPDATE`, which only ever - /// touches a record that exists, so a fabricated id would silently store - /// nothing. The tests above need no row — they read only the stint log. - async fn a_user(db: &Database) -> UserId { - let user = UserId::from_key(&Ulid::new().to_string()); - db.query("CREATE $usr SET username = $name, password_hash = 'x'") - .bind(("usr", user.record())) - .bind(("name", user.key().to_string())) - .await - .unwrap() - .check() - .unwrap(); - user - } - - /// `(finished_total, focus_ms_total)` re-read from the store — never off - /// what `finish` returned, which proves nothing about what was written. - async fn counters(user: &UserId, db: &Database) -> (i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({POMODORO_FINISHED_TOTAL_FIELD} ?? 0), - ({POMODORO_FOCUS_MS_TOTAL_FIELD} ?? 0)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - let row = rows.into_iter().next().expect("the user row"); - (row[0], row[1]) - } - - /// `(current, longest, last_day)` re-read from the store. - async fn streak(user: &UserId, db: &Database) -> (i64, i64, i64) { - let mut result = db - .query(format!( - "SELECT VALUE [({STUDY_STREAK_CURRENT_FIELD} ?? 0), - ({STUDY_STREAK_LONGEST_FIELD} ?? 0), - ({STUDY_STREAK_LAST_DAY_FIELD} ?? -1)] FROM $usr" - )) - .bind(("usr", user.record())) - .await - .unwrap() - .check() - .unwrap(); - let rows: Vec> = result.take(0).unwrap(); - let row = rows.into_iter().next().expect("the user row"); - (row[0], row[1], row[2]) - } - - /// Age *both* day buckets by `days`, so the next finish lands that many - /// days later on the calendar — the streak's and the day quota's, since - /// they are the same calendar and a test that moved one would be asserting - /// against a day the other has never heard of. The day is injected into the - /// stored state rather than into the clock, which keeps `Timestamp::now` - /// the sole clock read and the test free of sleeping. - /// - /// Known flake, left as-is: every caller assumes the UTC day does not turn - /// over mid-test — a crossing between two stints shifts the real day under - /// the injected one and reddens the run. That is one ~ms-wide window per - /// day (~5e-6 per run), and the alternative is a clock seam in production - /// code to serve a test. Re-run before believing a failure that only ever - /// happens near midnight UTC. - async fn age_by_days(user: &UserId, db: &Database, days: i64) { - db.query(format!( - "UPDATE $usr SET - {STUDY_STREAK_LAST_DAY_FIELD} = {STUDY_STREAK_LAST_DAY_FIELD} - $days, - {POMODORO_COUNTED_DAY_FIELD} = ({POMODORO_COUNTED_DAY_FIELD} ?? -1) - $days" - )) - .bind(("usr", user.record())) - .bind(("days", days)) - .await - .unwrap() - .check() - .unwrap(); - } - - /// Open a stint that has already been running for `ms` — the stamp the - /// close measures against, injected instead of slept through. - /// - /// One `UPSERT`, not `start` followed by a backdate: the concurrent test - /// races four of these onto the same open row, and a separate backdate can - /// be wiped by a rival's fresh `start`, handing whoever wins the `DELETE` a - /// zero-length stint and reddening the run for no defect. Same statement - /// `start` runs, one clock read earlier. - async fn start_aged(user: &UserId, db: &Database, ms: i64) -> Result<(), AppError> { - db.query("UPSERT $open CONTENT { user: $usr, started_at: $at }") - .bind(("open", PomodoroSessionId::open_for(user).record())) - .bind(("usr", user.record())) - .bind(("at", Timestamp::now().as_millis() - ms)) - .await? - .check()?; - Ok(()) - } - - /// Start and close one stint that counts: exactly the minimum on the clock, - /// so every streak assertion below is about the day and not the duration. - async fn one_stint(user: &UserId, db: &Database) { - start_aged(user, db, MIN_COUNTED_POMODORO_MS).await.unwrap(); - PomodoroSession::finish(user, db).await.unwrap(); - } - - #[tokio::test] - async fn consecutive_days_extend_the_streak_and_a_repeat_day_does_not() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - // The stale-data case: a row that predates all three columns reads as - // no streak at all, and its first finish opens a run of one. - assert_eq!(streak(&user, &db).await, (0, 0, -1)); - - one_stint(&user, &db).await; - let today = Timestamp::now().day_number(); - assert_eq!(streak(&user, &db).await, (1, 1, today)); - - // A second stint the same day is not a second day. - one_stint(&user, &db).await; - assert_eq!(streak(&user, &db).await, (1, 1, today)); - - // Days N+1 and N+2. - for day in 2..=3 { - age_by_days(&user, &db, 1).await; - one_stint(&user, &db).await; - assert_eq!(streak(&user, &db).await, (day, day, today)); - } - } - - #[tokio::test] - async fn a_gap_resets_the_run_but_never_the_high_water_mark() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - - one_stint(&user, &db).await; - age_by_days(&user, &db, 1).await; - one_stint(&user, &db).await; - assert_eq!(streak(&user, &db).await.0, 2); - - // Skip a day: the run restarts at one, the longest stays where it got. - age_by_days(&user, &db, 2).await; - one_stint(&user, &db).await; - let (current, longest, _) = streak(&user, &db).await; - assert_eq!((current, longest), (1, 2)); - - // A backwards day (a clock stepped back over a boundary) is a gap too, - // and still cannot lower the mark. - age_by_days(&user, &db, -5).await; - one_stint(&user, &db).await; - assert_eq!( - streak(&user, &db).await, - (1, 2, Timestamp::now().day_number()) - ); - } - - /// The transaction boundary itself, on a real server: the streak pair and - /// the counters must commit with the stint or not at all, under real - /// contention on one user row. - /// - /// Multi-threaded and off the embedded engine for the reason - /// [`crate::db::cap`] spells out: the in-memory engine does not - /// conflict-check two concurrent writes to one record, so it would answer - /// `Ok` to a write it dropped and *forge* the integrity failure this test - /// exists to catch. - /// - /// It bites — proved by mutation, not assumed: deleting the `BEGIN`/`COMMIT` - /// pair from the batch turns all 20 rounds red. A `THROW` then errors only - /// its own statement, so the losers of the open-row race run the rest of - /// the cascade anyway — they bump the counters for a stint they never - /// closed and `CREATE` a session row out of an empty `$before`, which comes - /// back as `500 … Expected record, got none` (the `errors` assertion below - /// fires first; `finished_total` running ahead of the `Ok` finishes is the - /// same wound one statement later). What it does *not* pin is the - /// streak arithmetic under concurrency: same-day finishes all compute the - /// same value, so that stays green either way — it is - /// `max(longest, current)` that makes that robust, not the isolation. - /// - /// The shape of the contention, measured rather than assumed: four racers - /// per round is four `start`s collapsing onto *one* open row (the id is - /// deterministic per user), so typically exactly one `finish` commits and - /// three lose the `DELETE` and abort their whole cascade — 20 finishes and - /// 60 conflicts over 20 rounds, measured. That is the contention: the - /// losers' cascades are live against the same user row, which is precisely - /// what must leave nothing behind. Two commits in one round are possible - /// (a racer scheduled entirely after another's finish frees the slot) and - /// the assertions allow it — the day count is per round, not per stint. - #[tokio::test(flavor = "multi_thread", worker_threads = 4)] - #[ignore = "needs a real SurrealDB server: podman start hezarfen-surrealdb && cargo test -- --ignored"] - async fn concurrent_finishes_commit_the_streak_with_the_stint_or_not_at_all() { - let (db, _serialized) = crate::database::init_test_server("pomodoro_streak_race").await; - let user = a_user(&db).await; - let (mut finished, mut conflicts, mut errors) = (0, 0, 0); - let mut last_error = String::new(); - for round in 1..=20 { - let racers: Vec<_> = (0..4) - .map(|_| { - let (user, db) = (user.clone(), db.clone()); - tokio::spawn(async move { - // Aged past the minimum, so whichever racer wins the - // open row closes a stint that *counts* — a fresh - // `start` here would hand the winner a zero-length - // stint, which now moves nothing and would leave this - // test asserting against an untouched counter. - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS).await?; - PomodoroSession::finish(&user, &db).await - }) - }) - .collect(); - let mut won = 0; - for racer in racers { - match racer.await.unwrap() { - Ok(_) => won += 1, - // Losing the open row is the correct answer for a racer - // whose stint someone else closed; only `Db` is a defect. - Err(AppError::Conflict(_)) => conflicts += 1, - Err(err) => { - errors += 1; - last_error = format!("{err:?}"); - } - } - } - finished += won; - // One day per round, however many stints landed in it, and the - // mark never lags the run in progress. - let (current, longest, _) = streak(&user, &db).await; - assert_eq!( - (current, longest), - (round, round), - "round {round} counted {won} finishes as {current} days" - ); - age_by_days(&user, &db, 1).await; - } - // The atomicity claim: the counter counts exactly the stints that were - // closed, never a loser's aborted round. - let (counted, _) = counters(&user, &db).await; - eprintln!( - "PomodoroSession::finish raced: {finished} finishes over 20 days, \ - {conflicts} rivals refused, {errors} 500s" - ); - assert_eq!( - errors, 0, - "a raced finish must conflict, not 500: {last_error}" - ); - assert_eq!( - counted, finished, - "the counter counted {counted} stints for {finished} finishes" - ); - assert!( - conflicts > 0, - "every racer won its own round, so no cascade was ever aborted mid-flight \ - and this run proves nothing about the transaction boundary" - ); - } - - #[tokio::test] - async fn finishing_bumps_the_stored_counters_and_an_open_stint_bumps_neither() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - assert_eq!(counters(&user, &db).await, (0, 0)); - - // An open stint is not a finished one: neither counter moves until it - // closes. - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) - .await - .unwrap(); - assert_eq!(counters(&user, &db).await, (0, 0)); - - let mut focus_ms = 0; - for _ in 0..2 { - let closed = PomodoroSession::finish(&user, &db).await.unwrap(); - focus_ms += - closed.get_finished_at().unwrap().as_millis() - closed.get_started_at().as_millis(); - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) - .await - .unwrap(); - } - // Three starts, two finishes — the third is still running. - assert_eq!(counters(&user, &db).await, (2, focus_ms)); - } - - #[tokio::test] - async fn a_backwards_clock_adds_zero_ms_to_the_counter_never_a_negative() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - - PomodoroSession::start(&user, &db).await.unwrap(); - db.query("UPDATE $open SET started_at = $future") - .bind(("open", PomodoroSessionId::open_for(&user).record())) - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) - .await - .unwrap() - .check() - .unwrap(); - - // The clamp holds: zero milliseconds, never a negative — and a stint - // measuring zero is below the minimum, so it moves neither counter. - let closed = PomodoroSession::finish(&user, &db).await.unwrap(); - assert_eq!(closed.get_counted(), Some(false)); - assert_eq!(counters(&user, &db).await, (0, 0)); - } - - /// The minimum, from both sides. A round-trip is not a study session, and - /// the boundary is inclusive (`>=`) — a stint of exactly the minimum - /// counts, which is the side these assertions pin. - /// - /// The near miss is a whole minute short, not one millisecond: `finish` - /// reads its own clock *after* the stint is opened, so a stint aged to - /// exactly one millisecond under the bar crosses it by the time the close - /// measures it (measured — that assertion failed on the first run). A - /// millisecond-exact probe would need a clock seam in production code, and - /// what matters here is the four orders of magnitude between a scripted - /// pair and a study session, not the last millisecond. - #[tokio::test] - async fn a_stint_under_the_minimum_is_logged_and_listed_but_counts_for_nothing() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS - 60_000) - .await - .unwrap(); - let short = PomodoroSession::finish(&user, &db).await.unwrap(); - assert_eq!(short.get_counted(), Some(false)); - assert_eq!(counters(&user, &db).await, (0, 0)); - // Not a study day either — and no streak column was even opened. - assert_eq!(streak(&user, &db).await, (0, 0, -1)); - // But it happened, and the log says so. - let log = PomodoroSession::list_for_user(&user, &db).await.unwrap(); - assert_eq!(log.len(), 1); - assert_eq!(log[0].get_finished_at(), short.get_finished_at()); - - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) - .await - .unwrap(); - let counted = PomodoroSession::finish(&user, &db).await.unwrap(); - assert_eq!(counted.get_counted(), Some(true)); - let (finished, focus_ms) = counters(&user, &db).await; - // The counter took the *same* duration the row stores, not a second - // reading of the clock. - assert_eq!( - (finished, focus_ms), - ( - 1, - counted.get_finished_at().unwrap().as_millis() - - counted.get_started_at().as_millis() - ) - ); - assert_eq!(streak(&user, &db).await.0, 1); - assert_eq!( - PomodoroSession::list_for_user(&user, &db) - .await - .unwrap() - .len(), - 2 - ); - } - - /// The day quota: it stops the counter, it never stops the log, and it - /// rolls at midnight UTC. - #[tokio::test] - async fn the_day_quota_caps_the_counter_and_rolls_at_midnight_utc() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - - for _ in 0..MAX_COUNTED_POMODORO_PER_DAY { - one_stint(&user, &db).await; - } - let (finished, focus_ms) = counters(&user, &db).await; - assert_eq!(finished, MAX_COUNTED_POMODORO_PER_DAY); - - // Past the quota: recorded, listed, worth nothing — neither stint count - // nor focus milliseconds. - for _ in 0..3 { - start_aged(&user, &db, MIN_COUNTED_POMODORO_MS) - .await - .unwrap(); - let over = PomodoroSession::finish(&user, &db).await.unwrap(); - assert_eq!(over.get_counted(), Some(false)); - } - assert_eq!(counters(&user, &db).await, (finished, focus_ms)); - assert_eq!( - PomodoroSession::list_for_user(&user, &db) - .await - .unwrap() - .len() as i64, - MAX_COUNTED_POMODORO_PER_DAY + 3 - ); - // The quota is a day's, not a lifetime's. - age_by_days(&user, &db, 1).await; - one_stint(&user, &db).await; - assert_eq!( - counters(&user, &db).await.0, - MAX_COUNTED_POMODORO_PER_DAY + 1 - ); - } - - /// The farm, run: `start`/`finish` in a loop is two requests a round with - /// no second person in it, which used to move `pomodoro_finished_total` one - /// per round — 200 of them minted `pomodoro_finished_10`, `_50` and `_200`, - /// and a badge is never taken back. - #[tokio::test] - async fn the_start_finish_farm_moves_no_counter_and_mints_no_badge() { - let db = database::init_mem().await.unwrap(); - let user = a_user(&db).await; - - for _ in 0..200 { - PomodoroSession::start(&user, &db).await.unwrap(); - PomodoroSession::finish(&user, &db).await.unwrap(); - } - assert_eq!(counters(&user, &db).await, (0, 0)); - assert_eq!(streak(&user, &db).await, (0, 0, -1)); - // Every one of them is still the student's own history. - assert_eq!( - PomodoroSession::list_for_user(&user, &db) - .await - .unwrap() - .len(), - 200 - ); - assert!( - badge::BadgeAward::list_for(&user, &db) - .await - .unwrap() - .is_empty(), - "the farm minted a permanent badge" - ); - - // And paying the minimum for each one only buys the day's quota. - for _ in 0..(MAX_COUNTED_POMODORO_PER_DAY * 2) { - one_stint(&user, &db).await; - } - assert_eq!(counters(&user, &db).await.0, MAX_COUNTED_POMODORO_PER_DAY); - } - - #[tokio::test] - async fn restart_replaces_the_open_session_and_finish_closes_it() { - let db = database::init_mem().await.unwrap(); - // A `record` column checks the table of the id, not row - // existence — a fabricated id keeps this test free of user ceremony. - let user = UserId::from_key(&Ulid::new().to_string()); - - // Nothing running yet — finishing conflicts. - assert!(matches!( - PomodoroSession::finish(&user, &db).await, - Err(AppError::Conflict(_)) - )); - - let first = PomodoroSession::start(&user, &db).await.unwrap(); - assert!(first.get_finished_at().is_none()); - assert_eq!(first.get_id().key(), format!("open_{}", user.key())); - - // A restart replaces the dangling session: still one row, fresh clock. - let second = PomodoroSession::start(&user, &db).await.unwrap(); - assert!(second.get_started_at() >= first.get_started_at()); - let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); - assert_eq!(sessions.len(), 1); - - let closed = PomodoroSession::finish(&user, &db).await.unwrap(); - assert!(closed.get_finished_at().unwrap() >= closed.get_started_at()); - - // The open slot is free again; a stray second finish conflicts. - assert!(matches!( - PomodoroSession::finish(&user, &db).await, - Err(AppError::Conflict(_)) - )); - PomodoroSession::start(&user, &db).await.unwrap(); - let sessions = PomodoroSession::list_for_user(&user, &db).await.unwrap(); - assert_eq!(sessions.len(), 2); - } - - #[tokio::test] - async fn a_backwards_clock_records_a_zero_stint_not_a_negative_one() { - let db = database::init_mem().await.unwrap(); - let user = UserId::from_key(&Ulid::new().to_string()); - - PomodoroSession::start(&user, &db).await.unwrap(); - // Stand in for the NTP step: push the running stint's start an hour - // ahead, so the server clock `finish` reads is *behind* it. - db.query("UPDATE $open SET started_at = $future") - .bind(("open", PomodoroSessionId::open_for(&user).record())) - .bind(("future", Timestamp::now().as_millis() + 3_600_000)) - .await - .unwrap() - .check() - .unwrap(); - - let closed = PomodoroSession::finish(&user, &db).await.unwrap(); - let started = closed.get_started_at().as_millis(); - assert_eq!(closed.get_finished_at().unwrap().as_millis(), started); - - // And the stat that sums these stays non-negative. - let stats = crate::domain::profile::ProfileStats::load(&user, 0, 0, &db) - .await - .unwrap(); - assert_eq!(stats.get_pomodoro_sessions(), 1); - assert_eq!(stats.get_pomodoro_focus_ms(), 0); - } } diff --git a/src/domain/profile.rs b/src/domain/profile.rs index 71ff2e8..3f20dd0 100644 --- a/src/domain/profile.rs +++ b/src/domain/profile.rs @@ -241,7 +241,7 @@ impl ProfileStats { // Floored at zero: a stint stamped by a wall clock that stepped // backwards mid-session sums as negative time, and "you focused for // minus five seconds" is never the truthful answer. New stints - // cannot go inverted (see [`PomodoroSession::finish`]); rows written + // cannot go inverted (see [`crate::db::pomodoro::finish`]); rows written // before that guard still can, and this is what covers them. pomodoro_focus_ms: row.map_or(0, |totals| totals.focus_ms.max(0)), courses, diff --git a/src/domain/registration.rs b/src/domain/registration.rs index 14dd932..1863edb 100644 --- a/src/domain/registration.rs +++ b/src/domain/registration.rs @@ -3,7 +3,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::{REGISTRATION_COUNT_FIELD, REGISTRATION_TABLE}; use crate::database::Database; use crate::db::cap; -use crate::domain::event::{Event, EventId}; +use crate::domain::event::EventId; use crate::domain::role::Role; use crate::domain::user::UserId; use crate::error::AppError; @@ -94,7 +94,7 @@ impl Registration { } // Read for its refusals only — the audience kind and the closing time. // The seat count itself is re-read by the claim. - Event::read(event, db) + crate::db::event::read(db, event) .await? .ok_or(AppError::NotFound)? .registration_capacity()?; @@ -131,7 +131,7 @@ impl Registration { // the holder fell to parent while this ran — the conditional writes // match nothing (or throw) either way, and only this path pays for // the reads that tell them apart. - cap::Claimed::Full => match Event::read(event, db).await? { + cap::Claimed::Full => match crate::db::event::read(db, event).await? { None => Err(AppError::NotFound), Some(_) => match crate::db::user::read(db, user).await? { Some(held) if held.get_role() == Role::Parent => Err(AppError::Forbidden( diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index 494f473..4b20fdd 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -1,10 +1,7 @@ use surrealdb::types::{RecordId, RecordIdKey, SurrealValue}; use crate::constant::WORK_ENTRY_TABLE; -use crate::database::{Database, transaction_with_retry}; -use crate::db::field_update::FieldUpdate; use crate::domain::monotonic_id::next_ulid; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; @@ -65,10 +62,10 @@ impl WorkEntryId { /// through an explicit endpoint instead). #[derive(Debug, Clone, SurrealValue)] pub struct WorkEntry { - id: WorkEntryId, - user: UserId, - check_in: Timestamp, - check_out: Option, + pub(crate) id: WorkEntryId, + pub(crate) user: UserId, + pub(crate) check_in: Timestamp, + pub(crate) check_out: Option, } impl WorkEntry { @@ -91,175 +88,4 @@ impl WorkEntry { pub fn is_open(&self) -> bool { self.check_out.is_none() } - - /// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE` - /// on the deterministic open id makes this atomic: if an open entry - /// already exists the insert is skipped (empty result) and the caller gets - /// a conflict — two racing check-ins can never create two open rows or - /// reset a running clock. - pub async fn check_in(user: &UserId, db: &Database) -> Result { - let entry = WorkEntry { - id: WorkEntryId::open_for(user), - user: user.clone(), - check_in: Timestamp::now(), - check_out: None, - }; - let mut result = db - .query("INSERT IGNORE INTO work_entry $entry") - .bind(("entry", entry)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::Conflict("already checked in — check out first")) - } - - /// Close `user`'s open stint: atomically take the open row and re-file it - /// under a ULID id, freeing the open slot for the next check-in. Take and - /// re-file share one transaction — a failed re-file rolls the take back, - /// so a stint can never vanish half-closed. Of two racing check-outs - /// exactly one receives the row (the other gets the conflict). - /// - /// A lost round is re-sent rather than reported (`transaction_with_retry`): - /// the abort wrote nothing, so the whole cascade is safe to repeat, and the - /// `CREATE` cannot answer "already exists" on the way back — the table - /// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. - /// Only the guard's own `THROW` is a decision, and it stays a 409. - pub async fn check_out(user: &UserId, db: &Database) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $before = (DELETE $open RETURN BEFORE); - IF array::len($before) = 0 { THROW 'not_checked_in' }; - CREATE $closed CONTENT { - user: $before[0].user, - check_in: $before[0].check_in, - check_out: $out, - }; - COMMIT TRANSACTION;", - &[ - ( - "open".into(), - WorkEntryId::open_for(user).record().into_value(), - ), - ( - "closed".into(), - WorkEntryId::generate().record().into_value(), - ), - ("out".into(), Timestamp::now().into_value()), - ], - &["not_checked_in"], - ) - .await?; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the THROW's own slot names the reason, so scan - // them all for the marker instead of trusting the first. - if errors - .values() - .any(|error| error.to_string().contains("not_checked_in")) - { - return Err(AppError::Conflict("not checked in")); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. - let saved: Option = result.take::>(3)?.into_iter().next(); - saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) - } - - pub async fn read(id: &WorkEntryId, db: &Database) -> Result, AppError> { - Ok(db.select(id.record()).await?) - } - - /// Every stint of `user`, newest first — the open one (if any) included. - /// Ordered by `check_in`, never by id alone: the open entry's `open_` key - /// doesn't sort with the ULIDs, so id order would misplace it. The `id` - /// tie-break behind it only ever separates two *closed* stints sharing a - /// `check_in` — there is one open row per user, so it can never tie with - /// itself — and that is what keeps offset paging from skipping a row. - pub async fn list_for_user( - user: &UserId, - limit: Option, - offset: i64, - db: &Database, - ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "work_entry WHERE user = $usr", - "ORDER BY check_in DESC, id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await - } - - /// Persist corrected instants (manager fix-ups on closed entries; the web - /// layer validates ordering and rejects open entries). - /// `None` = the correction left that instant out, so it is not written at - /// all — the stint's `user` and `check_in`/`check_out` stamps are never - /// replayed from a struct the handler read before its validation awaits. - /// `check_out` is never cleared here: an open stint is refused upstream, so - /// "absent" and "null" both mean keep. - pub async fn update( - self, - check_in: Option, - check_out: Option, - db: &Database, - ) -> Result { - FieldUpdate::new(self.id.record()) - .set("check_in", check_in) - .set("check_out", check_out) - // Same race closer as the schedule ranges, with this table's own - // field names and message: a correction of one instant is only - // written while it still orders against the other as *stored*. - .ordered("check_in", "check_out", out_before_in_error()) - .run::(db) - .await - } - - pub async fn remove(id: &WorkEntryId, db: &Database) -> Result, AppError> { - Ok(db.delete(id.record()).await?) - } -} - -#[cfg(test)] -mod tests { - use ulid::Ulid; - - use super::*; - use crate::database; - - #[tokio::test] - async fn check_in_is_exclusive_until_check_out() { - let db = database::init_mem().await.unwrap(); - // A `record` column checks the table of the id, not row - // existence — a fabricated id keeps this test free of user ceremony. - let user = UserId::from_key(&Ulid::new().to_string()); - - let open = WorkEntry::check_in(&user, &db).await.unwrap(); - assert!(open.is_open()); - assert_eq!(open.get_id().key(), format!("open_{}", user.key())); - - // Second check-in must not create a second stint or reset the clock. - let dup = WorkEntry::check_in(&user, &db).await; - assert!(matches!(dup, Err(AppError::Conflict(_)))); - let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap(); - assert_eq!(entries.len(), 1); - assert_eq!(entries[0].get_check_in(), open.get_check_in()); - - let closed = WorkEntry::check_out(&user, &db).await.unwrap(); - assert!(!closed.is_open()); - assert!(closed.get_check_out().unwrap() >= closed.get_check_in()); - - // The open slot is free again; a stray second check-out conflicts. - assert!(matches!( - WorkEntry::check_out(&user, &db).await, - Err(AppError::Conflict(_)) - )); - WorkEntry::check_in(&user, &db).await.unwrap(); - let (entries, _) = WorkEntry::list_for_user(&user, None, 0, &db).await.unwrap(); - assert_eq!(entries.len(), 2); - } } diff --git a/src/service/event.rs b/src/service/event.rs new file mode 100644 index 0000000..991c872 --- /dev/null +++ b/src/service/event.rs @@ -0,0 +1,82 @@ +//! Event surfacing: the calendar's create/read/update/delete and the +//! audience's live membership resolution. The queries live in +//! [`crate::db::event`]; there is no workflow of this domain's own — every +//! write is a single atomic statement or transaction, and the freeze rule +//! the signup flow leans on is the pure +//! [`crate::domain::event::Event::registration_capacity`]. + +use crate::database::Database; +use crate::db::event; +use crate::domain::event::{Event, EventAudience, EventDescription, EventId, EventTitle}; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::{User, UserId}; +use crate::error::AppError; + +pub async fn create( + db: &Database, + creator: &UserId, + title: EventTitle, + description: EventDescription, + audience: EventAudience, + starts_at: Option, + ends_at: Option, +) -> Result { + event::create( + db, + creator, + title, + description, + audience, + starts_at, + ends_at, + ) + .await +} + +pub async fn read(db: &Database, id: &EventId) -> Result, AppError> { + event::read(db, id).await +} + +/// Every event, newest first. +pub async fn list_all(db: &Database) -> Result, AppError> { + event::list_all(db).await +} + +/// Only what the request carried is written: an omitted field (`None`) is +/// not stored at all. The schedule columns take the set-or-clear spelling. +pub async fn update( + db: &Database, + event: Event, + title: Option, + description: Option, + audience: Option, + starts_at: Option>, + ends_at: Option>, +) -> Result { + event::update(db, event, title, description, audience, starts_at, ends_at).await +} + +/// Delete the event and cascade its attendance and signup rows. +pub async fn delete(db: &Database, event: Event) -> Result { + event::delete(db, event).await +} + +/// Is `user` in the event's audience roster right now — the point check +/// behind marking. +pub async fn includes( + db: &Database, + audience: &EventAudience, + event: &EventId, + user: &User, +) -> Result { + event::includes(db, audience, event, user).await +} + +/// The event's full expected-attendee roster, resolved live. +pub async fn members( + db: &Database, + audience: &EventAudience, + event: &EventId, +) -> Result, AppError> { + event::members(db, audience, event).await +} diff --git a/src/service/mod.rs b/src/service/mod.rs index 691aa94..ee45319 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -7,12 +7,15 @@ pub mod class_blueprint; pub mod course; pub mod course_session; pub mod enrollment; +pub mod event; pub mod exam; pub mod exam_attempt; pub mod exam_question; pub mod meal_booking; pub mod note; pub mod payment_ledger; +pub mod pomodoro; pub mod session; pub mod settings; pub mod user; +pub mod work_entry; diff --git a/src/service/pomodoro.rs b/src/service/pomodoro.rs new file mode 100644 index 0000000..a9116a6 --- /dev/null +++ b/src/service/pomodoro.rs @@ -0,0 +1,25 @@ +//! Pomodoro surfacing: the start/finish pair and the log the timer drives. +//! The queries live in [`crate::db::pomodoro`]; the counting verdict, the +//! lifetime counters, and the study streak are decided inside `finish`'s +//! single transaction there — there is no workflow of this domain's own. + +use crate::database::Database; +use crate::db::pomodoro; +use crate::domain::pomodoro::PomodoroSession; +use crate::domain::user::UserId; +use crate::error::AppError; + +pub async fn start(db: &Database, user: &UserId) -> Result { + pomodoro::start(db, user).await +} + +/// Close the running session (`409` when none runs); the returned row +/// carries the `counted` verdict. +pub async fn finish(db: &Database, user: &UserId) -> Result { + pomodoro::finish(db, user).await +} + +/// Every session of `user`, newest first — the running one included. +pub async fn list_for_user(db: &Database, user: &UserId) -> Result, AppError> { + pomodoro::list_for_user(db, user).await +} diff --git a/src/service/work_entry.rs b/src/service/work_entry.rs new file mode 100644 index 0000000..acc2f06 --- /dev/null +++ b/src/service/work_entry.rs @@ -0,0 +1,51 @@ +//! Work-log surfacing: the check-in/check-out pair, the staff log, and the +//! manager corrections. The queries live in +//! [`crate::db::work_entry`] — both transitions are single atomic writes on +//! the deterministic open id (`INSERT IGNORE` in, take-and-refile out), so +//! this domain has no workflow of its own. + +use crate::database::Database; +use crate::db::work_entry; +use crate::domain::timestamp::Timestamp; +use crate::domain::user::UserId; +use crate::domain::work_entry::WorkEntry; +use crate::domain::work_entry::WorkEntryId; +use crate::error::AppError; + +/// Check in (`409` while already checked in). +pub async fn check_in(db: &Database, user: &UserId) -> Result { + work_entry::check_in(db, user).await +} + +/// Check out (`409` when not checked in). +pub async fn check_out(db: &Database, user: &UserId) -> Result { + work_entry::check_out(db, user).await +} + +pub async fn read(db: &Database, id: &WorkEntryId) -> Result, AppError> { + work_entry::read(db, id).await +} + +/// Every stint of `user`, newest first — the open one included. +pub async fn list_for_user( + db: &Database, + user: &UserId, + limit: Option, + offset: i64, +) -> Result<(Vec, i64), AppError> { + work_entry::list_for_user(db, user, limit, offset).await +} + +/// Persist corrected instants on a closed entry; `None` keeps the field. +pub async fn update( + db: &Database, + entry: WorkEntry, + check_in: Option, + check_out: Option, +) -> Result { + work_entry::update(db, entry, check_in, check_out).await +} + +pub async fn remove(db: &Database, id: &WorkEntryId) -> Result, AppError> { + work_entry::remove(db, id).await +} diff --git a/src/web/boards.rs b/src/web/boards.rs index d816d0c..4544096 100644 --- a/src/web/boards.rs +++ b/src/web/boards.rs @@ -35,7 +35,7 @@ use crate::domain::board_stroke::BoardStroke; use crate::domain::class_group::{ClassGroup, ClassGroupId}; use crate::domain::class_member::ClassMember; use crate::domain::course::CourseId; -use crate::domain::event::{Event, EventId}; +use crate::domain::event::EventId; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -767,13 +767,13 @@ impl InviteSource { "requires teacher role or higher to invite an event's roster", )); } - let event = Event::read(&EventId::from_key(&event), db).await?.ok_or( - AppError::Validation(ValidationError::Invalid { + let event = crate::service::event::read(db, &EventId::from_key(&event)) + .await? + .ok_or(AppError::Validation(ValidationError::Invalid { field: "event", reason: "no such event", - }), - )?; - event.get_audience().members(event.get_id(), db).await + }))?; + crate::service::event::members(db, event.get_audience(), event.get_id()).await } } } diff --git a/src/web/events.rs b/src/web/events.rs index 68c82cd..b6be9c7 100644 --- a/src/web/events.rs +++ b/src/web/events.rs @@ -289,14 +289,14 @@ async fn create_event( check_not_past("starts_at", starts_at)?; check_not_past("ends_at", ends_at)?; check_time_range(starts_at, ends_at)?; - let event = Event::create( + let event = service::event::create( + &st.db, user.get_id(), title, description, audience, starts_at, ends_at, - &st.db, ) .await?; Ok((StatusCode::CREATED, Json(EventResponse::new(&event)))) @@ -329,7 +329,7 @@ async fn list_events( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let events = window.apply(Event::list_all(&st.db).await?)?; + let events = window.apply(service::event::list_all(&st.db).await?)?; let total = events.len() as i64; // Paged in the web layer: `WindowParams` filters and re-orders in Rust. let items = paginate(&events, limit, offset) @@ -357,7 +357,7 @@ async fn get_event( _user: CurrentUser, Path(id): Path, ) -> Result, AppError> { - let event = Event::read(&EventId::from_key(&id), &st.db) + let event = service::event::read(&st.db, &EventId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; Ok(Json(EventResponse::new(&event))) @@ -398,7 +398,7 @@ async fn update_event( .starts_at .map(|update| update.map(Timestamp::from_millis)); let ends_at = req.ends_at.map(|update| update.map(Timestamp::from_millis)); - let event = Event::read(&EventId::from_key(&id), &st.db) + let event = service::event::read(&st.db, &EventId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage(&event, &user) { @@ -432,16 +432,23 @@ async fn update_event( } // The range CHECK needs both ends: whichever the request omitted comes // from the stored row. Read for the check only — the omitted side is - // never written back. Pre-flight only: `Event::update` re-makes this check - // in the UPDATE's `WHERE`, so a concurrent move of the omitted end loses. + // never written back. Pre-flight only: the UPDATE's own `WHERE` re-makes + // this check, so a concurrent move of the omitted end loses. check_time_range( starts_at.unwrap_or_else(|| event.get_starts_at()), ends_at.unwrap_or_else(|| event.get_ends_at()), )?; - let updated = event - .update(title, description, audience, starts_at, ends_at, &st.db) - .await?; + let updated = service::event::update( + &st.db, + event, + title, + description, + audience, + starts_at, + ends_at, + ) + .await?; Ok(Json(EventResponse::new(&updated))) } @@ -465,7 +472,7 @@ async fn delete_event( RequireTeacher(user): RequireTeacher, Path(id): Path, ) -> Result { - let event = Event::read(&EventId::from_key(&id), &st.db) + let event = service::event::read(&st.db, &EventId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; if !can_manage(&event, &user) { @@ -473,7 +480,7 @@ async fn delete_event( "only the creator or a manager/admin can delete this event", )); } - event.delete(&st.db).await?; + service::event::delete(&st.db, event).await?; Ok(StatusCode::NO_CONTENT) } @@ -505,7 +512,7 @@ async fn mark( Json(req): Json, ) -> Result, AppError> { let event_id = EventId::from_key(&id); - let event = Event::read(&event_id, &st.db) + let event = service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; @@ -526,10 +533,7 @@ async fn mark( // Only expected attendees can be marked. The marker needn't be in the // audience — a teacher takes roll of a student-targeted event. - if !event - .get_audience() - .includes(event.get_id(), &target_user, &st.db) - .await? + if !service::event::includes(&st.db, event.get_audience(), event.get_id(), &target_user).await? { return Err(AppError::Validation(ValidationError::Invalid { field: "user_id", @@ -569,7 +573,7 @@ async fn list_attendance( let (limit, offset) = page.resolve()?; let event_id = EventId::from_key(&id); // Event must exist — a missing event is a 404, not an empty roster. - Event::read(&event_id, &st.db) + service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; let (rows, total) = Attendance::list_for_event(&event_id, limit, offset, &st.db).await?; @@ -661,11 +665,11 @@ async fn roster( ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; let event_id = EventId::from_key(&id); - let event = Event::read(&event_id, &st.db) + let event = service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; - let mut members = event.get_audience().members(event.get_id(), &st.db).await?; + let mut members = service::event::members(&st.db, event.get_audience(), event.get_id()).await?; // ULID keys sort by creation instant — a stable order keeps pages coherent. members.sort_by(|a, b| a.key().cmp(b.key())); let (marks, _) = Attendance::list_for_event(&event_id, None, 0, &st.db).await?; @@ -748,7 +752,7 @@ async fn register( Json(req): Json, ) -> Result, AppError> { let event_id = EventId::from_key(&id); - let event = Event::read(&event_id, &st.db) + let event = service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; // Fast-fail gate; the authoritative re-check runs inside @@ -822,7 +826,7 @@ async fn unregister( Path((id, target)): Path<(String, String)>, ) -> Result { let event_id = EventId::from_key(&id); - let event = Event::read(&event_id, &st.db) + let event = service::event::read(&st.db, &event_id) .await? .ok_or(AppError::NotFound)?; event.registration_capacity()?; @@ -868,7 +872,10 @@ mod tests { let user = crate::service::user::create(db, Username::try_new(username).unwrap(), hash) .await .unwrap(); - crate::service::user::set_role(db, user.get_id(), role).await.unwrap().0 + crate::service::user::set_role(db, user.get_id(), role) + .await + .unwrap() + .0 } /// `can_manage` is only reached behind `RequireTeacher` today, so this is @@ -878,14 +885,14 @@ mod tests { async fn demoted_event_creator_loses_management() { let db = init_mem().await.unwrap(); let creator = user("ogretmen", Role::Teacher, &db).await; - let event = Event::create( + let event = service::event::create( + &db, creator.get_id(), EventTitle::try_new("Gezi").unwrap(), EventDescription::try_new("").unwrap(), EventAudience::School, None, None, - &db, ) .await .unwrap(); diff --git a/src/web/pomodoro.rs b/src/web/pomodoro.rs index 377a67e..77635bc 100644 --- a/src/web/pomodoro.rs +++ b/src/web/pomodoro.rs @@ -11,6 +11,7 @@ use crate::domain::pomodoro::PomodoroSession; use crate::domain::role::Role; use crate::domain::user::{User, UserId}; use crate::error::{AppError, ErrorResponse}; +use crate::service::pomodoro; use crate::state::AppState; use super::{CurrentUser, PageParams, ensure_can_observe, paginate}; @@ -137,7 +138,7 @@ async fn start( CurrentUser(user): CurrentUser, ) -> Result<(StatusCode, Json), AppError> { ensure_student(&user)?; - let session = PomodoroSession::start(user.get_id(), &st.db).await?; + let session = pomodoro::start(&st.db, user.get_id()).await?; Ok((StatusCode::CREATED, Json(PomodoroResponse::new(&session)))) } @@ -168,7 +169,7 @@ async fn finish( State(st): State, CurrentUser(user): CurrentUser, ) -> Result, AppError> { - let session = PomodoroSession::finish(user.get_id(), &st.db).await?; + let session = pomodoro::finish(&st.db, user.get_id()).await?; Ok(Json(PomodoroResponse::new(&session))) } @@ -194,7 +195,7 @@ async fn my_pomodoro( Query(page): Query, ) -> Result, AppError> { let (limit, offset) = page.resolve()?; - let sessions = PomodoroSession::list_for_user(user.get_id(), &st.db).await?; + let sessions = pomodoro::list_for_user(&st.db, user.get_id()).await?; Ok(Json(PomodoroLog::new(&sessions, limit, offset))) } @@ -228,6 +229,6 @@ async fn user_pomodoro( crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; - let sessions = PomodoroSession::list_for_user(&target, &st.db).await?; + let sessions = pomodoro::list_for_user(&st.db, &target).await?; Ok(Json(PomodoroLog::new(&sessions, limit, offset))) } diff --git a/src/web/work.rs b/src/web/work.rs index 527092d..342e8c0 100644 --- a/src/web/work.rs +++ b/src/web/work.rs @@ -11,6 +11,7 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; use crate::error::{AppError, ErrorResponse}; +use crate::service::work_entry; use crate::state::AppState; use super::{Page, PageParams, RequireManager, RequireTeacher}; @@ -79,7 +80,7 @@ async fn check_in( State(st): State, RequireTeacher(user): RequireTeacher, ) -> Result<(StatusCode, Json), AppError> { - let entry = WorkEntry::check_in(user.get_id(), &st.db).await?; + let entry = work_entry::check_in(&st.db, user.get_id()).await?; Ok((StatusCode::CREATED, Json(WorkEntryResponse::new(&entry)))) } @@ -101,7 +102,7 @@ async fn check_out( State(st): State, RequireTeacher(user): RequireTeacher, ) -> Result, AppError> { - let entry = WorkEntry::check_out(user.get_id(), &st.db).await?; + let entry = work_entry::check_out(&st.db, user.get_id()).await?; Ok(Json(WorkEntryResponse::new(&entry))) } @@ -128,7 +129,7 @@ async fn my_work( Query(page): Query, ) -> Result>, AppError> { let (limit, offset) = page.resolve()?; - let (entries, total) = WorkEntry::list_for_user(user.get_id(), limit, offset, &st.db).await?; + let (entries, total) = work_entry::list_for_user(&st.db, user.get_id(), limit, offset).await?; let items = entries.iter().map(WorkEntryResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -162,7 +163,7 @@ async fn user_work( crate::service::user::read(&st.db, &target) .await? .ok_or(AppError::NotFound)?; - let (entries, total) = WorkEntry::list_for_user(&target, limit, offset, &st.db).await?; + let (entries, total) = work_entry::list_for_user(&st.db, &target, limit, offset).await?; let items = entries.iter().map(WorkEntryResponse::new).collect(); Ok(Json(Page::new(items, total, limit, offset))) } @@ -194,7 +195,7 @@ async fn update_entry( ) -> Result, AppError> { let check_in = req.check_in.map(Timestamp::from_millis); let check_out = req.check_out.map(Timestamp::from_millis); - let entry = WorkEntry::read(&WorkEntryId::from_key(&id), &st.db) + let entry = work_entry::read(&st.db, &WorkEntryId::from_key(&id)) .await? .ok_or(AppError::NotFound)?; let Some(current_out) = entry.get_check_out() else { @@ -205,12 +206,13 @@ async fn update_entry( // The side the correction left out is only *read* for the ordering check — // it is never written back, so a concurrent correction of it survives. - // Pre-flight only: `WorkEntry::update` re-makes this in the UPDATE's `WHERE`. + // Pre-flight only: the UPDATE's `WHERE` re-makes this check against the + // stored row. if check_out.unwrap_or(current_out) < check_in.unwrap_or_else(|| entry.get_check_in()) { return Err(out_before_in_error()); } - let updated = entry.update(check_in, check_out, &st.db).await?; + let updated = work_entry::update(&st.db, entry, check_in, check_out).await?; Ok(Json(WorkEntryResponse::new(&updated))) } @@ -233,7 +235,7 @@ async fn delete_entry( _manager: RequireManager, Path(id): Path, ) -> Result { - let removed = WorkEntry::remove(&WorkEntryId::from_key(&id), &st.db).await?; + let removed = work_entry::remove(&st.db, &WorkEntryId::from_key(&id)).await?; if removed.is_none() { return Err(AppError::NotFound); }