forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

work_entry.rs241 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!(
151 "SELECT count(*) FROM work_entry WHERE app_user = $1",
152 user.uuid()
153 )
154 .fetch_one(db)
155 .await?
156 .unwrap_or(0)
157 } else {
158 rows.len() as i64
159 };
160 Ok((rows.into_iter().map(WorkEntry::from).collect(), total))
161}
162
163/// Persist corrected instants (manager fix-ups on closed entries; the web
164/// layer validates ordering and rejects open entries).
165/// `None` = the correction left that instant out, so it is not written at
166/// all — the stint's `user` and `check_in`/`check_out` stamps are never
167/// replayed from a struct the handler read before its validation awaits.
168/// `check_out` is never cleared here: an open stint is refused upstream, so
169/// "absent" and "null" both mean keep.
170pub async fn update(
171 db: &Database,
172 entry: WorkEntry,
173 check_in: Option<Timestamp>,
174 check_out: Option<Timestamp>,
175) -> Result<WorkEntry, AppError> {
176 FieldUpdate::new("work_entry", entry.id.uuid())
177 .set("check_in", check_in.map(|t| t.as_millis()))
178 .set("check_out", check_out.map(|t| t.as_millis()))
179 // Same race closer as the schedule ranges, with this table's own
180 // field names and message: a correction of one instant is only
181 // written while it still orders against the other as *stored*.
182 .ordered("check_in", "check_out", out_before_in_error())
183 .run::<WorkEntry>(db)
184 .await
185}
186
187pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
188 let row = sqlx::query_as!(
189 WorkEntryRow,
190 "DELETE FROM work_entry WHERE id = $1 \
191 RETURNING id AS \"id: WorkEntryId\", app_user AS \"app_user: UserId\", check_in AS \"check_in: Timestamp\", check_out AS \"check_out: Timestamp\"",
192 id.uuid(),
193 )
194 .fetch_optional(db)
195 .await?;
196 Ok(row.map(WorkEntry::from))
197}
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202 use crate::database;
203
204 #[tokio::test]
205 async fn check_in_is_exclusive_until_check_out() {
206 let (db, _leases) = database::init_test_db().await;
207 // The stint's owner is a foreign key now: a real `app_user` row.
208 let user = UserId::generate();
209 sqlx::query(
210 "INSERT INTO app_user (id, username, created_at) \
211 VALUES ($1, 'work-fixture', 0)",
212 )
213 .bind(user.uuid())
214 .execute(&db)
215 .await
216 .unwrap();
217
218 let open = check_in(&db, &user).await.unwrap();
219 assert!(open.is_open());
220
221 // Second check-in must not create a second stint or reset the clock.
222 let dup = check_in(&db, &user).await;
223 assert!(matches!(dup, Err(AppError::Conflict(_))));
224 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
225 assert_eq!(entries.len(), 1);
226 assert_eq!(entries[0].get_check_in(), open.get_check_in());
227
228 let closed = check_out(&db, &user).await.unwrap();
229 assert!(!closed.is_open());
230 assert!(closed.get_check_out().unwrap() >= closed.get_check_in());
231
232 // The open slot is free again; a stray second check-out conflicts.
233 assert!(matches!(
234 check_out(&db, &user).await,
235 Err(AppError::Conflict(_))
236 ));
237 check_in(&db, &user).await.unwrap();
238 let (entries, _) = list_for_user(&db, &user, None, 0).await.unwrap();
239 assert_eq!(entries.len(), 2);
240 }
241}