diff --git a/src/db/fee_plan.rs b/src/db/fee_plan.rs index 4810bd2..ded1235 100644 --- a/src/db/fee_plan.rs +++ b/src/db/fee_plan.rs @@ -1,13 +1,18 @@ //! The `fee_plan` table: the create, the reads, and the guarded edit and //! delete. Both guards are conditional single-record writes on the plan's own -//! refcount — the WHERE clause *is* the assigned-plan freeze rule — so they -//! live here whole. The web-facing doors are [`crate::service::fee_plan`]. +//! refcount (`assignment_count`) — the WHERE clause *is* the assigned-plan +//! freeze rule — so they live here whole. The web-facing doors are +//! [`crate::service::fee_plan`]. +//! +//! Postgres replaces the old process lock with the row itself: the assign's +//! claim (`UPDATE fee_plan SET assignment_count = …` in +//! [`crate::db::fee_plan_assignment::create`]) and the guarded edit/delete +//! below all rewrite this one row, so they take its row lock and re-check +//! their condition against the committed winner — an assign racing an edit +//! either claims first (the edit is refused) or claims after (and bills the +//! edited plan, which it re-reads). No window, no mutex. -use surrealdb::types::SurrealValue; - -use crate::constant::FEE_PLAN_UNASSIGNED_GUARD; -use crate::database::{Database, write_with_retry}; -use crate::db::field_update::FieldUpdate; +use crate::database::Database; use crate::db::page::PagedList; use crate::domain::fee_plan::{ FeePlan, FeePlanId, FeePlanName, Installment, validate_installments, @@ -23,19 +28,34 @@ pub async fn create( created_by: &UserId, ) -> Result { validate_installments(&installments)?; - let plan = FeePlan { - id: FeePlanId::generate(), + let id = FeePlanId::generate(); + let created_at = Timestamp::now(); + sqlx::query_as!( + FeePlan, + "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \ + VALUES ($1, $2, $3, $4, $5) \ + RETURNING id, name, installments, created_by, created_at", + id, name, - installments, - created_by: created_by.clone(), - created_at: Timestamp::now(), - }; - let created: Option = db.create(plan.id.record()).content(plan).await?; - created.ok_or_else(|| AppError::Internal("failed to create fee plan".into())) + sqlx::types::Json(installments), + created_by, + created_at, + ) + .fetch_one(db) + .await + .map_err(Into::into) } pub async fn read(db: &Database, id: &FeePlanId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + sqlx::query_as!( + FeePlan, + "SELECT id, name, installments, created_by, created_at \ + FROM fee_plan WHERE id = $1", + id, + ) + .fetch_optional(db) + .await + .map_err(Into::into) } /// Every plan, newest first — a school runs a handful. @@ -50,20 +70,25 @@ pub async fn list_all( } /// Write only the fields the PATCH carried — `None` means the request -/// omitted it, so the column is left alone rather than re-stated from the -/// snapshot this struct was read into. `Err(Conflict)` = refused, nothing -/// was written: somebody is already on the plan. +/// omitted it, so the column is left alone (`COALESCE` keeps the stored +/// value) rather than re-stated from the snapshot this struct was read into. +/// Zero rows = refused, nothing was written: somebody is already on the plan. /// /// Editing a plan never moves money: charges are frozen copies of the /// installments as they stood when the plan was assigned. That is exactly /// why an assigned plan may not be edited at all — the plan and the charges /// raised from it would tell different stories. The roster is the plan's own -/// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same -/// transaction as the assignment row, so the check and the write are one -/// conditional `UPDATE` on one record: an assign racing this either claims -/// first (and the edit is refused) or claims after (and bills the edited -/// plan, which it re-reads). A `SELECT`-then-write could be, and was, -/// stepped over in the gap between the two. +/// `assignment_count` refcount, claimed in the same statement as the +/// assignment row ([`crate::db::fee_plan_assignment::create`]), so the check +/// and the write are one conditional `UPDATE` on one record: an assign +/// racing this either claims first (and the edit is refused) or claims +/// after (and bills the edited plan, which it re-reads). A +/// `SELECT`-then-write could be, and was, stepped over in the gap between +/// the two. +/// +/// A request that carried no field at all is answered before the guarded +/// statement: it writes nothing (and must not be refused as "assigned"), +/// so the row is simply read back. pub async fn update( db: &Database, plan: FeePlan, @@ -73,24 +98,35 @@ pub async fn update( if let Some(installments) = &installments { validate_installments(installments)?; } - let edited = FieldUpdate::new(plan.id.record()) - .set("name", name) - .set("installments", installments) - .guard( - FEE_PLAN_UNASSIGNED_GUARD, - AppError::Conflict("an assigned plan cannot be edited"), - ) - .run::(db) - .await; + if name.is_none() && installments.is_none() { + // A PATCH asking for no change writes nothing; the row (or its 404) + // is the whole answer, assigned or not. + return read(db, &plan.id).await?.ok_or(AppError::NotFound); + } + let edited = sqlx::query_as!( + FeePlan, + "UPDATE fee_plan \ + SET name = COALESCE($2, name), installments = COALESCE($3, installments) \ + WHERE id = $1 AND assignment_count = 0 \ + RETURNING id, name, installments, created_by, created_at", + plan.id, + name.map(|n| n.as_str().to_string()), + installments.map(sqlx::types::Json), + ) + .fetch_optional(db) + .await?; // Still assigned or already gone: the guarded `UPDATE` cannot tell those - // apart either (it reports the refusal it was given), so — exactly as - // [`crate::db::fee_plan::delete`] does — only the refusal path pays for the read - // that can. A plan deleted in the window since the handler read it must - // not be refused as "assigned": it never was. - if matches!(edited, Err(AppError::Conflict(_))) && read(db, &plan.id).await?.is_none() { - return Err(AppError::NotFound); + // apart (zero rows covers both), so — exactly as [`delete`] does — only + // the refusal path pays for the read that can. A plan deleted in the + // window since the handler read it must not be refused as "assigned": it + // never was. + match edited { + Some(plan) => Ok(plan), + None => match read(db, &plan.id).await? { + Some(_) => Err(AppError::Conflict("an assigned plan cannot be edited")), + None => Err(AppError::NotFound), + }, } - edited } /// Delete the plan, but only while nobody is on it. `false` = refused, @@ -99,16 +135,19 @@ pub async fn update( /// same reason — the charges an assignment raised name this plan, and a /// school's financial history keeps its references. /// -/// Retried while the store answers "conflict, retry": the guard reads a -/// counter an assign *writes*, so the two contend on this one record by -/// design — and a delete that loses that round has written nothing, so -/// re-sending it is the whole of the recovery. Without the retry an -/// ordinary raced delete answers 500 instead of the 404 or 409 it owes. +/// A single guarded statement needs no retry loop: the guard rewrites the +/// plan row itself, so it contends with an assign's claim on that row's lock +/// and whichever version lands, the loser re-evaluated against the winner's +/// committed state. Nothing was written on a loss, so there is nothing to +/// unwind. pub async fn delete(db: &Database, plan: FeePlan) -> Result { - let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE"); - let deleted: Vec = - write_with_retry(db, &sql, &[("plan".into(), plan.id.record().into_value())]).await?; - if !deleted.is_empty() { + let deleted = sqlx::query!( + "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id", + plan.id, + ) + .fetch_optional(db) + .await?; + if deleted.is_some() { return Ok(true); } // Still assigned or already gone: the one statement cannot tell those diff --git a/src/db/fee_plan_assignment.rs b/src/db/fee_plan_assignment.rs index 87ca89c..9f6fd66 100644 --- a/src/db/fee_plan_assignment.rs +++ b/src/db/fee_plan_assignment.rs @@ -1,13 +1,14 @@ -//! The `fee_plan_assignment` table: the reads over placements. The row is -//! written by [`crate::service::fee_plan_assignment::assign`], whose claim -//! ([`crate::db::cap::claim_and_create`]) is the write that freezes the plan. - -use surrealdb::types::RecordId; +//! The `fee_plan_assignment` table: the claim that places a student on a plan +//! (and freezes the plan), plus the reads over placements. The billing the +//! claim triggers lives in [`crate::service::fee_plan_assignment::assign`]; +//! the ledger appends in [`crate::db::payment_ledger`]. use crate::database::Database; +use crate::db::cap::{self, Claimed}; use crate::db::page::PagedList; use crate::domain::fee_plan::FeePlanId; use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId}; +use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; @@ -15,7 +16,68 @@ pub async fn read( db: &Database, id: &FeePlanAssignmentId, ) -> Result, AppError> { - Ok(db.select(id.record()).await?) + sqlx::query_as!( + FeePlanAssignment, + "SELECT plan, student, assigned_by, created_at \ + FROM fee_plan_assignment WHERE plan = $1 AND student = $2", + id.plan, + id.student, + ) + .fetch_optional(db) + .await + .map_err(Into::into) +} + +/// Place one (plan, student) assignment and claim the plan's assignment +/// refcount in the **same statement** — that increment is what makes the plan +/// un-editable and un-deletable ([`crate::db::fee_plan::update`]/[`delete`]), +/// and it has to be indivisible from the row it counts, or an edit could slip +/// between the two. The claim recipe ([`crate::db::cap`]'s +/// claim-and-create): a conditional `UPDATE` on the plan row seats the count, +/// the `INSERT` rides `WHERE EXISTS` on that seat, and one statement decides. +/// +/// The verdict maps as the guard layer promises: 23505 on +/// `fee_plan_assignment_plan` → [`Claimed::Duplicate`] (someone assigned this +/// pair first; their row is the answer); zero rows → [`Claimed::Full`] (the +/// counter is uncapped, so the only miss is a plan a concurrent delete +/// already removed); one row → [`Claimed::Made`]. +pub async fn create( + db: &Database, + plan: &FeePlanId, + student: &UserId, + assigned_by: &UserId, + created_at: Timestamp, +) -> Result, AppError> { + let created = sqlx::query_as!( + FeePlanAssignment, + // The seat bump and the row land together or not at all: a refused + // insert takes its own seat bump back. + r#"WITH seat AS ( + UPDATE fee_plan SET assignment_count = assignment_count + 1 + WHERE id = $1 AND assignment_count < $2 + RETURNING 1) + INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at) + SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat) + RETURNING plan, student, assigned_by, created_at"#, + plan, + cap::UNLIMITED, + plan, + student, + assigned_by, + created_at, + ) + .fetch_optional(db) + .await; + // Read the verdict off the *error* before the row count: a duplicate is + // the other writer's win, not a full house. + match created { + Ok(Some(row)) => Ok(Claimed::Made(row)), + Ok(None) => Ok(Claimed::Full), + Err(e) if crate::database::unique_violation(&e) == Some("fee_plan_assignment_plan") => { + Ok(Claimed::Duplicate) + } + Err(e) => Err(e.into()), + } } /// Who is on this plan, newest first. @@ -26,10 +88,10 @@ pub async fn list_for_plan( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "fee_plan_assignment WHERE plan = $plan", - "ORDER BY created_at DESC, id DESC", + "fee_plan_assignment WHERE plan = $1", + "ORDER BY created_at DESC, plan DESC, student DESC", ) - .bind("plan", plan.record()) + .bind(plan.uuid()) .run(limit, offset, db) .await } @@ -39,12 +101,13 @@ pub async fn list_for_plan( /// can be behind. Kept because a *test* asserting the rows and the counter /// agree is the only thing that would catch the counter drifting. pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result { - let mut result = db - .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1") - .bind(("plan", plan.record())) - .await? - .check()?; - Ok(!result.take::>(0)?.is_empty()) + let (exists,) = sqlx::query!( + "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1)", + plan + ) + .fetch_one(db) + .await?; + Ok(exists) } /// Which plans a student is on — one student may hold several. @@ -55,10 +118,10 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "fee_plan_assignment WHERE student = $student", - "ORDER BY created_at DESC, id DESC", + "fee_plan_assignment WHERE student = $1", + "ORDER BY created_at DESC, plan DESC, student DESC", ) - .bind("student", student.record()) + .bind(student.uuid()) .run(limit, offset, db) .await } diff --git a/src/db/payment_ledger.rs b/src/db/payment_ledger.rs index e3bdc0e..59233c3 100644 --- a/src/db/payment_ledger.rs +++ b/src/db/payment_ledger.rs @@ -1,13 +1,23 @@ -//! The `payment_ledger` table: the append-only `CREATE`s and the reads the -//! balance and the statement fold. Nothing here ever `UPDATE`s or `DELETE`s a -//! row — a mistake is corrected by appending the opposing line. The lock that -//! serializes the money arithmetic around these calls lives in -//! [`crate::service::payment_ledger`]. +//! The `payment_ledger` table: the append-only `INSERT`s and the reads the +//! balance and the over-payment cap fold. Nothing here ever `UPDATE`s or +//! `DELETE`s a row — a mistake is corrected by appending the opposing line. +//! The row locks that serialize the money arithmetic around these calls are +//! taken by the workflows in [`crate::service::payment_ledger`] +//! ([`lock_for_cap`]). +//! +//! The ledger row's `id` is a derived TEXT primary key, so Postgres itself is +//! the uniqueness check: a duplicate insert of the same key is the +//! "already billed" answer, surfaced here as +//! `INSERT … ON CONFLICT (id) DO NOTHING` plus a read-back of the row that +//! won. That is what makes every deterministic id (see +//! [`PaymentLedgerId::for_installment`] and friends) an idempotence key — +//! replaying the same append is a no-op, never a second line and never an +//! edit of the first, however the concurrent writers interleave. -use surrealdb::types::{AlreadyExistsError, SurrealValue}; +use sqlx::PgExecutor; -use crate::constant::{CAS_UPDATE_RETRIES, PAYMENT_LEDGER_TABLE}; -use crate::database::{Database, lost_the_race}; +use crate::constant::MAX_LEDGER_APPLIED_LINES; +use crate::database::Database; use crate::db::page::PagedList; use crate::domain::fee_plan::Installment; use crate::domain::fee_plan_assignment::FeePlanAssignment; @@ -16,73 +26,86 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::AppError; -/// Did this `CREATE` fail *only* because the row is already there? Matched on -/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text -/// and never on "any database error", because swallowing a real fault in money -/// code would be far worse than the 500 it saves. -fn is_duplicate_record(error: &surrealdb::Error) -> bool { - matches!( - error.already_exists_details(), - Some(AlreadyExistsError::Record { .. }) - ) -} - -/// The only writer: one `CREATE`, no update path anywhere in this module. +/// The only writer: one `INSERT`, no update path anywhere in this module. /// /// A line whose id already exists is left exactly as it is — the row wins, -/// the write is dropped. That is what makes a deterministic id (see -/// [`PaymentLedgerId::for_installment`]) an idempotence key: replaying the -/// same append is a no-op, never a second line and never an edit of the -/// first. The point read is on the id itself, so unlike a scan it cannot -/// miss a row a concurrent writer just made — but it is only a fast path. -/// The guarantee is `CREATE`'s own: on an existing id it *errors* and -/// leaves the row untouched, so the writer that lost the race reads back -/// the winner's line instead of failing the request with a 500. -/// -/// A *write conflict* is the same race decided one layer down — two appends -/// of one id arriving together are no longer serialized by a process-wide -/// lock, so the store aborts one as retryable instead of answering it -/// "already exists". Both are read back the same way, and a conflict that -/// turns out to have written nothing is simply tried again; no path here -/// can write a second line, since the id is the key. +/// the write is dropped, and the winner's line is read back in the *same +/// statement* (`ON CONFLICT (id) DO NOTHING`, and the `UNION ALL` arm answers +/// with the stored row when the insert was skipped). Unlike a scan, the point +/// read on the id cannot miss a row a concurrent writer just committed: an +/// insert that races an identical id waits on the unique index until the +/// other transaction settles, then takes the read-back arm. /// -/// Both read-backs check the stored line is the *kind* that was being -/// appended. Handing a caller someone else's row is only safe while every -/// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a -/// future marker or a widened key charset ever let two shapes meet, this is -/// the check that turns silently-wrong money into a 500 instead. It should -/// be unreachable, and it is cheap enough to keep it that way. -pub(crate) async fn append(db: &Database, row: PaymentLedger) -> Result { - let same_kind = |existing: PaymentLedger| { - if existing.kind == row.kind { - Ok(existing) - } else { - Err(AppError::Internal( - "a ledger id resolved to a line of another kind".into(), - )) - } - }; - if let Some(existing) = read(db, &row.id).await? { - return same_kind(existing); - } - let id = row.id.clone(); - for _ in 0..CAS_UPDATE_RETRIES { - match db.create(id.record()).content(row.clone()).await { - Ok(Some(created)) => return Ok(created), - Ok(None) => break, - Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => { - if let Some(existing) = read(db, &id).await? { - return same_kind(existing); - } - } - Err(e) => return Err(e.into()), - } +/// The read-back also checks the stored line is the *kind* that was being +/// appended. Handing a caller someone else's row is only safe while every id +/// shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a future +/// marker or a widened key charset ever let two shapes meet, this is the +/// check that turns silently-wrong money into a 500 instead. It should be +/// unreachable, and it is cheap enough to keep it that way. +pub(crate) async fn append( + exe: impl PgExecutor<'_>, + row: PaymentLedger, +) -> Result { + let created = sqlx::query_as!( + PaymentLedger, + r#"WITH ins AS ( + INSERT INTO payment_ledger + (id, student, kind, amount_minor, source, due_at, method, note, + recorded_by, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (id) DO NOTHING + RETURNING id, student, kind, amount_minor, source, due_at, method, note, + recorded_by, created_at) + SELECT id AS "id!", student AS "student!", + kind AS "kind!: PaymentLedgerKind", + amount_minor AS "amount_minor!", source, due_at, method, note, + recorded_by AS "recorded_by!", created_at AS "created_at!" + FROM ins + UNION ALL + SELECT id AS "id!", student AS "student!", + kind AS "kind!: PaymentLedgerKind", + amount_minor AS "amount_minor!", source, due_at, method, note, + recorded_by AS "recorded_by!", created_at AS "created_at!" + FROM payment_ledger + WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#, + row.id, + row.student, + row.kind, + row.amount_minor, + row.source, + row.due_at, + row.method, + row.note, + row.recorded_by, + row.created_at, + ) + .fetch_optional(exe) + .await?; + match created { + Some(line) if line.kind == row.kind => Ok(line), + Some(_) => Err(AppError::Internal( + "a ledger id resolved to a line of another kind".into(), + )), + // Unreachable: the statement either inserts or reads back the row + // with that very id. + None => Err(AppError::Internal("failed to write the ledger line".into())), } - Err(AppError::Internal("failed to write the ledger line".into())) } -pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result, AppError> { - Ok(db.select(id.record()).await?) +pub async fn read( + exe: impl PgExecutor<'_>, + id: &PaymentLedgerId, +) -> Result, AppError> { + sqlx::query_as!( + PaymentLedger, + "SELECT id, student, kind, amount_minor, source, due_at, method, note, \ + recorded_by, created_at \ + FROM payment_ledger WHERE id = $1", + id, + ) + .fetch_optional(exe) + .await + .map_err(Into::into) } /// Bill installment `n` (1-based) of `assignment`, at the amount and due @@ -93,20 +116,20 @@ pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result, assignment: &FeePlanAssignment, n: usize, installment: &Installment, recorded_by: &UserId, ) -> Result { append( - db, + exe, PaymentLedger { id: PaymentLedgerId::for_installment(assignment.get_id(), n), student: assignment.get_student().clone(), kind: PaymentLedgerKind::Charge, amount_minor: installment.get_amount_minor(), - source: Some(assignment.get_id().record()), + source: Some(assignment.get_id().key()), due_at: Some(installment.get_due_at()), method: None, note: None, @@ -125,35 +148,22 @@ pub async fn list_for_student( offset: i64, ) -> Result<(Vec, i64), AppError> { PagedList::new( - "payment_ledger WHERE student = $student", + "payment_ledger WHERE student = $1", "ORDER BY created_at DESC, id DESC", ) - .bind("student", student.record()) + .bind(student.uuid()) .run(limit, offset, db) .await } -/// Every line pointing at `source`: a charge's payments (and its reversal), -/// a credit's refunds. Feeds the over-payment cap and, later, the statement -/// rollup. Oldest first — this is a history, not a page. -pub async fn list_for_source( - db: &Database, - source: &PaymentLedgerId, -) -> Result, AppError> { - let mut result = db - .query("SELECT * FROM payment_ledger WHERE source = $source ORDER BY created_at, id") - .bind(("source", source.record())) - .await? - .check()?; - Ok(result.take::>(0)?) -} - -/// One kind's whole sum, as the `GROUP BY` in [`balance_of`] -/// hands it back — at most four rows, never the lines behind them. -#[derive(Debug, SurrealValue)] -struct KindTotal { +/// One kind's fold, as [`balance_of`] and [`applied_to`] read it off the +/// `GROUP BY` — at most four rows, never the lines behind them. +struct KindFold { kind: PaymentLedgerKind, total: i64, + /// Lines behind the fold. [`balance_of`] never looks at it; [`applied_to`] + /// enforces the applied-lines ceiling with it. + lines: i64, } /// The derived balance: `credits + reversals - charges - refunds`, in minor @@ -161,12 +171,7 @@ struct KindTotal { /// /// **The sum is taken per kind by the database** and only the four totals /// come back, so a balance read costs the same whether the ledger holds -/// four lines or forty thousand. It used to decode and fold every row, and -/// a fee ledger grows by design rather than only under abuse: one -/// assignment appends a charge *per installment* per student (up to -/// [`MAX_FEE_PLAN_ASSIGN_WRITES`](crate::constant::MAX_FEE_PLAN_ASSIGN_WRITES) -/// in a single request), and every one of those rows was decoded again by -/// every later `GET /payments/balance/*`. +/// four lines or forty thousand. /// /// **The signs stay here**, applied by the same /// `PaymentLedgerKind::sign` the documented formula is spelled in — @@ -179,20 +184,116 @@ struct KindTotal { /// running total was the third option and is a counter that can drift — a /// bug class this repo closes, not one it opens. pub async fn balance_of(db: &Database, student: &UserId) -> Result { - let totals: Vec = db - .query(format!( - "SELECT kind, math::sum(amount_minor) AS total \ - FROM {PAYMENT_LEDGER_TABLE} WHERE student = $student GROUP BY kind" - )) - .bind(("student", student.record())) - .await? - .check()? - .take(0)?; + let totals = sqlx::query_as!( + KindFold, + "SELECT kind AS \"kind!: PaymentLedgerKind\", \ + COALESCE(sum(amount_minor), 0)::bigint AS \"total!: i64\", \ + count(*)::bigint AS \"lines!: i64\" \ + FROM payment_ledger WHERE student = $1 GROUP BY kind", + student, + ) + .fetch_all(db) + .await?; Ok(PaymentLedger::fold_balance( totals.into_iter().map(|row| (row.kind, row.total)), )) } +/// Lock the **ancestor chain** of `id` (`FOR UPDATE`, the line first, then +/// its target, and so on up to a charge). Every write that moves the money +/// arithmetic of a subtree takes this walk in its transaction, so writers to +/// one subtree all contend on its **root's** row lock: a payment folding a +/// charge's subtree cannot land between a refund's fold and its append +/// deeper down. That is the whole guarantee the over-payment cap rests on — +/// it replaces a process-wide mutex with the rows the money lives on. +/// +/// Lock order is *deepest first*: a writer always wants the next ancestor, +/// never the reverse, and an ancestor is never a descendant, so no two +/// walks can cycle — no deadlock, nothing for the retry loop to unwind. +/// The chain is at most three rows (charge ← credit ← refund; a reversal +/// points at a charge or a refund), and a charge's `source` names a +/// fee-plan assignment rather than a ledger row, which is where the walk +/// stops. +pub(crate) async fn lock_for_cap( + exe: &mut sqlx::PgConnection, + id: &PaymentLedgerId, +) -> Result<(), AppError> { + let mut next = Some(id.clone()); + while let Some(key) = next { + let row = sqlx::query!( + r#"SELECT kind AS "kind: PaymentLedgerKind", source + FROM payment_ledger WHERE id = $1 FOR UPDATE"#, + key, + ) + .fetch_optional(&mut *exe) + .await?; + next = match row { + // Keep walking while the row points at another *ledger* row. + Some(row) if row.kind != PaymentLedgerKind::Charge => { + row.source.map(PaymentLedgerId::from_key) + } + // A charge's source is an assignment key, not a ledger row — + // and by then the root lock is held, which is the point. + _ => None, + }; + } + Ok(()) +} + +/// How much of `target` is already taken up — the balance fold restricted +/// to everything that points at it, however deep, and read the way `target` +/// is measured. Caller holds [`lock_for_cap`] on `target`'s chain in the +/// same transaction, so the fold and the append it authorizes cannot be +/// separated by a competing write. +/// +/// The whole subtree, not just the direct children, because money given +/// back frees the room it took: a charge paid in full and then *refunded* +/// is owed again, so it must be payable again (the fold nets to zero). The +/// same walk answers both sides, because the signs already say what each +/// line does — a credit adds under a charge, its refund takes that back, +/// and a reversal of that refund puts it back once more. `-target.sign()` +/// is what flips the reading for a credit, whose room is measured in the +/// refunds against it. The recursive CTE replaces the old +/// one-query-per-child walk; the signs still fold in Rust, by +/// [`PaymentLedger::fold_balance`](crate::domain::payment_ledger::PaymentLedger::fold_balance). +/// +/// **The ceiling stays.** Past [`MAX_LEDGER_APPLIED_LINES`] lines the fold +/// refuses — the count is what is refused, never the money already +/// recorded, so a line that is *already* over the ceiling still reads, +/// still refunds through its own children, and is still reversible. Only a +/// fresh line applied to *it* is turned away. +pub(crate) async fn applied_to( + exe: &mut sqlx::PgConnection, + target_key: &str, + target_kind: PaymentLedgerKind, +) -> Result { + let folds = sqlx::query_as!( + KindFold, + r#"WITH RECURSIVE applied(id, kind, amount_minor) AS ( + SELECT id, kind, amount_minor FROM payment_ledger WHERE source = $1 + UNION ALL + SELECT l.id, l.kind, l.amount_minor + FROM payment_ledger l JOIN applied a ON l.source = a.id + ) + SELECT kind AS "kind!: PaymentLedgerKind", + COALESCE(sum(amount_minor), 0)::bigint AS "total!: i64", + count(*)::bigint AS "lines!: i64" + FROM applied GROUP BY kind"#, + target_key, + ) + .fetch_all(exe) + .await?; + let lines: i64 = folds.iter().map(|fold| fold.lines).sum(); + if lines as usize >= MAX_LEDGER_APPLIED_LINES { + return Err(AppError::Conflict( + "this line already carries the most lines that may be applied to it; \ + record the rest against another", + )); + } + let total = PaymentLedger::fold_balance(folds.into_iter().map(|fold| (fold.kind, fold.total))); + Ok(total * -target_kind.sign()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/db/work_entry.rs b/src/db/work_entry.rs index 41ee636..79cf2db 100644 --- a/src/db/work_entry.rs +++ b/src/db/work_entry.rs @@ -1,117 +1,160 @@ //! The `work_entry` table: the open-slot check-in/check-out pair, the //! newest-first log, and manager corrections guarded by the stored order. +//! +//! "At most one open stint per staff member" is the database's own rule here: +//! the partial unique index `work_entry_open` covers only rows whose +//! `check_out` is NULL, so a second check-in is a 23505 (mapped to the +//! check-in conflict below) and a check-out is one conditional `UPDATE` — +//! zero rows means there was no open stint to close. The old +//! take-and-re-file dance existed only to free the deterministic open id; +//! with the index, closing the stint *is* freeing the slot. -use surrealdb::types::SurrealValue; - -use crate::database::{Database, transaction_with_retry}; +use crate::database::Database; use crate::db::field_update::FieldUpdate; -use crate::db::page::PagedList; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error}; use crate::error::AppError; -/// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE` -/// on the deterministic open id makes this atomic: if an open entry -/// already exists the insert is skipped (empty result) and the caller gets -/// a conflict — two racing check-ins can never create two open rows or -/// reset a running clock. +/// The row as the table spells it (`app_user` column), one step from the +/// domain struct (whose field is `user`). +struct WorkEntryRow { + id: WorkEntryId, + app_user: UserId, + check_in: Timestamp, + check_out: Option, +} + +impl From for WorkEntry { + fn from(row: WorkEntryRow) -> Self { + Self { + id: row.id, + user: row.app_user, + check_in: row.check_in, + check_out: row.check_out, + } + } +} + +/// Open a stint for `user`, stamped with the server clock. The +/// `work_entry_open` partial unique index makes this atomic: if an open +/// entry already exists the insert is refused and the caller gets the +/// conflict — two racing check-ins can never create two open rows or reset +/// a running clock. One statement, one verdict, no retry loop. pub async fn check_in(db: &Database, user: &UserId) -> Result { - let entry = WorkEntry { - id: WorkEntryId::open_for(user), - user: user.clone(), - check_in: Timestamp::now(), - check_out: None, - }; - let mut result = db - .query("INSERT IGNORE INTO work_entry $entry") - .bind(("entry", entry)) - .await? - .check()?; - result - .take::>(0)? - .into_iter() - .next() - .ok_or(AppError::Conflict("already checked in — check out first")) + let id = WorkEntryId::generate(); + let check_in = Timestamp::now(); + let inserted = sqlx::query_as!( + WorkEntryRow, + "INSERT INTO work_entry (id, app_user, check_in) VALUES ($1, $2, $3) \ + RETURNING id, app_user, check_in, check_out", + id, + user, + check_in, + ) + .fetch_one(db) + .await; + match inserted { + Ok(row) => Ok(row.into()), + Err(e) if crate::database::unique_violation(&e) == Some("work_entry_open") => { + Err(AppError::Conflict("already checked in — check out first")) + } + Err(e) => Err(e.into()), + } } -/// Close `user`'s open stint: atomically take the open row and re-file it -/// under a ULID id, freeing the open slot for the next check-in. Take and -/// re-file share one transaction — a failed re-file rolls the take back, -/// so a stint can never vanish half-closed. Of two racing check-outs -/// exactly one receives the row (the other gets the conflict). -/// -/// A lost round is re-sent rather than reported (`transaction_with_retry`): -/// the abort wrote nothing, so the whole cascade is safe to repeat, and the -/// `CREATE` cannot answer "already exists" on the way back — the table -/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID. -/// Only the guard's own `THROW` is a decision, and it stays a 409. +/// Close `user`'s open stint: one conditional `UPDATE` takes it and stamps +/// `check_out`, which also frees the open slot for the next check-in (the +/// partial unique index only covers rows with a NULL `check_out`). Zero +/// rows = no open stint, the caller's conflict. Of two racing check-outs +/// exactly one receives the row — the statement takes the row's lock and +/// the loser re-evaluates against the winner's committed state. pub async fn check_out(db: &Database, user: &UserId) -> Result { - let (mut result, mut errors) = transaction_with_retry( - db, - "BEGIN TRANSACTION; - LET $before = (DELETE $open RETURN BEFORE); - IF array::len($before) = 0 { THROW 'not_checked_in' }; - CREATE $closed CONTENT { - user: $before[0].user, - check_in: $before[0].check_in, - check_out: $out, - }; - COMMIT TRANSACTION;", - &[ - ( - "open".into(), - WorkEntryId::open_for(user).record().into_value(), - ), - ( - "closed".into(), - WorkEntryId::generate().record().into_value(), - ), - ("out".into(), Timestamp::now().into_value()), - ], - &["not_checked_in"], + let out = Timestamp::now(); + let closed = sqlx::query_as!( + WorkEntryRow, + "UPDATE work_entry SET check_out = $2 \ + WHERE app_user = $1 AND check_out IS NULL \ + RETURNING id, app_user, check_in, check_out", + user, + out, ) + .fetch_optional(db) .await?; - // An aborted transaction errors *every* slot, most with a generic - // "not executed" — only the THROW's own slot names the reason, so scan - // them all for the marker instead of trusting the first. - if errors - .values() - .any(|error| error.to_string().contains("not_checked_in")) - { - return Err(AppError::Conflict("not checked in")); - } - if let Some(error) = errors.drain().map(|(_, error)| error).next() { - return Err(error.into()); - } - // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3. - let saved: Option = result.take::>(3)?.into_iter().next(); - saved.ok_or_else(|| AppError::Internal("failed to close work entry".into())) + closed + .map(WorkEntry::from) + .ok_or(AppError::Conflict("not checked in")) } pub async fn read(db: &Database, id: &WorkEntryId) -> Result, AppError> { - Ok(db.select(id.record()).await?) + let row = sqlx::query_as!( + WorkEntryRow, + "SELECT id, app_user, check_in, check_out FROM work_entry WHERE id = $1", + id, + ) + .fetch_optional(db) + .await?; + Ok(row.map(WorkEntry::from)) } /// Every stint of `user`, newest first — the open one (if any) included. -/// Ordered by `check_in`, never by id alone: the open entry's `open_` key -/// doesn't sort with the ULIDs, so id order would misplace it. The `id` -/// tie-break behind it only ever separates two *closed* stints sharing a -/// `check_in` — there is one open row per user, so it can never tie with -/// itself — and that is what keeps offset paging from skipping a row. +/// Ordered by `check_in DESC`; the minted `id` breaks ties between two +/// stints sharing a `check_in` (uuid v7 sorts in mint order, which is what +/// keeps offset paging from skipping a row). pub async fn list_for_user( db: &Database, user: &UserId, limit: Option, offset: i64, ) -> Result<(Vec, i64), AppError> { - PagedList::new( - "work_entry WHERE user = $usr", - "ORDER BY check_in DESC, id DESC", - ) - .bind("usr", user.record()) - .run(limit, offset, db) - .await + let rows = match limit { + Some(limit) => { + sqlx::query_as!( + WorkEntryRow, + "SELECT id, app_user, check_in, check_out FROM work_entry \ + WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ + LIMIT $2 OFFSET $3", + user, + limit, + offset, + ) + .fetch_all(db) + .await? + } + None if offset > 0 => { + sqlx::query_as!( + WorkEntryRow, + "SELECT id, app_user, check_in, check_out FROM work_entry \ + WHERE app_user = $1 ORDER BY check_in DESC, id DESC \ + OFFSET $2", + user, + offset, + ) + .fetch_all(db) + .await? + } + None => { + sqlx::query_as!( + WorkEntryRow, + "SELECT id, app_user, check_in, check_out FROM work_entry \ + WHERE app_user = $1 ORDER BY check_in DESC, id DESC", + user, + ) + .fetch_all(db) + .await? + } + }; + // A window that can hide rows needs the count over the same WHERE; + // an unpaged read from row zero already holds every row. + let total = if limit.is_some() || offset > 0 { + sqlx::query!("SELECT count(*) FROM work_entry WHERE app_user = $1", user) + .fetch_one(db) + .await? + .0 + } else { + rows.len() as i64 + }; + Ok((rows.into_iter().map(WorkEntry::from).collect(), total)) } /// Persist corrected instants (manager fix-ups on closed entries; the web @@ -127,9 +170,9 @@ pub async fn update( check_in: Option, check_out: Option, ) -> Result { - FieldUpdate::new(entry.get_id().record()) - .set("check_in", check_in) - .set("check_out", check_out) + FieldUpdate::new("work_entry", entry.id.uuid()) + .set("check_in", check_in.map(|t| t.as_millis())) + .set("check_out", check_out.map(|t| t.as_millis())) // Same race closer as the schedule ranges, with this table's own // field names and message: a correction of one instant is only // written while it still orders against the other as *stored*. @@ -139,7 +182,15 @@ pub async fn update( } pub async fn remove(db: &Database, id: &WorkEntryId) -> Result, AppError> { - Ok(db.delete(id.record()).await?) + let row = sqlx::query_as!( + WorkEntryRow, + "DELETE FROM work_entry WHERE id = $1 \ + RETURNING id, app_user, check_in, check_out", + id, + ) + .fetch_optional(db) + .await?; + Ok(row.map(WorkEntry::from)) } #[cfg(test)] diff --git a/src/domain/fee_plan.rs b/src/domain/fee_plan.rs index 8c2cb41..cfbfde0 100644 --- a/src/domain/fee_plan.rs +++ b/src/domain/fee_plan.rs @@ -13,6 +13,7 @@ //! apply here. use sqlx::types::Json; +use uuid::Uuid; use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN}; use crate::domain::monotonic_id::next_uuid; diff --git a/src/domain/work_entry.rs b/src/domain/work_entry.rs index d3385b6..f5121a9 100644 --- a/src/domain/work_entry.rs +++ b/src/domain/work_entry.rs @@ -3,6 +3,7 @@ use uuid::Uuid; use crate::domain::monotonic_id::next_uuid; use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; +use crate::error::{AppError, ValidationError}; /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic /// generator, so `id` order is mint order. @@ -77,3 +78,13 @@ impl WorkEntry { self.check_out.is_none() } } + +/// The one ordering refusal both the web handler's pre-flight and the db +/// layer's write-time guard owe for a corrected stint: the correction must +/// still order as *stored* — check-out at or after check-in. +pub(crate) fn out_before_in_error() -> AppError { + AppError::Validation(ValidationError::Invalid { + field: "check_out", + reason: "must be at or after check_in", + }) +} diff --git a/src/service/fee_plan_assignment.rs b/src/service/fee_plan_assignment.rs index 4a4f725..64aaf56 100644 --- a/src/service/fee_plan_assignment.rs +++ b/src/service/fee_plan_assignment.rs @@ -12,11 +12,9 @@ //! "has this been billed yet?" — a scan can be slipped past by a concurrent //! writer, and the cost of that mistake here is a double-billed family. -use crate::constant::{ - FEE_PLAN_ASSIGNMENT_COUNT_FIELD, MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES, -}; +use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES}; use crate::database::Database; -use crate::db::cap::{self, Claimed}; +use crate::db::cap::Claimed; use crate::db::{fee_plan, fee_plan_assignment, payment_ledger}; use crate::domain::fee_plan::FeePlan; use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId}; @@ -29,8 +27,9 @@ use crate::error::{AppError, ValidationError}; /// whether it was *already* there, so the web layer can answer a replay /// honestly instead of pretending it just happened. /// -/// The row and the plan's assignment refcount are written in **one** -/// transaction ([`cap::claim_and_create`]): that increment is what makes the +/// The row and the plan's assignment refcount are written in **one +/// statement** ([`fee_plan_assignment::create`]'s claim): that increment is +/// what makes the /// plan un-editable and un-deletable, and it has to be indivisible from the /// row it counts, or an edit could slip between the two. A plan the counter /// cannot be claimed on is one a concurrent delete already removed, which is @@ -54,22 +53,9 @@ pub async fn assign( assigned_by: &UserId, ) -> Result<(FeePlanAssignment, bool), AppError> { let id = FeePlanAssignmentId::composite(plan.get_id(), student); - let row = FeePlanAssignment { - id: id.clone(), - plan: plan.get_id().clone(), - student: student.clone(), - assigned_by: assigned_by.clone(), - created_at: Timestamp::now(), - }; - let claimed = cap::claim_and_create( - &plan.get_id().record(), - FEE_PLAN_ASSIGNMENT_COUNT_FIELD, - cap::UNLIMITED, - &id.record(), - &row, - db, - ) - .await?; + let claimed = + fee_plan_assignment::create(db, plan.get_id(), student, assigned_by, Timestamp::now()) + .await?; let (assignment, existed) = match claimed { Claimed::Made(created) => (created, false), // Someone assigned this pair first — their row is the answer, and diff --git a/src/service/payment_ledger.rs b/src/service/payment_ledger.rs index 05a44fe..564ef64 100644 --- a/src/service/payment_ledger.rs +++ b/src/service/payment_ledger.rs @@ -1,56 +1,61 @@ //! The money workflows: recording a payment, handing one back, and undoing a -//! mistaken line, each under the lock the over-payment cap is built on. +//! mistaken line. //! //! **A payment or a refund is replayable when the client names it.** An //! optional `request_key` keys the line `_k_` (or `_kr_` for a //! refund), so a retry after a timeout derives the row the first attempt //! wrote — same identity rule, no scan. The key is scoped by the line it //! targets, so it never has to be globally unique. Without a key the id is a -//! fresh ulid and two identical calls are two payments, which is what a desk +//! fresh uuid and two identical calls are two payments, which is what a desk //! taking the same amount twice really means. The **replay read happens -//! before the cap check** and inside `PAYMENT_LOCK`: the first attempt's -//! line is already inside what the cap folds, so checking the cap first would -//! refuse the very payment that landed. A key replayed with a *different* -//! amount or against a *different* line is a `409`, never the stored line — -//! returning it would hide a client bug behind a `201`. +//! before the cap check** and inside the same transaction the append lands +//! in: the first attempt's line is already inside what the cap folds, so +//! checking the cap first would refuse the very payment that landed. A key +//! replayed with a *different* amount or against a *different* line is a +//! `409`, never the stored line — returning it would hide a client bug +//! behind a `201`. //! -//! **The over-payment cap is the lock's, not the database's.** [`credit`] -//! and [`refund`] refuse to take more than the line they target -//! is worth, by folding that line's whole subtree under `PAYMENT_LOCK`. The -//! fold, rather than a sum of the direct children, because money handed back -//! frees the room it took: a charge paid in full and then refunded is owed -//! again, and must be payable again. Every write that *moves* that arithmetic -//! takes the same lock — [`reversal`] included, since a reversal -//! landing between a payment's fold and its append would admit the payment -//! against room it no longer has. +//! **The over-payment cap is the row locks', not a process mutex's.** +//! [`credit`] and [`refund`] refuse to take more than the line they target +//! is worth, by folding that line's whole subtree in the transaction that +//! appends. The fold, rather than a sum of the direct children, because +//! money handed back frees the room it took: a charge paid in full and then +//! refunded is owed again, and must be payable again. //! -//! The lock is what makes that check mean anything, and it is load-bearing: -//! the fold is a count-then-write across rows, and SurrealDB does not -//! conflict-check a cross-record read against a concurrent insert (the -//! write-skew this repo has hit before), so a fold left unserialized would let -//! two payments both see room and both take it. Running as one process buys -//! nothing on its own — two request tasks interleave across the fold's `await` -//! exactly as two machines would. The cap therefore holds only for as long as -//! *every* write that moves this arithmetic is taken under `PAYMENT_LOCK`; -//! a future append that skips it re-opens the hole silently, which is why the -//! rule is stated here rather than left to be noticed. If an over-payment ever -//! does land it is not a crisis — an over-paid charge is plainly visible in the -//! statement and undone by appending a refund, and both entries are true -//! records of money that really arrived. A CAS counter row was rejected — -//! refunding would have to decrement it, which is a stored derived balance by -//! another name. What the fold costs is also what bounds it: at most -//! [`MAX_LEDGER_APPLIED_LINES`] lines may be applied to any one line, since -//! every one of them is another query taken with the lock held. +//! What makes that check mean something is the **ancestor-chain row lock** +//! ([`crate::db::payment_ledger::lock_for_cap`]): every write that *moves* +//! the arithmetic of a subtree — a payment into it, a refund under one of +//! its payments, a reversal anywhere inside it — walks its target's chain up +//! to the subtree's root charge and takes each row `FOR UPDATE`, **inside +//! the same transaction as its own fold and append**. Two writers to one +//! subtree therefore contend on the root's row: the second waits, and its +//! fold runs only after the first's append committed, against the state the +//! first left behind. There is no window between the fold and the append +//! for a competing write to slip into, which is exactly what the old +//! process-wide mutex it replaced bought and nothing more; unlike the +//! mutex it also survives multiple processes, and it never serializes +//! writers to *different* subtrees the way the global lock did. +//! ([`reversal`] takes the walk too, since a reversal landing between a +//! payment's fold and its append would admit the payment against room it no +//! longer has.) A future append that skips the walk re-opens the hole +//! silently, which is why the rule is stated here rather than left to be +//! noticed. If an over-payment ever does land it is not a crisis — an +//! over-paid charge is plainly visible in the statement and undone by +//! appending a refund, and both entries are true records of money that +//! really arrived. A CAS counter row was rejected — refunding would have to +//! decrement it, which is a stored derived balance by another name. What +//! the fold costs is also what bounds it: at most +//! [`MAX_LEDGER_APPLIED_LINES`](crate::constant::MAX_LEDGER_APPLIED_LINES) +//! lines may be applied to any one line, since every one of them widens the +//! subtree the fold walks. //! -//! The `request_key` mismatch `409` rides on the same lock: it is a -//! read-then-compare, and it is read *inside* the lock, so two first-time posts -//! of one key with different amounts cannot both walk past it. One line, one -//! amount, no double charge, and the "you reused a key" diagnostic is exact. +//! The `request_key` mismatch `409` rides on the same locks: it is a +//! read-then-compare, and it is read inside the transaction that would +//! append, so two first-time posts of one key with different amounts cannot +//! both walk past it. One line, one amount, no double charge, and the "you +//! reused a key" diagnostic is exact. -use tokio::sync::Mutex; - -use crate::constant::MAX_LEDGER_APPLIED_LINES; -use crate::database::Database; +use crate::database::{Database, tx_with_retry}; use crate::db::payment_ledger; use crate::domain::payment_ledger::{ LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, @@ -60,23 +65,14 @@ use crate::domain::timestamp::Timestamp; use crate::domain::user::UserId; use crate::error::{AppError, ValidationError}; -/// Serializes the over-payment check, the append it authorizes, and every -/// other append that changes the arithmetic that check does — nothing else. -/// It is the whole guarantee behind that cap, not a convenience: the fold it -/// protects is a cross-record read the database will not conflict-check -/// against a concurrent insert. Held across no other lock, and no other lock is -/// taken while it is held. -pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(()); - /// Money in, against one named `charge`. Partial payments are the norm, so -/// a charge may collect several credits; together they may not exceed it -/// (advisory — see the module doc's accepted race). A *reversed* charge -/// takes no payment either, and is refused saying so rather than claiming -/// it was paid. +/// a charge may collect several credits; together they may not exceed it. +/// A *reversed* charge takes no payment either, and is refused saying so +/// rather than claiming it was paid. /// /// With a `request_key` the line is keyed by it (see /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without -/// one the id is a fresh ulid and two identical calls are two payments, +/// one the id is a fresh uuid and two identical calls are two payments, /// which is what a cash desk taking the same amount twice really means. pub async fn credit( db: &Database, @@ -108,8 +104,8 @@ pub async fn credit( /// Money back out, against one named `credit` — how an over-payment or a /// payment recorded in error is returned. Partials allowed, and no more -/// than the credit was worth (advisory, same race). `request_key` makes it -/// retry-safe exactly as it does for [`credit`]. +/// than the credit was worth. `request_key` makes it retry-safe exactly as +/// it does for [`credit`]. pub async fn refund( db: &Database, credit: &PaymentLedger, @@ -140,15 +136,18 @@ pub async fn refund( } /// The shared body of `credit` and `refund`: check the target is the kind -/// this line may point at, then append under [`PAYMENT_LOCK`] while the -/// target's existing children still sum below its amount. +/// this line may point at, then — in one transaction, holding the target's +/// ancestor chain `FOR UPDATE` ([`payment_ledger::lock_for_cap`]) — read +/// any replay, fold the target's subtree, and append while the fold still +/// leaves room. /// -/// The replay read comes **before** the cap, and inside the lock: on a -/// retry the first attempt's line is already part of the subtree the cap -/// folds, so consulting the cap first would answer a payment that landed -/// with "already paid in full" — refusing precisely the request that -/// succeeded. Reading the id under the lock also keeps two simultaneous -/// retries from both walking into the cap check. +/// The replay read comes **before** the cap, and under the same row locks: +/// on a retry the first attempt's line is already part of the subtree the +/// cap folds, so consulting the cap first would answer a payment that +/// landed with "already paid in full" — refusing precisely the request that +/// succeeded. Reading it inside the transaction also keeps two simultaneous +/// retries from both walking into the cap check: the second waits on the +/// target's row until the first commits, then sees its line. #[allow(clippy::too_many_arguments)] async fn against( db: &Database, @@ -171,105 +170,64 @@ async fn against( } .into()); } - let _guard = PAYMENT_LOCK.lock().await; - if let Some(id) = &keyed - && let Some(existing) = payment_ledger::read(db, id).await? - { - // A replay is answered from the stored line — but only if it is the - // same money. The same key for a different amount or a different - // target is a client bug, and handing back the old line would hide - // it behind a `201`. - if existing.amount_minor.as_minor() != amount_minor.as_minor() - || existing.get_source_key() != Some(target.id.key()) - { - return Err(AppError::Conflict( - "this request_key was already used for a different amount or target", - )); - } - return Ok(existing); - } - let taken = applied_to(db, target).await?; - if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { - // The fold cannot say *why* the room is gone: a reversal is a child - // of the line it undoes and folds in at `+amount` exactly as a - // payment does, so a reversed charge reads as full to the kuruş. - // The stored answer is the same either way — nothing may be - // recorded against it — but "already paid in full" told a bursar - // money had arrived when none ever did. The reversal's id is - // derived from its target's, so telling the two apart is one read, - // taken only on the refusal path. - if let Some(reversed) = reversed - && payment_ledger::read(db, &PaymentLedgerId::for_reversal(&target.id)) - .await? - .is_some() + tx_with_retry(db, false, async |tx| { + // Every writer that can move this target's arithmetic holds some row + // on this chain; holding the whole walk to the root is what makes + // the fold below and the append it authorizes one decision. + payment_ledger::lock_for_cap(&mut *tx, &target.id).await?; + if let Some(id) = keyed.clone() + && let Some(existing) = payment_ledger::read(&mut *tx, &id).await? { - return Err(AppError::Conflict(reversed)); - } - return Err(AppError::Conflict(over)); - } - payment_ledger::append( - db, - PaymentLedger { - id: keyed.unwrap_or_else(PaymentLedgerId::generate), - student: target.student.clone(), - kind, - amount_minor, - source: Some(target.id.record()), - due_at: None, - method, - note, - recorded_by: recorded_by.clone(), - created_at: Timestamp::now(), - }, - ) - .await -} - -/// How much of `target` is already taken up — the balance fold restricted -/// to everything that points at it, however deep, and read the way `target` -/// is measured. -/// -/// The whole subtree, not just the direct children, because money given -/// back frees the room it took: a charge paid in full and then *refunded* -/// is owed again, so it must be payable again (the fold nets to zero). The -/// same walk answers both sides, because the signs already say what each -/// line does — a credit adds under a charge, its refund takes that back, -/// and a reversal of that refund puts it back once more. `-target.sign()` -/// is what flips the reading for a credit, whose room is measured in the -/// refunds against it. -/// -/// **The subtree is bounded, and that is what makes the walk affordable.** -/// One query per line, all of them while [`PAYMENT_LOCK`] is held, so an -/// unbounded subtree stalls every other payment in the school: a charge -/// settled 2 000 kuruş at a time would make the next payment issue 2 001 -/// sequential queries under the lock. Past -/// [`MAX_LEDGER_APPLIED_LINES`] the walk stops where it is and the write is -/// refused — the count is what is refused, never the money already -/// recorded, so a line that is *already* over the ceiling (written before -/// it existed) still reads, still refunds through its own children, and is -/// still reversible. Only a fresh line applied to *it* is turned away. -// corner-cut: one query per line, ceiling MAX_LEDGER_APPLIED_LINES; fold the -// walk into one recursive statement if that ceiling ever has to rise. -async fn applied_to(db: &Database, target: &PaymentLedger) -> Result { - let mut total = 0i64; - let mut seen = 0usize; - // The graph is a DAG by construction — a line can only point at one - // that already existed — so the walk terminates. - let mut pending = vec![target.id.clone()]; - while let Some(id) = pending.pop() { - for child in payment_ledger::list_for_source(db, &id).await? { - seen += 1; - if seen >= MAX_LEDGER_APPLIED_LINES { + // A replay is answered from the stored line — but only if it is + // the same money. The same key for a different amount or a + // different target is a client bug, and handing back the old + // line would hide it behind a `201`. + if existing.amount_minor.as_minor() != amount_minor.as_minor() + || existing.get_source_key() != Some(target.id.key()) + { return Err(AppError::Conflict( - "this line already carries the most lines that may be applied to it; \ - record the rest against another", + "this request_key was already used for a different amount or target", )); } - total = total.saturating_add(child.kind.sign() * child.amount_minor.as_minor()); - pending.push(child.id); + return Ok(existing); } - } - Ok(total * -target.kind.sign()) + let taken = payment_ledger::applied_to(&mut *tx, &target.id.key(), target.kind).await?; + if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() { + // The fold cannot say *why* the room is gone: a reversal is a + // child of the line it undoes and folds in at `+amount` exactly + // as a payment does, so a reversed charge reads as full to the + // kuruş. The stored answer is the same either way — nothing may + // be recorded against it — but "already paid in full" told a + // bursar money had arrived when none ever did. The reversal's + // id is derived from its target's, so telling the two apart is + // one read, taken only on the refusal path. + if let Some(reversed) = reversed + && payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id)) + .await? + .is_some() + { + return Err(AppError::Conflict(reversed)); + } + return Err(AppError::Conflict(over)); + } + payment_ledger::append( + &mut *tx, + PaymentLedger { + id: keyed.unwrap_or_else(PaymentLedgerId::generate), + student: target.student.clone(), + kind, + amount_minor, + source: Some(target.id.key()), + due_at: None, + method, + note, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + ) + .await + }) + .await } /// Undo a line entered by mistake, for its exact amount, with `source` @@ -281,12 +239,13 @@ async fn applied_to(db: &Database, target: &PaymentLedger) -> Result_r`, so a retried undo reverses once. /// -/// Appends under `PAYMENT_LOCK` — not for its own sake (the id makes it -/// idempotent by itself) but for the cap's: a reversal *changes* the -/// subtree `applied_to` folds, so one landing between a -/// concurrent payment's fold and its append would let that payment be -/// admitted against room it no longer has. The lock is what makes the cap -/// exact, which is the promise this module's doc makes. +/// The walk ([`payment_ledger::lock_for_cap`]) is taken in the same +/// transaction — not for its own sake (the id makes it idempotent by +/// itself) but for the cap's: a reversal *changes* the subtree every other +/// writer's fold reads, so one landing between a concurrent payment's fold +/// and its append would let that payment be admitted against room it no +/// longer has. The row locks are what make the cap exact, which is the +/// promise this module's doc makes. pub async fn reversal( db: &Database, line: &PaymentLedger, @@ -303,22 +262,25 @@ pub async fn reversal( } .into()); } - let _guard = PAYMENT_LOCK.lock().await; - payment_ledger::append( - db, - PaymentLedger { - id: PaymentLedgerId::for_reversal(line.get_id()), - student: line.student.clone(), - kind: PaymentLedgerKind::Reversal, - amount_minor: line.amount_minor, - source: Some(line.id.record()), - due_at: None, - method: None, - note, - recorded_by: recorded_by.clone(), - created_at: Timestamp::now(), - }, - ) + tx_with_retry(db, false, async |tx| { + payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?; + payment_ledger::append( + &mut *tx, + PaymentLedger { + id: PaymentLedgerId::for_reversal(line.get_id()), + student: line.student.clone(), + kind: PaymentLedgerKind::Reversal, + amount_minor: line.amount_minor, + source: Some(line.id.key()), + due_at: None, + method: None, + note, + recorded_by: recorded_by.clone(), + created_at: Timestamp::now(), + }, + ) + .await + }) .await } diff --git a/src/service/work_entry.rs b/src/service/work_entry.rs index acc2f06..a91e4d4 100644 --- a/src/service/work_entry.rs +++ b/src/service/work_entry.rs @@ -1,8 +1,9 @@ //! Work-log surfacing: the check-in/check-out pair, the staff log, and the -//! manager corrections. The queries live in -//! [`crate::db::work_entry`] — both transitions are single atomic writes on -//! the deterministic open id (`INSERT IGNORE` in, take-and-refile out), so -//! this domain has no workflow of its own. +//! manager corrections. The queries live in [`crate::db::work_entry`] — both +//! transitions are single atomic writes the database itself arbitrates (the +//! `work_entry_open` partial unique index refuses a second check-in; the +//! check-out's conditional `UPDATE` takes the one open row), so this domain +//! has no workflow of its own. use crate::database::Database; use crate::db::work_entry;