posting.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //! [`PostingStore`]: the immutable posting record plus one `live_postings` hot
  2. //! table whose membership is each posting's state.
  3. //!
  4. //! A posting is in `live_postings` while it is spendable. Once consumed the row
  5. //! is deleted, leaving the posting only in the immutable `postings` table, so
  6. //! the two tables never disagree about what is spent. See ADR-0022 (merged hot
  7. //! index) and ADR-0016.
  8. use std::collections::HashMap;
  9. use async_trait::async_trait;
  10. use sqlx::Row;
  11. use sqlx::any::AnyRow;
  12. use kuatia_storage::error::StoreError;
  13. use kuatia_storage::store::*;
  14. use kuatia_types::*;
  15. use crate::SqlStore;
  16. use crate::dialect::Dialect;
  17. use crate::row::{row_to_cent, row_to_posting, transfer_id_to_hex};
  18. /// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
  19. /// in-transaction overdraft floor in `commit`, so both read the balance the same
  20. /// way. The sum happens in the database and is exact on both backends
  21. /// (ADR-0024).
  22. pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
  23. format!(
  24. "SELECT {} AS total FROM live_postings \
  25. WHERE owner = $1 AND subaccount = $2 AND asset = $3",
  26. dialect.money_sum("value")
  27. )
  28. }
  29. /// The source table a posting read of the given filter targets. No UNION and no
  30. /// predicate: the live set is exactly one table's rows.
  31. fn filter_source(filter: PostingFilter) -> &'static str {
  32. match filter {
  33. PostingFilter::Live => "live_postings",
  34. PostingFilter::All => "postings",
  35. }
  36. }
  37. /// Maximum posting ids matched by a single statement. `id_predicate` expands to
  38. /// an `OR` of `n` equality pairs, so the binding constraint is SQLite's
  39. /// expression-tree depth limit (`SQLITE_MAX_EXPR_DEPTH`, default 1000), which a
  40. /// chain of `n` `OR`s reaches at roughly `n` deep. It caps well before the
  41. /// bind-parameter limits (SQLite 32766, PostgreSQL 65535) that `2 * n (+1)`
  42. /// parameters would hit. `500` stays comfortably under the expression-depth
  43. /// limit; callers that pass more ids are chunked, so the id-batch primitives
  44. /// have no practical ceiling on batch size.
  45. pub(crate) const MAX_IDS_PER_QUERY: usize = 500;
  46. /// Build a portable predicate matching a set of posting ids:
  47. /// `(transfer_id = $s AND idx = $s+1) OR (transfer_id = $s+2 AND idx = $s+3) ...`
  48. /// starting at placeholder `$start`. Row-value `IN ((a, b), ...)` is not
  49. /// portable across SQLite and PostgreSQL; an `OR` of equality pairs is. The
  50. /// caller binds each id as `(hex(transfer), idx as i16)` in order, matching the
  51. /// placeholder sequence. `ids` must be non-empty and no longer than
  52. /// [`MAX_IDS_PER_QUERY`]; larger sets are split into chunks by the caller.
  53. pub(crate) fn id_predicate(count: usize, start: u32) -> String {
  54. (0..count)
  55. .map(|i| {
  56. let p = start + (i as u32) * 2;
  57. format!("(transfer_id = ${} AND idx = ${})", p, p + 1)
  58. })
  59. .collect::<Vec<_>>()
  60. .join(" OR ")
  61. }
  62. #[async_trait]
  63. impl PostingStore for SqlStore {
  64. async fn get_postings(&self, ids: &[PostingId]) -> Result<Vec<Posting>, StoreError> {
  65. if ids.is_empty() {
  66. return Ok(Vec::new());
  67. }
  68. // Set-based query per chunk instead of one probe per id, reusing the
  69. // portable `id_predicate` and binding each id in order as
  70. // `(hex(transfer), idx as i16)`. Chunked so a large batch never exceeds
  71. // the backend's bind-parameter limit (see `MAX_IDS_PER_QUERY`).
  72. let mut found: HashMap<(String, i16), Posting> = HashMap::with_capacity(ids.len());
  73. for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
  74. let sql = format!(
  75. "SELECT {} FROM postings WHERE {}",
  76. self.dialect.posting_columns(),
  77. id_predicate(chunk.len(), 1)
  78. );
  79. let mut q = sqlx::query(&sql);
  80. for id in chunk {
  81. q = q
  82. .bind(transfer_id_to_hex(&id.transfer))
  83. .bind(id.index as i16);
  84. }
  85. let rows = q
  86. .fetch_all(&self.pool)
  87. .await
  88. .map_err(|e| StoreError::Internal(e.to_string()))?;
  89. // Index the fetched postings by the same `(hex, idx)` key that was bound.
  90. for row in &rows {
  91. let posting = row_to_posting(self.dialect, row)?;
  92. let key = (
  93. transfer_id_to_hex(&posting.id.transfer),
  94. posting.id.index as i16,
  95. );
  96. found.insert(key, posting);
  97. }
  98. }
  99. // Return in input order, erroring on the first id absent from the batch
  100. // (matching the per-id lookup's `NotFound` semantics).
  101. let mut result = Vec::with_capacity(ids.len());
  102. for id in ids {
  103. let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
  104. let posting = found
  105. .get(&key)
  106. .ok_or_else(|| StoreError::NotFound(format!("posting {id:?}")))?;
  107. result.push(posting.clone());
  108. }
  109. Ok(result)
  110. }
  111. async fn get_postings_by_account(
  112. &self,
  113. id: i64,
  114. sub: Option<i64>,
  115. asset: Option<&AssetId>,
  116. filter: PostingFilter,
  117. ) -> Result<Vec<Posting>, StoreError> {
  118. // Build the predicate dynamically: `sub == None` spans every subaccount
  119. // of `id`, `Some(s)` restricts to one. The subaccount is compared only
  120. // for equality, never as a magnitude.
  121. let source = filter_source(filter);
  122. let mut sql = format!(
  123. "SELECT {} FROM {source} WHERE owner = $1",
  124. self.dialect.posting_columns()
  125. );
  126. let mut placeholder = 2u32;
  127. if sub.is_some() {
  128. sql.push_str(&format!(" AND subaccount = ${placeholder}"));
  129. placeholder += 1;
  130. }
  131. if asset.is_some() {
  132. sql.push_str(&format!(" AND asset = ${placeholder}"));
  133. }
  134. // Deterministic order by the posting primary key, matching
  135. // `query_postings`, so callers (and pagination built on top) see a
  136. // stable sequence.
  137. sql.push_str(" ORDER BY transfer_id, idx");
  138. let mut q = sqlx::query(&sql).bind(id);
  139. if let Some(s) = sub {
  140. q = q.bind(s);
  141. }
  142. if let Some(a) = asset {
  143. q = q.bind(a.0 as i32);
  144. }
  145. let rows = q
  146. .fetch_all(&self.pool)
  147. .await
  148. .map_err(|e| StoreError::Internal(e.to_string()))?;
  149. rows.iter()
  150. .map(|row| row_to_posting(self.dialect, row))
  151. .collect()
  152. }
  153. async fn live_balance(&self, account: &AccountId, asset: &AssetId) -> Result<Cent, StoreError> {
  154. let row = sqlx::query(&live_balance_sql(self.dialect))
  155. .bind(account.id)
  156. .bind(account.sub)
  157. .bind(asset.0 as i32)
  158. .fetch_one(&self.pool)
  159. .await
  160. .map_err(|e| StoreError::Internal(e.to_string()))?;
  161. row_to_cent(self.dialect, &row, "total")
  162. }
  163. async fn get_posting_states(&self, ids: &[PostingId]) -> Result<Vec<PostingState>, StoreError> {
  164. if ids.is_empty() {
  165. return Ok(Vec::new());
  166. }
  167. // Two set-based queries per chunk: membership of the live table decides
  168. // Live, and `postings` decides Spent vs Missing for ids absent from it.
  169. // Reuses the portable `id_predicate` (an OR of equality pairs; row-value
  170. // `IN` is not portable across SQLite and PostgreSQL), binding each id as
  171. // `(hex, idx)`.
  172. // Key membership by the same `(hex, idx)` values that were bound, so the
  173. // per-id lookup below matches without decoding transfer ids back.
  174. let row_key = |row: &AnyRow| -> Result<(String, i16), StoreError> {
  175. let transfer_id: String = row
  176. .try_get("transfer_id")
  177. .map_err(|e| StoreError::Internal(e.to_string()))?;
  178. let idx: i16 = row
  179. .try_get("idx")
  180. .map_err(|e| StoreError::Internal(e.to_string()))?;
  181. Ok((transfer_id, idx))
  182. };
  183. // `present` is every id in the immutable record, which is what tells
  184. // Spent (present, not live) from Missing (absent).
  185. let mut live: std::collections::HashSet<(String, i16)> = std::collections::HashSet::new();
  186. let mut present: std::collections::HashSet<(String, i16)> =
  187. std::collections::HashSet::new();
  188. for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
  189. let predicate = id_predicate(chunk.len(), 1);
  190. let live_sql = format!("SELECT transfer_id, idx FROM live_postings WHERE {predicate}");
  191. let mut live_q = sqlx::query(&live_sql);
  192. for id in chunk {
  193. live_q = live_q
  194. .bind(transfer_id_to_hex(&id.transfer))
  195. .bind(id.index as i16);
  196. }
  197. let live_rows = live_q
  198. .fetch_all(&self.pool)
  199. .await
  200. .map_err(|e| StoreError::Internal(e.to_string()))?;
  201. for row in &live_rows {
  202. live.insert(row_key(row)?);
  203. }
  204. let present_sql = format!("SELECT transfer_id, idx FROM postings WHERE {predicate}");
  205. let mut present_q = sqlx::query(&present_sql);
  206. for id in chunk {
  207. present_q = present_q
  208. .bind(transfer_id_to_hex(&id.transfer))
  209. .bind(id.index as i16);
  210. }
  211. let present_rows = present_q
  212. .fetch_all(&self.pool)
  213. .await
  214. .map_err(|e| StoreError::Internal(e.to_string()))?;
  215. for row in &present_rows {
  216. present.insert(row_key(row)?);
  217. }
  218. }
  219. // Reconstruct each id's state in input order, live before spent before
  220. // missing, so a duplicated id resolves to the same state both times.
  221. let mut out = Vec::with_capacity(ids.len());
  222. for id in ids {
  223. let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
  224. out.push(if live.contains(&key) {
  225. PostingState::Live
  226. } else if present.contains(&key) {
  227. PostingState::Spent
  228. } else {
  229. PostingState::Missing
  230. });
  231. }
  232. Ok(out)
  233. }
  234. async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
  235. let (where_clause, count_clause) = {
  236. let source = filter_source(query.filter);
  237. let mut w = String::from("WHERE owner = $1");
  238. let mut idx = 2u32;
  239. if query.sub.is_some() {
  240. w.push_str(&format!(" AND subaccount = ${idx}"));
  241. idx += 1;
  242. }
  243. if query.asset.is_some() {
  244. w.push_str(&format!(" AND asset = ${idx}"));
  245. }
  246. let c = format!("SELECT COUNT(*) as cnt FROM {source} {w}");
  247. let (offset, limit) = kuatia_storage::query::window(query.offset, query.limit);
  248. // Order by the posting primary key so pagination is deterministic:
  249. // without it LIMIT/OFFSET could skip or repeat rows across pages.
  250. w.push_str(&format!(
  251. " ORDER BY transfer_id, idx LIMIT {limit} OFFSET {offset}"
  252. ));
  253. (
  254. format!(
  255. "SELECT {} FROM {source} {w}",
  256. self.dialect.posting_columns()
  257. ),
  258. c,
  259. )
  260. };
  261. // Build count query
  262. let mut count_q = sqlx::query(&count_clause).bind(query.account);
  263. if let Some(s) = query.sub {
  264. count_q = count_q.bind(s);
  265. }
  266. if let Some(ref a) = query.asset {
  267. count_q = count_q.bind(a.0 as i32);
  268. }
  269. let count_row = count_q
  270. .fetch_one(&self.pool)
  271. .await
  272. .map_err(|e| StoreError::Internal(e.to_string()))?;
  273. let total: i64 = count_row
  274. .try_get("cnt")
  275. .map_err(|e| StoreError::Internal(e.to_string()))?;
  276. // Build data query
  277. let mut data_q = sqlx::query(&where_clause).bind(query.account);
  278. if let Some(s) = query.sub {
  279. data_q = data_q.bind(s);
  280. }
  281. if let Some(ref a) = query.asset {
  282. data_q = data_q.bind(a.0 as i32);
  283. }
  284. let rows = data_q
  285. .fetch_all(&self.pool)
  286. .await
  287. .map_err(|e| StoreError::Internal(e.to_string()))?;
  288. let items: Vec<Posting> = rows
  289. .iter()
  290. .map(|row| row_to_posting(self.dialect, row))
  291. .collect::<Result<_, _>>()?;
  292. Ok(Page {
  293. items,
  294. total: total as u64,
  295. })
  296. }
  297. }