forge
Explore
Log in

Don't you dare go Hollow

Port payments+work to sqlx/Postgres

Browse files at this commit

876359cf565b9d68c4af1a241316d6929bbeedc6Ahmet Kaan GümüşParent: b3ab76f
  • feat
    • port payments+work to sqlx/Postgres
Show full message
🗃️ feat!: port payments+work to sqlx/Postgres
src/db/fee_plan.rsmodified+89 -50
@@ -1,13 +1,18 @@
1 //! The `fee_plan` table: the create, the reads, and the guarded edit and1 //! The `fee_plan` table: the create, the reads, and the guarded edit and
2 //! delete. Both guards are conditional single-record writes on the plan's own2 //! delete. Both guards are conditional single-record writes on the plan's own
3-//! refcount — the WHERE clause *is* the assigned-plan freeze rule — so they3+//! refcount (`assignment_count`) — the WHERE clause *is* the assigned-plan
4-//! live here whole. The web-facing doors are [`crate::service::fee_plan`].4+//! freeze rule — so they live here whole. The web-facing doors are
5+//! [`crate::service::fee_plan`].
6+//!
7+//! Postgres replaces the old process lock with the row itself: the assign's
8+//! claim (`UPDATE fee_plan SET assignment_count = …` in
9+//! [`crate::db::fee_plan_assignment::create`]) and the guarded edit/delete
10+//! below all rewrite this one row, so they take its row lock and re-check
11+//! their condition against the committed winner — an assign racing an edit
12+//! either claims first (the edit is refused) or claims after (and bills the
13+//! edited plan, which it re-reads). No window, no mutex.
5 14
6-use surrealdb::types::SurrealValue;15+use crate::database::Database;
7-
8-use crate::constant::FEE_PLAN_UNASSIGNED_GUARD;
9-use crate::database::{Database, write_with_retry};
10-use crate::db::field_update::FieldUpdate;
11 use crate::db::page::PagedList;16 use crate::db::page::PagedList;
12 use crate::domain::fee_plan::{17 use crate::domain::fee_plan::{
13 FeePlan, FeePlanId, FeePlanName, Installment, validate_installments,18 FeePlan, FeePlanId, FeePlanName, Installment, validate_installments,
@@ -23,19 +28,34 @@ pub async fn create(
23 created_by: &UserId,28 created_by: &UserId,
24 ) -> Result<FeePlan, AppError> {29 ) -> Result<FeePlan, AppError> {
25 validate_installments(&installments)?;30 validate_installments(&installments)?;
26- let plan = FeePlan {31+ let id = FeePlanId::generate();
27- id: FeePlanId::generate(),32+ let created_at = Timestamp::now();
33+ sqlx::query_as!(
34+ FeePlan,
35+ "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \
36+ VALUES ($1, $2, $3, $4, $5) \
37+ RETURNING id, name, installments, created_by, created_at",
38+ id,
28 name,39 name,
29- installments,40+ sqlx::types::Json(installments),
30- created_by: created_by.clone(),41+ created_by,
31- created_at: Timestamp::now(),42+ created_at,
32- };43+ )
33- let created: Option<FeePlan> = db.create(plan.id.record()).content(plan).await?;44+ .fetch_one(db)
34- created.ok_or_else(|| AppError::Internal("failed to create fee plan".into()))45+ .await
46+ .map_err(Into::into)
35 }47 }
36 48
37 pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> {49 pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> {
38- Ok(db.select(id.record()).await?)50+ sqlx::query_as!(
51+ FeePlan,
52+ "SELECT id, name, installments, created_by, created_at \
53+ FROM fee_plan WHERE id = $1",
54+ id,
55+ )
56+ .fetch_optional(db)
57+ .await
58+ .map_err(Into::into)
39 }59 }
40 60
41 /// Every plan, newest first — a school runs a handful.61 /// Every plan, newest first — a school runs a handful.
@@ -50,20 +70,25 @@ pub async fn list_all(
50 }70 }
51 71
52 /// Write only the fields the PATCH carried — `None` means the request72 /// Write only the fields the PATCH carried — `None` means the request
53-/// omitted it, so the column is left alone rather than re-stated from the73+/// omitted it, so the column is left alone (`COALESCE` keeps the stored
54-/// snapshot this struct was read into. `Err(Conflict)` = refused, nothing74+/// value) rather than re-stated from the snapshot this struct was read into.
55-/// was written: somebody is already on the plan.75+/// Zero rows = refused, nothing was written: somebody is already on the plan.
56 ///76 ///
57 /// Editing a plan never moves money: charges are frozen copies of the77 /// Editing a plan never moves money: charges are frozen copies of the
58 /// installments as they stood when the plan was assigned. That is exactly78 /// installments as they stood when the plan was assigned. That is exactly
59 /// why an assigned plan may not be edited at all — the plan and the charges79 /// why an assigned plan may not be edited at all — the plan and the charges
60 /// raised from it would tell different stories. The roster is the plan's own80 /// raised from it would tell different stories. The roster is the plan's own
61-/// [`crate::constant::FEE_PLAN_ASSIGNMENT_COUNT_FIELD`] refcount, claimed in the same81+/// `assignment_count` refcount, claimed in the same statement as the
62-/// transaction as the assignment row, so the check and the write are one82+/// assignment row ([`crate::db::fee_plan_assignment::create`]), so the check
63-/// conditional `UPDATE` on one record: an assign racing this either claims83+/// and the write are one conditional `UPDATE` on one record: an assign
64-/// first (and the edit is refused) or claims after (and bills the edited84+/// racing this either claims first (and the edit is refused) or claims
65-/// plan, which it re-reads). A `SELECT`-then-write could be, and was,85+/// after (and bills the edited plan, which it re-reads). A
66-/// stepped over in the gap between the two.86+/// `SELECT`-then-write could be, and was, stepped over in the gap between
87+/// the two.
88+///
89+/// A request that carried no field at all is answered before the guarded
90+/// statement: it writes nothing (and must not be refused as "assigned"),
91+/// so the row is simply read back.
67 pub async fn update(92 pub async fn update(
68 db: &Database,93 db: &Database,
69 plan: FeePlan,94 plan: FeePlan,
@@ -73,24 +98,35 @@ pub async fn update(
73 if let Some(installments) = &installments {98 if let Some(installments) = &installments {
74 validate_installments(installments)?;99 validate_installments(installments)?;
75 }100 }
76- let edited = FieldUpdate::new(plan.id.record())101+ if name.is_none() && installments.is_none() {
77- .set("name", name)102+ // A PATCH asking for no change writes nothing; the row (or its 404)
78- .set("installments", installments)103+ // is the whole answer, assigned or not.
79- .guard(104+ return read(db, &plan.id).await?.ok_or(AppError::NotFound);
80- FEE_PLAN_UNASSIGNED_GUARD,105+ }
81- AppError::Conflict("an assigned plan cannot be edited"),106+ let edited = sqlx::query_as!(
82- )107+ FeePlan,
83- .run::<FeePlan>(db)108+ "UPDATE fee_plan \
84- .await;109+ SET name = COALESCE($2, name), installments = COALESCE($3, installments) \
110+ WHERE id = $1 AND assignment_count = 0 \
111+ RETURNING id, name, installments, created_by, created_at",
112+ plan.id,
113+ name.map(|n| n.as_str().to_string()),
114+ installments.map(sqlx::types::Json),
115+ )
116+ .fetch_optional(db)
117+ .await?;
85 // Still assigned or already gone: the guarded `UPDATE` cannot tell those118 // Still assigned or already gone: the guarded `UPDATE` cannot tell those
86- // apart either (it reports the refusal it was given), so — exactly as119+ // apart (zero rows covers both), so — exactly as [`delete`] does — only
87- // [`crate::db::fee_plan::delete`] does — only the refusal path pays for the read120+ // the refusal path pays for the read that can. A plan deleted in the
88- // that can. A plan deleted in the window since the handler read it must121+ // window since the handler read it must not be refused as "assigned": it
89- // not be refused as "assigned": it never was.122+ // never was.
90- if matches!(edited, Err(AppError::Conflict(_))) && read(db, &plan.id).await?.is_none() {123+ match edited {
91- return Err(AppError::NotFound);124+ Some(plan) => Ok(plan),
125+ None => match read(db, &plan.id).await? {
126+ Some(_) => Err(AppError::Conflict("an assigned plan cannot be edited")),
127+ None => Err(AppError::NotFound),
128+ },
92 }129 }
93- edited
94 }130 }
95 131
96 /// Delete the plan, but only while nobody is on it. `false` = refused,132 /// Delete the plan, but only while nobody is on it. `false` = refused,
@@ -99,16 +135,19 @@ pub async fn update(
99 /// same reason — the charges an assignment raised name this plan, and a135 /// same reason — the charges an assignment raised name this plan, and a
100 /// school's financial history keeps its references.136 /// school's financial history keeps its references.
101 ///137 ///
102-/// Retried while the store answers "conflict, retry": the guard reads a138+/// A single guarded statement needs no retry loop: the guard rewrites the
103-/// counter an assign *writes*, so the two contend on this one record by139+/// plan row itself, so it contends with an assign's claim on that row's lock
104-/// design — and a delete that loses that round has written nothing, so140+/// and whichever version lands, the loser re-evaluated against the winner's
105-/// re-sending it is the whole of the recovery. Without the retry an141+/// committed state. Nothing was written on a loss, so there is nothing to
106-/// ordinary raced delete answers 500 instead of the 404 or 409 it owes.142+/// unwind.
107 pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> {143 pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> {
108- let sql = format!("DELETE $plan WHERE {FEE_PLAN_UNASSIGNED_GUARD} RETURN BEFORE");144+ let deleted = sqlx::query!(
109- let deleted: Vec<FeePlan> =145+ "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id",
110- write_with_retry(db, &sql, &[("plan".into(), plan.id.record().into_value())]).await?;146+ plan.id,
111- if !deleted.is_empty() {147+ )
148+ .fetch_optional(db)
149+ .await?;
150+ if deleted.is_some() {
112 return Ok(true);151 return Ok(true);
113 }152 }
114 // Still assigned or already gone: the one statement cannot tell those153 // Still assigned or already gone: the one statement cannot tell those
src/db/fee_plan_assignment.rsmodified+81 -18
@@ -1,13 +1,14 @@
1-//! The `fee_plan_assignment` table: the reads over placements. The row is1+//! The `fee_plan_assignment` table: the claim that places a student on a plan
2-//! written by [`crate::service::fee_plan_assignment::assign`], whose claim2+//! (and freezes the plan), plus the reads over placements. The billing the
3-//! ([`crate::db::cap::claim_and_create`]) is the write that freezes the plan.3+//! claim triggers lives in [`crate::service::fee_plan_assignment::assign`];
4-4+//! the ledger appends in [`crate::db::payment_ledger`].
5-use surrealdb::types::RecordId;
6 5
7 use crate::database::Database;6 use crate::database::Database;
7+use crate::db::cap::{self, Claimed};
8 use crate::db::page::PagedList;8 use crate::db::page::PagedList;
9 use crate::domain::fee_plan::FeePlanId;9 use crate::domain::fee_plan::FeePlanId;
10 use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};10 use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
11+use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
12 use crate::error::AppError;13 use crate::error::AppError;
13 14
@@ -15,7 +16,68 @@ pub async fn read(
15 db: &Database,16 db: &Database,
16 id: &FeePlanAssignmentId,17 id: &FeePlanAssignmentId,
17 ) -> Result<Option<FeePlanAssignment>, AppError> {18 ) -> Result<Option<FeePlanAssignment>, AppError> {
18- Ok(db.select(id.record()).await?)19+ sqlx::query_as!(
20+ FeePlanAssignment,
21+ "SELECT plan, student, assigned_by, created_at \
22+ FROM fee_plan_assignment WHERE plan = $1 AND student = $2",
23+ id.plan,
24+ id.student,
25+ )
26+ .fetch_optional(db)
27+ .await
28+ .map_err(Into::into)
29+}
30+
31+/// Place one (plan, student) assignment and claim the plan's assignment
32+/// refcount in the **same statement** — that increment is what makes the plan
33+/// un-editable and un-deletable ([`crate::db::fee_plan::update`]/[`delete`]),
34+/// and it has to be indivisible from the row it counts, or an edit could slip
35+/// between the two. The claim recipe ([`crate::db::cap`]'s
36+/// claim-and-create): a conditional `UPDATE` on the plan row seats the count,
37+/// the `INSERT` rides `WHERE EXISTS` on that seat, and one statement decides.
38+///
39+/// The verdict maps as the guard layer promises: 23505 on
40+/// `fee_plan_assignment_plan` → [`Claimed::Duplicate`] (someone assigned this
41+/// pair first; their row is the answer); zero rows → [`Claimed::Full`] (the
42+/// counter is uncapped, so the only miss is a plan a concurrent delete
43+/// already removed); one row → [`Claimed::Made`].
44+pub async fn create(
45+ db: &Database,
46+ plan: &FeePlanId,
47+ student: &UserId,
48+ assigned_by: &UserId,
49+ created_at: Timestamp,
50+) -> Result<Claimed<FeePlanAssignment>, AppError> {
51+ let created = sqlx::query_as!(
52+ FeePlanAssignment,
53+ // The seat bump and the row land together or not at all: a refused
54+ // insert takes its own seat bump back.
55+ r#"WITH seat AS (
56+ UPDATE fee_plan SET assignment_count = assignment_count + 1
57+ WHERE id = $1 AND assignment_count < $2
58+ RETURNING 1)
59+ INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at)
60+ SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
61+ RETURNING plan, student, assigned_by, created_at"#,
62+ plan,
63+ cap::UNLIMITED,
64+ plan,
65+ student,
66+ assigned_by,
67+ created_at,
68+ )
69+ .fetch_optional(db)
70+ .await;
71+ // Read the verdict off the *error* before the row count: a duplicate is
72+ // the other writer's win, not a full house.
73+ match created {
74+ Ok(Some(row)) => Ok(Claimed::Made(row)),
75+ Ok(None) => Ok(Claimed::Full),
76+ Err(e) if crate::database::unique_violation(&e) == Some("fee_plan_assignment_plan") => {
77+ Ok(Claimed::Duplicate)
78+ }
79+ Err(e) => Err(e.into()),
80+ }
19 }81 }
20 82
21 /// Who is on this plan, newest first.83 /// Who is on this plan, newest first.
@@ -26,10 +88,10 @@ pub async fn list_for_plan(
26 offset: i64,88 offset: i64,
27 ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {89 ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
28 PagedList::new(90 PagedList::new(
29- "fee_plan_assignment WHERE plan = $plan",91+ "fee_plan_assignment WHERE plan = $1",
30- "ORDER BY created_at DESC, id DESC",92+ "ORDER BY created_at DESC, plan DESC, student DESC",
31 )93 )
32- .bind("plan", plan.record())94+ .bind(plan.uuid())
33 .run(limit, offset, db)95 .run(limit, offset, db)
34 .await96 .await
35 }97 }
@@ -39,12 +101,13 @@ pub async fn list_for_plan(
39 /// can be behind. Kept because a *test* asserting the rows and the counter101 /// can be behind. Kept because a *test* asserting the rows and the counter
40 /// agree is the only thing that would catch the counter drifting.102 /// agree is the only thing that would catch the counter drifting.
41 pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> {103 pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> {
42- let mut result = db104+ let (exists,) = sqlx::query!(
43- .query("SELECT VALUE id FROM fee_plan_assignment WHERE plan = $plan LIMIT 1")105+ "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1)",
44- .bind(("plan", plan.record()))106+ plan
45- .await?107+ )
46- .check()?;108+ .fetch_one(db)
47- Ok(!result.take::<Vec<RecordId>>(0)?.is_empty())109+ .await?;
110+ Ok(exists)
48 }111 }
49 112
50 /// Which plans a student is on — one student may hold several.113 /// Which plans a student is on — one student may hold several.
@@ -55,10 +118,10 @@ pub async fn list_for_student(
55 offset: i64,118 offset: i64,
56 ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {119 ) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
57 PagedList::new(120 PagedList::new(
58- "fee_plan_assignment WHERE student = $student",121+ "fee_plan_assignment WHERE student = $1",
59- "ORDER BY created_at DESC, id DESC",122+ "ORDER BY created_at DESC, plan DESC, student DESC",
60 )123 )
61- .bind("student", student.record())124+ .bind(student.uuid())
62 .run(limit, offset, db)125 .run(limit, offset, db)
63 .await126 .await
64 }127 }
src/db/payment_ledger.rsmodified+209 -108
@@ -1,13 +1,23 @@
1-//! The `payment_ledger` table: the append-only `CREATE`s and the reads the1+//! The `payment_ledger` table: the append-only `INSERT`s and the reads the
2-//! balance and the statement fold. Nothing here ever `UPDATE`s or `DELETE`s a2+//! balance and the over-payment cap fold. Nothing here ever `UPDATE`s or
3-//! row — a mistake is corrected by appending the opposing line. The lock that3+//! `DELETE`s a row — a mistake is corrected by appending the opposing line.
4-//! serializes the money arithmetic around these calls lives in4+//! The row locks that serialize the money arithmetic around these calls are
5-//! [`crate::service::payment_ledger`].5+//! taken by the workflows in [`crate::service::payment_ledger`]
6+//! ([`lock_for_cap`]).
7+//!
8+//! The ledger row's `id` is a derived TEXT primary key, so Postgres itself is
9+//! the uniqueness check: a duplicate insert of the same key is the
10+//! "already billed" answer, surfaced here as
11+//! `INSERT … ON CONFLICT (id) DO NOTHING` plus a read-back of the row that
12+//! won. That is what makes every deterministic id (see
13+//! [`PaymentLedgerId::for_installment`] and friends) an idempotence key —
14+//! replaying the same append is a no-op, never a second line and never an
15+//! edit of the first, however the concurrent writers interleave.
6 16
7-use surrealdb::types::{AlreadyExistsError, SurrealValue};17+use sqlx::PgExecutor;
8 18
9-use crate::constant::{CAS_UPDATE_RETRIES, PAYMENT_LEDGER_TABLE};19+use crate::constant::MAX_LEDGER_APPLIED_LINES;
10-use crate::database::{Database, lost_the_race};20+use crate::database::Database;
11 use crate::db::page::PagedList;21 use crate::db::page::PagedList;
12 use crate::domain::fee_plan::Installment;22 use crate::domain::fee_plan::Installment;
13 use crate::domain::fee_plan_assignment::FeePlanAssignment;23 use crate::domain::fee_plan_assignment::FeePlanAssignment;
@@ -16,73 +26,86 @@ use crate::domain::timestamp::Timestamp;
16 use crate::domain::user::UserId;26 use crate::domain::user::UserId;
17 use crate::error::AppError;27 use crate::error::AppError;
18 28
19-/// Did this `CREATE` fail *only* because the row is already there? Matched on29+/// The only writer: one `INSERT`, no update path anywhere in this module.
20-/// the SDK's typed `AlreadyExists`/`Record` detail — never on the message text
21-/// and never on "any database error", because swallowing a real fault in money
22-/// code would be far worse than the 500 it saves.
23-fn is_duplicate_record(error: &surrealdb::Error) -> bool {
24- matches!(
25- error.already_exists_details(),
26- Some(AlreadyExistsError::Record { .. })
27- )
28-}
29-
30-/// The only writer: one `CREATE`, no update path anywhere in this module.
31 ///30 ///
32 /// A line whose id already exists is left exactly as it is — the row wins,31 /// A line whose id already exists is left exactly as it is — the row wins,
33-/// the write is dropped. That is what makes a deterministic id (see32+/// the write is dropped, and the winner's line is read back in the *same
34-/// [`PaymentLedgerId::for_installment`]) an idempotence key: replaying the33+/// statement* (`ON CONFLICT (id) DO NOTHING`, and the `UNION ALL` arm answers
35-/// same append is a no-op, never a second line and never an edit of the34+/// with the stored row when the insert was skipped). Unlike a scan, the point
36-/// first. The point read is on the id itself, so unlike a scan it cannot35+/// read on the id cannot miss a row a concurrent writer just committed: an
37-/// miss a row a concurrent writer just made — but it is only a fast path.36+/// insert that races an identical id waits on the unique index until the
38-/// The guarantee is `CREATE`'s own: on an existing id it *errors* and37+/// other transaction settles, then takes the read-back arm.
39-/// leaves the row untouched, so the writer that lost the race reads back
40-/// the winner's line instead of failing the request with a 500.
41-///
42-/// A *write conflict* is the same race decided one layer down — two appends
43-/// of one id arriving together are no longer serialized by a process-wide
44-/// lock, so the store aborts one as retryable instead of answering it
45-/// "already exists". Both are read back the same way, and a conflict that
46-/// turns out to have written nothing is simply tried again; no path here
47-/// can write a second line, since the id is the key.
48 ///38 ///
49-/// Both read-backs check the stored line is the *kind* that was being39+/// The read-back also checks the stored line is the *kind* that was being
50-/// appended. Handing a caller someone else's row is only safe while every40+/// appended. Handing a caller someone else's row is only safe while every id
51-/// id shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a41+/// shape is unambiguous (see [`PaymentLedgerId::for_request`]); if a future
52-/// future marker or a widened key charset ever let two shapes meet, this is42+/// marker or a widened key charset ever let two shapes meet, this is the
53-/// the check that turns silently-wrong money into a 500 instead. It should43+/// check that turns silently-wrong money into a 500 instead. It should be
54-/// be unreachable, and it is cheap enough to keep it that way.44+/// unreachable, and it is cheap enough to keep it that way.
55-pub(crate) async fn append(db: &Database, row: PaymentLedger) -> Result<PaymentLedger, AppError> {45+pub(crate) async fn append(
56- let same_kind = |existing: PaymentLedger| {46+ exe: impl PgExecutor<'_>,
57- if existing.kind == row.kind {47+ row: PaymentLedger,
58- Ok(existing)48+) -> Result<PaymentLedger, AppError> {
59- } else {49+ let created = sqlx::query_as!(
60- Err(AppError::Internal(50+ PaymentLedger,
61- "a ledger id resolved to a line of another kind".into(),51+ r#"WITH ins AS (
62- ))52+ INSERT INTO payment_ledger
63- }53+ (id, student, kind, amount_minor, source, due_at, method, note,
64- };54+ recorded_by, created_at)
65- if let Some(existing) = read(db, &row.id).await? {55+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
66- return same_kind(existing);56+ ON CONFLICT (id) DO NOTHING
67- }57+ RETURNING id, student, kind, amount_minor, source, due_at, method, note,
68- let id = row.id.clone();58+ recorded_by, created_at)
69- for _ in 0..CAS_UPDATE_RETRIES {59+ SELECT id AS "id!", student AS "student!",
70- match db.create(id.record()).content(row.clone()).await {60+ kind AS "kind!: PaymentLedgerKind",
71- Ok(Some(created)) => return Ok(created),61+ amount_minor AS "amount_minor!", source, due_at, method, note,
72- Ok(None) => break,62+ recorded_by AS "recorded_by!", created_at AS "created_at!"
73- Err(e) if is_duplicate_record(&e) || lost_the_race(&e) => {63+ FROM ins
74- if let Some(existing) = read(db, &id).await? {64+ UNION ALL
75- return same_kind(existing);65+ SELECT id AS "id!", student AS "student!",
76- }66+ kind AS "kind!: PaymentLedgerKind",
77- }67+ amount_minor AS "amount_minor!", source, due_at, method, note,
78- Err(e) => return Err(e.into()),68+ recorded_by AS "recorded_by!", created_at AS "created_at!"
79- }69+ FROM payment_ledger
70+ WHERE id = $1 AND NOT EXISTS (SELECT 1 FROM ins)"#,
71+ row.id,
72+ row.student,
73+ row.kind,
74+ row.amount_minor,
75+ row.source,
76+ row.due_at,
77+ row.method,
78+ row.note,
79+ row.recorded_by,
80+ row.created_at,
81+ )
82+ .fetch_optional(exe)
83+ .await?;
84+ match created {
85+ Some(line) if line.kind == row.kind => Ok(line),
86+ Some(_) => Err(AppError::Internal(
87+ "a ledger id resolved to a line of another kind".into(),
88+ )),
89+ // Unreachable: the statement either inserts or reads back the row
90+ // with that very id.
91+ None => Err(AppError::Internal("failed to write the ledger line".into())),
80 }92 }
81- Err(AppError::Internal("failed to write the ledger line".into()))
82 }93 }
83 94
84-pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result<Option<PaymentLedger>, AppError> {95+pub async fn read(
85- Ok(db.select(id.record()).await?)96+ exe: impl PgExecutor<'_>,
97+ id: &PaymentLedgerId,
98+) -> Result<Option<PaymentLedger>, AppError> {
99+ sqlx::query_as!(
100+ PaymentLedger,
101+ "SELECT id, student, kind, amount_minor, source, due_at, method, note, \
102+ recorded_by, created_at \
103+ FROM payment_ledger WHERE id = $1",
104+ id,
105+ )
106+ .fetch_optional(exe)
107+ .await
108+ .map_err(Into::into)
86 }109 }
87 110
88 /// Bill installment `n` (1-based) of `assignment`, at the amount and due111 /// 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<Option<PaymentL
93 /// assign writes nothing and an assignment whose charges landed only in116 /// assign writes nothing and an assignment whose charges landed only in
94 /// part self-heals on the next assign of the same pair.117 /// part self-heals on the next assign of the same pair.
95 pub async fn charge_for_installment(118 pub async fn charge_for_installment(
96- db: &Database,119+ exe: impl PgExecutor<'_>,
97 assignment: &FeePlanAssignment,120 assignment: &FeePlanAssignment,
98 n: usize,121 n: usize,
99 installment: &Installment,122 installment: &Installment,
100 recorded_by: &UserId,123 recorded_by: &UserId,
101 ) -> Result<PaymentLedger, AppError> {124 ) -> Result<PaymentLedger, AppError> {
102 append(125 append(
103- db,126+ exe,
104 PaymentLedger {127 PaymentLedger {
105 id: PaymentLedgerId::for_installment(assignment.get_id(), n),128 id: PaymentLedgerId::for_installment(assignment.get_id(), n),
106 student: assignment.get_student().clone(),129 student: assignment.get_student().clone(),
107 kind: PaymentLedgerKind::Charge,130 kind: PaymentLedgerKind::Charge,
108 amount_minor: installment.get_amount_minor(),131 amount_minor: installment.get_amount_minor(),
109- source: Some(assignment.get_id().record()),132+ source: Some(assignment.get_id().key()),
110 due_at: Some(installment.get_due_at()),133 due_at: Some(installment.get_due_at()),
111 method: None,134 method: None,
112 note: None,135 note: None,
@@ -125,35 +148,22 @@ pub async fn list_for_student(
125 offset: i64,148 offset: i64,
126 ) -> Result<(Vec<PaymentLedger>, i64), AppError> {149 ) -> Result<(Vec<PaymentLedger>, i64), AppError> {
127 PagedList::new(150 PagedList::new(
128- "payment_ledger WHERE student = $student",151+ "payment_ledger WHERE student = $1",
129 "ORDER BY created_at DESC, id DESC",152 "ORDER BY created_at DESC, id DESC",
130 )153 )
131- .bind("student", student.record())154+ .bind(student.uuid())
132 .run(limit, offset, db)155 .run(limit, offset, db)
133 .await156 .await
134 }157 }
135 158
136-/// Every line pointing at `source`: a charge's payments (and its reversal),159+/// One kind's fold, as [`balance_of`] and [`applied_to`] read it off the
137-/// a credit's refunds. Feeds the over-payment cap and, later, the statement160+/// `GROUP BY` — at most four rows, never the lines behind them.
138-/// rollup. Oldest first — this is a history, not a page.161+struct KindFold {
139-pub async fn list_for_source(
140- db: &Database,
141- source: &PaymentLedgerId,
142-) -> Result<Vec<PaymentLedger>, AppError> {
143- let mut result = db
144- .query("SELECT * FROM payment_ledger WHERE source = $source ORDER BY created_at, id")
145- .bind(("source", source.record()))
146- .await?
147- .check()?;
148- Ok(result.take::<Vec<PaymentLedger>>(0)?)
149-}
150-
151-/// One kind's whole sum, as the `GROUP BY` in [`balance_of`]
152-/// hands it back — at most four rows, never the lines behind them.
153-#[derive(Debug, SurrealValue)]
154-struct KindTotal {
155 kind: PaymentLedgerKind,162 kind: PaymentLedgerKind,
156 total: i64,163 total: i64,
164+ /// Lines behind the fold. [`balance_of`] never looks at it; [`applied_to`]
165+ /// enforces the applied-lines ceiling with it.
166+ lines: i64,
157 }167 }
158 168
159 /// The derived balance: `credits + reversals - charges - refunds`, in minor169 /// The derived balance: `credits + reversals - charges - refunds`, in minor
@@ -161,12 +171,7 @@ struct KindTotal {
161 ///171 ///
162 /// **The sum is taken per kind by the database** and only the four totals172 /// **The sum is taken per kind by the database** and only the four totals
163 /// come back, so a balance read costs the same whether the ledger holds173 /// come back, so a balance read costs the same whether the ledger holds
164-/// four lines or forty thousand. It used to decode and fold every row, and174+/// four lines or forty thousand.
165-/// a fee ledger grows by design rather than only under abuse: one
166-/// assignment appends a charge *per installment* per student (up to
167-/// [`MAX_FEE_PLAN_ASSIGN_WRITES`](crate::constant::MAX_FEE_PLAN_ASSIGN_WRITES)
168-/// in a single request), and every one of those rows was decoded again by
169-/// every later `GET /payments/balance/*`.
170 ///175 ///
171 /// **The signs stay here**, applied by the same176 /// **The signs stay here**, applied by the same
172 /// `PaymentLedgerKind::sign` the documented formula is spelled in —177 /// `PaymentLedgerKind::sign` the documented formula is spelled in —
@@ -179,20 +184,116 @@ struct KindTotal {
179 /// running total was the third option and is a counter that can drift — a184 /// running total was the third option and is a counter that can drift — a
180 /// bug class this repo closes, not one it opens.185 /// bug class this repo closes, not one it opens.
181 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {186 pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
182- let totals: Vec<KindTotal> = db187+ let totals = sqlx::query_as!(
183- .query(format!(188+ KindFold,
184- "SELECT kind, math::sum(amount_minor) AS total \189+ "SELECT kind AS \"kind!: PaymentLedgerKind\", \
185- FROM {PAYMENT_LEDGER_TABLE} WHERE student = $student GROUP BY kind"190+ COALESCE(sum(amount_minor), 0)::bigint AS \"total!: i64\", \
186- ))191+ count(*)::bigint AS \"lines!: i64\" \
187- .bind(("student", student.record()))192+ FROM payment_ledger WHERE student = $1 GROUP BY kind",
188- .await?193+ student,
189- .check()?194+ )
190- .take(0)?;195+ .fetch_all(db)
196+ .await?;
191 Ok(PaymentLedger::fold_balance(197 Ok(PaymentLedger::fold_balance(
192 totals.into_iter().map(|row| (row.kind, row.total)),198 totals.into_iter().map(|row| (row.kind, row.total)),
193 ))199 ))
194 }200 }
195 201
202+/// Lock the **ancestor chain** of `id` (`FOR UPDATE`, the line first, then
203+/// its target, and so on up to a charge). Every write that moves the money
204+/// arithmetic of a subtree takes this walk in its transaction, so writers to
205+/// one subtree all contend on its **root's** row lock: a payment folding a
206+/// charge's subtree cannot land between a refund's fold and its append
207+/// deeper down. That is the whole guarantee the over-payment cap rests on —
208+/// it replaces a process-wide mutex with the rows the money lives on.
209+///
210+/// Lock order is *deepest first*: a writer always wants the next ancestor,
211+/// never the reverse, and an ancestor is never a descendant, so no two
212+/// walks can cycle — no deadlock, nothing for the retry loop to unwind.
213+/// The chain is at most three rows (charge ← credit ← refund; a reversal
214+/// points at a charge or a refund), and a charge's `source` names a
215+/// fee-plan assignment rather than a ledger row, which is where the walk
216+/// stops.
217+pub(crate) async fn lock_for_cap(
218+ exe: &mut sqlx::PgConnection,
219+ id: &PaymentLedgerId,
220+) -> Result<(), AppError> {
221+ let mut next = Some(id.clone());
222+ while let Some(key) = next {
223+ let row = sqlx::query!(
224+ r#"SELECT kind AS "kind: PaymentLedgerKind", source
225+ FROM payment_ledger WHERE id = $1 FOR UPDATE"#,
226+ key,
227+ )
228+ .fetch_optional(&mut *exe)
229+ .await?;
230+ next = match row {
231+ // Keep walking while the row points at another *ledger* row.
232+ Some(row) if row.kind != PaymentLedgerKind::Charge => {
233+ row.source.map(PaymentLedgerId::from_key)
234+ }
235+ // A charge's source is an assignment key, not a ledger row —
236+ // and by then the root lock is held, which is the point.
237+ _ => None,
238+ };
239+ }
240+ Ok(())
241+}
242+
243+/// How much of `target` is already taken up — the balance fold restricted
244+/// to everything that points at it, however deep, and read the way `target`
245+/// is measured. Caller holds [`lock_for_cap`] on `target`'s chain in the
246+/// same transaction, so the fold and the append it authorizes cannot be
247+/// separated by a competing write.
248+///
249+/// The whole subtree, not just the direct children, because money given
250+/// back frees the room it took: a charge paid in full and then *refunded*
251+/// is owed again, so it must be payable again (the fold nets to zero). The
252+/// same walk answers both sides, because the signs already say what each
253+/// line does — a credit adds under a charge, its refund takes that back,
254+/// and a reversal of that refund puts it back once more. `-target.sign()`
255+/// is what flips the reading for a credit, whose room is measured in the
256+/// refunds against it. The recursive CTE replaces the old
257+/// one-query-per-child walk; the signs still fold in Rust, by
258+/// [`PaymentLedger::fold_balance`](crate::domain::payment_ledger::PaymentLedger::fold_balance).
259+///
260+/// **The ceiling stays.** Past [`MAX_LEDGER_APPLIED_LINES`] lines the fold
261+/// refuses — the count is what is refused, never the money already
262+/// recorded, so a line that is *already* over the ceiling still reads,
263+/// still refunds through its own children, and is still reversible. Only a
264+/// fresh line applied to *it* is turned away.
265+pub(crate) async fn applied_to(
266+ exe: &mut sqlx::PgConnection,
267+ target_key: &str,
268+ target_kind: PaymentLedgerKind,
269+) -> Result<i64, AppError> {
270+ let folds = sqlx::query_as!(
271+ KindFold,
272+ r#"WITH RECURSIVE applied(id, kind, amount_minor) AS (
273+ SELECT id, kind, amount_minor FROM payment_ledger WHERE source = $1
274+ UNION ALL
275+ SELECT l.id, l.kind, l.amount_minor
276+ FROM payment_ledger l JOIN applied a ON l.source = a.id
277+ )
278+ SELECT kind AS "kind!: PaymentLedgerKind",
279+ COALESCE(sum(amount_minor), 0)::bigint AS "total!: i64",
280+ count(*)::bigint AS "lines!: i64"
281+ FROM applied GROUP BY kind"#,
282+ target_key,
283+ )
284+ .fetch_all(exe)
285+ .await?;
286+ let lines: i64 = folds.iter().map(|fold| fold.lines).sum();
287+ if lines as usize >= MAX_LEDGER_APPLIED_LINES {
288+ return Err(AppError::Conflict(
289+ "this line already carries the most lines that may be applied to it; \
290+ record the rest against another",
291+ ));
292+ }
293+ let total = PaymentLedger::fold_balance(folds.into_iter().map(|fold| (fold.kind, fold.total)));
294+ Ok(total * -target_kind.sign())
295+}
296+
196 #[cfg(test)]297 #[cfg(test)]
197 mod tests {298 mod tests {
198 use super::*;299 use super::*;
src/db/work_entry.rsmodified+142 -91
@@ -1,117 +1,160 @@
1 //! The `work_entry` table: the open-slot check-in/check-out pair, the1 //! The `work_entry` table: the open-slot check-in/check-out pair, the
2 //! newest-first log, and manager corrections guarded by the stored order.2 //! newest-first log, and manager corrections guarded by the stored order.
3+//!
4+//! "At most one open stint per staff member" is the database's own rule here:
5+//! the partial unique index `work_entry_open` covers only rows whose
6+//! `check_out` is NULL, so a second check-in is a 23505 (mapped to the
7+//! check-in conflict below) and a check-out is one conditional `UPDATE` —
8+//! zero rows means there was no open stint to close. The old
9+//! take-and-re-file dance existed only to free the deterministic open id;
10+//! with the index, closing the stint *is* freeing the slot.
3 11
4-use surrealdb::types::SurrealValue;12+use crate::database::Database;
5-
6-use crate::database::{Database, transaction_with_retry};
7 use crate::db::field_update::FieldUpdate;13 use crate::db::field_update::FieldUpdate;
8-use crate::db::page::PagedList;
9 use crate::domain::timestamp::Timestamp;14 use crate::domain::timestamp::Timestamp;
10 use crate::domain::user::UserId;15 use crate::domain::user::UserId;
11 use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};16 use crate::domain::work_entry::{WorkEntry, WorkEntryId, out_before_in_error};
12 use crate::error::AppError;17 use crate::error::AppError;
13 18
14-/// Open a stint for `user`, stamped with the server clock. `INSERT IGNORE`19+/// The row as the table spells it (`app_user` column), one step from the
15-/// on the deterministic open id makes this atomic: if an open entry20+/// domain struct (whose field is `user`).
16-/// already exists the insert is skipped (empty result) and the caller gets21+struct WorkEntryRow {
17-/// a conflict — two racing check-ins can never create two open rows or22+ id: WorkEntryId,
18-/// reset a running clock.23+ app_user: UserId,
24+ check_in: Timestamp,
25+ check_out: Option<Timestamp>,
26+}
27+
28+impl From<WorkEntryRow> for WorkEntry {
29+ fn from(row: WorkEntryRow) -> Self {
30+ Self {
31+ id: row.id,
32+ user: row.app_user,
33+ check_in: row.check_in,
34+ check_out: row.check_out,
35+ }
36+ }
37+}
38+
39+/// Open a stint for `user`, stamped with the server clock. The
40+/// `work_entry_open` partial unique index makes this atomic: if an open
41+/// entry already exists the insert is refused and the caller gets the
42+/// conflict — two racing check-ins can never create two open rows or reset
43+/// a running clock. One statement, one verdict, no retry loop.
19 pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {44 pub async fn check_in(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
20- let entry = WorkEntry {45+ let id = WorkEntryId::generate();
21- id: WorkEntryId::open_for(user),46+ let check_in = Timestamp::now();
22- user: user.clone(),47+ let inserted = sqlx::query_as!(
23- check_in: Timestamp::now(),48+ WorkEntryRow,
24- check_out: None,49+ "INSERT INTO work_entry (id, app_user, check_in) VALUES ($1, $2, $3) \
25- };50+ RETURNING id, app_user, check_in, check_out",
26- let mut result = db51+ id,
27- .query("INSERT IGNORE INTO work_entry $entry")52+ user,
28- .bind(("entry", entry))53+ check_in,
29- .await?54+ )
30- .check()?;55+ .fetch_one(db)
31- result56+ .await;
32- .take::<Vec<WorkEntry>>(0)?57+ match inserted {
33- .into_iter()58+ Ok(row) => Ok(row.into()),
34- .next()59+ Err(e) if crate::database::unique_violation(&e) == Some("work_entry_open") => {
35- .ok_or(AppError::Conflict("already checked in — check out first"))60+ Err(AppError::Conflict("already checked in — check out first"))
61+ }
62+ Err(e) => Err(e.into()),
63+ }
36 }64 }
37 65
38-/// Close `user`'s open stint: atomically take the open row and re-file it66+/// Close `user`'s open stint: one conditional `UPDATE` takes it and stamps
39-/// under a ULID id, freeing the open slot for the next check-in. Take and67+/// `check_out`, which also frees the open slot for the next check-in (the
40-/// re-file share one transaction — a failed re-file rolls the take back,68+/// partial unique index only covers rows with a NULL `check_out`). Zero
41-/// so a stint can never vanish half-closed. Of two racing check-outs69+/// rows = no open stint, the caller's conflict. Of two racing check-outs
42-/// exactly one receives the row (the other gets the conflict).70+/// exactly one receives the row — the statement takes the row's lock and
43-///71+/// the loser re-evaluates against the winner's committed state.
44-/// A lost round is re-sent rather than reported (`transaction_with_retry`):
45-/// the abort wrote nothing, so the whole cascade is safe to repeat, and the
46-/// `CREATE` cannot answer "already exists" on the way back — the table
47-/// carries no `UNIQUE` index and `$closed` is one freshly minted ULID.
48-/// Only the guard's own `THROW` is a decision, and it stays a 409.
49 pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {72 pub async fn check_out(db: &Database, user: &UserId) -> Result<WorkEntry, AppError> {
50- let (mut result, mut errors) = transaction_with_retry(73+ let out = Timestamp::now();
51- db,74+ let closed = sqlx::query_as!(
52- "BEGIN TRANSACTION;75+ WorkEntryRow,
53- LET $before = (DELETE $open RETURN BEFORE);76+ "UPDATE work_entry SET check_out = $2 \
54- IF array::len($before) = 0 { THROW 'not_checked_in' };77+ WHERE app_user = $1 AND check_out IS NULL \
55- CREATE $closed CONTENT {78+ RETURNING id, app_user, check_in, check_out",
56- user: $before[0].user,79+ user,
57- check_in: $before[0].check_in,80+ out,
58- check_out: $out,
59- };
60- COMMIT TRANSACTION;",
61- &[
62- (
63- "open".into(),
64- WorkEntryId::open_for(user).record().into_value(),
65- ),
66- (
67- "closed".into(),
68- WorkEntryId::generate().record().into_value(),
69- ),
70- ("out".into(), Timestamp::now().into_value()),
71- ],
72- &["not_checked_in"],
73 )81 )
82+ .fetch_optional(db)
74 .await?;83 .await?;
75- // An aborted transaction errors *every* slot, most with a generic84+ closed
76- // "not executed" — only the THROW's own slot names the reason, so scan85+ .map(WorkEntry::from)
77- // them all for the marker instead of trusting the first.86+ .ok_or(AppError::Conflict("not checked in"))
78- if errors
79- .values()
80- .any(|error| error.to_string().contains("not_checked_in"))
81- {
82- return Err(AppError::Conflict("not checked in"));
83- }
84- if let Some(error) = errors.drain().map(|(_, error)| error).next() {
85- return Err(error.into());
86- }
87- // Statement slots count BEGIN, the LET, and the IF: the CREATE is slot 3.
88- let saved: Option<WorkEntry> = result.take::<Vec<WorkEntry>>(3)?.into_iter().next();
89- saved.ok_or_else(|| AppError::Internal("failed to close work entry".into()))
90 }87 }
91 88
92 pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {89 pub async fn read(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
93- Ok(db.select(id.record()).await?)90+ let row = sqlx::query_as!(
91+ WorkEntryRow,
92+ "SELECT id, app_user, check_in, check_out FROM work_entry WHERE id = $1",
93+ id,
94+ )
95+ .fetch_optional(db)
96+ .await?;
97+ Ok(row.map(WorkEntry::from))
94 }98 }
95 99
96 /// Every stint of `user`, newest first — the open one (if any) included.100 /// Every stint of `user`, newest first — the open one (if any) included.
97-/// Ordered by `check_in`, never by id alone: the open entry's `open_` key101+/// Ordered by `check_in DESC`; the minted `id` breaks ties between two
98-/// doesn't sort with the ULIDs, so id order would misplace it. The `id`102+/// stints sharing a `check_in` (uuid v7 sorts in mint order, which is what
99-/// tie-break behind it only ever separates two *closed* stints sharing a103+/// keeps offset paging from skipping a row).
100-/// `check_in` — there is one open row per user, so it can never tie with
101-/// itself — and that is what keeps offset paging from skipping a row.
102 pub async fn list_for_user(104 pub async fn list_for_user(
103 db: &Database,105 db: &Database,
104 user: &UserId,106 user: &UserId,
105 limit: Option<i64>,107 limit: Option<i64>,
106 offset: i64,108 offset: i64,
107 ) -> Result<(Vec<WorkEntry>, i64), AppError> {109 ) -> Result<(Vec<WorkEntry>, i64), AppError> {
108- PagedList::new(110+ let rows = match limit {
109- "work_entry WHERE user = $usr",111+ Some(limit) => {
110- "ORDER BY check_in DESC, id DESC",112+ sqlx::query_as!(
111- )113+ WorkEntryRow,
112- .bind("usr", user.record())114+ "SELECT id, app_user, check_in, check_out FROM work_entry \
113- .run(limit, offset, db)115+ WHERE app_user = $1 ORDER BY check_in DESC, id DESC \
114- .await116+ LIMIT $2 OFFSET $3",
117+ user,
118+ limit,
119+ offset,
120+ )
121+ .fetch_all(db)
122+ .await?
123+ }
124+ None if offset > 0 => {
125+ sqlx::query_as!(
126+ WorkEntryRow,
127+ "SELECT id, app_user, check_in, check_out FROM work_entry \
128+ WHERE app_user = $1 ORDER BY check_in DESC, id DESC \
129+ OFFSET $2",
130+ user,
131+ offset,
132+ )
133+ .fetch_all(db)
134+ .await?
135+ }
136+ None => {
137+ sqlx::query_as!(
138+ WorkEntryRow,
139+ "SELECT id, app_user, check_in, check_out FROM work_entry \
140+ WHERE app_user = $1 ORDER BY check_in DESC, id DESC",
141+ user,
142+ )
143+ .fetch_all(db)
144+ .await?
145+ }
146+ };
147+ // A window that can hide rows needs the count over the same WHERE;
148+ // an unpaged read from row zero already holds every row.
149+ let total = if limit.is_some() || offset > 0 {
150+ sqlx::query!("SELECT count(*) FROM work_entry WHERE app_user = $1", user)
151+ .fetch_one(db)
152+ .await?
153+ .0
154+ } else {
155+ rows.len() as i64
156+ };
157+ Ok((rows.into_iter().map(WorkEntry::from).collect(), total))
115 }158 }
116 159
117 /// Persist corrected instants (manager fix-ups on closed entries; the web160 /// Persist corrected instants (manager fix-ups on closed entries; the web
@@ -127,9 +170,9 @@ pub async fn update(
127 check_in: Option<Timestamp>,170 check_in: Option<Timestamp>,
128 check_out: Option<Timestamp>,171 check_out: Option<Timestamp>,
129 ) -> Result<WorkEntry, AppError> {172 ) -> Result<WorkEntry, AppError> {
130- FieldUpdate::new(entry.get_id().record())173+ FieldUpdate::new("work_entry", entry.id.uuid())
131- .set("check_in", check_in)174+ .set("check_in", check_in.map(|t| t.as_millis()))
132- .set("check_out", check_out)175+ .set("check_out", check_out.map(|t| t.as_millis()))
133 // Same race closer as the schedule ranges, with this table's own176 // Same race closer as the schedule ranges, with this table's own
134 // field names and message: a correction of one instant is only177 // field names and message: a correction of one instant is only
135 // written while it still orders against the other as *stored*.178 // written while it still orders against the other as *stored*.
@@ -139,7 +182,15 @@ pub async fn update(
139 }182 }
140 183
141 pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {184 pub async fn remove(db: &Database, id: &WorkEntryId) -> Result<Option<WorkEntry>, AppError> {
142- Ok(db.delete(id.record()).await?)185+ let row = sqlx::query_as!(
186+ WorkEntryRow,
187+ "DELETE FROM work_entry WHERE id = $1 \
188+ RETURNING id, app_user, check_in, check_out",
189+ id,
190+ )
191+ .fetch_optional(db)
192+ .await?;
193+ Ok(row.map(WorkEntry::from))
143 }194 }
144 195
145 #[cfg(test)]196 #[cfg(test)]
src/domain/fee_plan.rsmodified+1 -0
@@ -13,6 +13,7 @@
13 //! apply here.13 //! apply here.
14 14
15 use sqlx::types::Json;15 use sqlx::types::Json;
16+use uuid::Uuid;
16 17
17 use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN};18 use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN};
18 use crate::domain::monotonic_id::next_uuid;19 use crate::domain::monotonic_id::next_uuid;
src/domain/work_entry.rsmodified+11 -0
@@ -3,6 +3,7 @@ use uuid::Uuid;
3 use crate::domain::monotonic_id::next_uuid;3 use crate::domain::monotonic_id::next_uuid;
4 use crate::domain::timestamp::Timestamp;4 use crate::domain::timestamp::Timestamp;
5 use crate::domain::user::UserId;5 use crate::domain::user::UserId;
6+use crate::error::{AppError, ValidationError};
6 7
7 /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic8 /// Typed work-entry row id. A UUIDv7 minted by the process-wide monotonic
8 /// generator, so `id` order is mint order.9 /// generator, so `id` order is mint order.
@@ -77,3 +78,13 @@ impl WorkEntry {
77 self.check_out.is_none()78 self.check_out.is_none()
78 }79 }
79 }80 }
81+
82+/// The one ordering refusal both the web handler's pre-flight and the db
83+/// layer's write-time guard owe for a corrected stint: the correction must
84+/// still order as *stored* — check-out at or after check-in.
85+pub(crate) fn out_before_in_error() -> AppError {
86+ AppError::Validation(ValidationError::Invalid {
87+ field: "check_out",
88+ reason: "must be at or after check_in",
89+ })
90+}
src/service/fee_plan_assignment.rsmodified+8 -22
@@ -12,11 +12,9 @@
12 //! "has this been billed yet?" — a scan can be slipped past by a concurrent12 //! "has this been billed yet?" — a scan can be slipped past by a concurrent
13 //! writer, and the cost of that mistake here is a double-billed family.13 //! writer, and the cost of that mistake here is a double-billed family.
14 14
15-use crate::constant::{15+use crate::constant::{MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES};
16- FEE_PLAN_ASSIGNMENT_COUNT_FIELD, MAX_FEE_PLAN_ASSIGN_STUDENTS, MAX_FEE_PLAN_ASSIGN_WRITES,
17-};
18 use crate::database::Database;16 use crate::database::Database;
19-use crate::db::cap::{self, Claimed};17+use crate::db::cap::Claimed;
20 use crate::db::{fee_plan, fee_plan_assignment, payment_ledger};18 use crate::db::{fee_plan, fee_plan_assignment, payment_ledger};
21 use crate::domain::fee_plan::FeePlan;19 use crate::domain::fee_plan::FeePlan;
22 use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};20 use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
@@ -29,8 +27,9 @@ use crate::error::{AppError, ValidationError};
29 /// whether it was *already* there, so the web layer can answer a replay27 /// whether it was *already* there, so the web layer can answer a replay
30 /// honestly instead of pretending it just happened.28 /// honestly instead of pretending it just happened.
31 ///29 ///
32-/// The row and the plan's assignment refcount are written in **one**30+/// The row and the plan's assignment refcount are written in **one
33-/// transaction ([`cap::claim_and_create`]): that increment is what makes the31+/// statement** ([`fee_plan_assignment::create`]'s claim): that increment is
32+/// what makes the
34 /// plan un-editable and un-deletable, and it has to be indivisible from the33 /// plan un-editable and un-deletable, and it has to be indivisible from the
35 /// row it counts, or an edit could slip between the two. A plan the counter34 /// row it counts, or an edit could slip between the two. A plan the counter
36 /// cannot be claimed on is one a concurrent delete already removed, which is35 /// cannot be claimed on is one a concurrent delete already removed, which is
@@ -54,22 +53,9 @@ pub async fn assign(
54 assigned_by: &UserId,53 assigned_by: &UserId,
55 ) -> Result<(FeePlanAssignment, bool), AppError> {54 ) -> Result<(FeePlanAssignment, bool), AppError> {
56 let id = FeePlanAssignmentId::composite(plan.get_id(), student);55 let id = FeePlanAssignmentId::composite(plan.get_id(), student);
57- let row = FeePlanAssignment {56+ let claimed =
58- id: id.clone(),57+ fee_plan_assignment::create(db, plan.get_id(), student, assigned_by, Timestamp::now())
59- plan: plan.get_id().clone(),58+ .await?;
60- student: student.clone(),
61- assigned_by: assigned_by.clone(),
62- created_at: Timestamp::now(),
63- };
64- let claimed = cap::claim_and_create(
65- &plan.get_id().record(),
66- FEE_PLAN_ASSIGNMENT_COUNT_FIELD,
67- cap::UNLIMITED,
68- &id.record(),
69- &row,
70- db,
71- )
72- .await?;
73 let (assignment, existed) = match claimed {59 let (assignment, existed) = match claimed {
74 Claimed::Made(created) => (created, false),60 Claimed::Made(created) => (created, false),
75 // Someone assigned this pair first — their row is the answer, and61 // Someone assigned this pair first — their row is the answer, and
src/service/payment_ledger.rsmodified+142 -180
@@ -1,56 +1,61 @@
1 //! The money workflows: recording a payment, handing one back, and undoing a1 //! The money workflows: recording a payment, handing one back, and undoing a
2-//! mistaken line, each under the lock the over-payment cap is built on.2+//! mistaken line.
3 //!3 //!
4 //! **A payment or a refund is replayable when the client names it.** An4 //! **A payment or a refund is replayable when the client names it.** An
5 //! optional `request_key` keys the line `<target>_k_<key>` (or `_kr_` for a5 //! optional `request_key` keys the line `<target>_k_<key>` (or `_kr_` for a
6 //! refund), so a retry after a timeout derives the row the first attempt6 //! refund), so a retry after a timeout derives the row the first attempt
7 //! wrote — same identity rule, no scan. The key is scoped by the line it7 //! wrote — same identity rule, no scan. The key is scoped by the line it
8 //! targets, so it never has to be globally unique. Without a key the id is a8 //! targets, so it never has to be globally unique. Without a key the id is a
9-//! fresh ulid and two identical calls are two payments, which is what a desk9+//! fresh uuid and two identical calls are two payments, which is what a desk
10 //! taking the same amount twice really means. The **replay read happens10 //! taking the same amount twice really means. The **replay read happens
11-//! before the cap check** and inside `PAYMENT_LOCK`: the first attempt's11+//! before the cap check** and inside the same transaction the append lands
12-//! line is already inside what the cap folds, so checking the cap first would12+//! in: the first attempt's line is already inside what the cap folds, so
13-//! refuse the very payment that landed. A key replayed with a *different*13+//! checking the cap first would refuse the very payment that landed. A key
14-//! amount or against a *different* line is a `409`, never the stored line —14+//! replayed with a *different* amount or against a *different* line is a
15-//! returning it would hide a client bug behind a `201`.15+//! `409`, never the stored line — returning it would hide a client bug
16+//! behind a `201`.
16 //!17 //!
17-//! **The over-payment cap is the lock's, not the database's.** [`credit`]18+//! **The over-payment cap is the row locks', not a process mutex's.**
18-//! and [`refund`] refuse to take more than the line they target19+//! [`credit`] and [`refund`] refuse to take more than the line they target
19-//! is worth, by folding that line's whole subtree under `PAYMENT_LOCK`. The20+//! is worth, by folding that line's whole subtree in the transaction that
20-//! fold, rather than a sum of the direct children, because money handed back21+//! appends. The fold, rather than a sum of the direct children, because
21-//! frees the room it took: a charge paid in full and then refunded is owed22+//! money handed back frees the room it took: a charge paid in full and then
22-//! again, and must be payable again. Every write that *moves* that arithmetic23+//! refunded is owed again, and must be payable again.
23-//! takes the same lock — [`reversal`] included, since a reversal
24-//! landing between a payment's fold and its append would admit the payment
25-//! against room it no longer has.
26 //!24 //!
27-//! The lock is what makes that check mean anything, and it is load-bearing:25+//! What makes that check mean something is the **ancestor-chain row lock**
28-//! the fold is a count-then-write across rows, and SurrealDB does not26+//! ([`crate::db::payment_ledger::lock_for_cap`]): every write that *moves*
29-//! conflict-check a cross-record read against a concurrent insert (the27+//! the arithmetic of a subtree — a payment into it, a refund under one of
30-//! write-skew this repo has hit before), so a fold left unserialized would let28+//! its payments, a reversal anywhere inside it — walks its target's chain up
31-//! two payments both see room and both take it. Running as one process buys29+//! to the subtree's root charge and takes each row `FOR UPDATE`, **inside
32-//! nothing on its own — two request tasks interleave across the fold's `await`30+//! the same transaction as its own fold and append**. Two writers to one
33-//! exactly as two machines would. The cap therefore holds only for as long as31+//! subtree therefore contend on the root's row: the second waits, and its
34-//! *every* write that moves this arithmetic is taken under `PAYMENT_LOCK`;32+//! fold runs only after the first's append committed, against the state the
35-//! a future append that skips it re-opens the hole silently, which is why the33+//! first left behind. There is no window between the fold and the append
36-//! rule is stated here rather than left to be noticed. If an over-payment ever34+//! for a competing write to slip into, which is exactly what the old
37-//! does land it is not a crisis — an over-paid charge is plainly visible in the35+//! process-wide mutex it replaced bought and nothing more; unlike the
38-//! statement and undone by appending a refund, and both entries are true36+//! mutex it also survives multiple processes, and it never serializes
39-//! records of money that really arrived. A CAS counter row was rejected —37+//! writers to *different* subtrees the way the global lock did.
40-//! refunding would have to decrement it, which is a stored derived balance by38+//! ([`reversal`] takes the walk too, since a reversal landing between a
41-//! another name. What the fold costs is also what bounds it: at most39+//! payment's fold and its append would admit the payment against room it no
42-//! [`MAX_LEDGER_APPLIED_LINES`] lines may be applied to any one line, since40+//! longer has.) A future append that skips the walk re-opens the hole
43-//! every one of them is another query taken with the lock held.41+//! silently, which is why the rule is stated here rather than left to be
42+//! noticed. If an over-payment ever does land it is not a crisis — an
43+//! over-paid charge is plainly visible in the statement and undone by
44+//! appending a refund, and both entries are true records of money that
45+//! really arrived. A CAS counter row was rejected — refunding would have to
46+//! decrement it, which is a stored derived balance by another name. What
47+//! the fold costs is also what bounds it: at most
48+//! [`MAX_LEDGER_APPLIED_LINES`](crate::constant::MAX_LEDGER_APPLIED_LINES)
49+//! lines may be applied to any one line, since every one of them widens the
50+//! subtree the fold walks.
44 //!51 //!
45-//! The `request_key` mismatch `409` rides on the same lock: it is a52+//! The `request_key` mismatch `409` rides on the same locks: it is a
46-//! read-then-compare, and it is read *inside* the lock, so two first-time posts53+//! read-then-compare, and it is read inside the transaction that would
47-//! of one key with different amounts cannot both walk past it. One line, one54+//! append, so two first-time posts of one key with different amounts cannot
48-//! amount, no double charge, and the "you reused a key" diagnostic is exact.55+//! both walk past it. One line, one amount, no double charge, and the "you
56+//! reused a key" diagnostic is exact.
49 57
50-use tokio::sync::Mutex;58+use crate::database::{Database, tx_with_retry};
51-
52-use crate::constant::MAX_LEDGER_APPLIED_LINES;
53-use crate::database::Database;
54 use crate::db::payment_ledger;59 use crate::db::payment_ledger;
55 use crate::domain::payment_ledger::{60 use crate::domain::payment_ledger::{
56 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,61 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
@@ -60,23 +65,14 @@ use crate::domain::timestamp::Timestamp;
60 use crate::domain::user::UserId;65 use crate::domain::user::UserId;
61 use crate::error::{AppError, ValidationError};66 use crate::error::{AppError, ValidationError};
62 67
63-/// Serializes the over-payment check, the append it authorizes, and every
64-/// other append that changes the arithmetic that check does — nothing else.
65-/// It is the whole guarantee behind that cap, not a convenience: the fold it
66-/// protects is a cross-record read the database will not conflict-check
67-/// against a concurrent insert. Held across no other lock, and no other lock is
68-/// taken while it is held.
69-pub(crate) static PAYMENT_LOCK: Mutex<()> = Mutex::const_new(());
70-
71 /// Money in, against one named `charge`. Partial payments are the norm, so68 /// Money in, against one named `charge`. Partial payments are the norm, so
72-/// a charge may collect several credits; together they may not exceed it69+/// a charge may collect several credits; together they may not exceed it.
73-/// (advisory — see the module doc's accepted race). A *reversed* charge70+/// A *reversed* charge takes no payment either, and is refused saying so
74-/// takes no payment either, and is refused saying so rather than claiming71+/// rather than claiming it was paid.
75-/// it was paid.
76 ///72 ///
77 /// With a `request_key` the line is keyed by it (see73 /// With a `request_key` the line is keyed by it (see
78 /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without74 /// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without
79-/// one the id is a fresh ulid and two identical calls are two payments,75+/// one the id is a fresh uuid and two identical calls are two payments,
80 /// which is what a cash desk taking the same amount twice really means.76 /// which is what a cash desk taking the same amount twice really means.
81 pub async fn credit(77 pub async fn credit(
82 db: &Database,78 db: &Database,
@@ -108,8 +104,8 @@ pub async fn credit(
108 104
109 /// Money back out, against one named `credit` — how an over-payment or a105 /// Money back out, against one named `credit` — how an over-payment or a
110 /// payment recorded in error is returned. Partials allowed, and no more106 /// payment recorded in error is returned. Partials allowed, and no more
111-/// than the credit was worth (advisory, same race). `request_key` makes it107+/// than the credit was worth. `request_key` makes it retry-safe exactly as
112-/// retry-safe exactly as it does for [`credit`].108+/// it does for [`credit`].
113 pub async fn refund(109 pub async fn refund(
114 db: &Database,110 db: &Database,
115 credit: &PaymentLedger,111 credit: &PaymentLedger,
@@ -140,15 +136,18 @@ pub async fn refund(
140 }136 }
141 137
142 /// The shared body of `credit` and `refund`: check the target is the kind138 /// The shared body of `credit` and `refund`: check the target is the kind
143-/// this line may point at, then append under [`PAYMENT_LOCK`] while the139+/// this line may point at, then — in one transaction, holding the target's
144-/// target's existing children still sum below its amount.140+/// ancestor chain `FOR UPDATE` ([`payment_ledger::lock_for_cap`]) — read
141+/// any replay, fold the target's subtree, and append while the fold still
142+/// leaves room.
145 ///143 ///
146-/// The replay read comes **before** the cap, and inside the lock: on a144+/// The replay read comes **before** the cap, and under the same row locks:
147-/// retry the first attempt's line is already part of the subtree the cap145+/// on a retry the first attempt's line is already part of the subtree the
148-/// folds, so consulting the cap first would answer a payment that landed146+/// cap folds, so consulting the cap first would answer a payment that
149-/// with "already paid in full" — refusing precisely the request that147+/// landed with "already paid in full" — refusing precisely the request that
150-/// succeeded. Reading the id under the lock also keeps two simultaneous148+/// succeeded. Reading it inside the transaction also keeps two simultaneous
151-/// retries from both walking into the cap check.149+/// retries from both walking into the cap check: the second waits on the
150+/// target's row until the first commits, then sees its line.
152 #[allow(clippy::too_many_arguments)]151 #[allow(clippy::too_many_arguments)]
153 async fn against(152 async fn against(
154 db: &Database,153 db: &Database,
@@ -171,105 +170,64 @@ async fn against(
171 }170 }
172 .into());171 .into());
173 }172 }
174- let _guard = PAYMENT_LOCK.lock().await;173+ tx_with_retry(db, false, async |tx| {
175- if let Some(id) = &keyed174+ // Every writer that can move this target's arithmetic holds some row
176- && let Some(existing) = payment_ledger::read(db, id).await?175+ // on this chain; holding the whole walk to the root is what makes
177- {176+ // the fold below and the append it authorizes one decision.
178- // A replay is answered from the stored line — but only if it is the177+ payment_ledger::lock_for_cap(&mut *tx, &target.id).await?;
179- // same money. The same key for a different amount or a different178+ if let Some(id) = keyed.clone()
180- // target is a client bug, and handing back the old line would hide179+ && let Some(existing) = payment_ledger::read(&mut *tx, &id).await?
181- // it behind a `201`.
182- if existing.amount_minor.as_minor() != amount_minor.as_minor()
183- || existing.get_source_key() != Some(target.id.key())
184- {
185- return Err(AppError::Conflict(
186- "this request_key was already used for a different amount or target",
187- ));
188- }
189- return Ok(existing);
190- }
191- let taken = applied_to(db, target).await?;
192- if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() {
193- // The fold cannot say *why* the room is gone: a reversal is a child
194- // of the line it undoes and folds in at `+amount` exactly as a
195- // payment does, so a reversed charge reads as full to the kuruş.
196- // The stored answer is the same either way — nothing may be
197- // recorded against it — but "already paid in full" told a bursar
198- // money had arrived when none ever did. The reversal's id is
199- // derived from its target's, so telling the two apart is one read,
200- // taken only on the refusal path.
201- if let Some(reversed) = reversed
202- && payment_ledger::read(db, &PaymentLedgerId::for_reversal(&target.id))
203- .await?
204- .is_some()
205 {180 {
206- return Err(AppError::Conflict(reversed));181+ // A replay is answered from the stored line — but only if it is
207- }182+ // the same money. The same key for a different amount or a
208- return Err(AppError::Conflict(over));183+ // different target is a client bug, and handing back the old
209- }184+ // line would hide it behind a `201`.
210- payment_ledger::append(185+ if existing.amount_minor.as_minor() != amount_minor.as_minor()
211- db,186+ || existing.get_source_key() != Some(target.id.key())
212- PaymentLedger {187+ {
213- id: keyed.unwrap_or_else(PaymentLedgerId::generate),
214- student: target.student.clone(),
215- kind,
216- amount_minor,
217- source: Some(target.id.record()),
218- due_at: None,
219- method,
220- note,
221- recorded_by: recorded_by.clone(),
222- created_at: Timestamp::now(),
223- },
224- )
225- .await
226-}
227-
228-/// How much of `target` is already taken up — the balance fold restricted
229-/// to everything that points at it, however deep, and read the way `target`
230-/// is measured.
231-///
232-/// The whole subtree, not just the direct children, because money given
233-/// back frees the room it took: a charge paid in full and then *refunded*
234-/// is owed again, so it must be payable again (the fold nets to zero). The
235-/// same walk answers both sides, because the signs already say what each
236-/// line does — a credit adds under a charge, its refund takes that back,
237-/// and a reversal of that refund puts it back once more. `-target.sign()`
238-/// is what flips the reading for a credit, whose room is measured in the
239-/// refunds against it.
240-///
241-/// **The subtree is bounded, and that is what makes the walk affordable.**
242-/// One query per line, all of them while [`PAYMENT_LOCK`] is held, so an
243-/// unbounded subtree stalls every other payment in the school: a charge
244-/// settled 2 000 kuruş at a time would make the next payment issue 2 001
245-/// sequential queries under the lock. Past
246-/// [`MAX_LEDGER_APPLIED_LINES`] the walk stops where it is and the write is
247-/// refused — the count is what is refused, never the money already
248-/// recorded, so a line that is *already* over the ceiling (written before
249-/// it existed) still reads, still refunds through its own children, and is
250-/// still reversible. Only a fresh line applied to *it* is turned away.
251-// corner-cut: one query per line, ceiling MAX_LEDGER_APPLIED_LINES; fold the
252-// walk into one recursive statement if that ceiling ever has to rise.
253-async fn applied_to(db: &Database, target: &PaymentLedger) -> Result<i64, AppError> {
254- let mut total = 0i64;
255- let mut seen = 0usize;
256- // The graph is a DAG by construction — a line can only point at one
257- // that already existed — so the walk terminates.
258- let mut pending = vec![target.id.clone()];
259- while let Some(id) = pending.pop() {
260- for child in payment_ledger::list_for_source(db, &id).await? {
261- seen += 1;
262- if seen >= MAX_LEDGER_APPLIED_LINES {
263 return Err(AppError::Conflict(188 return Err(AppError::Conflict(
264- "this line already carries the most lines that may be applied to it; \189+ "this request_key was already used for a different amount or target",
265- record the rest against another",
266 ));190 ));
267 }191 }
268- total = total.saturating_add(child.kind.sign() * child.amount_minor.as_minor());192+ return Ok(existing);
269- pending.push(child.id);
270 }193 }
271- }194+ let taken = payment_ledger::applied_to(&mut *tx, &target.id.key(), target.kind).await?;
272- Ok(total * -target.kind.sign())195+ if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() {
196+ // The fold cannot say *why* the room is gone: a reversal is a
197+ // child of the line it undoes and folds in at `+amount` exactly
198+ // as a payment does, so a reversed charge reads as full to the
199+ // kuruş. The stored answer is the same either way — nothing may
200+ // be recorded against it — but "already paid in full" told a
201+ // bursar money had arrived when none ever did. The reversal's
202+ // id is derived from its target's, so telling the two apart is
203+ // one read, taken only on the refusal path.
204+ if let Some(reversed) = reversed
205+ && payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id))
206+ .await?
207+ .is_some()
208+ {
209+ return Err(AppError::Conflict(reversed));
210+ }
211+ return Err(AppError::Conflict(over));
212+ }
213+ payment_ledger::append(
214+ &mut *tx,
215+ PaymentLedger {
216+ id: keyed.unwrap_or_else(PaymentLedgerId::generate),
217+ student: target.student.clone(),
218+ kind,
219+ amount_minor,
220+ source: Some(target.id.key()),
221+ due_at: None,
222+ method,
223+ note,
224+ recorded_by: recorded_by.clone(),
225+ created_at: Timestamp::now(),
226+ },
227+ )
228+ .await
229+ })
230+ .await
273 }231 }
274 232
275 /// Undo a line entered by mistake, for its exact amount, with `source`233 /// 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<i64, AppErr
281 /// which is the same money leaving the school and is spelled that one way.239 /// which is the same money leaving the school and is spelled that one way.
282 /// Keyed `<line>_r`, so a retried undo reverses once.240 /// Keyed `<line>_r`, so a retried undo reverses once.
283 ///241 ///
284-/// Appends under `PAYMENT_LOCK` — not for its own sake (the id makes it242+/// The walk ([`payment_ledger::lock_for_cap`]) is taken in the same
285-/// idempotent by itself) but for the cap's: a reversal *changes* the243+/// transaction — not for its own sake (the id makes it idempotent by
286-/// subtree `applied_to` folds, so one landing between a244+/// itself) but for the cap's: a reversal *changes* the subtree every other
287-/// concurrent payment's fold and its append would let that payment be245+/// writer's fold reads, so one landing between a concurrent payment's fold
288-/// admitted against room it no longer has. The lock is what makes the cap246+/// and its append would let that payment be admitted against room it no
289-/// exact, which is the promise this module's doc makes.247+/// longer has. The row locks are what make the cap exact, which is the
248+/// promise this module's doc makes.
290 pub async fn reversal(249 pub async fn reversal(
291 db: &Database,250 db: &Database,
292 line: &PaymentLedger,251 line: &PaymentLedger,
@@ -303,22 +262,25 @@ pub async fn reversal(
303 }262 }
304 .into());263 .into());
305 }264 }
306- let _guard = PAYMENT_LOCK.lock().await;265+ tx_with_retry(db, false, async |tx| {
307- payment_ledger::append(266+ payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?;
308- db,267+ payment_ledger::append(
309- PaymentLedger {268+ &mut *tx,
310- id: PaymentLedgerId::for_reversal(line.get_id()),269+ PaymentLedger {
311- student: line.student.clone(),270+ id: PaymentLedgerId::for_reversal(line.get_id()),
312- kind: PaymentLedgerKind::Reversal,271+ student: line.student.clone(),
313- amount_minor: line.amount_minor,272+ kind: PaymentLedgerKind::Reversal,
314- source: Some(line.id.record()),273+ amount_minor: line.amount_minor,
315- due_at: None,274+ source: Some(line.id.key()),
316- method: None,275+ due_at: None,
317- note,276+ method: None,
318- recorded_by: recorded_by.clone(),277+ note,
319- created_at: Timestamp::now(),278+ recorded_by: recorded_by.clone(),
320- },279+ created_at: Timestamp::now(),
321- )280+ },
281+ )
282+ .await
283+ })
322 .await284 .await
323 }285 }
324 286
src/service/work_entry.rsmodified+5 -4
@@ -1,8 +1,9 @@
1 //! Work-log surfacing: the check-in/check-out pair, the staff log, and the1 //! Work-log surfacing: the check-in/check-out pair, the staff log, and the
2-//! manager corrections. The queries live in2+//! manager corrections. The queries live in [`crate::db::work_entry`] — both
3-//! [`crate::db::work_entry`] — both transitions are single atomic writes on3+//! transitions are single atomic writes the database itself arbitrates (the
4-//! the deterministic open id (`INSERT IGNORE` in, take-and-refile out), so4+//! `work_entry_open` partial unique index refuses a second check-in; the
5-//! this domain has no workflow of its own.5+//! check-out's conditional `UPDATE` takes the one open row), so this domain
6+//! has no workflow of its own.
6 7
7 use crate::database::Database;8 use crate::database::Database;
8 use crate::db::work_entry;9 use crate::db::work_entry;