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

settings.rs383 lines, 17.8 KiBHistoryRawDownload
1//! The `settings` singleton: one row (`settings`, id `'school'`) holding the
2//! school's policy knobs. An absent row reads as the built-in defaults
3//! everywhere.
4//!
5//! The two vocabulary lists (`attendance_statuses`, `dietary_tags`) are no
6//! longer array columns: they live in the child tables
7//! `settings_attendance_status` and `settings_dietary_tag`, one row per
8//! entry. The junction keeps no order, so every read sorts by entry and the
9//! compare-and-set guard below compares row *sets*, not bytes.
10
11use sqlx::types::Json;
12
13use crate::database::{Database, tx_with_retry};
14use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
15use crate::error::AppError;
16
17/// Both sides of every set compare are sorted: the child tables keep no
18/// order, and set equality does not want one.
19fn sorted(values: &[String]) -> Vec<String> {
20 let mut sorted = values.to_vec();
21 sorted.sort();
22 sorted
23}
24
25/// One optional JSONB list as the value a statement binds: the list when the
26/// setting carries one, SQL `NULL` when it does not.
27fn encode_optional(
28 values: &Option<Json<Vec<String>>>,
29) -> Result<Option<serde_json::Value>, AppError> {
30 values
31 .as_ref()
32 .map(|list| serde_json::to_value(&list.0))
33 .transpose()
34 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))
35}
36
37/// The one read: row columns plus both vocabularies re-assembled from their
38/// child tables. An absent dietary set reads as `None` — the same shape an
39/// unset column used to carry.
40async fn load_row<'e, E>(db: E) -> Result<Option<Settings>, AppError>
41where
42 E: sqlx::PgExecutor<'e>,
43{
44 let settings = sqlx::query_as!(
45 Settings,
46 r#"SELECT s.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
47 COALESCE((SELECT array_agg(t.status ORDER BY t.status)
48 FROM settings_attendance_status t
49 WHERE t.settings = s.id), '{}') AS "attendance_statuses!: Vec<String>",
50 s.grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
51 s.max_file_bytes,
52 s.chatbot_history_turns,
53 s.max_chatbot_message_len,
54 s.max_chatbot_threads,
55 s.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
56 (SELECT array_agg(t.tag ORDER BY t.tag)
57 FROM settings_dietary_tag t
58 WHERE t.settings = s.id) AS dietary_tags,
59 s.meal_cancel_cutoff_minutes,
60 s.branches AS "branches: Json<Vec<String>>",
61 s.excuse_kinds AS "excuse_kinds: Json<Vec<String>>",
62 s.max_excused_absent_days,
63 s.max_unexcused_absent_days,
64 s.timezone
65 FROM settings s WHERE s.id = 'school'"#
66 )
67 .fetch_optional(db)
68 .await?;
69 Ok(settings)
70}
71
72pub async fn load(db: &Database) -> Result<Settings, AppError> {
73 let settings = load_row(db).await?;
74 Ok(settings.unwrap_or_else(Settings::defaults))
75}
76
77/// Replace the attendance vocabulary wholesale. Callers run inside a
78/// transaction (or inside the single CAS statement), so the delete and the
79/// insert cannot be observed apart.
80async fn replace_statuses(
81 conn: &mut sqlx::PgConnection,
82 statuses: &[String],
83) -> Result<(), AppError> {
84 sqlx::query!("DELETE FROM settings_attendance_status WHERE settings = 'school'")
85 .execute(&mut *conn)
86 .await?;
87 sqlx::query!(
88 "INSERT INTO settings_attendance_status (settings, status)
89 SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)",
90 statuses,
91 )
92 .execute(&mut *conn)
93 .await?;
94 Ok(())
95}
96
97/// Replace the dietary vocabulary wholesale. `None` and `Some(empty)` both
98/// write zero rows — "explicitly empty" and "never set" are the same state
99/// on the child tables.
100async fn replace_tags(
101 conn: &mut sqlx::PgConnection,
102 tags: Option<&[String]>,
103) -> Result<(), AppError> {
104 sqlx::query!("DELETE FROM settings_dietary_tag WHERE settings = 'school'")
105 .execute(&mut *conn)
106 .await?;
107 sqlx::query!(
108 "INSERT INTO settings_dietary_tag (settings, tag)
109 SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)",
110 tags,
111 )
112 .execute(&mut *conn)
113 .await?;
114 Ok(())
115}
116
117/// Persist the policy (single UPSERT on the fixed singleton id plus a
118/// wholesale rewrite of both vocabularies, one transaction), unconditionally
119/// — last write wins. Prefer [`save_if_unchanged`] wherever the new policy
120/// was merged from a loaded snapshot.
121pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {
122 // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged
123 let exam_kinds = serde_json::to_value(&settings.exam_kinds.0)
124 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
125 let grade_bands = serde_json::to_value(&settings.grade_bands.0)
126 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
127 let meal_slots = settings
128 .meal_slots
129 .as_ref()
130 .map(|slots| serde_json::to_value(&slots.0))
131 .transpose()
132 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
133 // The two JSONB vocabularies ride the row like `meal_slots`: an unset
134 // list stays NULL rather than being coerced to `[]`, because a whole-row
135 // save that wrote `[]` for a field it never carried would erase the
136 // distinction an unset column carries.
137 let branches = encode_optional(&settings.branches)?;
138 let excuse_kinds = encode_optional(&settings.excuse_kinds)?;
139 let attendance = sorted(&settings.attendance_statuses);
140 let dietary = settings.dietary_tags.clone();
141 tx_with_retry(db, true, async move |tx| {
142 sqlx::query!(
143 r#"INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
144 chatbot_history_turns, max_chatbot_message_len,
145 max_chatbot_threads, meal_slots,
146 meal_cancel_cutoff_minutes, branches, excuse_kinds,
147 max_excused_absent_days, max_unexcused_absent_days,
148 timezone)
149 VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
150 ON CONFLICT (id) DO UPDATE SET
151 exam_kinds = EXCLUDED.exam_kinds,
152 grade_bands = EXCLUDED.grade_bands,
153 max_file_bytes = EXCLUDED.max_file_bytes,
154 chatbot_history_turns = EXCLUDED.chatbot_history_turns,
155 max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,
156 max_chatbot_threads = EXCLUDED.max_chatbot_threads,
157 meal_slots = EXCLUDED.meal_slots,
158 meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes,
159 branches = EXCLUDED.branches,
160 excuse_kinds = EXCLUDED.excuse_kinds,
161 max_excused_absent_days = EXCLUDED.max_excused_absent_days,
162 max_unexcused_absent_days = EXCLUDED.max_unexcused_absent_days,
163 timezone = EXCLUDED.timezone"#,
164 exam_kinds,
165 grade_bands,
166 settings.max_file_bytes,
167 settings.chatbot_history_turns,
168 settings.max_chatbot_message_len,
169 settings.max_chatbot_threads,
170 meal_slots,
171 settings.meal_cancel_cutoff_minutes,
172 branches,
173 excuse_kinds,
174 settings.max_excused_absent_days,
175 settings.max_unexcused_absent_days,
176 settings.timezone,
177 )
178 .execute(&mut *tx)
179 .await?;
180 replace_statuses(&mut *tx, &attendance).await?;
181 replace_tags(&mut *tx, dietary.as_deref()).await?;
182 load_row(&mut *tx).await?.ok_or(AppError::NotFound)
183 })
184 .await
185}
186
187/// Persist the policy only while the stored row still matches `expected`
188/// — the snapshot the caller merged omitted fields from. `None` means a
189/// concurrent edit landed in between and nothing was written: reload,
190/// re-merge, retry. Without this compare-and-set, two managers patching
191/// *different* fields silently revert each other (both merge from the
192/// same snapshot; the later whole-row write restores its stale copy of
193/// the other's field).
194///
195/// ONE guarded statement, generic over the executor so the workflow can run
196/// the same guarded save inside its own transaction (a stale save must roll
197/// its retirements back, which only an abort can do). The `INSERT` arm
198/// materializes the defaults-as-loaded state when no row exists yet (`load`
199/// reported the defaults, so the defaults are what the caller merged over —
200/// nothing to compare), and the `ON CONFLICT DO UPDATE … WHERE` arm applies
201/// `settings` only if the stored state (still) equals `expected`: row
202/// columns each compared with `IS NOT DISTINCT FROM`, and the two
203/// vocabularies compared as sorted aggregates over their child tables — the
204/// row *sets*, since the junctions keep no order. The settings row's own
205/// lock is the serialization point: a waiter for the same row re-runs the
206/// whole guard against the winner's committed state, and its child-table
207/// subqueries then read the winner's committed vocabulary.
208///
209/// The vocabulary rewrites are CTEs gated on the row write having produced a
210/// row (`new_row`), and each insert waits for its delete through the
211/// delete's RETURNING count — data-modifying CTEs share one snapshot, so
212/// without that chain the insert could race its own delete and drop rows.
213/// The returned row's vocabulary comes from the inserts' RETURNING, not a
214/// re-read: the statement cannot see its own writes to the child tables.
215pub async fn save_if_unchanged<'e, E>(
216 db: E,
217 settings: Settings,
218 expected: &Settings,
219) -> Result<Option<Settings>, AppError>
220where
221 E: sqlx::PgExecutor<'e>,
222{
223 let exam_kinds = serde_json::to_value(&settings.exam_kinds.0)
224 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
225 let grade_bands = serde_json::to_value(&settings.grade_bands.0)
226 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
227 let meal_slots = settings
228 .meal_slots
229 .as_ref()
230 .map(|slots| serde_json::to_value(&slots.0))
231 .transpose()
232 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
233 let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0)
234 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
235 let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0)
236 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
237 let expected_meal_slots = expected
238 .meal_slots
239 .as_ref()
240 .map(|slots| serde_json::to_value(&slots.0))
241 .transpose()
242 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
243 let branches = encode_optional(&settings.branches)?;
244 let excuse_kinds = encode_optional(&settings.excuse_kinds)?;
245 let expected_branches = encode_optional(&expected.branches)?;
246 let expected_excuse_kinds = encode_optional(&expected.excuse_kinds)?;
247 let attendance = sorted(&settings.attendance_statuses);
248 let expected_attendance = sorted(&expected.attendance_statuses);
249 // An empty `Some` must compare equal to the stored NULL an empty set
250 // reads as, so it is normalized away on the expected side.
251 let expected_dietary = expected
252 .dietary_tags
253 .as_ref()
254 .filter(|tags| !tags.is_empty())
255 .map(|tags| tags.as_slice());
256 let saved = sqlx::query_as!(
257 Settings,
258 r#"WITH new_row AS (
259 INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
260 chatbot_history_turns, max_chatbot_message_len,
261 max_chatbot_threads, meal_slots,
262 meal_cancel_cutoff_minutes, branches, excuse_kinds,
263 max_excused_absent_days, max_unexcused_absent_days,
264 timezone)
265 VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10, $21, $22, $23, $24, $25)
266 ON CONFLICT (id) DO UPDATE SET
267 exam_kinds = $1,
268 grade_bands = $3,
269 max_file_bytes = $4,
270 chatbot_history_turns = $5,
271 max_chatbot_message_len = $6,
272 max_chatbot_threads = $7,
273 meal_slots = $8,
274 meal_cancel_cutoff_minutes = $10,
275 branches = $21,
276 excuse_kinds = $22,
277 max_excused_absent_days = $23,
278 max_unexcused_absent_days = $24,
279 timezone = $25
280 WHERE settings.exam_kinds IS NOT DISTINCT FROM $13
281 AND settings.grade_bands IS NOT DISTINCT FROM $14
282 AND settings.max_file_bytes IS NOT DISTINCT FROM $15
283 AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16
284 AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17
285 AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18
286 AND settings.meal_slots IS NOT DISTINCT FROM $19
287 AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20
288 AND settings.branches IS NOT DISTINCT FROM $26
289 AND settings.excuse_kinds IS NOT DISTINCT FROM $27
290 AND settings.max_excused_absent_days IS NOT DISTINCT FROM $28
291 AND settings.max_unexcused_absent_days IS NOT DISTINCT FROM $29
292 AND settings.timezone IS NOT DISTINCT FROM $30
293 AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)
294 FROM settings_attendance_status s
295 WHERE s.settings = settings.id), '{}')
296 IS NOT DISTINCT FROM $11::text[]
297 AND (SELECT array_agg(t.tag ORDER BY t.tag)
298 FROM settings_dietary_tag t
299 WHERE t.settings = settings.id)
300 IS NOT DISTINCT FROM $12::text[]
301 RETURNING exam_kinds, grade_bands, max_file_bytes,
302 chatbot_history_turns, max_chatbot_message_len,
303 max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes,
304 branches, excuse_kinds, max_excused_absent_days,
305 max_unexcused_absent_days, timezone),
306 status_del AS (
307 DELETE FROM settings_attendance_status
308 WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)
309 RETURNING 1),
310 status_ins AS (
311 INSERT INTO settings_attendance_status (settings, status)
312 SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)
313 CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d
314 WHERE EXISTS (SELECT 1 FROM new_row)
315 RETURNING status),
316 tag_del AS (
317 DELETE FROM settings_dietary_tag
318 WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)
319 RETURNING 1),
320 tag_ins AS (
321 INSERT INTO settings_dietary_tag (settings, tag)
322 SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)
323 CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d
324 WHERE EXISTS (SELECT 1 FROM new_row)
325 RETURNING tag)
326 SELECT r.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
327 COALESCE((SELECT array_agg(status ORDER BY status)
328 FROM status_ins), '{}') AS "attendance_statuses!: Vec<String>",
329 r.grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
330 r.max_file_bytes,
331 r.chatbot_history_turns,
332 r.max_chatbot_message_len,
333 r.max_chatbot_threads,
334 r.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
335 (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,
336 r.meal_cancel_cutoff_minutes,
337 r.branches AS "branches: Json<Vec<String>>",
338 r.excuse_kinds AS "excuse_kinds: Json<Vec<String>>",
339 r.max_excused_absent_days,
340 r.max_unexcused_absent_days,
341 r.timezone
342 FROM new_row r"#,
343 exam_kinds,
344 &attendance,
345 grade_bands,
346 settings.max_file_bytes,
347 settings.chatbot_history_turns,
348 settings.max_chatbot_message_len,
349 settings.max_chatbot_threads,
350 meal_slots,
351 settings.dietary_tags.as_deref(),
352 settings.meal_cancel_cutoff_minutes,
353 &expected_attendance,
354 expected_dietary,
355 expected_exam_kinds,
356 expected_grade_bands,
357 expected.max_file_bytes,
358 expected.chatbot_history_turns,
359 expected.max_chatbot_message_len,
360 expected.max_chatbot_threads,
361 expected_meal_slots,
362 expected.meal_cancel_cutoff_minutes,
363 branches,
364 excuse_kinds,
365 settings.max_excused_absent_days,
366 settings.max_unexcused_absent_days,
367 settings.timezone,
368 expected_branches,
369 expected_excuse_kinds,
370 expected.max_excused_absent_days,
371 expected.max_unexcused_absent_days,
372 expected.timezone,
373 )
374 .fetch_optional(db)
375 .await?;
376 // An empty result means the row no longer matched `expected`.
377 Ok(saved)
378}
379
380#[cfg(test)]
381mod tests {
382 // Ported in wave 3: they need a live school database.
383}