forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB08aa13eAhmet Kaan Gümüş2 months ago378 commits

work_entry.rs183 lines, 7.2 KiBHistoryRawDownload
1//! The `work_entry` table: the open-slot check-in/check-out pair, the
2//! newest-first log, and manager corrections guarded by the stored order.
3
4use surrealdb::types::SurrealValue;
5
6use crate::database::{Database, transaction_with_retry};
7use crate::db::field_update::FieldUpdate;
8use crate::db::page::PagedList;
9use crate::domain::timestamp::Timestamp;
10use crate::domain::user::UserId;
11use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
12use crate::error::AppError;
13
14/// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE`
15/// on the deterministic open id makes this atomic: if an open entry
16/// already exists the insert is skipped (empty result) and the caller gets
17/// a conflict — two racing check-ins can never create two open rows or
18/// reset a running clock.
19pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
20 let entry = WorkEntry {
21 id: WorkEntryId::open_for(user),
22 user: user.clone(),
23 check_in: Timestamp::now(),
24 check_out: None,
25 };
26 let mut result = db
27 .query("INSERT IGNORE INTO work_entry $entry")
28 .bind(("entry", entry))
29 .await?
30 .check()?;
31 result
32 .take::<Vec<WorkEntry>>(0)?
33 .into_iter()
34 .next()
35 .ok_or(AppError::Conflict("already checked in — check out first"))
36}
37
38/// Close `user`'s open stint: atomically take the open row and re-file it
39/// under a ULID id, freeing the open slot for the next check-in. Take and
40/// re-file share one transaction — a failed re-file rolls the take back,
41/// so a stint can never vanish half-closed. Of two racing check-outs
42/// exactly one receives the row (the other gets the conflict).
43///
44/// A lost round is re-sent rather than reported (`transaction_with_retry`):
45/// the abort wrote nothing, so the whole cascade is safe to repeat, and the
46/// `CREATE` cannot answer "already exists" on the way back — the table
47/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
48/// Only the guard's own `THROW` is a decision, and it stays a 409.
49pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
50 let (mut result, mut errors) = transaction_with_retry(
51 db,
52 "BEGIN TRANSACTION;
53 LET $before = (DELETE $open RETURN BEFORE);
54 IF array::len($before) = 0 { THROW 'not_checked_in' };
55 CREATE $closed CONTENT {
56 user: $before[0].user,
57 check_in: $before[0].check_in,
58 check_out: $out,
59 };
60 COMMIT TRANSACTION;",
61 &[
62 (
63 "open".into(),
64 WorkEntryId::open_for(user).record().into_value(),
65 ),
66 (
67 "closed".into(),
68 WorkEntryId::generate().record().into_value(),
69 ),
70 ("out".into(), Timestamp::now().into_value()),
71 ],
72 &["not_checked_in"],
73 )
74 .await?;
75 // An aborted transaction errors *every* slot, most with a generic
76 // "not executed" — only the THROW's own slot names the reason, so scan
77 // them all for the marker instead of trusting the first.
78 if errors
79 .values()
80 .any(|error| error.to_string().contains("not_checked_in"))
81 {
82 return Err(AppError::Conflict("not checked in"));
83 }
84 if let Some(error) = errors.drain().map(|(_, error)| error).next() {
85 return Err(error.into());
86 }
87 // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3.
88 let saved: Option<WorkEntry> = result.take::<Vec<WorkEntry>>(3)?.into_iter().next();
89 saved.ok_or_else(|| AppError::Internal("failed to close work entry".into()))
90}
91
92pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
93 Ok(db.select(id.record()).await?)
94}
95
96/// Every stint of `user`, newest first — the open one (if any) included.
97/// Ordered by `check_in`, never by id alone: the open entry's `open_` key
98/// doesn't sort with the ULIDs, so id order would misplace it. The `id`
99/// tie-break behind it only ever separates two *closed* stints sharing a
100/// `check_in` — there is one open row per user, so it can never tie with
101/// itself — and that is what keeps offset paging from skipping a row.
102pub async fn list_for_user(
103 db: &Database,
104 user: &UserId,
105 limit: Option<i64>,
106 offset: i64,
107) -> Result<(Vec<WorkEntry>, i64), AppError> {
108 PagedList::new(
109 "work_entry WHERE user = $usr",
110 "ORDER BY check_in DESC, id DESC",
111 )
112 .bind("usr", user.record())
113 .run(limit, offset, db)
114 .await
115}
116
117/// Persist corrected instants (manager fix-ups on closed entries; the web
118/// layer validates ordering and rejects open entries).
119/// `None` = the correction left that instant out, so it is not written at
120/// all — the stint's `user` and `check_in`/`check_out` stamps are never
121/// replayed from a struct the handler read before its validation awaits.
122/// `check_out` is never cleared here: an open stint is refused upstream, so
123/// "absent" and "null" both mean keep.
124pub async fn update(
125 db: &Database,
126 entry: WorkEntry,
127 check_in: Option<Timestamp>,
128 check_out: Option<Timestamp>,
129) -> Result<WorkEntry, AppError> {
130 FieldUpdate::new(entry.get_id().record())
131 .set("check_in", check_in)
132 .set("check_out", check_out)
133 // Same race closer as the schedule ranges, with this table's own
134 // field names and message: a correction of one instant is only
135 // written while it still orders against the other as *stored*.
136 .ordered("check_in", "check_out", out_before_in_error())
137 .run::<WorkEntry>(db)
138 .await
139}
140
141pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
142 Ok(db.delete(id.record()).await?)
143}
144
145#[cfg(test)]
146mod tests {
147 use ulid::Ulid;
148
149 use super::*;
150 use crate::database;
151
152 #[tokio::test]
153 async fn check_in_is_exclusive_until_check_out() {
154 let db = database::init_mem().await.unwrap();
155 // A `record<user>` column checks the table of the id, not row
156 // existence — a fabricated id keeps this test free of user ceremony.
157 let user = UserId::from_key(&Ulid::new().to_string());
158
159 let open = check_in(&db, &user).await.unwrap();
160 assert!(open.is_open());
161 assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
162
163 // Second check-in must not create a second stint or reset the clock.
164 let dup = check_in(&db, &user).await;
165 assert!(matches!(dup, Err(AppError::Conflict(_))));
166 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
167 assert_eq!(entries.len(), 1);
168 assert_eq!(entries[0].get_check_in(), open.get_check_in());
169
170 let closed = check_out(&db, &user).await.unwrap();
171 assert!(!closed.is_open());
172 assert!(closed.get_check_out().unwrap() >= closed.get_check_in());
173
174 // The open slot is free again; a stray second check-out conflicts.
175 assert!(matches!(
176 check_out(&db, &user).await,
177 Err(AppError::Conflict(_))
178 ));
179 check_in(&db, &user).await.unwrap();
180 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
181 assert_eq!(entries.len(), 2);
182 }
183}