commit.rs 15 KB

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