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

cap.rs273 lines, 12.3 KiBHistoryRawDownload
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#![allow(dead_code)] // 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.
160pub(crate) const UNLIMITED: i64 = i64::MAX;
161
162/// What the claim-and-create recipe (module docs) settled.
163pub(crate) enum Claimed<T> {
164 /// The seat and the row committed together.
165 Made(T),
166 /// The cap is full or the parent row is gone — nothing was written.
167 Full,
168 /// Another writer placed this very row first, so this caller never owed a
169 /// seat: nothing was written, and the winner's row is the answer.
170 Duplicate,
171}
172
173/// What the two-counter recipe (module docs) settled.
174pub(crate) enum ClaimedTwo<T> {
175 /// Both seats and the row committed together.
176 Made(T),
177 /// The *resettable* counter (the soft, epoch-scoped one) is full —
178 /// nothing was written, and whatever empties it lets the caller through
179 /// again.
180 FullSoft,
181 /// The *lifetime* counter is full, the guard failed, or the parent row is
182 /// gone — nothing was written. The caller re-reads the parent to tell
183 /// those apart, and only to pick the message: both are refusals the
184 /// caller cannot retry into a success.
185 FullHard,
186}
187
188/// What the reference-counter recipe (module docs) settled.
189pub(crate) enum ClaimedRef<T> {
190 /// The reference and the row committed together.
191 Made(T),
192 /// The name is retired — nothing was written, and no retry helps until
193 /// the name is put back in service.
194 Retired,
195 /// Another writer placed this very row first, so this caller never owed a
196 /// reference: nothing was written, and the winner's row is the answer.
197 Duplicate,
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.
208pub(crate) enum Switched {
209 /// This call flipped the bit; a rollback owes the opposite write.
210 Flipped,
211 /// The bit already stood that way — this call wrote nothing, so there is
212 /// nothing to take back, and taking it back would undo somebody else.
213 Unchanged,
214 /// Retirement only: something still references the name and the caller
215 /// must refuse. Nothing was written.
216 InUse,
217}
218
219/// Which of [`ClaimedTwo`]'s caps refused a zero-row dual claim.
220pub(crate) enum FullKind {
221 /// The resettable counter is full — recoverable by whatever empties it.
222 Soft,
223 /// The lifetime counter is full, the guard failed, or the parent row is
224 /// gone — terminal.
225 Hard,
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.
239pub(crate) fn full_kind(
240 soft_count: i64,
241 soft_cap: i64,
242 hard_count: i64,
243 hard_cap: i64,
244) -> FullKind {
245 if soft_count >= soft_cap && hard_count < hard_cap {
246 FullKind::Soft
247 } else {
248 FullKind::Hard
249 }
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255
256 /// The terminal cap outranks the recoverable one: only a soft-full-with-
257 /// hard-room claim is recoverable, everything else answers Hard — the old
258 /// claim order (hard first, guard attached), preserved as a re-read.
259 #[test]
260 fn the_terminal_cap_outranks_the_recoverable_one() {
261 // Soft full, hard with room: the one recoverable answer.
262 assert!(matches!(full_kind(5, 5, 9, 10), FullKind::Soft));
263 // Both full: terminal.
264 assert!(matches!(full_kind(5, 5, 9, 9), FullKind::Hard));
265 // Hard full alone.
266 assert!(matches!(full_kind(4, 5, 9, 9), FullKind::Hard));
267 // Neither full — the guard failed or the parent is gone, and both fold
268 // into the terminal answer, whose contract already covers them.
269 assert!(matches!(full_kind(4, 5, 8, 9), FullKind::Hard));
270 // Boundaries: exactly-at-cap is full.
271 assert!(matches!(full_kind(5, 5, 10, 10), FullKind::Hard));
272 }
273}