hezarfen_backend
Clone
https://git.tahinli.com/archive/hezarfen_backend.git
0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits
| 1 | //! Count caps the database enforces, not the process. |
| 2 | //! |
| 3 | //! Every "at most N children per parent" rule used to be a count-then-write |
| 4 | //! under a process-wide `Mutex`, because the old store did not conflict-check |
| 5 | //! a cross-record `count()` against a concurrent insert (write-skew): two |
| 6 | //! racing writers both saw a free slot. A mutex serialized the writers, but |
| 7 | //! only around whatever it wrapped — every one of those caps held a lock |
| 8 | //! across a database round trip, and the count it was protecting was already |
| 9 | //! a guess by the time the insert landed. |
| 10 | //! |
| 11 | //! The guard that survives is a single-record conditional write: an |
| 12 | //! `UPDATE … SET n = n + 1 WHERE n < cap` on the *parent* row is atomic, so |
| 13 | //! of N concurrent claimers exactly `cap` get a non-empty result and the rest |
| 14 | //! are refused, with no lock and no window. The counter is therefore the |
| 15 | //! authority on how many slots are taken, and the child rows follow it: the |
| 16 | //! claim and the child's insert land in one statement (the CTE recipes |
| 17 | //! below), and a decrement rides the *same transaction* as every delete of a |
| 18 | //! child row. |
| 19 | //! |
| 20 | //! Postgres takes over the rest of what the old builders hand-rolled: |
| 21 | //! |
| 22 | //! * **Existence proof** — a real `FOREIGN KEY` refuses a child whose parent |
| 23 | //! is gone (SQLSTATE 23503), so the old bump-and-restore "touch" trick is |
| 24 | //! deleted. A gated variant ("parent must still be open") is |
| 25 | //! `INSERT … SELECT … WHERE EXISTS (SELECT 1 FROM parent WHERE id = $n AND <gate>)`. |
| 26 | //! * **Duplicate detection** — the child's primary key answers "another |
| 27 | //! writer placed this very row first" as SQLSTATE 23505 |
| 28 | //! (`crate::database::unique_violation`). |
| 29 | //! * **Retry** — `crate::database::tx_with_retry` owns the retry loop; a |
| 30 | //! refusal is an `Err` from the closure and is never retried, because a |
| 31 | //! refusal is a decision. |
| 32 | //! |
| 33 | //! ## The per-call-site recipes |
| 34 | //! |
| 35 | //! Table, column and cap names are crate constants, so every call site writes |
| 36 | //! its own static, macro-checkable statement (`sqlx::query!`). This module |
| 37 | //! keeps only the result types the call sites answer with, plus the one |
| 38 | //! genuinely shared mapping ([`full_kind`]). The shapes: |
| 39 | //! |
| 40 | //! ### Claim a seat and create the child (`claim_and_create` and its variants) |
| 41 | //! |
| 42 | //! ```sql |
| 43 | //! WITH seat AS ( |
| 44 | //! UPDATE <parent> |
| 45 | //! SET <cnt> = <cnt> + <bump> -- bump 0 for the uncounted create |
| 46 | //! WHERE id = $1 |
| 47 | //! AND <cnt> < $2 -- or: < (SELECT <cap_expr> …) (live cap) |
| 48 | //! -- AND (<guard>) -- the guarded variant: one predicate decides cap and precondition |
| 49 | //! RETURNING 1) |
| 50 | //! INSERT INTO <child> (id, <cols>) |
| 51 | //! SELECT $3, $4, … WHERE EXISTS (SELECT 1 FROM seat) |
| 52 | //! RETURNING <cols>; |
| 53 | //! ``` |
| 54 | //! |
| 55 | //! One statement is atomic: a refused insert takes its own seat bump back. |
| 56 | //! The verdict maps: one row → [`Claimed::Made`]; 23505 on the child key → |
| 57 | //! [`Claimed::Duplicate`] (read before the row count); zero rows → |
| 58 | //! [`Claimed::Full`] — deliberately still one marker for "full, guard failed, |
| 59 | //! parent gone", as before: the caller re-reads the parent to pick the |
| 60 | //! message, and only on that path. A live cap reads its capacity as a |
| 61 | //! subselect inside the same `WHERE`, so the write that lowers the cap and |
| 62 | //! the write that reads it still contend on one record; a lowered cap refuses |
| 63 | //! the very next claimer instead of admitting everyone whose snapshot predates |
| 64 | //! the edit. The uncounted create (`bump = 0`) still writes the seat |
| 65 | //! statement, so a missing parent row is refused as [`Claimed::Full`] on both |
| 66 | //! paths rather than silently writing a child of nobody. |
| 67 | //! |
| 68 | //! ### Two counters, one verdict (`claim_two_when_and_create`) |
| 69 | //! |
| 70 | //! ```sql |
| 71 | //! WITH bump AS ( |
| 72 | //! UPDATE board |
| 73 | //! SET total_stroke_count = total_stroke_count + 1, -- hard (lifetime) cap first |
| 74 | //! epoch_stroke_count = epoch_stroke_count + 1 -- soft (resettable) counter with it |
| 75 | //! WHERE id = $1 |
| 76 | //! AND total_stroke_count < $2 -- the hard cap carries the guard |
| 77 | //! AND epoch = $3 |
| 78 | //! AND epoch_stroke_count < $4 |
| 79 | //! RETURNING 1) |
| 80 | //! INSERT INTO board_stroke (id, <cols>) |
| 81 | //! SELECT $5, … WHERE EXISTS (SELECT 1 FROM bump) |
| 82 | //! RETURNING <cols>; |
| 83 | //! ``` |
| 84 | //! |
| 85 | //! One `UPDATE` moves both counters, so the row is written once and the |
| 86 | //! two-statement interleave the old process lock existed for cannot happen. |
| 87 | //! Zero rows means "hard full, guard failed, board gone, or soft full": the |
| 88 | //! caller re-reads both counters and maps them with [`full_kind`] — the |
| 89 | //! terminal cap outranks the recoverable one, as [`ClaimedTwo`] documents. |
| 90 | //! The child id is freshly minted, so no rival can aim at it and no 23505 |
| 91 | //! verdict exists on this path. |
| 92 | //! |
| 93 | //! ### Claim a reference on a name (`claim_ref_and_create`) |
| 94 | //! |
| 95 | //! In the caller's transaction, the duplicate gate stays *ahead* of the |
| 96 | //! retired check, so "you already have it" still outranks "the name is |
| 97 | //! retired": |
| 98 | //! |
| 99 | //! ```sql |
| 100 | //! SELECT 1 FROM <child> WHERE <its primary key>; -- found → ClaimedRef::Duplicate, stop |
| 101 | //! WITH ref AS ( |
| 102 | //! INSERT INTO <ref_table> (name, count) |
| 103 | //! VALUES ($1, $2) |
| 104 | //! ON CONFLICT (name) DO UPDATE |
| 105 | //! SET count = <ref_table>.count + EXCLUDED.count |
| 106 | //! WHERE <ref_table>.retired = false -- zero rows → ClaimedRef::Retired |
| 107 | //! RETURNING 1) |
| 108 | //! INSERT INTO <child> (…) |
| 109 | //! SELECT … WHERE EXISTS (SELECT 1 FROM ref) |
| 110 | //! RETURNING …; -- 23505 on the child key → ClaimedRef::Duplicate |
| 111 | //! ``` |
| 112 | //! |
| 113 | //! The 23505 backstop covers the rival that passed the same gate a moment |
| 114 | //! ago (referential integrity keeps "row exists ∧ name retired" unreachable: |
| 115 | //! retiring requires count = 0, and a live row holds a count). The counted |
| 116 | //! row and the count still commit together or not at all — a name counted for |
| 117 | //! a row that does not exist is a name nobody can ever retire. |
| 118 | //! |
| 119 | //! ### Retire / un-retire a name (produces a [`Switched`]) |
| 120 | //! |
| 121 | //! Two statements in the caller's transaction; the row lock makes the read |
| 122 | //! and the write one switch, which is why the old process lock is gone: |
| 123 | //! |
| 124 | //! ```sql |
| 125 | //! SELECT retired FROM <ref_table> WHERE name = $1 FOR UPDATE; -- absent → treated as false |
| 126 | //! INSERT INTO <ref_table> (name, count, retired) |
| 127 | //! VALUES ($1, 0, $2) |
| 128 | //! ON CONFLICT (name) DO UPDATE |
| 129 | //! SET retired = $2 |
| 130 | //! WHERE <ref_table>.count = 0 -- retire only |
| 131 | //! AND <ref_table>.retired IS DISTINCT FROM $2 -- idempotence |
| 132 | //! RETURNING 1; -- empty result → the write did not land |
| 133 | //! ``` |
| 134 | //! |
| 135 | //! `(landed, was.unwrap_or(false))` maps exactly as [`Switched`] documents. |
| 136 | //! Retiring a never-claimed name still creates its ref row retired (the |
| 137 | //! `INSERT` arm), as before. |
| 138 | //! |
| 139 | //! ### Role-gated grants (the old `role_claim` handshake) |
| 140 | //! |
| 141 | //! The grant-survives-demotion handshake is now two statements in the |
| 142 | //! caller's transaction — the old counter bump-and-restore dance is dead: |
| 143 | //! |
| 144 | //! ```sql |
| 145 | //! SELECT role FROM app_user WHERE id = $1 FOR NO KEY UPDATE; |
| 146 | //! -- Rust checks the role it found; unfit → the call-site refusal (no retry). |
| 147 | //! INSERT INTO <grant> …; |
| 148 | //! ``` |
| 149 | //! |
| 150 | //! The demotion cascade's transaction `UPDATE`s that same user row before its |
| 151 | //! sweeps, so grant and demotion serialize on the row lock in both |
| 152 | //! directions: either the sweep sees the grant row, or the grant saw the new |
| 153 | //! role. |
| 154 | |
| 155 | // the types below are the wave-2 lanes' verdict vocabulary |
| 156 | |
| 157 | /// "No cap" as a number, so the guard stays one comparison instead of a |
| 158 | /// nullable branch: `NULL` bind ambiguity is a worse trade than a sentinel no |
| 159 | /// roster will ever reach. |
| 160 | pub const UNLIMITED: i64 = i64MAX; |
| 161 | |
| 162 | /// What the claim-and-create recipe (module docs) settled. |
| 163 | pub |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | /// What the two-counter recipe (module docs) settled. |
| 174 | pub |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | /// What the reference-counter recipe (module docs) settled. |
| 189 | pub |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | /// What a retire / un-retire write did to the name's bit. |
| 201 | /// |
| 202 | /// The distinction a rollback lives on. Both writes are idempotent, so "it |
| 203 | /// ended up retired" says nothing about *who* retired it: a caller that undoes |
| 204 | /// a no-op undoes whoever really did flip the bit — two settings PATCHes each |
| 205 | /// dropping the same exam kind, one of them losing the row's compare-and-set, |
| 206 | /// left the kind gone from the list with its counter reading "in service", |
| 207 | /// which is a kind that grades again and can then never be removed. |
| 208 | pub |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | /// Which of [`ClaimedTwo`]'s caps refused a zero-row dual claim. |
| 220 | pub |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | |
| 227 | |
| 228 | /// Map a zero-row dual-counter claim, re-read off the parent row, onto |
| 229 | /// [`ClaimedTwo`]'s two full states. |
| 230 | /// |
| 231 | /// The recipe bumps both counters in one `UPDATE` with the hard cap's |
| 232 | /// conditions first, so zero rows means "hard full, guard failed, parent |
| 233 | /// gone, or soft full". The terminal cap outranks the recoverable one |
| 234 | /// everywhere: [`FullKind::Soft`] only when the soft counter is full *while* |
| 235 | /// the hard one still has room — every other answer, including the ambiguous |
| 236 | /// guard/gone case, folds into [`FullKind::Hard`], whose contract already |
| 237 | /// covers it. This is the old claim order (hard claim, guard attached, before |
| 238 | /// the soft one) expressed as a re-read. |
| 239 | pub |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 |