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

field_update.rs454 lines, 19.2 KiBHistoryRawDownload
1//! One `UPDATE <table> … WHERE id = $n RETURNING *` built from *only* the
2//! fields a PATCH actually carried.
3//!
4//! WHY: a handler reads the row, then writes. Filling a field the request
5//! omitted from that snapshot re-sends a value the client never gave, so a
6//! concurrent PATCH of the *other* field that landed in between is silently
7//! reverted — the lost update a whole-row save causes, just spelled field by
8//! field. Scoping the `SET` is not enough; the *values* must come from the
9//! request, so an absent field is never written at all.
10//!
11//! Callers take `Option<T>` per field (`None` = absent, keep) and hand them
12//! straight here:
13//!
14//! ```ignore
15//! FieldUpdate::new("note", note.id.0)
16//! .set("title", title)
17//! .set("content", content)
18//! .run::<Note>(db)
19//! .await
20//! ```
21//!
22//! Clearing a nullable column is `Some(None)` on an `Option<Option<T>>`
23//! field — pass it as `Some(value_or_none)` so `NULL` is written explicitly
24//! (for a link column, `Param::OptUuid(None)`).
25//!
26//! Runtime-checked SQL by design (this module is the named exemption from the
27//! compile-time `query!` rule): the `SET` list is the request's shape. All
28//! emitted statements are plain Postgres — positional `$n` placeholders, the
29//! row read back with `RETURNING *` (the old store's return-updated-document
30//! spelling), and an explicit clear written as a bound `NULL`; there is no
31//! remove-a-key statement a row needs a counterpart for.
32//!
33//! The dynamic parts of every statement here are table/column names (in-crate
34//! `&'static str` constants, never client text) and the `$n` numbers this
35//! builder prints itself; every value binds — which is the audit the
36//! [`AssertSqlSafe`] wraps stand on.
37
38use sqlx::postgres::{PgArguments, PgRow};
39use sqlx::{AssertSqlSafe, FromRow, PgConnection};
40use uuid::Uuid;
41
42use crate::database::{Database, tx_with_retry};
43use crate::db::page::Param;
44use crate::error::AppError;
45
46/// The statement-shaped markers [`run_with_refcount`]'s transaction aborts
47/// with, mapped to their answers right after [`tx_with_retry`] returns. They
48/// never reach the wire: a refusal is a decision, never a retry, and the
49/// marker `Internal` error is replaced before it can escape.
50const REFUSAL_MARK: &str = "ref_claim_gone";
51const STALE_MARK: &str = "ref_stale_move";
52const GONE_MARK: &str = "ref_row_gone";
53
54/// The answer a moved link has always carried.
55const STALE_MOVE: &str = "the link this update moves changed since it was read; re-read and retry";
56
57/// An abort marker packed as the one error arm no caller ever observes.
58fn mark(kind: &'static str) -> AppError {
59 AppError::Internal(kind.to_owned())
60}
61
62/// The counter move [`FieldUpdate::refcount`] arms: the table and field that
63/// count the link, the column carrying it, the link value the handler's
64/// snapshot read, the claim/release pair, and the caller's answer when the
65/// claimed counter row is gone.
66pub(crate) struct Refcount {
67 pub(crate) counter_table: &'static str,
68 pub(crate) counter_field: &'static str,
69 pub(crate) link: &'static str,
70 pub(crate) expected: Option<Uuid>,
71 pub(crate) claim: Option<Uuid>,
72 pub(crate) release: Option<Uuid>,
73 pub(crate) refused: AppError,
74}
75
76pub(crate) struct FieldUpdate {
77 /// The row's own table — an in-crate constant, never user input.
78 table: &'static str,
79 id: Uuid,
80 /// `(field, value)` fragments, in the order they were set; a value's
81 /// placeholder number is its position here plus one.
82 sets: Vec<(&'static str, Param)>,
83 /// `(low, high, refusal)` for [`FieldUpdate::ordered`].
84 ordered: Option<(&'static str, &'static str, AppError)>,
85 /// The armed counter move, from [`FieldUpdate::refcount`].
86 refcount: Option<Refcount>,
87}
88
89impl FieldUpdate {
90 /// `table` names the row's table; `id` is its uuid primary key.
91 pub(crate) fn new(table: &'static str, id: Uuid) -> Self {
92 Self {
93 table,
94 id,
95 sets: Vec::new(),
96 ordered: None,
97 refcount: None,
98 }
99 }
100
101 /// Write `field` only when the request carried it. The value binds as the
102 /// `SET` list's next positional parameter, in call order.
103 #[must_use]
104 pub(crate) fn set<T: Into<Param>>(mut self, field: &'static str, value: Option<T>) -> Self {
105 if let Some(value) = value {
106 self.sets.push((field, value.into()));
107 }
108 self
109 }
110
111 /// Refuse the write unless `low <= high` still holds on the *merged* row —
112 /// the new value for an end this PATCH carries, the stored column for one
113 /// it omits. Emitted as a `WHERE` on the same `UPDATE`, so the comparison
114 /// the handler made against its snapshot is re-made by the database at
115 /// write time, against the row as it is *then*: two PATCHes each moving
116 /// one end, each fine on its own, cannot commit an inverted range between
117 /// them. That is what an in-process `Mutex` used to buy, without a window
118 /// between the snapshot and the write for a concurrent request to slip
119 /// into.
120 ///
121 /// Call it after the `.set()`s of both fields. A PATCH that moves neither
122 /// end emits no guard at all (nothing to race), so a pre-existing inverted
123 /// row stays editable field by field. `NULL` on either side passes,
124 /// exactly like [`crate::web::check_time_range`] skipping an absent end.
125 #[must_use]
126 pub(crate) fn ordered(
127 mut self,
128 low: &'static str,
129 high: &'static str,
130 refused: AppError,
131 ) -> Self {
132 self.ordered = Some((low, high, refused));
133 self
134 }
135
136 /// Move a reference counter *with* this write: `claim` takes one on the
137 /// row the link moves to (in `counter_table`), `release` gives one back
138 /// on the row it moves off, and both ride the same transaction as the
139 /// `UPDATE` that moves the link.
140 ///
141 /// That is the whole point. A claim sent as its own statement leaves a
142 /// window where a crash strands a count on a row nothing links any more —
143 /// and a count is what a delete guard reads, so the stranded one makes
144 /// its parent undeletable forever. `refused` is the answer when the
145 /// claimed row is gone (the conditional claim doubles as the existence
146 /// check); the transaction then aborts, so the release and the row write
147 /// never happened either.
148 ///
149 /// Only ever called alongside a `.set()` of the very column that carries
150 /// the link, so the empty-request short-circuit below cannot swallow a
151 /// move.
152 ///
153 /// `link` is that column (never a `.set()` field on this row: the counter
154 /// lives on the *other* table — `course_count` on the term against a
155 /// `term` link) and `expected` is what the handler's snapshot said it
156 /// held — `None` for a link that was absent. The pair becomes a CAS on
157 /// the row write, because claim and release are computed from that
158 /// snapshot: two PATCHes moving the same link A→B both read A, and both
159 /// would claim B, leaving B counted twice for one link — a count with no
160 /// link is exactly what makes a term undeletable forever. The loser's row
161 /// write matches nothing and the whole transaction aborts, so it claims
162 /// nothing and answers 409.
163 ///
164 /// **Carrying the link and shifting a counter are separate questions**,
165 /// and the CAS keys off the first one — `run` arms it for any request
166 /// that `.set()`s this column, `claim`/`release` both `None` included. A
167 /// PATCH *re-stating* the link its snapshot showed shifts no counter, but
168 /// it is the same stale read: run it against a row someone else has since
169 /// moved and the unguarded write silently drags the link back, stranding
170 /// the winner's claim on a term nothing points at (undeletable forever)
171 /// and leaving the reverted-to term linked at zero (deletable while
172 /// linked). Gating the CAS on the counters is what let that through.
173 #[must_use]
174 pub(crate) fn refcount(mut self, refcount: Refcount) -> Self {
175 self.refcount = Some(refcount);
176 self
177 }
178
179 /// Run the update and return the stored row. An empty request writes
180 /// nothing at all and reads the row back unchanged.
181 pub(crate) async fn run<T>(mut self, db: &Database) -> Result<T, AppError>
182 where
183 T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
184 {
185 // Armed by the *request*, not by the counters: a PATCH that carries
186 // the link column gets the CAS even when it re-states the value it
187 // read and so shifts nothing. Decided here rather than in `refcount`
188 // so the builder's call order cannot silently disarm it — `run` is
189 // always last.
190 let moved = self.refcount.take().filter(|rc| self.is_set(rc.link));
191 if self.sets.is_empty() {
192 let row: Option<T> = sqlx::query_as(AssertSqlSafe(format!(
193 "SELECT * FROM {} WHERE id = $1",
194 self.table
195 )))
196 .bind(self.id)
197 .fetch_optional(db)
198 .await?;
199 return row.ok_or(AppError::NotFound);
200 }
201 // The `SET` list, each value binding as the next positional
202 // parameter.
203 let mut binds: Vec<Param> = Vec::new();
204 let mut set_sql = String::new();
205 for (index, (field, value)) in self.sets.iter().enumerate() {
206 if index > 0 {
207 set_sql.push_str(", ");
208 }
209 set_sql.push_str(field);
210 set_sql.push_str(&format!(" = ${}", binds.len() + 1));
211 binds.push(value.clone());
212 }
213 // Both ends stored: name the placeholder for an end this request set,
214 // the column for one it left alone.
215 let (ordered, mut refused) = match self.ordered.take() {
216 Some((low, high, err)) if self.is_set(low) || self.is_set(high) => {
217 let side = |field: &str, set: bool| {
218 if set {
219 format!("${}", self.number_of(field))
220 } else {
221 field.to_owned()
222 }
223 };
224 (
225 Some(format!(
226 "({} IS NULL OR {} IS NULL OR {} <= {})",
227 side(low, self.is_set(low)),
228 side(high, self.is_set(high)),
229 side(low, self.is_set(low)),
230 side(high, self.is_set(high)),
231 )),
232 Some(err),
233 )
234 }
235 _ => (None, None),
236 };
237 // A PATCH that does not carry the link at all writes the same
238 // unguarded `UPDATE` it always did — it re-states nothing and races
239 // nobody. The CAS is `IS NOT DISTINCT FROM`, so an absent link
240 // (bound `None`) still compares truthfully.
241 let mut expected_at: Option<usize> = None;
242 let cas = moved.as_ref().map(|rc| {
243 binds.push(Param::OptUuid(rc.expected));
244 expected_at = Some(binds.len());
245 format!("{} IS NOT DISTINCT FROM ${}", rc.link, binds.len())
246 });
247 // The ordered guard is kept apart from the CAS: the probe below has
248 // to ask "did *only* the link move?", and a probe that ignores it
249 // answers "the link moved" to a write the guard refused outright.
250 let own = ordered.iter().cloned().collect::<Vec<_>>().join(" AND ");
251 let conditions: Vec<String> = ordered.into_iter().chain(cas).collect();
252 let guard_sql = if conditions.is_empty() {
253 String::new()
254 } else {
255 format!("{} AND ", conditions.join(" AND "))
256 };
257 // The row id binds last, after the CAS value.
258 binds.push(Param::Uuid(self.id));
259 let id_at = binds.len();
260 let update = format!(
261 "UPDATE {} SET {} WHERE {guard_sql}id = ${id_at} RETURNING *",
262 self.table, set_sql
263 );
264 let rows: Vec<PgRow> = match moved {
265 Some(rc) => {
266 let still_mine = if own.is_empty() {
267 String::new()
268 } else {
269 format!("({own}) AND ")
270 };
271 let probe = format!(
272 "SELECT 1 FROM {} WHERE id = ${id_at} AND {still_mine}{} \
273 IS DISTINCT FROM ${} LIMIT 1",
274 self.table,
275 rc.link,
276 expected_at.expect("the CAS arms with its link"),
277 );
278 run_with_refcount(db, update, probe, binds, rc).await?
279 }
280 None => {
281 let mut args = PgArguments::default();
282 for bind in binds {
283 bind.add_to(&mut args);
284 }
285 sqlx::query_with(AssertSqlSafe(update), args)
286 .fetch_all(db)
287 .await?
288 }
289 };
290 let rows = rows
291 .iter()
292 .map(T::from_row)
293 .collect::<Result<Vec<T>, sqlx::Error>>()?;
294 // No row back means the guard bit failed (or, in the window after the
295 // handler's read, the row was deleted — the guard cannot tell the two
296 // apart, and reports the refusal it was given).
297 rows.into_iter()
298 .next()
299 .ok_or_else(|| refused.take().unwrap_or(AppError::NotFound))
300 }
301
302 /// The `$n` the field's value bound as (set order is bind order).
303 fn number_of(&self, field: &str) -> usize {
304 self.sets
305 .iter()
306 .position(|(name, _)| *name == field)
307 .expect("ordered() sides are .set() fields")
308 + 1
309 }
310
311 fn is_set(&self, field: &str) -> bool {
312 self.sets.iter().any(|(name, _)| *name == field)
313 }
314}
315
316/// Send the update with its counter move, as one transaction.
317///
318/// A re-statement shifts no counter, so `claim` and `release` are both `None`
319/// and the transaction is the CAS'd row write and its probe alone — still a
320/// transaction, because the probe must see the same snapshot the write was
321/// refused against.
322///
323/// Statement order is the old one, for the old reason: the release goes
324/// first, so a move to a counter row that is gone decrements before the claim
325/// refuses — and the rolled-back transaction demonstrably undid it. Every
326/// abort takes the whole move back with it: nothing is committed unless the
327/// row write landed.
328async fn run_with_refcount(
329 db: &Database,
330 update: String,
331 probe: String,
332 binds: Vec<Param>,
333 refcount: Refcount,
334) -> Result<Vec<PgRow>, AppError> {
335 // Destructured in the body, not the signature: a `&'static str` binding
336 // lifted from an async fn's *pattern parameter* poisons the higher-ranked
337 // `AsyncFnMut`/`Send` evaluation of any closure that captures it
338 // ("`Send` would have to be implemented for `&'0 str`, for any lifetime").
339 let Refcount {
340 counter_table,
341 counter_field,
342 claim,
343 release,
344 refused,
345 ..
346 } = refcount;
347 // Owned into the closure: a captured `&str` — even `'static` — drags the
348 // async closure's arg lifetime off the higher-ranked one `tx_with_retry`
349 // needs ("AsyncFnMut is not general enough" at the route registration).
350 let counter_table = counter_table.to_owned();
351 let counter_field = counter_field.to_owned();
352
353 // The body lives in a named `async fn` over raw rows, the closure a
354 // thin delegate (the house `decision_cas`/`save_in` shape): an inline
355 // body of raw sqlx chains — or a delegate generic over the row type —
356 // fails the higher-ranked `Send` check axum's handler registration runs
357 // on `tx_with_retry`'s future. The `FromRow` decode happens on the
358 // caller's side of that check.
359 let outcome = tx_with_retry(db, false, async move |tx| {
360 run_refcount_tx(
361 &mut *tx,
362 update.clone(),
363 probe.clone(),
364 binds.clone(),
365 (&counter_table, &counter_field),
366 claim,
367 release,
368 )
369 .await
370 })
371 .await;
372 match outcome {
373 // The claim's refusal rides out of the transaction as the bare mark
374 // (a refusal is never retryable, so the loop stopped at it) and is
375 // answered with the caller's real error here.
376 Err(AppError::Internal(m)) if m == REFUSAL_MARK => Err(refused),
377 Err(AppError::Internal(m)) if m == STALE_MARK => Err(AppError::Conflict(STALE_MOVE)),
378 // The row is gone: exactly the "wrote nothing" answer the plain path
379 // reports, so the caller's refusal is unchanged.
380 Err(AppError::Internal(m)) if m == GONE_MARK => Ok(Vec::new()),
381 other => other,
382 }
383}
384
385/// One attempt of [`run_with_refcount`]'s transaction: the release, the
386/// claim, the guarded row write, and — on an empty write — the probe that
387/// tells a stale link apart from a row that is simply gone.
388async fn run_refcount_tx(
389 tx: &mut PgConnection,
390 update: String,
391 probe: String,
392 binds: Vec<Param>,
393 counter: (&str, &str),
394 claim: Option<Uuid>,
395 release: Option<Uuid>,
396) -> Result<Vec<PgRow>, AppError> {
397 let (counter_table, counter_field) = counter;
398 if let Some(release) = release {
399 sqlx::query(AssertSqlSafe(format!(
400 "UPDATE {counter_table} \
401 SET {counter_field} = GREATEST({counter_field} - 1, 0) WHERE id = $1"
402 )))
403 .bind(release)
404 .execute(&mut *tx)
405 .await?;
406 }
407 // The conditional claim doubles as the existence check: zero rows
408 // is the claimed row being gone, the caller's own refusal.
409 if let Some(claim) = claim {
410 let seat: Option<i32> = sqlx::query_scalar(AssertSqlSafe(format!(
411 "UPDATE {counter_table} SET {counter_field} = {counter_field} + 1 \
412 WHERE id = $1 RETURNING 1"
413 )))
414 .bind(claim)
415 .fetch_optional(&mut *tx)
416 .await?;
417 if seat.is_none() {
418 return Err(mark(REFUSAL_MARK));
419 }
420 }
421 let mut args = PgArguments::default();
422 for bind in binds.iter().cloned() {
423 bind.add_to(&mut args);
424 }
425 let rows: Vec<PgRow> = sqlx::query_with(AssertSqlSafe(update), args)
426 .fetch_all(&mut *tx)
427 .await?;
428 if !rows.is_empty() {
429 return Ok(rows);
430 }
431 // Zero rows: the caller's own guard bit, the row deleted in the
432 // window after the handler's read, or — the CAS only — the link
433 // moved since the handler read it. Nothing was written yet either
434 // way, so the probe that tells the cases apart is free: it matches
435 // only a row that is *there*, whose *own* guards still hold, and
436 // whose link has moved off what the handler read — which is the
437 // CAS, and nothing else, having bitten. Carrying the caller's
438 // guards is what keeps that true when a write is refused for
439 // *both* reasons at once: a `.guard()`/`.ordered()` refusal is the
440 // caller's own answer to give, and reporting it as "the link
441 // moved" would send the client to re-read a link that was never
442 // its problem.
443 let mut args = PgArguments::default();
444 for bind in binds.iter().cloned() {
445 bind.add_to(&mut args);
446 }
447 let live: Option<i32> = sqlx::query_scalar_with(AssertSqlSafe(probe), args)
448 .fetch_optional(&mut *tx)
449 .await?;
450 match live {
451 Some(_) => Err(mark(STALE_MARK)),
452 None => Err(mark(GONE_MARK)),
453 }
454}