commit.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. //! [`CommitStore`]: the atomic write boundary (ADR-0023).
  2. //!
  3. //! A whole transfer, or a whole account-version transition, is applied in one
  4. //! `BEGIN..COMMIT`. Because the write is all-or-nothing there is no half-applied
  5. //! state for recovery to reconcile, and the three stateful guards (double-spend,
  6. //! freeze/close, overdraft floor) are enforced inside the transaction rather than
  7. //! best-effort before it. On Postgres the account-head reads take `FOR UPDATE`
  8. //! before the live-posting writes; on SQLite the single write transaction
  9. //! serializes writers and the delete-affected-count is the double-spend backstop.
  10. use std::collections::HashSet;
  11. use async_trait::async_trait;
  12. use sqlx::{Row, Transaction};
  13. use kuatia_storage::error::StoreError;
  14. use kuatia_storage::events::{LedgerEvent, event_dedup_key};
  15. use kuatia_storage::store::{
  16. CommitOutcome, CommitRejection, CommitRequest, CommitStore, TransitionOutcome,
  17. TransitionRejection,
  18. };
  19. use kuatia_types::*;
  20. use crate::SqlStore;
  21. use crate::posting::{MAX_IDS_PER_QUERY, id_predicate, live_balance_sql};
  22. use crate::row::{
  23. bind_money, deserialize_json, row_to_account, row_to_cent, serialize_json, transfer_id_to_hex,
  24. };
  25. fn internal(e: impl std::fmt::Display) -> StoreError {
  26. StoreError::Internal(e.to_string())
  27. }
  28. impl SqlStore {
  29. /// Load one account at its head version inside `tx`, taking the pessimistic
  30. /// lock (`FOR UPDATE` on Postgres). `None` means no such account.
  31. async fn locked_account(
  32. &self,
  33. tx: &mut Transaction<'_, sqlx::Any>,
  34. id: &AccountId,
  35. ) -> Result<Option<Account>, StoreError> {
  36. let lock = self.dialect.lock_clause();
  37. let row = sqlx::query(&format!(
  38. "SELECT a.* FROM accounts a \
  39. JOIN account_head h \
  40. ON h.id = a.id AND h.subaccount = a.subaccount AND h.version = a.version \
  41. WHERE h.id = $1 AND h.subaccount = $2{lock}"
  42. ))
  43. .bind(id.id)
  44. .bind(id.sub)
  45. .fetch_optional(&mut **tx)
  46. .await
  47. .map_err(internal)?;
  48. match row {
  49. Some(row) => Ok(Some(row_to_account(&row)?)),
  50. None => Ok(None),
  51. }
  52. }
  53. /// Sum the live-posting values for one `(owner, asset)` inside `tx`.
  54. ///
  55. /// The database does the addition, in one row rather than one row per
  56. /// posting, and it is exact either way: PostgreSQL sums arbitrary-precision
  57. /// `NUMERIC`, SQLite folds with `i128::checked_add` and raises on overflow
  58. /// (ADR-0024). Deliberately unlocked: an aggregate cannot carry `FOR UPDATE`
  59. /// on PostgreSQL, and it does not need to, because the caller already holds
  60. /// the account-head lock that serializes the floor check.
  61. async fn live_balance(
  62. &self,
  63. tx: &mut Transaction<'_, sqlx::Any>,
  64. owner: &AccountId,
  65. asset: &AssetId,
  66. ) -> Result<Cent, StoreError> {
  67. let row = sqlx::query(&live_balance_sql(self.dialect))
  68. .bind(owner.id)
  69. .bind(owner.sub)
  70. .bind(asset.0 as i32)
  71. .fetch_one(&mut **tx)
  72. .await
  73. .map_err(internal)?;
  74. row_to_cent(self.dialect, &row, "total")
  75. }
  76. }
  77. /// Append `event` inside `tx`, deduping on its key. Mirrors the standalone
  78. /// `EventStore::append_event` but runs on the commit's transaction.
  79. async fn append_event_tx(
  80. tx: &mut Transaction<'_, sqlx::Any>,
  81. autoid: &kuatia_types::autoid::AutoId,
  82. event: &LedgerEvent,
  83. ) -> Result<(), StoreError> {
  84. let kind_str = serde_json::to_string(&event.kind).map_err(internal)?;
  85. let data = serialize_json(event)?;
  86. let seq = autoid.next();
  87. match event_dedup_key(&event.kind) {
  88. Some(dedup_key) => {
  89. sqlx::query("INSERT INTO events (seq, timestamp, kind, data, dedup_key) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (dedup_key) DO NOTHING")
  90. .bind(seq)
  91. .bind(event.timestamp)
  92. .bind(&kind_str)
  93. .bind(&data)
  94. .bind(&dedup_key)
  95. .execute(&mut **tx)
  96. .await
  97. .map_err(internal)?;
  98. }
  99. None => {
  100. sqlx::query("INSERT INTO events (seq, timestamp, kind, data) VALUES ($1, $2, $3, $4)")
  101. .bind(seq)
  102. .bind(event.timestamp)
  103. .bind(&kind_str)
  104. .bind(&data)
  105. .execute(&mut **tx)
  106. .await
  107. .map_err(internal)?;
  108. }
  109. }
  110. Ok(())
  111. }
  112. /// Bind a chunk of posting ids onto a query as `(hex(transfer), idx)` pairs, in
  113. /// the order [`id_predicate`] expects.
  114. fn bind_ids<'q>(
  115. mut q: sqlx::query::Query<'q, sqlx::Any, sqlx::any::AnyArguments<'q>>,
  116. ids: &[PostingId],
  117. ) -> sqlx::query::Query<'q, sqlx::Any, sqlx::any::AnyArguments<'q>> {
  118. for id in ids {
  119. q = q
  120. .bind(transfer_id_to_hex(&id.transfer))
  121. .bind(id.index as i16);
  122. }
  123. q
  124. }
  125. #[async_trait]
  126. impl CommitStore for SqlStore {
  127. async fn commit_envelope(&self, req: CommitRequest<'_>) -> Result<CommitOutcome, StoreError> {
  128. let lock = self.dialect.lock_clause();
  129. let mut tx = self.pool.begin().await.map_err(internal)?;
  130. let tid_hex = transfer_id_to_hex(&req.transfer_id);
  131. // Idempotency: an already-committed transfer returns its receipt.
  132. if let Some(row) = sqlx::query(&format!(
  133. "SELECT receipt FROM transfers WHERE id = $1{lock}"
  134. ))
  135. .bind(&tid_hex)
  136. .fetch_optional(&mut *tx)
  137. .await
  138. .map_err(internal)?
  139. {
  140. let receipt_json: String = row.try_get("receipt").map_err(internal)?;
  141. return Ok(CommitOutcome::AlreadyCommitted(deserialize_json(
  142. &receipt_json,
  143. )?));
  144. }
  145. // Freeze/close guard, strict inside the transaction. Account-head reads
  146. // take the lock before any live-posting write (Postgres lock order).
  147. for aid in req.involved {
  148. let account = self
  149. .locked_account(&mut tx, aid)
  150. .await?
  151. .ok_or_else(|| StoreError::Internal(format!("commit: account {aid:?} missing")))?;
  152. if account.is_frozen() {
  153. return Ok(CommitOutcome::Rejected(CommitRejection::AccountFrozen(
  154. *aid,
  155. )));
  156. }
  157. if account.is_closed() {
  158. return Ok(CommitOutcome::Rejected(CommitRejection::AccountClosed(
  159. *aid,
  160. )));
  161. }
  162. }
  163. // Double-spend guard: read the still-Active consumed rows under the lock,
  164. // collecting their (owner, asset) for the floor check, and reject if any
  165. // consumed id is not live. Then delete them in the same transaction.
  166. let mut present: HashSet<(String, i16)> = HashSet::new();
  167. let mut touched: HashSet<(AccountId, AssetId)> = HashSet::new();
  168. for chunk in req.consume.chunks(MAX_IDS_PER_QUERY) {
  169. let sql = format!(
  170. "SELECT transfer_id, idx, owner, subaccount, asset FROM live_postings WHERE ({}){lock}",
  171. id_predicate(chunk.len(), 1)
  172. );
  173. let rows = bind_ids(sqlx::query(&sql), chunk)
  174. .fetch_all(&mut *tx)
  175. .await
  176. .map_err(internal)?;
  177. for row in &rows {
  178. let transfer_id: String = row.try_get("transfer_id").map_err(internal)?;
  179. let idx: i16 = row.try_get("idx").map_err(internal)?;
  180. let owner: i64 = row.try_get("owner").map_err(internal)?;
  181. let subaccount: i64 = row.try_get("subaccount").map_err(internal)?;
  182. let asset: i32 = row.try_get("asset").map_err(internal)?;
  183. present.insert((transfer_id, idx));
  184. touched.insert((
  185. AccountId::with_sub(owner, subaccount),
  186. AssetId::new(asset as u32),
  187. ));
  188. }
  189. }
  190. if let Some(missing) = req
  191. .consume
  192. .iter()
  193. .find(|id| !present.contains(&(transfer_id_to_hex(&id.transfer), id.index as i16)))
  194. {
  195. return Ok(CommitOutcome::Rejected(CommitRejection::DoubleSpend(
  196. *missing,
  197. )));
  198. }
  199. for chunk in req.consume.chunks(MAX_IDS_PER_QUERY) {
  200. let sql = format!(
  201. "DELETE FROM live_postings WHERE ({})",
  202. id_predicate(chunk.len(), 1)
  203. );
  204. bind_ids(sqlx::query(&sql), chunk)
  205. .execute(&mut *tx)
  206. .await
  207. .map_err(internal)?;
  208. }
  209. // Insert and activate the created postings.
  210. for p in req.create {
  211. let hex = transfer_id_to_hex(&p.id.transfer);
  212. let sql = format!(
  213. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
  214. self.dialect.money_bind(6)
  215. );
  216. let q = sqlx::query(&sql)
  217. .bind(hex.clone())
  218. .bind(p.id.index as i16)
  219. .bind(p.owner.id)
  220. .bind(p.owner.sub)
  221. .bind(p.asset.0 as i32);
  222. bind_money(q, self.dialect, p.value)
  223. .execute(&mut *tx)
  224. .await
  225. .map_err(internal)?;
  226. let sql = format!(
  227. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
  228. self.dialect.money_bind(6)
  229. );
  230. let q = sqlx::query(&sql)
  231. .bind(hex.clone())
  232. .bind(p.id.index as i16)
  233. .bind(p.owner.id)
  234. .bind(p.owner.sub)
  235. .bind(p.asset.0 as i32);
  236. bind_money(q, self.dialect, p.value)
  237. .execute(&mut *tx)
  238. .await
  239. .map_err(internal)?;
  240. touched.insert((p.owner, p.asset));
  241. }
  242. // Overdraft floor: with consumed rows deleted and created rows inserted,
  243. // the live set already reflects the post-commit balance. For each
  244. // overdraft-forbidding owner touched, its projected balance must be
  245. // non-negative.
  246. for (owner, asset) in &touched {
  247. let forbids = self
  248. .locked_account(&mut tx, owner)
  249. .await?
  250. .map(|a| a.forbids_overdraft())
  251. .unwrap_or(false);
  252. if !forbids {
  253. continue;
  254. }
  255. let projected = self.live_balance(&mut tx, owner, asset).await?;
  256. if projected.is_negative() {
  257. return Ok(CommitOutcome::Rejected(
  258. CommitRejection::OverdraftExceeded {
  259. account: *owner,
  260. asset: *asset,
  261. projected,
  262. },
  263. ));
  264. }
  265. }
  266. // Store the transfer record and index it under the involved accounts.
  267. let transfer_json = serialize_json(&req.record.envelope)?;
  268. let receipt_json = serialize_json(&req.record.receipt)?;
  269. sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book, value_date) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO NOTHING")
  270. .bind(&tid_hex)
  271. .bind(&transfer_json)
  272. .bind(&receipt_json)
  273. .bind(req.record.created_at)
  274. .bind(req.record.envelope.book().0)
  275. .bind(req.record.envelope.value_date().map(|d| d.days()))
  276. .execute(&mut *tx)
  277. .await
  278. .map_err(internal)?;
  279. for account in req.involved {
  280. sqlx::query("INSERT INTO transfer_accounts (transfer_id, account_id, subaccount) VALUES ($1, $2, $3) ON CONFLICT (transfer_id, account_id, subaccount) DO NOTHING")
  281. .bind(&tid_hex)
  282. .bind(account.id)
  283. .bind(account.sub)
  284. .execute(&mut *tx)
  285. .await
  286. .map_err(internal)?;
  287. }
  288. append_event_tx(&mut tx, &self.autoid, &req.event).await?;
  289. tx.commit().await.map_err(internal)?;
  290. Ok(CommitOutcome::Committed(req.record.receipt))
  291. }
  292. async fn commit_transition(
  293. &self,
  294. next: Account,
  295. event: LedgerEvent,
  296. ) -> Result<TransitionOutcome, StoreError> {
  297. let mut tx = self.pool.begin().await.map_err(internal)?;
  298. let current = self
  299. .locked_account(&mut tx, &next.id)
  300. .await?
  301. .ok_or_else(|| {
  302. StoreError::Internal(format!("transition: account {:?} missing", next.id))
  303. })?;
  304. if current.is_closed() {
  305. return Ok(TransitionOutcome::Rejected(
  306. TransitionRejection::AlreadyClosed(next.id),
  307. ));
  308. }
  309. if current.version >= next.version {
  310. // Already applied: ensure the (idempotent) event and report it.
  311. append_event_tx(&mut tx, &self.autoid, &event).await?;
  312. tx.commit().await.map_err(internal)?;
  313. return Ok(TransitionOutcome::AlreadyApplied);
  314. }
  315. let expected = current
  316. .version
  317. .checked_add(1)
  318. .ok_or_else(|| StoreError::Internal("account version overflow".to_string()))?;
  319. if next.version != expected {
  320. return Ok(TransitionOutcome::Rejected(
  321. TransitionRejection::VersionConflict {
  322. account: next.id,
  323. expected: next.version,
  324. },
  325. ));
  326. }
  327. sqlx::query(
  328. "INSERT INTO accounts (id, subaccount, version, flags, book, metadata) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id, subaccount, version) DO NOTHING",
  329. )
  330. .bind(next.id.id)
  331. .bind(next.id.sub)
  332. .bind(next.version as i64)
  333. .bind(next.flags.bits() as i32)
  334. .bind(next.book.0)
  335. .bind(serialize_json(&next.metadata)?)
  336. .execute(&mut *tx)
  337. .await
  338. .map_err(internal)?;
  339. sqlx::query("DELETE FROM account_head WHERE id = $1 AND subaccount = $2")
  340. .bind(next.id.id)
  341. .bind(next.id.sub)
  342. .execute(&mut *tx)
  343. .await
  344. .map_err(internal)?;
  345. sqlx::query("INSERT INTO account_head (id, subaccount, version) VALUES ($1, $2, $3)")
  346. .bind(next.id.id)
  347. .bind(next.id.sub)
  348. .bind(next.version as i64)
  349. .execute(&mut *tx)
  350. .await
  351. .map_err(internal)?;
  352. append_event_tx(&mut tx, &self.autoid, &event).await?;
  353. tx.commit().await.map_err(internal)?;
  354. Ok(TransitionOutcome::Applied)
  355. }
  356. }