|
|
@@ -1,10 +1,10 @@
|
|
|
//! [`PostingStore`]: the immutable posting record plus one `live_postings` hot
|
|
|
-//! table whose `reservation` column derives each posting's lifecycle state.
|
|
|
+//! table whose membership is each posting's state.
|
|
|
//!
|
|
|
-//! A posting is in `live_postings` while it is spendable or reserved:
|
|
|
-//! `reservation IS NULL` = Active, `reservation = rid` = Reserved by that saga.
|
|
|
-//! Once consumed the row is deleted, leaving the posting only in the immutable
|
|
|
-//! `postings` table (= Spent). See ADR-0022 (merged hot index) and ADR-0016.
|
|
|
+//! A posting is in `live_postings` while it is spendable. Once consumed the row
|
|
|
+//! is deleted, leaving the posting only in the immutable `postings` table, so
|
|
|
+//! the two tables never disagree about what is spent. See ADR-0022 (merged hot
|
|
|
+//! index) and ADR-0016.
|
|
|
|
|
|
use std::collections::HashMap;
|
|
|
|
|
|
@@ -18,7 +18,7 @@ use kuatia_types::*;
|
|
|
|
|
|
use crate::SqlStore;
|
|
|
use crate::dialect::Dialect;
|
|
|
-use crate::row::{bind_money, envelope_id_to_hex, row_to_cent, row_to_posting};
|
|
|
+use crate::row::{row_to_cent, row_to_posting, transfer_id_to_hex};
|
|
|
|
|
|
/// The live-balance aggregate, shared by [`PostingStore::live_balance`] and the
|
|
|
/// in-transaction overdraft floor in `commit`, so both read the balance the same
|
|
|
@@ -32,16 +32,12 @@ pub(crate) fn live_balance_sql(dialect: Dialect) -> String {
|
|
|
)
|
|
|
}
|
|
|
|
|
|
-/// The `(source_table, state_predicate)` a posting read of the given filter
|
|
|
-/// targets. Live/Active/Reserved read the single `live_postings` hot table,
|
|
|
-/// narrowed by the `reservation` column; `All` reads the immutable record. No
|
|
|
-/// UNION: the live set is one table.
|
|
|
-fn filter_source(filter: PostingFilter) -> (&'static str, &'static str) {
|
|
|
+/// The source table a posting read of the given filter targets. No UNION and no
|
|
|
+/// predicate: the live set is exactly one table's rows.
|
|
|
+fn filter_source(filter: PostingFilter) -> &'static str {
|
|
|
match filter {
|
|
|
- PostingFilter::Active => ("live_postings", " AND reservation IS NULL"),
|
|
|
- PostingFilter::Reserved => ("live_postings", " AND reservation IS NOT NULL"),
|
|
|
- PostingFilter::Live => ("live_postings", ""),
|
|
|
- PostingFilter::All => ("postings", ""),
|
|
|
+ PostingFilter::Live => "live_postings",
|
|
|
+ PostingFilter::All => "postings",
|
|
|
}
|
|
|
}
|
|
|
|
|
|
@@ -93,7 +89,7 @@ impl PostingStore for SqlStore {
|
|
|
let mut q = sqlx::query(&sql);
|
|
|
for id in chunk {
|
|
|
q = q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
+ .bind(transfer_id_to_hex(&id.transfer))
|
|
|
.bind(id.index as i16);
|
|
|
}
|
|
|
let rows = q
|
|
|
@@ -105,7 +101,7 @@ impl PostingStore for SqlStore {
|
|
|
for row in &rows {
|
|
|
let posting = row_to_posting(self.dialect, row)?;
|
|
|
let key = (
|
|
|
- envelope_id_to_hex(&posting.id.transfer),
|
|
|
+ transfer_id_to_hex(&posting.id.transfer),
|
|
|
posting.id.index as i16,
|
|
|
);
|
|
|
found.insert(key, posting);
|
|
|
@@ -116,7 +112,7 @@ impl PostingStore for SqlStore {
|
|
|
// (matching the per-id lookup's `NotFound` semantics).
|
|
|
let mut result = Vec::with_capacity(ids.len());
|
|
|
for id in ids {
|
|
|
- let key = (envelope_id_to_hex(&id.transfer), id.index as i16);
|
|
|
+ let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
|
|
|
let posting = found
|
|
|
.get(&key)
|
|
|
.ok_or_else(|| StoreError::NotFound(format!("posting {id:?}")))?;
|
|
|
@@ -134,9 +130,8 @@ impl PostingStore for SqlStore {
|
|
|
) -> Result<Vec<Posting>, StoreError> {
|
|
|
// Build the predicate dynamically: `sub == None` spans every subaccount
|
|
|
// of `id`, `Some(s)` restricts to one. The subaccount is compared only
|
|
|
- // for equality, never as a magnitude. The filter picks the source table
|
|
|
- // and, for the live table, the `reservation` state predicate.
|
|
|
- let (source, state) = filter_source(filter);
|
|
|
+ // for equality, never as a magnitude.
|
|
|
+ let source = filter_source(filter);
|
|
|
let mut sql = format!(
|
|
|
"SELECT {} FROM {source} WHERE owner = $1",
|
|
|
self.dialect.posting_columns()
|
|
|
@@ -149,7 +144,6 @@ impl PostingStore for SqlStore {
|
|
|
if asset.is_some() {
|
|
|
sql.push_str(&format!(" AND asset = ${placeholder}"));
|
|
|
}
|
|
|
- sql.push_str(state);
|
|
|
// Deterministic order by the posting primary key, matching
|
|
|
// `query_postings`, so callers (and pagination built on top) see a
|
|
|
// stable sequence.
|
|
|
@@ -188,12 +182,11 @@ impl PostingStore for SqlStore {
|
|
|
return Ok(Vec::new());
|
|
|
}
|
|
|
|
|
|
- // Two set-based queries per chunk (was three, before the hot tables were
|
|
|
- // merged): the live table carries both Active (`reservation IS NULL`) and
|
|
|
- // Reserved (`reservation = rid`) in one row, and `postings` decides Spent
|
|
|
- // vs Missing for ids absent from the live set. Reuses the portable
|
|
|
- // `id_predicate` (an OR of equality pairs; row-value `IN` is not portable
|
|
|
- // across SQLite and PostgreSQL), binding each id as `(hex, idx)`.
|
|
|
+ // Two set-based queries per chunk: membership of the live table decides
|
|
|
+ // Live, and `postings` decides Spent vs Missing for ids absent from it.
|
|
|
+ // Reuses the portable `id_predicate` (an OR of equality pairs; row-value
|
|
|
+ // `IN` is not portable across SQLite and PostgreSQL), binding each id as
|
|
|
+ // `(hex, idx)`.
|
|
|
|
|
|
// Key membership by the same `(hex, idx)` values that were bound, so the
|
|
|
// per-id lookup below matches without decoding transfer ids back.
|
|
|
@@ -207,23 +200,20 @@ impl PostingStore for SqlStore {
|
|
|
Ok((transfer_id, idx))
|
|
|
};
|
|
|
|
|
|
- // `live` maps each present id to its reservation: `None` = Active,
|
|
|
- // `Some(rid)` = Reserved. `present` is every id in the immutable record,
|
|
|
- // used to tell Spent (present, not live) from Missing (absent).
|
|
|
- let mut live: HashMap<(String, i16), Option<i64>> = HashMap::new();
|
|
|
+ // `present` is every id in the immutable record, which is what tells
|
|
|
+ // Spent (present, not live) from Missing (absent).
|
|
|
+ let mut live: std::collections::HashSet<(String, i16)> = std::collections::HashSet::new();
|
|
|
let mut present: std::collections::HashSet<(String, i16)> =
|
|
|
std::collections::HashSet::new();
|
|
|
|
|
|
for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
|
|
|
let predicate = id_predicate(chunk.len(), 1);
|
|
|
|
|
|
- let live_sql = format!(
|
|
|
- "SELECT transfer_id, idx, reservation FROM live_postings WHERE {predicate}"
|
|
|
- );
|
|
|
+ let live_sql = format!("SELECT transfer_id, idx FROM live_postings WHERE {predicate}");
|
|
|
let mut live_q = sqlx::query(&live_sql);
|
|
|
for id in chunk {
|
|
|
live_q = live_q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
+ .bind(transfer_id_to_hex(&id.transfer))
|
|
|
.bind(id.index as i16);
|
|
|
}
|
|
|
let live_rows = live_q
|
|
|
@@ -231,18 +221,14 @@ impl PostingStore for SqlStore {
|
|
|
.await
|
|
|
.map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
for row in &live_rows {
|
|
|
- // `reservation` is nullable: NULL decodes to `None` = Active.
|
|
|
- let rid: Option<i64> = row
|
|
|
- .try_get("reservation")
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- live.insert(row_key(row)?, rid);
|
|
|
+ live.insert(row_key(row)?);
|
|
|
}
|
|
|
|
|
|
let present_sql = format!("SELECT transfer_id, idx FROM postings WHERE {predicate}");
|
|
|
let mut present_q = sqlx::query(&present_sql);
|
|
|
for id in chunk {
|
|
|
present_q = present_q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
+ .bind(transfer_id_to_hex(&id.transfer))
|
|
|
.bind(id.index as i16);
|
|
|
}
|
|
|
let present_rows = present_q
|
|
|
@@ -254,16 +240,17 @@ impl PostingStore for SqlStore {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- // Reconstruct each id's state in input order, preserving the active >
|
|
|
- // reserved > spent > missing precedence of the original probes.
|
|
|
+ // Reconstruct each id's state in input order, live before spent before
|
|
|
+ // missing, so a duplicated id resolves to the same state both times.
|
|
|
let mut out = Vec::with_capacity(ids.len());
|
|
|
for id in ids {
|
|
|
- let key = (envelope_id_to_hex(&id.transfer), id.index as i16);
|
|
|
- out.push(match live.get(&key) {
|
|
|
- Some(None) => PostingState::Active,
|
|
|
- Some(Some(rid)) => PostingState::Reserved(ReservationId::new(*rid)),
|
|
|
- None if present.contains(&key) => PostingState::Spent,
|
|
|
- None => PostingState::Missing,
|
|
|
+ let key = (transfer_id_to_hex(&id.transfer), id.index as i16);
|
|
|
+ out.push(if live.contains(&key) {
|
|
|
+ PostingState::Live
|
|
|
+ } else if present.contains(&key) {
|
|
|
+ PostingState::Spent
|
|
|
+ } else {
|
|
|
+ PostingState::Missing
|
|
|
});
|
|
|
}
|
|
|
Ok(out)
|
|
|
@@ -271,7 +258,7 @@ impl PostingStore for SqlStore {
|
|
|
|
|
|
async fn query_postings(&self, query: &PostingQuery) -> Result<Page<Posting>, StoreError> {
|
|
|
let (where_clause, count_clause) = {
|
|
|
- let (source, state) = filter_source(query.filter);
|
|
|
+ let source = filter_source(query.filter);
|
|
|
let mut w = String::from("WHERE owner = $1");
|
|
|
let mut idx = 2u32;
|
|
|
if query.sub.is_some() {
|
|
|
@@ -281,7 +268,6 @@ impl PostingStore for SqlStore {
|
|
|
if query.asset.is_some() {
|
|
|
w.push_str(&format!(" AND asset = ${idx}"));
|
|
|
}
|
|
|
- w.push_str(state);
|
|
|
let c = format!("SELECT COUNT(*) as cnt FROM {source} {w}");
|
|
|
let (offset, limit) = kuatia_storage::query::window(query.offset, query.limit);
|
|
|
// Order by the posting primary key so pagination is deterministic:
|
|
|
@@ -336,208 +322,4 @@ impl PostingStore for SqlStore {
|
|
|
total: total as u64,
|
|
|
})
|
|
|
}
|
|
|
-
|
|
|
- async fn reserve_postings(
|
|
|
- &self,
|
|
|
- ids: &[PostingId],
|
|
|
- reservation: ReservationId,
|
|
|
- ) -> Result<u64, StoreError> {
|
|
|
- // Dumb instruction over the whole id set: flip each still-Active row's
|
|
|
- // `reservation` from NULL to this saga's id. `WHERE reservation IS NULL`
|
|
|
- // is the atomic single-winner claim: concurrent reserves serialize on the
|
|
|
- // row lock, and the loser's predicate no longer matches, so exactly one
|
|
|
- // wins each contended id. `rows_affected` is the number claimed; an
|
|
|
- // already-reserved or spent id does not match and is not counted.
|
|
|
- if ids.is_empty() {
|
|
|
- return Ok(0);
|
|
|
- }
|
|
|
- let mut tx = self
|
|
|
- .pool
|
|
|
- .begin()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
-
|
|
|
- // Chunked so a large id set stays under the bind-parameter limit; all
|
|
|
- // chunks share one transaction so the whole claim is atomic.
|
|
|
- let mut claimed: u64 = 0;
|
|
|
- for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
|
|
|
- // Reservation is $1; each id pair follows starting at $2.
|
|
|
- let sql = format!(
|
|
|
- "UPDATE live_postings SET reservation = $1 WHERE ({}) AND reservation IS NULL",
|
|
|
- id_predicate(chunk.len(), 2)
|
|
|
- );
|
|
|
- let mut q = sqlx::query(&sql).bind(reservation.0);
|
|
|
- for id in chunk {
|
|
|
- q = q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
- .bind(id.index as i16);
|
|
|
- }
|
|
|
- let res = q
|
|
|
- .execute(&mut *tx)
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- claimed += res.rows_affected();
|
|
|
- }
|
|
|
-
|
|
|
- tx.commit()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- Ok(claimed)
|
|
|
- }
|
|
|
-
|
|
|
- async fn release_postings(
|
|
|
- &self,
|
|
|
- ids: &[PostingId],
|
|
|
- reservation: ReservationId,
|
|
|
- ) -> Result<u64, StoreError> {
|
|
|
- // Dumb instruction over the whole id set: clear the `reservation` of the
|
|
|
- // rows this saga holds, returning them to Active. `rows_affected` is the
|
|
|
- // number released; an id already Active or reserved by another saga does
|
|
|
- // not match `reservation = rid` and is left untouched.
|
|
|
- if ids.is_empty() {
|
|
|
- return Ok(0);
|
|
|
- }
|
|
|
- let mut tx = self
|
|
|
- .pool
|
|
|
- .begin()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
-
|
|
|
- let mut released: u64 = 0;
|
|
|
- for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
|
|
|
- // Reservation is $1; each id pair follows starting at $2.
|
|
|
- let sql = format!(
|
|
|
- "UPDATE live_postings SET reservation = NULL WHERE ({}) AND reservation = $1",
|
|
|
- id_predicate(chunk.len(), 2)
|
|
|
- );
|
|
|
- let mut q = sqlx::query(&sql).bind(reservation.0);
|
|
|
- for id in chunk {
|
|
|
- q = q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
- .bind(id.index as i16);
|
|
|
- }
|
|
|
- let res = q
|
|
|
- .execute(&mut *tx)
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- released += res.rows_affected();
|
|
|
- }
|
|
|
-
|
|
|
- tx.commit()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- Ok(released)
|
|
|
- }
|
|
|
-
|
|
|
- async fn deactivate_postings(
|
|
|
- &self,
|
|
|
- ids: &[PostingId],
|
|
|
- reservation: Option<ReservationId>,
|
|
|
- ) -> Result<u64, StoreError> {
|
|
|
- // Dumb instruction over the whole id set: DELETE the ids from the live
|
|
|
- // table so they become spent (present only in the immutable `postings`).
|
|
|
- // The raw path removes still-Active rows (`reservation IS NULL`); the saga
|
|
|
- // path removes only the rows reserved by `rid`. `rows_affected` is the
|
|
|
- // count; the caller interprets a shortfall. Chunked under one transaction.
|
|
|
- if ids.is_empty() {
|
|
|
- return Ok(0);
|
|
|
- }
|
|
|
- let mut tx = self
|
|
|
- .pool
|
|
|
- .begin()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- let mut removed: u64 = 0;
|
|
|
- for chunk in ids.chunks(MAX_IDS_PER_QUERY) {
|
|
|
- let (sql, rid) = match reservation {
|
|
|
- // Raw path: remove still-Active rows.
|
|
|
- None => (
|
|
|
- format!(
|
|
|
- "DELETE FROM live_postings WHERE ({}) AND reservation IS NULL",
|
|
|
- id_predicate(chunk.len(), 1)
|
|
|
- ),
|
|
|
- None,
|
|
|
- ),
|
|
|
- // Saga path: remove only the rows reserved by `rid`.
|
|
|
- Some(rid) => (
|
|
|
- format!(
|
|
|
- "DELETE FROM live_postings WHERE ({}) AND reservation = $1",
|
|
|
- id_predicate(chunk.len(), 2)
|
|
|
- ),
|
|
|
- Some(rid),
|
|
|
- ),
|
|
|
- };
|
|
|
- let mut q = sqlx::query(&sql);
|
|
|
- if let Some(rid) = rid {
|
|
|
- q = q.bind(rid.0);
|
|
|
- }
|
|
|
- for id in chunk {
|
|
|
- q = q
|
|
|
- .bind(envelope_id_to_hex(&id.transfer))
|
|
|
- .bind(id.index as i16);
|
|
|
- }
|
|
|
- let res = q
|
|
|
- .execute(&mut *tx)
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- removed += res.rows_affected();
|
|
|
- }
|
|
|
- tx.commit()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- Ok(removed)
|
|
|
- }
|
|
|
-
|
|
|
- async fn insert_postings(&self, postings: &[Posting]) -> Result<u64, StoreError> {
|
|
|
- // Dumb instruction: insert each posting into the immutable table and, only
|
|
|
- // when the row was newly inserted, add it to the live table as Active
|
|
|
- // (reservation NULL). Return the count of immutable rows inserted. The
|
|
|
- // newness gate stops a replayed finalize from re-activating a since-spent
|
|
|
- // posting.
|
|
|
- let mut tx = self
|
|
|
- .pool
|
|
|
- .begin()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- let mut inserted: u64 = 0;
|
|
|
- for posting in postings {
|
|
|
- let hex = envelope_id_to_hex(&posting.id.transfer);
|
|
|
- let sql = format!(
|
|
|
- "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ($1, $2, $3, $4, $5, {}) ON CONFLICT (transfer_id, idx) DO NOTHING",
|
|
|
- self.dialect.money_bind(6)
|
|
|
- );
|
|
|
- let q = sqlx::query(&sql)
|
|
|
- .bind(hex.clone())
|
|
|
- .bind(posting.id.index as i16)
|
|
|
- .bind(posting.owner.id)
|
|
|
- .bind(posting.owner.sub)
|
|
|
- .bind(posting.asset.0 as i32);
|
|
|
- let res = bind_money(q, self.dialect, posting.value)
|
|
|
- .execute(&mut *tx)
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- if res.rows_affected() == 1 {
|
|
|
- // Activate a full copy (reservation NULL) so spendable reads never merge.
|
|
|
- let sql = format!(
|
|
|
- "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, $2, $3, $4, $5, {}, NULL) ON CONFLICT (transfer_id, idx) DO NOTHING",
|
|
|
- self.dialect.money_bind(6)
|
|
|
- );
|
|
|
- let q = sqlx::query(&sql)
|
|
|
- .bind(hex)
|
|
|
- .bind(posting.id.index as i16)
|
|
|
- .bind(posting.owner.id)
|
|
|
- .bind(posting.owner.sub)
|
|
|
- .bind(posting.asset.0 as i32);
|
|
|
- bind_money(q, self.dialect, posting.value)
|
|
|
- .execute(&mut *tx)
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- inserted += 1;
|
|
|
- }
|
|
|
- }
|
|
|
- tx.commit()
|
|
|
- .await
|
|
|
- .map_err(|e| StoreError::Internal(e.to_string()))?;
|
|
|
- Ok(inserted)
|
|
|
- }
|
|
|
}
|