forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

payment_ledger.rs629 lines, 24.8 KiBHistoryRawDownload
1//! The money workflows: recording a payment, handing one back, and undoing a
2//! mistaken line.
3//!
4//! **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 a
6//! 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 it
8//! targets, so it never has to be globally unique. Without a key the id is a
9//! 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 happens
11//! before the cap check** and inside the same transaction the append lands
12//! in: the first attempt's line is already inside what the cap folds, so
13//! checking the cap first would refuse the very payment that landed. A key
14//! replayed with a *different* amount or against a *different* line is a
15//! `409`, never the stored line — returning it would hide a client bug
16//! behind a `201`.
17//!
18//! **The over-payment cap is the row locks', not a process mutex's.**
19//! [`credit`] and [`refund`] refuse to take more than the line they target
20//! is worth, by folding that line's whole subtree in the transaction that
21//! appends. The fold, rather than a sum of the direct children, because
22//! money handed back frees the room it took: a charge paid in full and then
23//! refunded is owed again, and must be payable again.
24//!
25//! What makes that check mean something is the **ancestor-chain row lock**
26//! ([`crate::db::payment_ledger::lock_for_cap`]): every write that *moves*
27//! the arithmetic of a subtree — a payment into it, a refund under one of
28//! its payments, a reversal anywhere inside it — walks its target's chain up
29//! to the subtree's root charge and takes each row `FOR UPDATE`, **inside
30//! the same transaction as its own fold and append**. Two writers to one
31//! subtree therefore contend on the root's row: the second waits, and its
32//! fold runs only after the first's append committed, against the state the
33//! first left behind. There is no window between the fold and the append
34//! for a competing write to slip into, which is exactly what the old
35//! process-wide mutex it replaced bought and nothing more; unlike the
36//! mutex it also survives multiple processes, and it never serializes
37//! writers to *different* subtrees the way the global lock did.
38//! ([`reversal`] takes the walk too, since a reversal landing between a
39//! payment's fold and its append would admit the payment against room it no
40//! longer has.) A future append that skips the walk re-opens the hole
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.
51//!
52//! The `request_key` mismatch `409` rides on the same locks: it is a
53//! read-then-compare, and it is read inside the transaction that would
54//! append, so two first-time posts of one key with different amounts cannot
55//! both walk past it. One line, one amount, no double charge, and the "you
56//! reused a key" diagnostic is exact.
57
58use crate::database::{Database, tx_with_retry};
59use crate::db::payment_ledger;
60use crate::domain::payment_ledger::{
61 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
62 PaymentRequestKey,
63};
64use crate::domain::timestamp::Timestamp;
65use crate::domain::user::UserId;
66use crate::error::{AppError, ValidationError};
67
68/// Money in, against one named `charge`. Partial payments are the norm, so
69/// a charge may collect several credits; together they may not exceed it.
70/// A *reversed* charge takes no payment either, and is refused saying so
71/// rather than claiming it was paid.
72///
73/// With a `request_key` the line is keyed by it (see
74/// [`PaymentLedgerId::for_request`]) and the call is retry-safe; without
75/// one the id is a fresh uuid and two identical calls are two payments,
76/// which is what a cash desk taking the same amount twice really means.
77pub async fn credit(
78 db: &Database,
79 charge: &PaymentLedger,
80 amount_minor: LedgerAmount,
81 method: Option<LedgerMethod>,
82 note: Option<LedgerNote>,
83 request_key: Option<&PaymentRequestKey>,
84 recorded_by: &UserId,
85) -> Result<PaymentLedger, AppError> {
86 against(
87 db,
88 charge,
89 PaymentLedgerKind::Charge,
90 PaymentLedgerKind::Credit,
91 "a payment must be recorded against a charge",
92 "the charge is already paid in full",
93 // A charge *is* reversible, and its reversal fills the same room a
94 // payment would, so the fold refuses the two cases identically.
95 Some("the charge was reversed, so it is no longer owed"),
96 amount_minor,
97 method,
98 note,
99 request_key.map(|key| PaymentLedgerId::for_request(charge.get_id(), "k", key)),
100 recorded_by,
101 )
102 .await
103}
104
105/// Money back out, against one named `credit` — how an over-payment or a
106/// payment recorded in error is returned. Partials allowed, and no more
107/// than the credit was worth. `request_key` makes it retry-safe exactly as
108/// it does for [`credit`].
109pub async fn refund(
110 db: &Database,
111 credit: &PaymentLedger,
112 amount_minor: LedgerAmount,
113 method: Option<LedgerMethod>,
114 note: Option<LedgerNote>,
115 request_key: Option<&PaymentRequestKey>,
116 recorded_by: &UserId,
117) -> Result<PaymentLedger, AppError> {
118 against(
119 db,
120 credit,
121 PaymentLedgerKind::Credit,
122 PaymentLedgerKind::Refund,
123 "a refund must be recorded against a payment",
124 "the payment is already refunded in full",
125 // A credit is never reversed ([`reversal`] refuses
126 // it), so a full fold here can only mean the refunds, and there is
127 // no second reason to tell apart — nor a read to spend looking.
128 None,
129 amount_minor,
130 method,
131 note,
132 request_key.map(|key| PaymentLedgerId::for_request(credit.get_id(), "kr", key)),
133 recorded_by,
134 )
135 .await
136}
137
138/// The shared body of `credit` and `refund`: check the target is the kind
139/// this line may point at, then — in one transaction, holding the target's
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.
143///
144/// The replay read comes **before** the cap, and under the same row locks:
145/// on a retry the first attempt's line is already part of the subtree the
146/// cap folds, so consulting the cap first would answer a payment that
147/// landed with "already paid in full" — refusing precisely the request that
148/// succeeded. Reading it inside the transaction also keeps two simultaneous
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.
151#[allow(clippy::too_many_arguments)]
152async fn against(
153 db: &Database,
154 target: &PaymentLedger,
155 expected: PaymentLedgerKind,
156 kind: PaymentLedgerKind,
157 wrong_target: &'static str,
158 over: &'static str,
159 reversed: Option<&'static str>,
160 amount_minor: LedgerAmount,
161 method: Option<LedgerMethod>,
162 note: Option<LedgerNote>,
163 keyed: Option<PaymentLedgerId>,
164 recorded_by: &UserId,
165) -> Result<PaymentLedger, AppError> {
166 if target.kind != expected {
167 return Err(ValidationError::Invalid {
168 field: "source",
169 reason: wrong_target,
170 }
171 .into());
172 }
173 // Owned captures: a closure holding a `&T` — a reference parameter or a
174 // `&str` of any lifetime, `'static` included — fails the higher-ranked
175 // `Send`/`AsyncFnMut` check `tx_with_retry`'s future must pass.
176 let target = target.clone();
177 let recorded_by = *recorded_by;
178 let over = over.to_owned();
179 let reversed = reversed.map(str::to_owned);
180 tx_with_retry(db, false, async move |tx| {
181 // Every writer that can move this target's arithmetic holds some row
182 // on this chain; holding the whole walk to the root is what makes
183 // the fold below and the append it authorizes one decision.
184 payment_ledger::lock_for_cap(&mut *tx, &target.id).await?;
185 // Awaits sit in match arms, never in a `let`-chain condition: an
186 // awaited condition poisons the closure future's higher-ranked
187 // `Send` that `tx_with_retry` requires.
188 let replay = match keyed.clone() {
189 Some(id) => payment_ledger::read(&mut *tx, &id).await?,
190 None => None,
191 };
192 if let Some(existing) = replay {
193 // A replay is answered from the stored line — but only if it is
194 // the same money. The same key for a different amount or a
195 // different target is a client bug, and handing back the old
196 // line would hide it behind a `201`.
197 if existing.amount_minor.as_minor() != amount_minor.as_minor()
198 || existing.get_source_key() != Some(target.id.key())
199 {
200 return Err(AppError::Conflict(
201 "this request_key was already used for a different amount or target",
202 ));
203 }
204 return Ok(existing);
205 }
206 let taken = payment_ledger::applied_to(&mut *tx, target.id.key(), target.kind).await?;
207 if taken.saturating_add(amount_minor.as_minor()) > target.amount_minor.as_minor() {
208 // The fold cannot say *why* the room is gone: a reversal is a
209 // child of the line it undoes and folds in at `+amount` exactly
210 // as a payment does, so a reversed charge reads as full down to
211 // the minor unit. The stored answer is the same either way —
212 // nothing may be recorded against it — but "already paid in full"
213 // told a bursar money had arrived when none ever did. The
214 // reversal's id is derived from its target's, so telling the two
215 // apart is one read, taken only on the refusal path.
216 if let Some(text) = &reversed {
217 let reversed_there =
218 payment_ledger::read(&mut *tx, &PaymentLedgerId::for_reversal(&target.id))
219 .await?
220 .is_some();
221 if reversed_there {
222 return Err(AppError::ConflictOwned(text.clone()));
223 }
224 }
225 return Err(AppError::ConflictOwned(over.clone()));
226 }
227 payment_ledger::append(
228 &mut *tx,
229 PaymentLedger {
230 id: keyed.clone().unwrap_or_else(PaymentLedgerId::generate),
231 student: target.student,
232 kind,
233 amount_minor,
234 source: Some(target.id.key().to_string()),
235 due_at: None,
236 method: method.clone(),
237 note: note.clone(),
238 recorded_by,
239 created_at: Timestamp::now(),
240 },
241 )
242 .await
243 })
244 .await
245}
246
247/// Undo a line entered by mistake, for its exact amount, with `source`
248/// pointing at it. The line itself is never touched.
249///
250/// Only a *negative-fold* line may be reversed: a charge that should never
251/// have been raised, or a refund that should never have been paid out. A
252/// mistaken credit is corrected by a [`refund`] against it,
253/// which is the same money leaving the school and is spelled that one way.
254/// Keyed `<line>_r`, so a retried undo reverses once.
255///
256/// The walk ([`payment_ledger::lock_for_cap`]) is taken in the same
257/// transaction — not for its own sake (the id makes it idempotent by
258/// itself) but for the cap's: a reversal *changes* the subtree every other
259/// writer's fold reads, so one landing between a concurrent payment's fold
260/// and its append would let that payment be admitted against room it no
261/// longer has. The row locks are what make the cap exact, which is the
262/// promise this module's doc makes.
263pub async fn reversal(
264 db: &Database,
265 line: &PaymentLedger,
266 note: Option<LedgerNote>,
267 recorded_by: &UserId,
268) -> Result<PaymentLedger, AppError> {
269 if !matches!(
270 line.kind,
271 PaymentLedgerKind::Charge | PaymentLedgerKind::Refund
272 ) {
273 return Err(ValidationError::Invalid {
274 field: "source",
275 reason: "only a charge or a refund can be reversed; refund a payment instead",
276 }
277 .into());
278 }
279 // Owned captures (`Send` rule of `tx_with_retry` closures).
280 let line = line.clone();
281 let recorded_by = *recorded_by;
282 tx_with_retry(db, false, async move |tx| {
283 payment_ledger::lock_for_cap(&mut *tx, line.get_id()).await?;
284 payment_ledger::append(
285 &mut *tx,
286 PaymentLedger {
287 id: PaymentLedgerId::for_reversal(line.get_id()),
288 student: line.student,
289 kind: PaymentLedgerKind::Reversal,
290 amount_minor: line.amount_minor,
291 source: Some(line.id.key().to_string()),
292 due_at: None,
293 method: None,
294 note: note.clone(),
295 recorded_by,
296 created_at: Timestamp::now(),
297 },
298 )
299 .await
300 })
301 .await
302}
303
304pub async fn read(db: &Database, id: &PaymentLedgerId) -> Result<Option<PaymentLedger>, AppError> {
305 payment_ledger::read(db, id).await
306}
307
308/// A student's whole statement, newest first.
309pub async fn list_for_student(
310 db: &Database,
311 student: &UserId,
312 limit: Option<i64>,
313 offset: i64,
314) -> Result<(Vec<PaymentLedger>, i64), AppError> {
315 payment_ledger::list_for_student(db, student, limit, offset).await
316}
317
318/// The derived balance: `credits + reversals - charges - refunds`, in minor
319/// units. Negative means the family owes the school.
320pub async fn balance_of(db: &Database, student: &UserId) -> Result<i64, AppError> {
321 payment_ledger::balance_of(db, student).await
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327
328 /// Raise one charge of `amount` on a fresh student, and hand it back.
329 async fn one_charge(amount: i64, db: &Database) -> (PaymentLedger, UserId, UserId) {
330 use crate::db::fee_plan;
331 use crate::domain::fee_plan::{FeePlanName, Installment};
332
333 let manager = crate::db::class_member::tests::fixture_user(db, "ledger-manager").await;
334 let student = crate::db::class_member::tests::fixture_user(db, "ledger-student").await;
335 let plan = fee_plan::create(
336 db,
337 FeePlanName::try_new("Yearly").unwrap(),
338 vec![Installment::new(
339 LedgerAmount::try_new(amount).unwrap(),
340 Timestamp::from_millis(1_000),
341 )],
342 &manager,
343 )
344 .await
345 .unwrap();
346 crate::service::fee_plan_assignment::assign(db, &plan, &student, &manager)
347 .await
348 .unwrap();
349 let (lines, _) = payment_ledger::list_for_student(db, &student, None, 0)
350 .await
351 .unwrap();
352 (lines.into_iter().next().unwrap(), student, manager)
353 }
354
355 /// The collision the id grammar must not admit: with `_` legal in a key, a
356 /// refund keyed `abc_r` derived exactly `<refund>_r` — the id that refund's
357 /// own reversal must own — and whichever came second was handed the other's
358 /// line, of the wrong kind and the wrong amount, with the real reversal
359 /// impossible ever after. `_` is now illegal in a key, so the collision
360 /// cannot be constructed; the nearest legal key still works, and the
361 /// reversal still gets its own line.
362 #[tokio::test]
363 async fn a_keyed_refund_cannot_take_the_id_of_its_own_reversal() {
364 assert!(
365 PaymentRequestKey::try_new("abc_r").is_err(),
366 "the key that spelled a reversal's id must not parse"
367 );
368 let (db, _leases) = crate::database::init_test_db().await;
369 let (charge, _, manager) = one_charge(100, &db).await;
370 let key = PaymentRequestKey::try_new("abc-r").unwrap();
371 let credit_line = credit(
372 &db,
373 &charge,
374 LedgerAmount::try_new(100).unwrap(),
375 None,
376 None,
377 None,
378 &manager,
379 )
380 .await
381 .unwrap();
382 let refund_line = refund(
383 &db,
384 &credit_line,
385 LedgerAmount::try_new(100).unwrap(),
386 None,
387 None,
388 Some(&key),
389 &manager,
390 )
391 .await
392 .unwrap();
393 let reversal_line = reversal(&db, &refund_line, None, &manager).await.unwrap();
394 assert_ne!(reversal_line.get_id(), refund_line.get_id());
395 assert_eq!(reversal_line.get_kind(), PaymentLedgerKind::Reversal);
396 assert_eq!(reversal_line.get_amount_minor().as_minor(), 100);
397
398 // And the last-ditch guard bites: an id that resolves to another kind
399 // is a 500, never that other line handed back as this one.
400 let intruder = PaymentLedger {
401 id: charge.get_id().clone(),
402 student: charge.student,
403 kind: PaymentLedgerKind::Credit,
404 amount_minor: LedgerAmount::try_new(1).unwrap(),
405 source: Some(charge.id.key().to_owned()),
406 due_at: None,
407 method: None,
408 note: None,
409 recorded_by: manager,
410 created_at: Timestamp::now(),
411 };
412 assert!(
413 matches!(
414 payment_ledger::append(&db, intruder).await,
415 Err(AppError::Internal(_))
416 ),
417 "a read-back of another kind must not pass for the appended line"
418 );
419 }
420
421 /// The defect this fold replaced a plain sum for: a payment that was handed
422 /// back frees the room it took, so the charge it paid can be paid again. It
423 /// is the same charge, still owed — refusing the second payment would leave
424 /// a family unable to settle a bill the school itself refunded.
425 #[tokio::test]
426 async fn a_refund_frees_the_room_it_took_under_the_charge() {
427 let (db, _leases) = crate::database::init_test_db().await;
428 let (charge, student, manager) = one_charge(100, &db).await;
429 let pay = |amount| {
430 credit(
431 &db,
432 &charge,
433 LedgerAmount::try_new(amount).unwrap(),
434 None,
435 None,
436 None,
437 &manager,
438 )
439 };
440
441 let credit_line = pay(100).await.unwrap();
442 // Still fully paid: a second payment has no room.
443 assert!(
444 matches!(
445 pay(100).await,
446 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
447 ),
448 "a charge paid in full may not be paid twice"
449 );
450
451 refund(
452 &db,
453 &credit_line,
454 LedgerAmount::try_new(100).unwrap(),
455 None,
456 None,
457 None,
458 &manager,
459 )
460 .await
461 .unwrap();
462 assert_eq!(
463 balance_of(&db, &student).await.unwrap(),
464 -100,
465 "the refund puts the charge back on the family"
466 );
467 let repaid = pay(100)
468 .await
469 .expect("the refunded charge is payable again");
470 assert_eq!(repaid.get_amount_minor().as_minor(), 100);
471 assert_eq!(balance_of(&db, &student).await.unwrap(), 0);
472
473 // And the room is gone again, so the cap still bites after all that.
474 assert!(matches!(
475 pay(1).await,
476 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
477 ));
478 }
479
480 /// The other half of the fold: reversing a refund un-does the money going
481 /// out, so the room that refund freed is taken back.
482 #[tokio::test]
483 async fn a_reversed_refund_takes_its_room_back() {
484 let (db, _leases) = crate::database::init_test_db().await;
485 let (charge, _, manager) = one_charge(100, &db).await;
486 let credit_line = credit(
487 &db,
488 &charge,
489 LedgerAmount::try_new(100).unwrap(),
490 None,
491 None,
492 None,
493 &manager,
494 )
495 .await
496 .unwrap();
497 let refund_line = refund(
498 &db,
499 &credit_line,
500 LedgerAmount::try_new(100).unwrap(),
501 None,
502 None,
503 None,
504 &manager,
505 )
506 .await
507 .unwrap();
508 reversal(&db, &refund_line, None, &manager).await.unwrap();
509
510 assert!(
511 matches!(
512 credit(
513 &db,
514 &charge,
515 LedgerAmount::try_new(100).unwrap(),
516 None,
517 None,
518 None,
519 &manager
520 )
521 .await,
522 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
523 ),
524 "the refund was undone, so the charge is paid in full again"
525 );
526 }
527
528 /// The money branches, end to end against the engine: partial payments
529 /// accumulate, the advisory cap refuses the one that would overshoot the
530 /// charge, a refund is capped by *its* credit, and neither a credit nor a
531 /// reversal may point at a line of the wrong kind.
532 #[tokio::test]
533 async fn payments_are_capped_by_the_line_they_target() {
534 use crate::db::fee_plan;
535 use crate::domain::fee_plan::{FeePlanName, Installment};
536
537 let (db, _leases) = crate::database::init_test_db().await;
538 let manager = crate::db::class_member::tests::fixture_user(&db, "ledger-manager").await;
539 let student = crate::db::class_member::tests::fixture_user(&db, "ledger-student").await;
540 let plan = fee_plan::create(
541 &db,
542 FeePlanName::try_new("Yearly").unwrap(),
543 vec![Installment::new(
544 LedgerAmount::try_new(10_000).unwrap(),
545 Timestamp::from_millis(1_000),
546 )],
547 &manager,
548 )
549 .await
550 .unwrap();
551 crate::service::fee_plan_assignment::assign(&db, &plan, &student, &manager)
552 .await
553 .unwrap();
554 let (charges, _) = payment_ledger::list_for_student(&db, &student, None, 0)
555 .await
556 .unwrap();
557 let charge = charges.into_iter().next().unwrap();
558 assert_eq!(charge.get_due_at(), Some(Timestamp::from_millis(1_000)));
559
560 let paid = |amount| {
561 credit(
562 &db,
563 &charge,
564 LedgerAmount::try_new(amount).unwrap(),
565 None,
566 None,
567 None,
568 &manager,
569 )
570 };
571 let first = paid(6_000).await.unwrap();
572 assert!(
573 matches!(
574 paid(5_000).await,
575 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
576 ),
577 "6 000 + 5 000 overshoots a 10 000 charge"
578 );
579 paid(4_000).await.expect("the exact remainder is allowed");
580 assert_eq!(balance_of(&db, &student).await.unwrap(), 0);
581
582 // A refund is bounded by the credit it returns, not by the charge.
583 let refund_amount = |amount| {
584 refund(
585 &db,
586 &first,
587 LedgerAmount::try_new(amount).unwrap(),
588 None,
589 None,
590 None,
591 &manager,
592 )
593 };
594 assert!(matches!(
595 refund_amount(6_001).await,
596 Err(AppError::Conflict(_) | AppError::ConflictOwned(_))
597 ));
598 refund_amount(6_000).await.unwrap();
599 assert_eq!(
600 balance_of(&db, &student).await.unwrap(),
601 -6_000,
602 "money handed back puts the debt back on the family"
603 );
604
605 // Wrong-kind targets are refused, and a credit is never reversed.
606 assert!(
607 credit(
608 &db,
609 &first,
610 LedgerAmount::try_new(1).unwrap(),
611 None,
612 None,
613 None,
614 &manager,
615 )
616 .await
617 .is_err()
618 );
619 assert!(reversal(&db, &first, None, &manager).await.is_err());
620 // A charge, though, reverses — once, however often it is retried.
621 let reversed = reversal(&db, &charge, None, &manager).await.unwrap();
622 let again = reversal(&db, &charge, None, &manager).await.unwrap();
623 assert_eq!(reversed.get_id(), again.get_id());
624 let (lines, _) = payment_ledger::list_for_student(&db, &student, None, 0)
625 .await
626 .unwrap();
627 assert_eq!(lines.len(), 5, "charge, two credits, refund, one reversal");
628 }
629}