Skip to main content

adk_payments/wallet/
store.rs

1//! The wallet's journal: payments, held payments and paused categories
2//! (spec 3.5 §7.14, §9.3).
3
4use std::collections::{BTreeMap, HashMap};
5use std::sync::Arc;
6
7use adk_core::Result;
8use adk_core::principal::SubjectRef;
9use async_trait::async_trait;
10use chrono::{DateTime, Utc};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use tokio::sync::RwLock;
14
15use super::policy::{Payee, RailRef, SpendCategory};
16use super::provider::Debit;
17use super::rail::RailSettlement;
18
19/// Where a payment stands.
20///
21/// # Example
22///
23/// ```
24/// use adk_payments::wallet::PaymentState;
25///
26/// assert!(PaymentState::Settled.is_spent());
27/// assert!(!PaymentState::Held.is_spent());
28/// ```
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31#[non_exhaustive]
32pub enum PaymentState {
33    /// Waiting for the owner's decision.
34    Held,
35    /// Allowed and being paid.
36    Executing,
37    /// Paid.
38    Settled,
39    /// The owner refused it.
40    Rejected,
41    /// The rail or provider failed; nothing was paid unless `debit_outstanding` says so.
42    Failed,
43}
44
45impl PaymentState {
46    /// Whether the payment's money is spent.
47    pub fn is_spent(self) -> bool {
48        matches!(self, Self::Settled)
49    }
50
51    /// Whether the payment can change no further.
52    pub fn is_final(self) -> bool {
53        matches!(self, Self::Settled | Self::Rejected | Self::Failed)
54    }
55}
56
57/// Why a payment was held for the owner (spec 3.5 §7.14).
58///
59/// # Example
60///
61/// ```
62/// use adk_payments::wallet::HoldReason;
63///
64/// let reason = HoldReason::OverCategoryCap { cap: 10_000, spent: 9_000, requested: 2_000 };
65/// assert!(reason.to_string().contains("cap"));
66/// ```
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(tag = "reason", rename_all = "snake_case")]
69#[non_exhaustive]
70pub enum HoldReason {
71    /// The payment is larger than the mandate's per-payment limit.
72    OverPaymentLimit {
73        /// The mandate's `max_per_payment`.
74        max_per_payment: u64,
75        /// The payment's amount.
76        requested: u64,
77    },
78    /// The payment would take the category past its cap for the period.
79    OverCategoryCap {
80        /// The mandate's `cap_per_period`.
81        cap: u64,
82        /// What the category has spent or is spending this period.
83        spent: u64,
84        /// The payment's amount.
85        requested: u64,
86    },
87}
88
89impl std::fmt::Display for HoldReason {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match self {
92            Self::OverPaymentLimit { max_per_payment, requested } => write!(
93                f,
94                "{requested} is over the mandate's limit of {max_per_payment} per payment"
95            ),
96            Self::OverCategoryCap { cap, spent, requested } => write!(
97                f,
98                "{requested} on top of {spent} spent this period is over the category cap of {cap}"
99            ),
100        }
101    }
102}
103
104/// Who decided a held payment, and how (spec 3.5 §7.14, A-I16).
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "camelCase")]
107pub struct OwnerDecisionRecord {
108    /// The person who decided, or the subject the run's approval was given for.
109    pub decided_by: SubjectRef,
110    /// Whether the payment was approved.
111    pub approved: bool,
112    /// Where the decision came from: `owner` for a decision through the wallet's API,
113    /// `governed_path` for a confirmation the run's approval sources gave.
114    pub source: String,
115    /// What the decider said.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub message: Option<String>,
118    /// When.
119    pub decided_at: DateTime<Utc>,
120}
121
122/// One payment in the wallet's journal.
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
124#[serde(rename_all = "camelCase")]
125pub struct PaymentRecord {
126    /// The payment's id; providers and rails see it as the payment reference.
127    pub id: String,
128    /// The wallet it belongs to.
129    pub wallet: String,
130    /// The caller's idempotency key: one payment per key.
131    pub key: String,
132    /// Digest of what was asked, so a reused key with another payment is refused.
133    pub request_digest: String,
134    /// The category it is spent in.
135    pub category: SpendCategory,
136    /// Who receives it.
137    pub payee: Payee,
138    /// Amount in minor units.
139    pub amount: u64,
140    /// ISO 4217 currency code.
141    pub currency: String,
142    /// The rail it goes through.
143    pub rail: RailRef,
144    /// What it is for.
145    pub description: String,
146    /// The rail's data, kept so a held payment can be paid once approved.
147    #[serde(default, skip_serializing_if = "Option::is_none")]
148    pub rail_data: Option<Value>,
149    /// Where it stands.
150    pub state: PaymentState,
151    /// Why it was held, when it was.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub hold: Option<HoldReason>,
154    /// The agent that asked for it.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub agent: Option<String>,
157    /// The owner's decision on a held payment.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub decision: Option<OwnerDecisionRecord>,
160    /// The provider's debit, for a wallet-funded rail.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub debit: Option<Debit>,
163    /// Whether a debit is still outstanding on a failed payment, for reconciliation.
164    #[serde(default)]
165    pub debit_outstanding: bool,
166    /// What the rail reported once it settled.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub settlement: Option<RailSettlement>,
169    /// Why it failed.
170    #[serde(default, skip_serializing_if = "Option::is_none")]
171    pub error: Option<String>,
172    /// When it was asked for.
173    pub created_at: DateTime<Utc>,
174    /// When it settled.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub settled_at: Option<DateTime<Utc>>,
177}
178
179impl PaymentRecord {
180    /// Whether an owner approved it beyond the mandate.
181    pub fn owner_approved(&self) -> bool {
182        self.decision.as_ref().is_some_and(|decision| decision.approved)
183    }
184
185    /// The proof a use-based payment carries for the metered request's retry.
186    pub fn use_based_proof(&self) -> Option<super::PaymentProof> {
187        let proof = self.settlement.as_ref()?.proof.clone()?;
188        serde_json::from_value(proof).ok()
189    }
190}
191
192/// Which payments to list.
193///
194/// # Example
195///
196/// ```
197/// use adk_payments::wallet::{PaymentQuery, PaymentState, SpendCategory};
198///
199/// let held = PaymentQuery::new("site-1").state(PaymentState::Held).category(SpendCategory::Advertising);
200/// # let _ = held;
201/// ```
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct PaymentQuery {
204    /// The wallet.
205    pub wallet: String,
206    /// Only this category.
207    pub category: Option<SpendCategory>,
208    /// Only this state.
209    pub state: Option<PaymentState>,
210    /// Only payments settled, or for unsettled ones asked for, at or after this time.
211    pub from: Option<DateTime<Utc>>,
212    /// Only payments settled, or asked for, before this time.
213    pub to: Option<DateTime<Utc>>,
214}
215
216impl PaymentQuery {
217    /// Every payment of `wallet`.
218    pub fn new(wallet: impl Into<String>) -> Self {
219        Self { wallet: wallet.into(), category: None, state: None, from: None, to: None }
220    }
221
222    /// Only payments in `category`.
223    #[must_use]
224    pub fn category(mut self, category: SpendCategory) -> Self {
225        self.category = Some(category);
226        self
227    }
228
229    /// Only payments in `state`.
230    #[must_use]
231    pub fn state(mut self, state: PaymentState) -> Self {
232        self.state = Some(state);
233        self
234    }
235
236    /// Only payments in `[from, to)`, by settlement time, else by when they were asked for.
237    #[must_use]
238    pub fn between(mut self, from: DateTime<Utc>, to: DateTime<Utc>) -> Self {
239        self.from = Some(from);
240        self.to = Some(to);
241        self
242    }
243
244    /// Whether `record` matches.
245    pub fn matches(&self, record: &PaymentRecord) -> bool {
246        let at = record.settled_at.unwrap_or(record.created_at);
247        record.wallet == self.wallet
248            && self.category.is_none_or(|category| record.category == category)
249            && self.state.is_none_or(|state| record.state == state)
250            && self.from.is_none_or(|from| at >= from)
251            && self.to.is_none_or(|to| at < to)
252    }
253}
254
255/// A category paused by an anomaly alarm until an owner resumes it (spec 3.5 §7.14).
256#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
257#[serde(rename_all = "camelCase")]
258pub struct CategoryPause {
259    /// The wallet.
260    pub wallet: String,
261    /// The paused category.
262    pub category: SpendCategory,
263    /// Why.
264    pub reason: String,
265    /// When.
266    pub paused_at: DateTime<Utc>,
267}
268
269/// Where a wallet keeps its journal and pauses.
270///
271/// Every query is scoped by wallet id, so one store serves several sites without one
272/// seeing another's payments (A-I22).
273/// [`conformance::wallet_store_conformance`](super::conformance::wallet_store_conformance)
274/// checks an implementation.
275#[async_trait]
276pub trait WalletStore: Send + Sync {
277    /// Stores `record` unless its wallet already has a payment with its key; returns the
278    /// stored record and whether it was inserted.
279    ///
280    /// # Errors
281    ///
282    /// Returns the store's error.
283    async fn insert(&self, record: PaymentRecord) -> Result<(PaymentRecord, bool)>;
284
285    /// Replaces the stored payment with `record`'s id.
286    ///
287    /// # Errors
288    ///
289    /// Returns `wallet.payment_not_found` when there is none, or the store's error.
290    async fn update(&self, record: &PaymentRecord) -> Result<()>;
291
292    /// Replaces the stored payment with `record`'s id only while it is in `expected` state,
293    /// as one compare-and-set (spec 3.5 §7.14, A-I16): returns `true` when it replaced the
294    /// payment and `false` when the stored payment has moved to another state.
295    ///
296    /// Wallets decide a held payment through it, so of two decisions racing on one payment,
297    /// from one instance or several sharing the store, exactly one proceeds.
298    ///
299    /// The provided implementation reads the payment and then updates it, which is atomic
300    /// only while one wallet instance uses the store; a store shared by several instances
301    /// overrides it with one atomic step, as the built-in stores do.
302    ///
303    /// # Example
304    ///
305    /// ```
306    /// use adk_payments::wallet::{InMemoryWalletStore, PaymentState, WalletStore};
307    ///
308    /// # async fn decide(store: &InMemoryWalletStore, mut held: adk_payments::wallet::PaymentRecord) -> adk_core::Result<()> {
309    /// held.state = PaymentState::Executing;
310    /// if !store.update_if(&held, PaymentState::Held).await? {
311    ///     // Another decision got there first.
312    /// }
313    /// # Ok(())
314    /// # }
315    /// ```
316    ///
317    /// # Errors
318    ///
319    /// Returns `wallet.payment_not_found` when there is none, or the store's error.
320    async fn update_if(&self, record: &PaymentRecord, expected: PaymentState) -> Result<bool> {
321        let stored = self.get(&record.wallet, &record.id).await?.ok_or_else(|| {
322            super::error::not_found(
323                super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
324                format!("wallet {} has no payment {}", record.wallet, record.id),
325            )
326        })?;
327        if stored.state != expected {
328            return Ok(false);
329        }
330        self.update(record).await?;
331        Ok(true)
332    }
333
334    /// The payment `id` of `wallet`.
335    ///
336    /// # Errors
337    ///
338    /// Returns the store's error.
339    async fn get(&self, wallet: &str, id: &str) -> Result<Option<PaymentRecord>>;
340
341    /// The payment of `wallet` with idempotency key `key`.
342    ///
343    /// # Errors
344    ///
345    /// Returns the store's error.
346    async fn by_key(&self, wallet: &str, key: &str) -> Result<Option<PaymentRecord>>;
347
348    /// The payments `query` matches, oldest first.
349    ///
350    /// # Errors
351    ///
352    /// Returns the store's error.
353    async fn list(&self, query: &PaymentQuery) -> Result<Vec<PaymentRecord>>;
354
355    /// Pauses a category; pausing a paused category keeps the first pause.
356    ///
357    /// # Errors
358    ///
359    /// Returns the store's error.
360    async fn pause(&self, pause: CategoryPause) -> Result<()>;
361
362    /// Lifts the pause of `category`, returning it, or `None` when it was not paused.
363    ///
364    /// # Errors
365    ///
366    /// Returns the store's error.
367    async fn resume(&self, wallet: &str, category: SpendCategory) -> Result<Option<CategoryPause>>;
368
369    /// The paused categories of `wallet`.
370    ///
371    /// # Errors
372    ///
373    /// Returns the store's error.
374    async fn pauses(&self, wallet: &str) -> Result<Vec<CategoryPause>>;
375}
376
377#[derive(Debug, Default)]
378struct StoreState {
379    payments: Vec<PaymentRecord>,
380    by_id: HashMap<(String, String), usize>,
381    by_key: HashMap<(String, String), usize>,
382    pauses: BTreeMap<(String, SpendCategory), CategoryPause>,
383}
384
385/// A process-local [`WalletStore`], for tests and single-process deployments.
386///
387/// # Example
388///
389/// ```
390/// use adk_payments::wallet::InMemoryWalletStore;
391///
392/// let store = InMemoryWalletStore::new();
393/// # let _ = store;
394/// ```
395#[derive(Debug, Clone, Default)]
396pub struct InMemoryWalletStore {
397    state: Arc<RwLock<StoreState>>,
398}
399
400impl InMemoryWalletStore {
401    /// An empty store.
402    pub fn new() -> Self {
403        Self::default()
404    }
405}
406
407#[async_trait]
408impl WalletStore for InMemoryWalletStore {
409    async fn insert(&self, record: PaymentRecord) -> Result<(PaymentRecord, bool)> {
410        let mut state = self.state.write().await;
411        let key = (record.wallet.clone(), record.key.clone());
412        if let Some(index) = state.by_key.get(&key) {
413            return Ok((state.payments[*index].clone(), false));
414        }
415        let index = state.payments.len();
416        state.by_id.insert((record.wallet.clone(), record.id.clone()), index);
417        state.by_key.insert(key, index);
418        state.payments.push(record.clone());
419        Ok((record, true))
420    }
421
422    async fn update(&self, record: &PaymentRecord) -> Result<()> {
423        let mut state = self.state.write().await;
424        let index =
425            *state.by_id.get(&(record.wallet.clone(), record.id.clone())).ok_or_else(|| {
426                super::error::not_found(
427                    super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
428                    format!("wallet {} has no payment {}", record.wallet, record.id),
429                )
430            })?;
431        state.payments[index] = record.clone();
432        Ok(())
433    }
434
435    async fn update_if(&self, record: &PaymentRecord, expected: PaymentState) -> Result<bool> {
436        let mut state = self.state.write().await;
437        let index =
438            *state.by_id.get(&(record.wallet.clone(), record.id.clone())).ok_or_else(|| {
439                super::error::not_found(
440                    super::error::WALLET_PAYMENT_NOT_FOUND_CODE,
441                    format!("wallet {} has no payment {}", record.wallet, record.id),
442                )
443            })?;
444        if state.payments[index].state != expected {
445            return Ok(false);
446        }
447        state.payments[index] = record.clone();
448        Ok(true)
449    }
450
451    async fn get(&self, wallet: &str, id: &str) -> Result<Option<PaymentRecord>> {
452        let state = self.state.read().await;
453        Ok(state
454            .by_id
455            .get(&(wallet.to_string(), id.to_string()))
456            .map(|index| state.payments[*index].clone()))
457    }
458
459    async fn by_key(&self, wallet: &str, key: &str) -> Result<Option<PaymentRecord>> {
460        let state = self.state.read().await;
461        Ok(state
462            .by_key
463            .get(&(wallet.to_string(), key.to_string()))
464            .map(|index| state.payments[*index].clone()))
465    }
466
467    async fn list(&self, query: &PaymentQuery) -> Result<Vec<PaymentRecord>> {
468        let state = self.state.read().await;
469        Ok(state.payments.iter().filter(|record| query.matches(record)).cloned().collect())
470    }
471
472    async fn pause(&self, pause: CategoryPause) -> Result<()> {
473        let mut state = self.state.write().await;
474        state.pauses.entry((pause.wallet.clone(), pause.category)).or_insert(pause);
475        Ok(())
476    }
477
478    async fn resume(&self, wallet: &str, category: SpendCategory) -> Result<Option<CategoryPause>> {
479        Ok(self.state.write().await.pauses.remove(&(wallet.to_string(), category)))
480    }
481
482    async fn pauses(&self, wallet: &str) -> Result<Vec<CategoryPause>> {
483        let state = self.state.read().await;
484        Ok(state
485            .pauses
486            .iter()
487            .filter(|((owner, _), _)| owner == wallet)
488            .map(|(_, pause)| pause.clone())
489            .collect())
490    }
491}