transfer.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //! [`TransferStore`]: committed envelope records and their account index.
  2. use async_trait::async_trait;
  3. use sqlx::Row;
  4. use kuatia_storage::error::StoreError;
  5. use kuatia_storage::store::*;
  6. use kuatia_types::*;
  7. use crate::SqlStore;
  8. use crate::row::{deserialize_json, envelope_id_to_hex, serialize_json};
  9. #[async_trait]
  10. impl TransferStore for SqlStore {
  11. async fn get_transfer(&self, id: &EnvelopeId) -> Result<Option<EnvelopeRecord>, StoreError> {
  12. let row = sqlx::query("SELECT transfer, receipt, created_at FROM transfers WHERE id = $1")
  13. .bind(envelope_id_to_hex(id))
  14. .fetch_optional(&self.pool)
  15. .await
  16. .map_err(|e| StoreError::Internal(e.to_string()))?;
  17. match row {
  18. None => Ok(None),
  19. Some(row) => {
  20. let transfer_json: String = row
  21. .try_get("transfer")
  22. .map_err(|e| StoreError::Internal(e.to_string()))?;
  23. let receipt_json: String = row
  24. .try_get("receipt")
  25. .map_err(|e| StoreError::Internal(e.to_string()))?;
  26. let created_at: i64 = row
  27. .try_get("created_at")
  28. .map_err(|e| StoreError::Internal(e.to_string()))?;
  29. Ok(Some(EnvelopeRecord {
  30. envelope: deserialize_json(&transfer_json)?,
  31. receipt: deserialize_json(&receipt_json)?,
  32. created_at,
  33. }))
  34. }
  35. }
  36. }
  37. async fn store_transfer(
  38. &self,
  39. record: EnvelopeRecord,
  40. involved: &[AccountId],
  41. ) -> Result<u64, StoreError> {
  42. let tid = record.receipt.transfer_id;
  43. let tid_hex = envelope_id_to_hex(&tid);
  44. let transfer_json = serialize_json(&record.envelope)?;
  45. let receipt_json = serialize_json(&record.receipt)?;
  46. let mut tx = self
  47. .pool
  48. .begin()
  49. .await
  50. .map_err(|e| StoreError::Internal(e.to_string()))?;
  51. let res = sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING")
  52. .bind(&tid_hex)
  53. .bind(&transfer_json)
  54. .bind(&receipt_json)
  55. .bind(record.created_at)
  56. .bind(record.envelope.book().0)
  57. .execute(&mut *tx)
  58. .await
  59. .map_err(|e| StoreError::Internal(e.to_string()))?;
  60. let inserted = res.rows_affected();
  61. // Index every involved account (caller supplies the set; storage does no
  62. // computation). Idempotent so a replay is harmless.
  63. for account in involved {
  64. sqlx::query("INSERT INTO transfer_accounts (transfer_id, account_id, subaccount) VALUES ($1, $2, $3) ON CONFLICT (transfer_id, account_id, subaccount) DO NOTHING")
  65. .bind(&tid_hex)
  66. .bind(account.id)
  67. .bind(account.sub)
  68. .execute(&mut *tx)
  69. .await
  70. .map_err(|e| StoreError::Internal(e.to_string()))?;
  71. }
  72. tx.commit()
  73. .await
  74. .map_err(|e| StoreError::Internal(e.to_string()))?;
  75. Ok(inserted)
  76. }
  77. async fn get_transfers_for_account(
  78. &self,
  79. id: i64,
  80. sub: Option<i64>,
  81. ) -> Result<Vec<EnvelopeRecord>, StoreError> {
  82. // `sub == None` spans every subaccount of `id`; `Some(s)` restricts to
  83. // one. The subaccount is matched only for equality.
  84. let mut sql = String::from(
  85. "SELECT t.id, t.transfer, t.receipt, t.created_at FROM transfers t INNER JOIN transfer_accounts ta ON t.id = ta.transfer_id WHERE ta.account_id = $1",
  86. );
  87. if sub.is_some() {
  88. sql.push_str(" AND ta.subaccount = $2");
  89. }
  90. sql.push_str(" ORDER BY t.created_at");
  91. let mut q = sqlx::query(&sql).bind(id);
  92. if let Some(s) = sub {
  93. q = q.bind(s);
  94. }
  95. let rows = q
  96. .fetch_all(&self.pool)
  97. .await
  98. .map_err(|e| StoreError::Internal(e.to_string()))?;
  99. let mut result = Vec::with_capacity(rows.len());
  100. for row in &rows {
  101. let transfer_json: String = row
  102. .try_get("transfer")
  103. .map_err(|e| StoreError::Internal(e.to_string()))?;
  104. let receipt_json: String = row
  105. .try_get("receipt")
  106. .map_err(|e| StoreError::Internal(e.to_string()))?;
  107. let created_at: i64 = row
  108. .try_get("created_at")
  109. .map_err(|e| StoreError::Internal(e.to_string()))?;
  110. result.push(EnvelopeRecord {
  111. envelope: deserialize_json(&transfer_json)?,
  112. receipt: deserialize_json(&receipt_json)?,
  113. created_at,
  114. });
  115. }
  116. Ok(result)
  117. }
  118. async fn query_transfers(
  119. &self,
  120. query: &TransferQuery,
  121. ) -> Result<Page<EnvelopeRecord>, StoreError> {
  122. // Push every predicate into SQL so the database returns only the
  123. // requested page, not the whole table (or the account's whole history).
  124. // This is what bounds the `balance()` tail scan by the watermark
  125. // (ADR-0019): `fold_tail` passes `from_ts = Some(watermark + 1)`, and
  126. // that lower bound now reaches the DB instead of being applied in Rust
  127. // after loading everything. Every bound is an `i64`, so they collect into
  128. // one ordered bind list. The account join is only added when an account
  129. // is requested (subaccount narrows within it).
  130. let from_clause = if query.account.is_some() {
  131. "FROM transfers t INNER JOIN transfer_accounts ta ON t.id = ta.transfer_id"
  132. } else {
  133. "FROM transfers t"
  134. };
  135. let mut conds: Vec<String> = Vec::new();
  136. let mut binds: Vec<i64> = Vec::new();
  137. let mut p = 1u32;
  138. if let Some(account) = query.account {
  139. conds.push(format!("ta.account_id = ${p}"));
  140. binds.push(account);
  141. p += 1;
  142. if let Some(sub) = query.sub {
  143. conds.push(format!("ta.subaccount = ${p}"));
  144. binds.push(sub);
  145. p += 1;
  146. }
  147. }
  148. if let Some(from) = query.from_ts {
  149. conds.push(format!("t.created_at >= ${p}"));
  150. binds.push(from);
  151. p += 1;
  152. }
  153. if let Some(to) = query.to_ts {
  154. conds.push(format!("t.created_at < ${p}"));
  155. binds.push(to);
  156. p += 1;
  157. }
  158. if let Some(book) = query.book {
  159. conds.push(format!("t.book = ${p}"));
  160. binds.push(book.0);
  161. }
  162. let where_sql = if conds.is_empty() {
  163. String::new()
  164. } else {
  165. format!(" WHERE {}", conds.join(" AND "))
  166. };
  167. let count_sql = format!("SELECT COUNT(*) as cnt {from_clause}{where_sql}");
  168. let mut count_q = sqlx::query(&count_sql);
  169. for b in &binds {
  170. count_q = count_q.bind(*b);
  171. }
  172. let total: i64 = count_q
  173. .fetch_one(&self.pool)
  174. .await
  175. .map_err(|e| StoreError::Internal(e.to_string()))?
  176. .try_get("cnt")
  177. .map_err(|e| StoreError::Internal(e.to_string()))?;
  178. let (offset, limit) = kuatia_storage::query::window(query.offset, query.limit);
  179. let data_sql = format!(
  180. "SELECT t.transfer, t.receipt, t.created_at {from_clause}{where_sql} \
  181. ORDER BY t.created_at LIMIT {limit} OFFSET {offset}"
  182. );
  183. let mut data_q = sqlx::query(&data_sql);
  184. for b in &binds {
  185. data_q = data_q.bind(*b);
  186. }
  187. let rows = data_q
  188. .fetch_all(&self.pool)
  189. .await
  190. .map_err(|e| StoreError::Internal(e.to_string()))?;
  191. let mut items = Vec::with_capacity(rows.len());
  192. for row in &rows {
  193. let transfer_json: String = row
  194. .try_get("transfer")
  195. .map_err(|e| StoreError::Internal(e.to_string()))?;
  196. let receipt_json: String = row
  197. .try_get("receipt")
  198. .map_err(|e| StoreError::Internal(e.to_string()))?;
  199. let created_at: i64 = row
  200. .try_get("created_at")
  201. .map_err(|e| StoreError::Internal(e.to_string()))?;
  202. items.push(EnvelopeRecord {
  203. envelope: deserialize_json(&transfer_json)?,
  204. receipt: deserialize_json(&receipt_json)?,
  205. created_at,
  206. });
  207. }
  208. Ok(Page {
  209. items,
  210. total: total as u64,
  211. })
  212. }
  213. }