Shared primitives for parent-collision claims
Browse files at this commit558c39a55a57843e5c8da4bd4555cbaf382d1f3dParent: 12f2280- feat
- shared primitives for parent-collision claims
2 changed files +258 -23
- src/constant.rs +50 -8
- src/domain/cap.rs +208 -15
src/constant.rsmodified+50 -8
| @@ -231,6 +231,18 @@ pub const MAX_LEDGER_AMOUNT_MINOR: i64 = 10_000_000; | ||
| 231 | 231 | pub const MAX_LEDGER_METHOD_LEN: usize = 50; |
| 232 | 232 | pub const MAX_LEDGER_NOTE_LEN: usize = 500; |
| 233 | 233 | |
| 234 | +/// How many times one seat may be taken on one menu: the first booking plus | |
| 235 | +/// nine re-bookings after a cancel. | |
| 236 | +/// | |
| 237 | +/// A cap on *storage*, not on indecision. Every cycle appends two permanent, | |
| 238 | +/// undeletable ledger lines — the charge and its reversal, both keyed to the | |
| 239 | +/// attempt — and nothing else bounded them: at the API's own request ceiling | |
| 240 | +/// one account could grow its statement by hundreds of thousands of rows a | |
| 241 | +/// day, which every later balance read then answers for. Ten is far past what | |
| 242 | +/// a family changing its mind about lunch needs, and a menu whose seat really | |
| 243 | +/// must move again is the canteen's to cancel. | |
| 244 | +pub const MAX_MEAL_BOOKING_ATTEMPTS: i64 = 10; | |
| 245 | + | |
| 234 | 246 | /// Ceiling on the settings knob that closes booking (and cancelling) ahead of |
| 235 | 247 | /// a meal — one week. The knob itself is optional: absent means no cutoff. |
| 236 | 248 | pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60; |
| @@ -241,8 +253,10 @@ pub const MAX_MEAL_CANCEL_CUTOFF_MINUTES: i64 = 7 * 24 * 60; | ||
| 241 | 253 | /// |
| 242 | 254 | /// **The clock is UTC.** This backend deliberately stores no school timezone |
| 243 | 255 | /// (rejected feature), so staff enter the serving time in UTC: a UTC+3 school |
| 244 | -/// types `540` (09:00) to mean noon locally. Optional per slot — a slot | |
| 245 | -/// without one keeps the old behaviour, midnight UTC of the menu's date. | |
| 256 | +/// types `540` (09:00) to mean noon locally. Optional per slot — and a slot | |
| 257 | +/// without one has **no cutoff at all**, since there is no instant to count a | |
| 258 | +/// deadline back from; the cutoff knob starts binding that slot the day the | |
| 259 | +/// school sets its hour. | |
| 246 | 260 | pub const MAX_MEAL_SERVING_MINUTE: i64 = 24 * 60 - 1; |
| 247 | 261 | |
| 248 | 262 | /// The only accepted course kinds. `course`: a regular class (ders). `study`: |
| @@ -298,11 +312,27 @@ pub const MAX_FEE_PLAN_NAME_LEN: usize = 120; | ||
| 298 | 312 | pub const MAX_FEE_PLAN_INSTALLMENTS: usize = 60; |
| 299 | 313 | |
| 300 | 314 | /// How many students one `POST /payments/plans/{id}/assignments` may name. |
| 301 | -/// Bulk placement is a whole class at a time, not the whole school: each named | |
| 302 | -/// student appends every installment of the plan, so this is what bounds one | |
| 303 | -/// request's writes. | |
| 315 | +/// Bulk placement is a whole class at a time, not the whole school. | |
| 304 | 316 | pub const MAX_FEE_PLAN_ASSIGN_STUDENTS: usize = 200; |
| 305 | 317 | |
| 318 | +/// How many charge lines one assignment request may append: the students it | |
| 319 | +/// names times the plan's installments. The student cap alone cannot see the | |
| 320 | +/// schedule — 200 students on a 60-installment plan is 12 000 sequential | |
| 321 | +/// writes in one HTTP request, and nothing in the stack times a request out. | |
| 322 | +/// Three thousand leaves the ordinary shapes whole (200 students up to a | |
| 323 | +/// 15-installment plan, 50 students on the largest plan there is) and the | |
| 324 | +/// refusal tells the caller to split the batch. | |
| 325 | +pub const MAX_FEE_PLAN_ASSIGN_WRITES: usize = 3_000; | |
| 326 | + | |
| 327 | +/// How many lines may be applied to one ledger line — the payments under a | |
| 328 | +/// charge, the refunds under a payment, and every reversal among them. The | |
| 329 | +/// over-payment cap folds that whole subtree one query per line while holding | |
| 330 | +/// the process-global payment lock, so an unbounded subtree is an unbounded | |
| 331 | +/// stall for every other payment in the school: 2 000 one-kuruş payments make | |
| 332 | +/// the next one issue 2 001 queries with the lock held. Twenty pieces is | |
| 333 | +/// already a pathological way to settle a single installment. | |
| 334 | +pub const MAX_LEDGER_APPLIED_LINES: usize = 20; | |
| 335 | + | |
| 306 | 336 | /// Ceiling on the client-chosen `request_key` that makes a credit or a refund |
| 307 | 337 | /// retry-safe: it becomes part of the ledger line's record id, so it is bounded |
| 308 | 338 | /// and drawn from `[A-Za-z0-9-]` — `_` joins the parts of a ledger id, so a key |
| @@ -851,6 +881,14 @@ pub const FEE_PLAN_UNASSIGNED_GUARD: &str = "(assignment_count ?? 0) = 0"; | ||
| 851 | 881 | pub const NOTE_FILE_COUNT_FIELD: &str = "file_count"; |
| 852 | 882 | pub const SUBMISSION_FILE_COUNT_FIELD: &str = "file_count"; |
| 853 | 883 | pub const CHATBOT_THREAD_COUNT_FIELD: &str = "chatbot_thread_count"; |
| 884 | +/// The column a *grant* claim moves and puts back, so its transaction writes | |
| 885 | +/// the holder's own `user` record — the one key | |
| 886 | +/// [`crate::domain::user::User::set_role`] writes (see | |
| 887 | +/// [`crate::domain::cap::role_claim`]). Any `option<int>` on the row would do: | |
| 888 | +/// the claim nets zero and never reads it, so this is an alias rather than a | |
| 889 | +/// column of its own — a new one would mean a migration on a SCHEMAFULL table | |
| 890 | +/// for a value nothing ever observes. | |
| 891 | +pub const USER_ROLE_CLAIM_FIELD: &str = CHATBOT_THREAD_COUNT_FIELD; | |
| 854 | 892 | /// How many boards this user created, on the user row — the same per-user shape |
| 855 | 893 | /// as `CHATBOT_THREAD_COUNT_FIELD`, capped at `MAX_BOARDS_PER_CREATOR`. It is |
| 856 | 894 | /// what closes the "open another board" way around the two board counters |
| @@ -865,9 +903,13 @@ pub const USER_BOARD_COUNT_FIELD: &str = "board_count"; | ||
| 865 | 903 | /// submit/delete/submit), and a teacher un-grading gives back |
| 866 | 904 | /// `MARKS_GIVEN` — with `HIGH_MARK` on the exam side, credited to the student |
| 867 | 905 | /// by the same act (else one exam becomes fifty by grade/ungrade/regrade). |
| 868 | -/// The exam and pomodoro totals never decrease at all: there is no delete | |
| 869 | -/// behind them but a teacher's, so sitting an exam or finishing a stint is a | |
| 870 | -/// lifetime fact. Nothing else decrements: the cascades (an exam, a homework or | |
| 906 | +/// The exam and pomodoro totals never decrease at all, and each earns that by | |
| 907 | +/// counting something a repeat cannot re-earn rather than by anyone's restraint: | |
| 908 | +/// `EXAM_SAT_TOTAL` counts *exams sat*, moving only on a student's first sitting | |
| 909 | +/// of an exam (`seq == 1`), because retakes are a loop the student drives alone — | |
| 910 | +/// an open exam with unlimited attempts is start/finish/start, no teacher in it — | |
| 911 | +/// and a stint is a span of time that has to be lived through to be finished. | |
| 912 | +/// Nothing else decrements: the cascades (an exam, a homework or | |
| 871 | 913 | /// a course delete, which do take the attempt and result rows with them) leave |
| 872 | 914 | /// them alone, since history a teacher erased is still history the student |
| 873 | 915 | /// lived. A badge already earned is never taken back either, whatever a counter |
src/domain/cap.rsmodified+208 -15
| @@ -22,16 +22,19 @@ | ||
| 22 | 22 | //! (every parent's `.content()` write is a create of a fresh row). |
| 23 | 23 | // |
| 24 | 24 | // ponytail: a counter can only drift if a future delete path forgets its |
| 25 | -// decrement, and the boot backfill seeds counters once rather than recomputing | |
| 26 | -// them (recomputing on every boot would clobber a live peer's increments). If | |
| 27 | -// drift is ever observed, the repair is the same GROUP BY count the backfill | |
| 28 | -// runs, issued by hand with the field's `= NONE` guard dropped. | |
| 25 | +// decrement, and the boot backfill seeds most counters once rather than | |
| 26 | +// recomputing them. `enrollment_count` is the one that already drifted (the boot | |
| 27 | +// sweep of promoted users' rows kept their seats), so it is recomputed on every | |
| 28 | +// boot instead — see the repair in `migration_sql::BACKFILL`. That is the shape | |
| 29 | +// to copy for any other counter drift observed: a counter whose meaning is | |
| 30 | +// exactly "the live child rows" converges on a recompute, a lifetime tally does | |
| 31 | +// not and must stay seeded once. | |
| 29 | 32 | |
| 30 | 33 | use surrealdb::types::{RecordId, SurrealValue}; |
| 31 | 34 | use tokio::sync::Mutex; |
| 32 | 35 | |
| 33 | -use crate::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD}; | |
| 34 | -use crate::database::{Database, backoff, lost_the_race}; | |
| 36 | +use crate::constant::{CAP_WRITE_TRIES, REF_COUNT_FIELD, REF_RETIRED_FIELD, USER_ROLE_CLAIM_FIELD}; | |
| 37 | +use crate::database::{Database, backoff, lost_the_race, transaction_with_retry}; | |
| 35 | 38 | use crate::error::AppError; |
| 36 | 39 | |
| 37 | 40 | /// One counter writer at a time, over every counter. |
| @@ -160,7 +163,34 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | ||
| 160 | 163 | content: &T, |
| 161 | 164 | db: &Database, |
| 162 | 165 | ) -> Result<Claimed<T>, AppError> { |
| 163 | - claim_at_and_create(parent, field, "$num", cap, "", id, content, db).await | |
| 166 | + claim_at_and_create(parent, field, "$num", cap, "", 1, None, id, content, db).await | |
| 167 | +} | |
| 168 | + | |
| 169 | +/// [`claim_and_create`] for a counter only *some* of a parent's children move: | |
| 170 | +/// the row lands either way, and `counts` decides whether the tally follows it. | |
| 171 | +/// | |
| 172 | +/// The one live user is `exam_sat_total`, which counts exams sat rather than | |
| 173 | +/// sittings — a retake writes a row and moves nothing. Splitting that into | |
| 174 | +/// "count and create" versus a bare create outside this module would put the | |
| 175 | +/// uncounted write on a different statement to the counted one, and a | |
| 176 | +/// deterministic child id needs the duplicate abort either way: whichever | |
| 177 | +/// branch runs, exactly one writer's `CREATE` commits, and only that one's | |
| 178 | +/// increment survives with it. `counts` false still writes the seat statement | |
| 179 | +/// (`+ 0`), so a missing parent row is refused as [`Claimed::Full`] on both | |
| 180 | +/// paths rather than silently writing a child of nobody. | |
| 181 | +pub(crate) async fn create_counting<T: SurrealValue + Clone>( | |
| 182 | + parent: &RecordId, | |
| 183 | + field: &str, | |
| 184 | + counts: bool, | |
| 185 | + id: &RecordId, | |
| 186 | + content: &T, | |
| 187 | + db: &Database, | |
| 188 | +) -> Result<Claimed<T>, AppError> { | |
| 189 | + let bump = i64::from(counts); | |
| 190 | + claim_at_and_create( | |
| 191 | + parent, field, "$num", UNLIMITED, "", bump, None, id, content, db, | |
| 192 | + ) | |
| 193 | + .await | |
| 164 | 194 | } |
| 165 | 195 | |
| 166 | 196 | /// [`claim_and_create`] against a cap the *statement* reads rather than one the |
| @@ -177,16 +207,27 @@ pub(crate) async fn claim_and_create<T: SurrealValue + Clone>( | ||
| 177 | 207 | /// the write that lowered it and the write that reads it contend on one record. |
| 178 | 208 | /// |
| 179 | 209 | /// `cap_expr` is always an in-crate SQL literal, never text from a client. |
| 210 | +/// | |
| 211 | +/// `holder` is the child's *other* parent when that parent is a user whose live | |
| 212 | +/// role decides whether the row may exist at all: `(the user record, the role | |
| 213 | +/// it may not carry)`, claimed by [`role_claim`] in this same transaction. A | |
| 214 | +/// refusal from it arrives as [`Claimed::Full`], which already means "full, or | |
| 215 | +/// the guard failed, or the parent is gone" — the caller re-reads to pick the | |
| 216 | +/// message, and only on that path. | |
| 180 | 217 | pub(crate) async fn claim_live_and_create<T: SurrealValue + Clone>( |
| 181 | 218 | parent: &RecordId, |
| 182 | 219 | field: &str, |
| 183 | 220 | cap_expr: &str, |
| 184 | 221 | fallback: i64, |
| 222 | + holder: Option<(&RecordId, &str)>, | |
| 185 | 223 | id: &RecordId, |
| 186 | 224 | content: &T, |
| 187 | 225 | db: &Database, |
| 188 | 226 | ) -> Result<Claimed<T>, AppError> { |
| 189 | - claim_at_and_create(parent, field, cap_expr, fallback, "", id, content, db).await | |
| 227 | + claim_at_and_create( | |
| 228 | + parent, field, cap_expr, fallback, "", 1, holder, id, content, db, | |
| 229 | + ) | |
| 230 | + .await | |
| 190 | 231 | } |
| 191 | 232 | |
| 192 | 233 | /// [`claim_and_create`], but only while `guard` — an extra predicate on that |
| @@ -212,7 +253,7 @@ pub(crate) async fn claim_when_and_create<T: SurrealValue + Clone>( | ||
| 212 | 253 | content: &T, |
| 213 | 254 | db: &Database, |
| 214 | 255 | ) -> Result<Claimed<T>, AppError> { |
| 215 | - claim_at_and_create(parent, field, "$num", cap, guard, id, content, db).await | |
| 256 | + claim_at_and_create(parent, field, "$num", cap, guard, 1, None, id, content, db).await | |
| 216 | 257 | } |
| 217 | 258 | |
| 218 | 259 | #[allow(clippy::too_many_arguments)] |
| @@ -222,6 +263,8 @@ async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 222 | 263 | cap_expr: &str, |
| 223 | 264 | cap: i64, |
| 224 | 265 | extra: &str, |
| 266 | + bump: i64, | |
| 267 | + holder: Option<(&RecordId, &str)>, | |
| 225 | 268 | id: &RecordId, |
| 226 | 269 | content: &T, |
| 227 | 270 | db: &Database, |
| @@ -231,11 +274,23 @@ async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 231 | 274 | } else { |
| 232 | 275 | format!(" AND ({extra})") |
| 233 | 276 | }; |
| 277 | + // The holder's claim rides between the duplicate gate and the seat, so a | |
| 278 | + // caller whose row a rival placed is still told "you already have it", and | |
| 279 | + // a demotion outranks a full cap: `Full` on a list with room left sends | |
| 280 | + // nobody looking for a seat that is not the problem. | |
| 281 | + let held_by = holder.map_or_else(Vec::new, |(_, unfit)| { | |
| 282 | + role_claim("holder", unfit, FULL_MARK) | |
| 283 | + }); | |
| 284 | + let hold = if held_by.is_empty() { | |
| 285 | + String::new() | |
| 286 | + } else { | |
| 287 | + format!("{};\n", held_by.join(";\n")) | |
| 288 | + }; | |
| 234 | 289 | let sql = format!( |
| 235 | 290 | "BEGIN TRANSACTION; |
| 236 | 291 | LET $held = (SELECT VALUE id FROM $id); |
| 237 | 292 | IF array::len($held) > 0 {{ THROW '{HELD_MARK}' }}; |
| 238 | - LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 \ | |
| 293 | + {hold}LET $seat = (UPDATE $parent SET {field} = ({field} ?? 0) + $bump \ | |
| 239 | 294 | WHERE ({field} ?? 0) < ({cap_expr}){extra} RETURN VALUE id); |
| 240 | 295 | IF array::len($seat) = 0 {{ THROW '{FULL_MARK}' }}; |
| 241 | 296 | CREATE $id CONTENT $row; |
| @@ -245,13 +300,17 @@ async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 245 | 300 | let mut last = None; |
| 246 | 301 | for attempt in 0..CAP_WRITE_TRIES { |
| 247 | 302 | backoff(attempt).await; |
| 248 | - let attempted = db | |
| 303 | + let mut query = db | |
| 249 | 304 | .query(sql.as_str()) |
| 250 | 305 | .bind(("parent", parent.clone())) |
| 251 | 306 | .bind(("num", cap)) |
| 307 | + .bind(("bump", bump)) | |
| 252 | 308 | .bind(("id", id.clone())) |
| 253 | - .bind(("row", content.clone())) | |
| 254 | - .await; | |
| 309 | + .bind(("row", content.clone())); | |
| 310 | + if let Some((record, _)) = holder { | |
| 311 | + query = query.bind(("holder", record.clone())); | |
| 312 | + } | |
| 313 | + let attempted = query.await; | |
| 255 | 314 | let mut result = match attempted { |
| 256 | 315 | Ok(result) => result, |
| 257 | 316 | Err(err) if lost_the_race(&err) => { |
| @@ -289,9 +348,13 @@ async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 289 | 348 | if let Some(error) = errors.drain().map(|(_, error)| error).next() { |
| 290 | 349 | return Err(error.into()); |
| 291 | 350 | } |
| 292 | - // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5. | |
| 351 | + // Slots count BEGIN, two LETs and two IFs: the CREATE is slot 5, plus | |
| 352 | + // the holder claim's own statements when one is carried — counted, not | |
| 353 | + // tallied by hand, so a statement added there cannot read back the | |
| 354 | + // wrong result. | |
| 355 | + let slot = 5 + held_by.len(); | |
| 293 | 356 | return result |
| 294 | - .take::<Vec<T>>(5)? | |
| 357 | + .take::<Vec<T>>(slot)? | |
| 295 | 358 | .into_iter() |
| 296 | 359 | .next() |
| 297 | 360 | .map(Claimed::Made) |
| @@ -302,6 +365,134 @@ async fn claim_at_and_create<T: SurrealValue + Clone>( | ||
| 302 | 365 | .unwrap_or_else(|| AppError::Internal("cap counter write never ran".into()))) |
| 303 | 366 | } |
| 304 | 367 | |
| 368 | +/// The marker [`touch_and_create`] aborts with: the parent row is gone. | |
| 369 | +const GONE_MARK: &str = "cap_gone"; | |
| 370 | + | |
| 371 | +/// Write a child of `parent` while *colliding* with anything that removes the | |
| 372 | +/// parent — no seat spent, only the proof. `Ok(None)` = the parent is gone and | |
| 373 | +/// nothing was written. | |
| 374 | +/// | |
| 375 | +/// Reading the parent first and then inserting cannot promise this, and neither | |
| 376 | +/// can a `SELECT` inside the transaction: SurrealDB 3.2.3 conflict-checks write | |
| 377 | +/// sets, not read sets, so a create landing inside a parent delete's window | |
| 378 | +/// reads a row that is still there (removed, uncommitted) while the delete's | |
| 379 | +/// `DELETE <child> WHERE parent = $parent` sweep already ran on a snapshot | |
| 380 | +/// without this row — both commit, and the child outlives its parent | |
| 381 | +/// unreachably, because every route to it goes through the parent. | |
| 382 | +/// | |
| 383 | +/// So the proof is a *write* on the parent's own record, which is the key the | |
| 384 | +/// delete writes. `field` is moved — bumped and put back by captured value, | |
| 385 | +/// `NONE` included, so the row is byte-identical afterwards — because an | |
| 386 | +/// `UPDATE` that leaves the document unchanged is elided and never enters the | |
| 387 | +/// write set: `SET x = x` sits on no key at all and collides with nothing | |
| 388 | +/// (measured on 3.2.3, and the reason | |
| 389 | +/// [`crate::domain::class_pump::Axis::pivot_claim`] and | |
| 390 | +/// [`crate::domain::exam_answer::ExamAnswer::save`] have the same shape). Both | |
| 391 | +/// statements are inside the transaction, so an abort between them cannot leave | |
| 392 | +/// the counter up. | |
| 393 | +/// | |
| 394 | +/// It lives here because it is [`claim_and_create`] with the cap removed: the | |
| 395 | +/// same single-record conditional write on the parent, asked "are you still | |
| 396 | +/// there?" instead of "is there room?". No [`CLAIM_LOCK`] either — the counter | |
| 397 | +/// nets zero, so no cap depends on the order these arrive in. | |
| 398 | +/// | |
| 399 | +/// Admissible for [`crate::database::transaction_with_retry`]: `UPDATE`s and a | |
| 400 | +/// `CREATE` whose id is a freshly minted ULID no rival can aim at, so no | |
| 401 | +/// statement can legitimately answer "already exists" and a lost round wrote | |
| 402 | +/// nothing. | |
| 403 | +pub(crate) async fn touch_and_create<T: SurrealValue + Clone>( | |
| 404 | + parent: &RecordId, | |
| 405 | + field: &str, | |
| 406 | + id: &RecordId, | |
| 407 | + content: &T, | |
| 408 | + db: &Database, | |
| 409 | +) -> Result<Option<T>, AppError> { | |
| 410 | + let sql = format!( | |
| 411 | + "BEGIN TRANSACTION; | |
| 412 | + LET $was = (SELECT VALUE {field} FROM ONLY $parent); | |
| 413 | + LET $alive = (UPDATE $parent SET {field} = ({field} ?? 0) + 1 RETURN VALUE id); | |
| 414 | + IF array::len($alive) = 0 {{ THROW '{GONE_MARK}' }}; | |
| 415 | + UPDATE $parent SET {field} = $was; | |
| 416 | + LET $made = (CREATE $id CONTENT $row RETURN AFTER); | |
| 417 | + RETURN $made[0]; | |
| 418 | + COMMIT TRANSACTION;" | |
| 419 | + ); | |
| 420 | + let (mut result, mut errors) = transaction_with_retry( | |
| 421 | + db, | |
| 422 | + &sql, | |
| 423 | + &[ | |
| 424 | + ("parent".into(), parent.clone().into_value()), | |
| 425 | + ("id".into(), id.clone().into_value()), | |
| 426 | + ("row".into(), content.clone().into_value()), | |
| 427 | + ], | |
| 428 | + &[GONE_MARK], | |
| 429 | + ) | |
| 430 | + .await?; | |
| 431 | + // An aborted transaction errors *every* slot, most with a generic "not | |
| 432 | + // executed" — only the THROW's own slot names the marker. | |
| 433 | + if errors | |
| 434 | + .values() | |
| 435 | + .any(|error| error.to_string().contains(GONE_MARK)) | |
| 436 | + { | |
| 437 | + return Ok(None); | |
| 438 | + } | |
| 439 | + if let Some(error) = errors.drain().map(|(_, error)| error).next() { | |
| 440 | + return Err(error.into()); | |
| 441 | + } | |
| 442 | + // The trailing `RETURN` is the last statement before `COMMIT`, so its slot | |
| 443 | + // follows the statement count rather than a hand-kept number; | |
| 444 | + // `num_statements` counts BEGIN and COMMIT. | |
| 445 | + let slot = result.num_statements().saturating_sub(2); | |
| 446 | + result | |
| 447 | + .take::<Vec<T>>(slot)? | |
| 448 | + .into_iter() | |
| 449 | + .next() | |
| 450 | + .map(Some) | |
| 451 | + .ok_or_else(|| AppError::Internal("the parent touch wrote no row".into())) | |
| 452 | +} | |
| 453 | + | |
| 454 | +/// The statements that put a transaction's write on a **user's own record** | |
| 455 | +/// while the role that row still carries may hold the grant being written — | |
| 456 | +/// [`touch_and_create`]'s trick pointed at the one key | |
| 457 | +/// [`crate::domain::user::User::set_role`] writes. | |
| 458 | +/// | |
| 459 | +/// WHY: a demotion sheds every grant the old role implied, and it does that in | |
| 460 | +/// the role write's own transaction — but its sweeps are *snapshots* | |
| 461 | +/// (`DELETE <child> WHERE user = $usr`), and SurrealDB 3.2.3 conflict-checks | |
| 462 | +/// write sets, not read sets. A seat, an enrollment or a class membership | |
| 463 | +/// created after that snapshot therefore survives the sweep, and nothing ever | |
| 464 | +/// re-sweeps: the grant stands forever under a role that may not hold it. Every | |
| 465 | +/// one of those creates writes its *other* parent (the event, the course, the | |
| 466 | +/// class), so it shares no key with the demotion and the store has nothing to | |
| 467 | +/// settle. | |
| 468 | +/// | |
| 469 | +/// So the counter named by [`USER_ROLE_CLAIM_FIELD`] is **moved** — bumped and | |
| 470 | +/// put back by captured value, `NONE` included, so the row is byte-identical | |
| 471 | +/// afterwards — because re-stating a value claims nothing: an `UPDATE` that | |
| 472 | +/// leaves the document unchanged is elided and enters no write set. The same | |
| 473 | +/// `UPDATE` hands back the role it found, so one statement is both the write | |
| 474 | +/// that collides and the read that decides. Either the sweep sees this row, or | |
| 475 | +/// this statement sees the demotion; and the caller that *loses* the conflict | |
| 476 | +/// re-sends into a fresh transaction that reads the new role, which is what | |
| 477 | +/// keeps the retry from turning a refusal into a success. | |
| 478 | +/// | |
| 479 | +/// A user row that is not there claims nothing and refuses nothing: the | |
| 480 | +/// `UPDATE` matches no key, and every caller has already answered a missing | |
| 481 | +/// target its own way. `holder` names the binding the user record is bound to, | |
| 482 | +/// and `unfit` is an in-crate comparison against the role that may *not* hold | |
| 483 | +/// this grant — never text from a client. | |
| 484 | +pub(crate) fn role_claim(holder: &str, unfit: &str, mark: &str) -> Vec<String> { | |
| 485 | + vec![ | |
| 486 | + format!("LET $role_was = (SELECT VALUE {USER_ROLE_CLAIM_FIELD} FROM ONLY ${holder})"), | |
| 487 | + format!( | |
| 488 | + "LET $role_now = (UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = \ | |
| 489 | + ({USER_ROLE_CLAIM_FIELD} ?? 0) + 1 RETURN VALUE role)" | |
| 490 | + ), | |
| 491 | + format!("IF array::len($role_now) > 0 AND $role_now[0] {unfit} {{ THROW '{mark}' }}"), | |
| 492 | + format!("UPDATE ${holder} SET {USER_ROLE_CLAIM_FIELD} = $role_was"), | |
| 493 | + ] | |
| 494 | +} | |
| 495 | + | |
| 305 | 496 | /// What [`claim_two_when_and_create`] settled. |
| 306 | 497 | pub(crate) enum ClaimedTwo<T> { |
| 307 | 498 | /// Both seats and the row committed together. |
| @@ -1046,6 +1237,7 @@ mod tests { | ||
| 1046 | 1237 | BOARD_EPOCH_STROKE_COUNT_FIELD, |
| 1047 | 1238 | "epoch ?? $num", |
| 1048 | 1239 | UNLIMITED, |
| 1240 | + None, | |
| 1049 | 1241 | &RecordId::new("board_stroke", "s1"), |
| 1050 | 1242 | &a_stroke(), |
| 1051 | 1243 | &db, |
| @@ -1072,6 +1264,7 @@ mod tests { | ||
| 1072 | 1264 | BOARD_EPOCH_STROKE_COUNT_FIELD, |
| 1073 | 1265 | "capacity ?? $num", |
| 1074 | 1266 | UNLIMITED, |
| 1267 | + None, | |
| 1075 | 1268 | &RecordId::new("board_stroke", "s1"), |
| 1076 | 1269 | &a_stroke(), |
| 1077 | 1270 | &db, |