forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiBaf331ecAhmet Kaan Gümüş2 months ago451 commits

work_entry.rs234 lines, 9.3 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//!
4//! "At most one open stint per staff member" is the database's own rule here:
5//! the partial unique index `work_entry_open` covers only rows whose
6//! `check_out` is NULL, so a second check-in is a 23505 (mapped to the
7//! check-in conflict below) and a check-out is one conditional `UPDATE` —
8//! zero rows means there was no open stint to close. The old
9//! take-and-re-file dance existed only to free the deterministic open id;
10//! with the index, closing the stint *is* freeing the slot.
11
12use crate::database::Database;
13use crate::db::field_update::FieldUpdate;
14use crate::domain::timestamp::Timestamp;
15use crate::domain::user::UserId;
16use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
17use crate::error::AppError;
18
19/// The row as the table spells it (`app_user` column), one step from the
20/// domain struct (whose field is `user`).
21struct WorkEntryRow {
22 id: WorkEntryId,
23 app_user: UserId,
24 check_in: Timestamp,
25 check_out: Option<Timestamp>,
26}
27
28impl From<WorkEntryRow> for WorkEntry {
29 fn from(row: WorkEntryRow) -> Self {
30 Self {
31 id: row.id,
32 user: row.app_user,
33 check_in: row.check_in,
34 check_out: row.check_out,
35 }
36 }
37}
38
39/// Open a stint for `user`, stamped with the server clock. The
40/// `work_entry_open` partial unique index makes this atomic: if an open
41/// entry already exists the insert is refused and the caller gets the
42/// conflict — two racing check-ins can never create two open rows or reset
43/// a running clock. One statement, one verdict, no retry loop.
44pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
45 let id = WorkEntryId::generate();
46 let check_in = Timestamp::now();
47 let inserted = sqlx::query_as!(
48 WorkEntryRow,
49 "INSERT INTO work_entry (id, app_user, check_in) VALUES ($1, $2, $3) \
50 RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"",
51 id.uuid(),
52 user.uuid(),
53 check_in.as_millis(),
54 )
55 .fetch_one(db)
56 .await;
57 match inserted {
58 Ok(row) => Ok(row.into()),
59 Err(e) if crate::database::unique_violation(&e) == Some("work_entry_open") => {
60 Err(AppError::Conflict("already checked in — check out first"))
61 }
62 Err(e) => Err(e.into()),
63 }
64}
65
66/// Close `user`'s open stint: one conditional `UPDATE` takes it and stamps
67/// `check_out`, which also frees the open slot for the next check-in (the
68/// partial unique index only covers rows with a NULL `check_out`). Zero
69/// rows = no open stint, the caller's conflict. Of two racing check-outs
70/// exactly one receives the row — the statement takes the row's lock and
71/// the loser re-evaluates against the winner's committed state.
72pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
73 let out = Timestamp::now();
74 let closed = sqlx::query_as!(
75 WorkEntryRow,
76 "UPDATE work_entry SET check_out = $2 \
77 WHERE app_user = $1 AND check_out IS NULL \
78 RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"",
79 user.uuid(),
80 out.as_millis(),
81 )
82 .fetch_optional(db)
83 .await?;
84 closed
85 .map(WorkEntry::from)
86 .ok_or(AppError::Conflict("not checked in"))
87}
88
89pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
90 let row = sqlx::query_as!(
91 WorkEntryRow,
92 "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry WHERE id = $1",
93 id.uuid(),
94 )
95 .fetch_optional(db)
96 .await?;
97 Ok(row.map(WorkEntry::from))
98}
99
100/// Every stint of `user`, newest first — the open one (if any) included.
101/// Ordered by `check_in DESC`; the minted `id` breaks ties between two
102/// stints sharing a `check_in` (uuid v7 sorts in mint order, which is what
103/// keeps offset paging from skipping a row).
104pub async fn list_for_user(
105 db: &Database,
106 user: &UserId,
107 limit: Option<i64>,
108 offset: i64,
109) -> Result<(Vec<WorkEntry>, i64), AppError> {
110 let rows = match limit {
111 Some(limit) => {
112 sqlx::query_as!(
113 WorkEntryRow,
114 "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \
115 WHERE app_user = $1 ORDER BY check_in DESC, id DESC \
116 LIMIT $2 OFFSET $3",
117 user.uuid(),
118 limit,
119 offset,
120 )
121 .fetch_all(db)
122 .await?
123 }
124 None if offset > 0 => {
125 sqlx::query_as!(
126 WorkEntryRow,
127 "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \
128 WHERE app_user = $1 ORDER BY check_in DESC, id DESC \
129 OFFSET $2",
130 user.uuid(),
131 offset,
132 )
133 .fetch_all(db)
134 .await?
135 }
136 None => {
137 sqlx::query_as!(
138 WorkEntryRow,
139 "SELECT id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\" FROM work_entry \
140 WHERE app_user = $1 ORDER BY check_in DESC, id DESC",
141 user.uuid(),
142 )
143 .fetch_all(db)
144 .await?
145 }
146 };
147 // A window that can hide rows needs the count over the same WHERE;
148 // an unpaged read from row zero already holds every row.
149 let total = if limit.is_some() || offset > 0 {
150 sqlx::query_scalar!("SELECT count(*) FROM work_entry WHERE app_user = $1", user.uuid())
151 .fetch_one(db)
152 .await?
153 .unwrap_or(0)
154 } else {
155 rows.len() as i64
156 };
157 Ok((rows.into_iter().map(WorkEntry::from).collect(), total))
158}
159
160/// Persist corrected instants (manager fix-ups on closed entries; the web
161/// layer validates ordering and rejects open entries).
162/// `None` = the correction left that instant out, so it is not written at
163/// all — the stint's `user` and `check_in`/`check_out` stamps are never
164/// replayed from a struct the handler read before its validation awaits.
165/// `check_out` is never cleared here: an open stint is refused upstream, so
166/// "absent" and "null" both mean keep.
167pub async fn update(
168 db: &Database,
169 entry: WorkEntry,
170 check_in: Option<Timestamp>,
171 check_out: Option<Timestamp>,
172) -> Result<WorkEntry, AppError> {
173 FieldUpdate::new("work_entry", entry.id.uuid())
174 .set("check_in", check_in.map(|t| t.as_millis()))
175 .set("check_out", check_out.map(|t| t.as_millis()))
176 // Same race closer as the schedule ranges, with this table's own
177 // field names and message: a correction of one instant is only
178 // written while it still orders against the other as *stored*.
179 .ordered("check_in", "check_out", out_before_in_error())
180 .run::<WorkEntry>(db)
181 .await
182}
183
184pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
185 let row = sqlx::query_as!(
186 WorkEntryRow,
187 "DELETE FROM work_entry WHERE id = $1 \
188 RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"",
189 id.uuid(),
190 )
191 .fetch_optional(db)
192 .await?;
193 Ok(row.map(WorkEntry::from))
194}
195
196#[cfg(test)]
197mod tests {
198 use ulid::Ulid;
199
200 use super::*;
201 use crate::database;
202
203 #[tokio::test]
204 async fn check_in_is_exclusive_until_check_out() {
205 let db = database::init_mem().await.unwrap();
206 // A `record<user>` column checks the table of the id, not row
207 // existence — a fabricated id keeps this test free of user ceremony.
208 let user = UserId::from_key(&Ulid::generate().to_string());
209
210 let open = check_in(&db, &user).await.unwrap();
211 assert!(open.is_open());
212 assert_eq!(open.get_id().key(), format!("open_{}", user.key()));
213
214 // Second check-in must not create a second stint or reset the clock.
215 let dup = check_in(&db, &user).await;
216 assert!(matches!(dup, Err(AppError::Conflict(_))));
217 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
218 assert_eq!(entries.len(), 1);
219 assert_eq!(entries[0].get_check_in(), open.get_check_in());
220
221 let closed = check_out(&db, &user).await.unwrap();
222 assert!(!closed.is_open());
223 assert!(closed.get_check_out().unwrap() >= closed.get_check_in());
224
225 // The open slot is free again; a stray second check-out conflicts.
226 assert!(matches!(
227 check_out(&db, &user).await,
228 Err(AppError::Conflict(_))
229 ));
230 check_in(&db, &user).await.unwrap();
231 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
232 assert_eq!(entries.len(), 2);
233 }
234}