adk_payments/wallet/rail.rs
1//! Payment rails: how money reaches a payee (spec 3.5 §7.14).
2//!
3//! | Rail | Name | Funding | For |
4//! |------|------|---------|-----|
5//! | [`Ap2Rail`](super::Ap2Rail) (`ap2`) | `ap2` | the wallet's provider | purchases under AP2 mandates |
6//! | [`UseBasedRail`](super::UseBasedRail) | `use_based` | the wallet's provider | metered APIs and model tokens, answering `402 Payment Required` challenges |
7//! | [`ProviderBillingRail`] | `provider_billing:{provider}` | the owner's account at the provider | hosting, registrars and other services that bill the owner, within caps |
8//!
9//! None is the default: a mandate names its rail, and the wallet holds the adapters the
10//! owner configured.
11
12use std::sync::{Arc, Mutex};
13
14use adk_core::{Clock, Result, SystemClock};
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use serde_json::Value;
19
20use super::error::{WALLET_RAIL_DATA_MISMATCH_CODE, refused};
21use super::policy::{Payee, RailRef, SpendCategory};
22use super::provider::{Debit, StatementEntry, StatementKind};
23
24/// Where a rail's money comes from.
25///
26/// # Example
27///
28/// ```
29/// use adk_payments::wallet::RailFunding;
30///
31/// assert_ne!(RailFunding::Wallet, RailFunding::ProviderBilling);
32/// ```
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum RailFunding {
37 /// The wallet debits its provider before the rail pays, and voids the debit when the
38 /// rail fails.
39 Wallet,
40 /// The payee bills the owner's own account with it; the wallet authorises the charge
41 /// within the cap and reconciles against the provider's invoice.
42 ProviderBilling,
43}
44
45/// One payment a rail executes, after the wallet's policy allowed it and, for a
46/// wallet-funded rail, the provider debited the funds.
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct RailPayment {
50 /// The wallet's payment id.
51 pub payment_id: String,
52 /// The category it is spent in.
53 pub category: SpendCategory,
54 /// Who receives it.
55 pub payee: Payee,
56 /// Amount in minor units of `currency`.
57 pub amount: u64,
58 /// ISO 4217 currency code.
59 pub currency: String,
60 /// What it is for.
61 pub description: String,
62 /// The rail's own data: an AP2 cart mandate, a use-based challenge.
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub rail_data: Option<Value>,
65 /// The provider's debit, for a wallet-funded rail.
66 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub debit: Option<Debit>,
68}
69
70/// What a rail reports once a payment settled.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72#[serde(rename_all = "camelCase")]
73pub struct RailSettlement {
74 /// The payee's or rail's reference for the settled payment.
75 pub reference: String,
76 /// What settled, in minor units.
77 pub amount: u64,
78 /// When it settled.
79 pub settled_at: DateTime<Utc>,
80 /// What the caller presents to the payee or keeps as evidence: a use-based payment
81 /// header, an AP2 payment receipt.
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub proof: Option<Value>,
84}
85
86/// How money reaches a payee (spec 3.5 §7.14).
87///
88/// The wallet calls [`check`](Self::check) before any money moves, so rail data that does
89/// not describe the payment the policy allowed — another merchant, another amount — is
90/// refused; then [`execute`](Self::execute) once the policy, the cap and, for a
91/// wallet-funded rail, the provider's debit allow it.
92///
93/// [`conformance::payment_rail_conformance`](super::conformance::payment_rail_conformance)
94/// checks an implementation.
95#[async_trait]
96pub trait PaymentRail: Send + Sync {
97 /// The rail's name, as mandates name it.
98 fn rail(&self) -> RailRef;
99
100 /// Where the rail's money comes from.
101 fn funding(&self) -> RailFunding {
102 RailFunding::Wallet
103 }
104
105 /// Refuses a payment whose rail data does not describe it.
106 ///
107 /// # Errors
108 ///
109 /// Returns `wallet.rail_data_mismatch` naming the disagreement.
110 fn check(&self, payment: &RailPayment) -> Result<()> {
111 let _ = payment;
112 Ok(())
113 }
114
115 /// Pays `payment`.
116 ///
117 /// # Errors
118 ///
119 /// Returns the rail's error when the payment did not settle; for a wallet-funded rail
120 /// the wallet then voids the debit.
121 async fn execute(&self, payment: &RailPayment) -> Result<RailSettlement>;
122
123 /// The rail's own statement for `[from, to)`, for rails whose money does not pass
124 /// through the wallet's provider; `None` for the others.
125 ///
126 /// # Errors
127 ///
128 /// Returns the rail's error when it cannot answer.
129 async fn statement(
130 &self,
131 from: DateTime<Utc>,
132 to: DateTime<Utc>,
133 ) -> Result<Option<Vec<StatementEntry>>> {
134 let _ = (from, to);
135 Ok(None)
136 }
137}
138
139/// The owner's account at a provider that bills it directly: a host, a registrar, a model
140/// provider (spec 3.5 §7.14).
141///
142/// The adapter records each charge the wallet allowed, so the provider bills it to the
143/// owner, and reads the provider's invoice for reconciliation. It has no method to add a
144/// payment method or change the account: those are the owner's acts.
145#[async_trait]
146pub trait BillingAccount: Send + Sync {
147 /// The provider's name; payments through its rail go to the payee with this id.
148 fn provider(&self) -> &str;
149
150 /// Records a charge the provider bills to the owner's account, returning the
151 /// provider's reference for it.
152 ///
153 /// # Errors
154 ///
155 /// Returns the provider's error when it refuses the charge.
156 async fn charge(&self, payment: &RailPayment) -> Result<String>;
157
158 /// The provider's invoice lines in `[from, to)`.
159 ///
160 /// # Errors
161 ///
162 /// Returns the provider's error when it cannot answer.
163 async fn invoice(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<StatementEntry>>;
164}
165
166/// Provider billing under the owner's accounts within caps (spec 3.5 §7.14).
167///
168/// Named `provider_billing:{provider}`, so a wallet holds one per provider. A payment to a
169/// payee other than the provider is refused.
170///
171/// # Example
172///
173/// ```
174/// use std::sync::Arc;
175/// use adk_payments::wallet::{InMemoryBillingAccount, PaymentRail, ProviderBillingRail, RailRef};
176///
177/// let rail = ProviderBillingRail::new(Arc::new(InMemoryBillingAccount::new("hostco", "USD")));
178/// assert_eq!(rail.rail(), RailRef::provider_billing("hostco"));
179/// ```
180pub struct ProviderBillingRail {
181 account: Arc<dyn BillingAccount>,
182}
183
184impl ProviderBillingRail {
185 /// A rail billing `account`.
186 pub fn new(account: Arc<dyn BillingAccount>) -> Self {
187 Self { account }
188 }
189}
190
191#[async_trait]
192impl PaymentRail for ProviderBillingRail {
193 fn rail(&self) -> RailRef {
194 RailRef::provider_billing(self.account.provider())
195 }
196
197 fn funding(&self) -> RailFunding {
198 RailFunding::ProviderBilling
199 }
200
201 fn check(&self, payment: &RailPayment) -> Result<()> {
202 if payment.payee.id != self.account.provider() {
203 return Err(refused(
204 WALLET_RAIL_DATA_MISMATCH_CODE,
205 format!(
206 "the {} billing rail bills only {}, not payee {}",
207 self.account.provider(),
208 self.account.provider(),
209 payment.payee.id
210 ),
211 ));
212 }
213 Ok(())
214 }
215
216 async fn execute(&self, payment: &RailPayment) -> Result<RailSettlement> {
217 let reference = self.account.charge(payment).await?;
218 Ok(RailSettlement {
219 reference,
220 amount: payment.amount,
221 settled_at: Utc::now(),
222 proof: None,
223 })
224 }
225
226 async fn statement(
227 &self,
228 from: DateTime<Utc>,
229 to: DateTime<Utc>,
230 ) -> Result<Option<Vec<StatementEntry>>> {
231 Ok(Some(self.account.invoice(from, to).await?))
232 }
233}
234
235/// A [`BillingAccount`] kept in memory, so tests are hermetic.
236///
237/// [`push_invoice_line`](Self::push_invoice_line) stands for a charge on the provider's
238/// invoice the wallet did not make.
239#[derive(Debug, Clone)]
240pub struct InMemoryBillingAccount {
241 provider: String,
242 currency: String,
243 lines: Arc<Mutex<Vec<StatementEntry>>>,
244 clock: Arc<dyn Clock>,
245}
246
247impl InMemoryBillingAccount {
248 /// The owner's account at `provider`, billed in `currency`.
249 pub fn new(provider: &str, currency: &str) -> Self {
250 Self {
251 provider: provider.to_string(),
252 currency: currency.to_ascii_uppercase(),
253 lines: Arc::new(Mutex::new(Vec::new())),
254 clock: Arc::new(SystemClock),
255 }
256 }
257
258 /// Sets the clock that stamps invoice lines.
259 #[must_use]
260 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
261 self.clock = clock;
262 self
263 }
264
265 /// Adds an invoice line the wallet did not make.
266 pub fn push_invoice_line(&self, line: StatementEntry) {
267 self.lines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(line);
268 }
269
270 /// Every invoice line so far, for tests.
271 pub fn lines(&self) -> Vec<StatementEntry> {
272 self.lines.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
273 }
274}
275
276#[async_trait]
277impl BillingAccount for InMemoryBillingAccount {
278 fn provider(&self) -> &str {
279 &self.provider
280 }
281
282 async fn charge(&self, payment: &RailPayment) -> Result<String> {
283 let mut lines = self.lines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
284 if let Some(line) =
285 lines.iter().find(|line| line.reference.as_deref() == Some(&payment.payment_id))
286 {
287 return Ok(line.id.clone());
288 }
289 let id = format!("{}-charge-{}", self.provider, lines.len() + 1);
290 lines.push(StatementEntry {
291 id: id.clone(),
292 reference: Some(payment.payment_id.clone()),
293 kind: StatementKind::Debit,
294 amount: payment.amount,
295 currency: self.currency.clone(),
296 payee: Some(self.provider.clone()),
297 at: self.clock.now(),
298 });
299 Ok(id)
300 }
301
302 async fn invoice(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<StatementEntry>> {
303 let lines = self.lines.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
304 Ok(lines.iter().filter(|line| line.at >= from && line.at < to).cloned().collect())
305 }
306}