posting.rs 14 KB

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