saga.rs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. #![allow(missing_docs)]
  2. use std::sync::Arc;
  3. use kuatia::ledger::Ledger;
  4. use kuatia::mem_store::InMemoryStore;
  5. use kuatia::saga::*;
  6. use kuatia_core::*;
  7. use legend::{ExecutionResult, legend};
  8. use std::collections::BTreeMap;
  9. fn usd() -> AssetId {
  10. AssetId::new(1)
  11. }
  12. fn account(id: i64) -> AccountId {
  13. AccountId::new(id)
  14. }
  15. fn external() -> AccountId {
  16. AccountId::new(99)
  17. }
  18. fn make_account(id: i64, policy: AccountPolicy) -> Account {
  19. Account {
  20. id: AccountId::new(id),
  21. version: 1,
  22. policy,
  23. flags: AccountFlags::empty(),
  24. book: BookId(0),
  25. metadata: BTreeMap::new(),
  26. }
  27. }
  28. async fn setup_ledger() -> Arc<Ledger> {
  29. let store = InMemoryStore::new();
  30. let ledger = Arc::new(Ledger::new(store));
  31. for (id, policy) in [
  32. (1, AccountPolicy::NoOverdraft),
  33. (2, AccountPolicy::NoOverdraft),
  34. (3, AccountPolicy::NoOverdraft),
  35. (99, AccountPolicy::ExternalAccount),
  36. ] {
  37. ledger
  38. .store()
  39. .create_account(make_account(id, policy))
  40. .await
  41. .unwrap();
  42. }
  43. ledger
  44. }
  45. // Define a two-step saga: deposit then pay
  46. legend! {
  47. FundAndPay<LedgerCtx, SagaError> {
  48. deposit: DepositMovementStep,
  49. pay: PayMovementStep,
  50. }
  51. }
  52. #[tokio::test]
  53. async fn saga_happy_path() {
  54. let ledger = setup_ledger().await;
  55. let saga = FundAndPay::new(FundAndPayInputs {
  56. deposit: DepositInput {
  57. to: account(1),
  58. asset: usd(),
  59. amount: Cent::from(100),
  60. external: external(),
  61. },
  62. pay: PayInput {
  63. from: account(1),
  64. to: account(2),
  65. asset: usd(),
  66. amount: Cent::from(60),
  67. },
  68. });
  69. let ctx = LedgerCtx::new(ledger.clone());
  70. let execution = saga.build(ctx);
  71. match execution.start().await {
  72. ExecutionResult::Completed(e) => {
  73. assert_eq!(e.context().receipts.len(), 2);
  74. }
  75. other => panic!("expected Completed, got {:?}", result_debug(&other)),
  76. }
  77. assert_eq!(
  78. ledger.balance(&account(1), &usd()).await.unwrap(),
  79. Cent::from(40)
  80. );
  81. assert_eq!(
  82. ledger.balance(&account(2), &usd()).await.unwrap(),
  83. Cent::from(60)
  84. );
  85. assert_eq!(
  86. ledger.balance(&external(), &usd()).await.unwrap(),
  87. Cent::from(-100)
  88. );
  89. }
  90. // Define a saga that will fail on the second step and trigger compensation
  91. legend! {
  92. DepositAndOverspend<LedgerCtx, SagaError> {
  93. deposit: DepositMovementStep,
  94. pay: PayMovementStep,
  95. }
  96. }
  97. #[tokio::test]
  98. async fn saga_compensation_on_failure() {
  99. let ledger = setup_ledger().await;
  100. // Deposit 50 then try to pay 100 -> pay fails -> deposit should be reversed
  101. let saga = DepositAndOverspend::new(DepositAndOverspendInputs {
  102. deposit: DepositInput {
  103. to: account(1),
  104. asset: usd(),
  105. amount: Cent::from(50),
  106. external: external(),
  107. },
  108. pay: PayInput {
  109. from: account(1),
  110. to: account(2),
  111. asset: usd(),
  112. amount: Cent::from(100), // more than available
  113. },
  114. });
  115. let ctx = LedgerCtx::new(ledger.clone());
  116. let execution = saga.build(ctx);
  117. match execution.start().await {
  118. ExecutionResult::Failed(_, _err) => {
  119. // The deposit should have been compensated (reversed)
  120. // Note: balances won't be exactly 0 because the deposit reversal
  121. // creates new postings, but the net effect should be zero
  122. assert_eq!(
  123. ledger.balance(&account(1), &usd()).await.unwrap(),
  124. Cent::ZERO
  125. );
  126. assert_eq!(
  127. ledger.balance(&external(), &usd()).await.unwrap(),
  128. Cent::ZERO
  129. );
  130. }
  131. other => panic!("expected Failed, got {:?}", result_debug(&other)),
  132. }
  133. }
  134. // Three-step saga
  135. legend! {
  136. ThreeStepFlow<LedgerCtx, SagaError> {
  137. deposit: DepositMovementStep,
  138. pay_ab: PayMovementStep,
  139. pay_bc: PayMovementStep,
  140. }
  141. }
  142. #[tokio::test]
  143. async fn saga_three_steps_happy() {
  144. let ledger = setup_ledger().await;
  145. let saga = ThreeStepFlow::new(ThreeStepFlowInputs {
  146. deposit: DepositInput {
  147. to: account(1),
  148. asset: usd(),
  149. amount: Cent::from(100),
  150. external: external(),
  151. },
  152. pay_ab: PayInput {
  153. from: account(1),
  154. to: account(2),
  155. asset: usd(),
  156. amount: Cent::from(60),
  157. },
  158. pay_bc: PayInput {
  159. from: account(2),
  160. to: account(3),
  161. asset: usd(),
  162. amount: Cent::from(30),
  163. },
  164. });
  165. let ctx = LedgerCtx::new(ledger.clone());
  166. let execution = saga.build(ctx);
  167. match execution.start().await {
  168. ExecutionResult::Completed(e) => {
  169. assert_eq!(e.context().receipts.len(), 3);
  170. }
  171. other => panic!("expected Completed, got {:?}", result_debug(&other)),
  172. }
  173. assert_eq!(
  174. ledger.balance(&account(1), &usd()).await.unwrap(),
  175. Cent::from(40)
  176. );
  177. assert_eq!(
  178. ledger.balance(&account(2), &usd()).await.unwrap(),
  179. Cent::from(30)
  180. );
  181. assert_eq!(
  182. ledger.balance(&account(3), &usd()).await.unwrap(),
  183. Cent::from(30)
  184. );
  185. }
  186. fn result_debug<Ctx, Err, Steps>(r: &ExecutionResult<Ctx, Err, Steps>) -> &'static str
  187. where
  188. Ctx: Send + Sync,
  189. Err: Send + Sync + Clone,
  190. Steps: legend::hlist::InstructionList<Ctx, Err>,
  191. {
  192. match r {
  193. ExecutionResult::Completed(_) => "Completed",
  194. ExecutionResult::Paused(_) => "Paused",
  195. ExecutionResult::Failed(_, _) => "Failed",
  196. ExecutionResult::CompensationFailed { .. } => "CompensationFailed",
  197. }
  198. }