Skip to main content

adk_website/edge/
commerce.rs

1//! The edge's commerce, kept durable (spec 3.5 §7.5 "Commerce", §7.9, §7.16 `quote`, `order`,
2//! `booking`, A-I7, A-I25): the quotes the site issued, the orders placed against them and
3//! the calendar slots taken survive a restart, so a buyer's quote keeps its price and an order
4//! is paid once.
5//!
6//! | Part | What it does |
7//! |---|---|
8//! | [`CommerceStore`] | Quotes, orders with a compare-and-set on their status, and bookings that take a slot once |
9//! | [`InMemoryCommerceStore`] | The store in memory, for tests |
10//! | [`SqliteCommerceStore`] | The store in SQLite: a served site's `data/edge.db` |
11//! | [`StoredCalendar`] | The slots of `calendar.json`, booked in a [`CommerceStore`] |
12//! | [`conformance`] | The check every [`CommerceStore`] passes |
13//!
14//! The edge's [`QuoteBook`](super::handlers::QuoteBook) and
15//! [`OrderBook`](super::handlers::OrderBook) read and write through a store; the payment
16//! handler moves an order from `awaiting_payment` to `paying` and on to `paid` with the
17//! store's compare-and-set, so two payments for one order never both start, in one process or
18//! several.
19
20use std::collections::BTreeMap;
21use std::sync::Arc;
22
23use adk_core::{AdkError, Result};
24use async_trait::async_trait;
25use awp_types::QuoteDocument;
26use chrono::{DateTime, Utc};
27use sqlx::Row as _;
28use tokio::sync::Mutex;
29use uuid::Uuid;
30
31use super::handlers::{Calendar, Order, Slot};
32
33fn store_error(error: impl std::fmt::Display) -> AdkError {
34    AdkError::config(format!("the site's commerce store: {error}"))
35}
36
37/// Where the edge keeps its quotes, orders and bookings (spec 3.5 §7.5, §7.9).
38///
39/// # Example
40///
41/// ```rust
42/// use adk_website::edge::commerce::{CommerceStore, InMemoryCommerceStore};
43///
44/// # #[tokio::main(flavor = "current_thread")]
45/// # async fn main() -> adk_core::Result<()> {
46/// let store = InMemoryCommerceStore::default();
47/// assert!(store.book("slot-1", "key-a").await?);
48/// assert!(store.book("slot-1", "key-a").await?, "the same booking again");
49/// assert!(!store.book("slot-1", "key-b").await?, "another booking finds it taken");
50/// # Ok(())
51/// # }
52/// ```
53#[async_trait]
54pub trait CommerceStore: Send + Sync {
55    /// Keeps `quote`, replacing one with its id.
56    ///
57    /// # Errors
58    ///
59    /// The store's error.
60    async fn put_quote(&self, quote: &QuoteDocument) -> Result<()>;
61
62    /// The quote `id`.
63    ///
64    /// # Errors
65    ///
66    /// The store's error.
67    async fn quote(&self, id: Uuid) -> Result<Option<QuoteDocument>>;
68
69    /// Keeps `order` unless one with its id exists; returns the order kept.
70    ///
71    /// # Errors
72    ///
73    /// The store's error.
74    async fn place_order(&self, order: &Order) -> Result<Order>;
75
76    /// The order `id`.
77    ///
78    /// # Errors
79    ///
80    /// The store's error.
81    async fn order(&self, id: &str) -> Result<Option<Order>>;
82
83    /// Moves order `id` to `status`; `None` when there is no such order.
84    ///
85    /// # Errors
86    ///
87    /// The store's error.
88    async fn set_order_status(&self, id: &str, status: &str) -> Result<Option<Order>>;
89
90    /// Moves order `id` from `from` to `to` in one atomic step; `None` when there is no such
91    /// order or it is not in `from`.
92    ///
93    /// # Errors
94    ///
95    /// The store's error.
96    async fn transition_order(&self, id: &str, from: &str, to: &str) -> Result<Option<Order>>;
97
98    /// Takes slot `slot` for booking `key`: `true` when it is taken now or was already taken
99    /// by `key`, `false` when another booking holds it.
100    ///
101    /// # Errors
102    ///
103    /// The store's error.
104    async fn book(&self, slot: &str, key: &str) -> Result<bool>;
105
106    /// The slots taken, each with the booking that holds it.
107    ///
108    /// # Errors
109    ///
110    /// The store's error.
111    async fn bookings(&self) -> Result<BTreeMap<String, String>>;
112}
113
114/// A [`CommerceStore`] in memory, for tests and sandboxes.
115#[derive(Debug, Default)]
116pub struct InMemoryCommerceStore {
117    quotes: Mutex<BTreeMap<Uuid, QuoteDocument>>,
118    orders: Mutex<BTreeMap<String, Order>>,
119    bookings: Mutex<BTreeMap<String, String>>,
120}
121
122#[async_trait]
123impl CommerceStore for InMemoryCommerceStore {
124    async fn put_quote(&self, quote: &QuoteDocument) -> Result<()> {
125        self.quotes.lock().await.insert(quote.id, quote.clone());
126        Ok(())
127    }
128
129    async fn quote(&self, id: Uuid) -> Result<Option<QuoteDocument>> {
130        Ok(self.quotes.lock().await.get(&id).cloned())
131    }
132
133    async fn place_order(&self, order: &Order) -> Result<Order> {
134        Ok(self
135            .orders
136            .lock()
137            .await
138            .entry(order.id.clone())
139            .or_insert_with(|| order.clone())
140            .clone())
141    }
142
143    async fn order(&self, id: &str) -> Result<Option<Order>> {
144        Ok(self.orders.lock().await.get(id).cloned())
145    }
146
147    async fn set_order_status(&self, id: &str, status: &str) -> Result<Option<Order>> {
148        let mut orders = self.orders.lock().await;
149        let Some(order) = orders.get_mut(id) else { return Ok(None) };
150        order.status = status.to_string();
151        Ok(Some(order.clone()))
152    }
153
154    async fn transition_order(&self, id: &str, from: &str, to: &str) -> Result<Option<Order>> {
155        let mut orders = self.orders.lock().await;
156        let Some(order) = orders.get_mut(id).filter(|order| order.status == from) else {
157            return Ok(None);
158        };
159        order.status = to.to_string();
160        Ok(Some(order.clone()))
161    }
162
163    async fn book(&self, slot: &str, key: &str) -> Result<bool> {
164        let mut bookings = self.bookings.lock().await;
165        Ok(bookings.entry(slot.to_string()).or_insert_with(|| key.to_string()) == key)
166    }
167
168    async fn bookings(&self) -> Result<BTreeMap<String, String>> {
169        Ok(self.bookings.lock().await.clone())
170    }
171}
172
173/// A [`CommerceStore`] in SQLite, such as a served site's `data/edge.db` (spec 3.5 §7.9).
174///
175/// One site's records sit under its namespace, so one database holds several sites. Call
176/// [`migrate`](Self::migrate) once.
177///
178/// # Example
179///
180/// ```rust
181/// use adk_website::edge::commerce::{CommerceStore, SqliteCommerceStore};
182///
183/// # #[tokio::main(flavor = "current_thread")]
184/// # async fn main() -> adk_core::Result<()> {
185/// let pool = sqlx::sqlite::SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await.unwrap();
186/// let store = SqliteCommerceStore::new(pool).with_site("bakery");
187/// store.migrate().await?;
188/// assert!(store.order("order-1").await?.is_none());
189/// # Ok(())
190/// # }
191/// ```
192#[derive(Debug, Clone)]
193pub struct SqliteCommerceStore {
194    pool: sqlx::SqlitePool,
195    site: String,
196}
197
198impl SqliteCommerceStore {
199    /// The store over `pool`, in the `default` namespace.
200    pub fn new(pool: sqlx::SqlitePool) -> Self {
201        Self { pool, site: "default".into() }
202    }
203
204    /// Keeps the records under `site`.
205    #[must_use]
206    pub fn with_site(mut self, site: impl Into<String>) -> Self {
207        self.site = site.into();
208        self
209    }
210
211    /// Creates the tables.
212    ///
213    /// # Errors
214    ///
215    /// The database's error.
216    pub async fn migrate(&self) -> Result<()> {
217        for statement in [
218            "CREATE TABLE IF NOT EXISTS website_quotes (
219                site TEXT NOT NULL, id TEXT NOT NULL, quote TEXT NOT NULL,
220                PRIMARY KEY (site, id))",
221            "CREATE TABLE IF NOT EXISTS website_orders (
222                site TEXT NOT NULL, id TEXT NOT NULL, status TEXT NOT NULL,
223                placed_at TEXT NOT NULL, record TEXT NOT NULL, PRIMARY KEY (site, id))",
224            "CREATE TABLE IF NOT EXISTS website_bookings (
225                site TEXT NOT NULL, slot TEXT NOT NULL, key TEXT NOT NULL, at TEXT NOT NULL,
226                PRIMARY KEY (site, slot))",
227        ] {
228            sqlx::query(statement).execute(&self.pool).await.map_err(store_error)?;
229        }
230        Ok(())
231    }
232
233    fn encode(order: &Order) -> Result<String> {
234        serde_json::to_string(order).map_err(store_error)
235    }
236}
237
238#[async_trait]
239impl CommerceStore for SqliteCommerceStore {
240    async fn put_quote(&self, quote: &QuoteDocument) -> Result<()> {
241        sqlx::query(
242            "INSERT INTO website_quotes (site, id, quote) VALUES (?, ?, ?)
243             ON CONFLICT (site, id) DO UPDATE SET quote = excluded.quote",
244        )
245        .bind(&self.site)
246        .bind(quote.id.to_string())
247        .bind(serde_json::to_string(quote).map_err(store_error)?)
248        .execute(&self.pool)
249        .await
250        .map_err(store_error)?;
251        Ok(())
252    }
253
254    async fn quote(&self, id: Uuid) -> Result<Option<QuoteDocument>> {
255        let row = sqlx::query("SELECT quote FROM website_quotes WHERE site = ? AND id = ?")
256            .bind(&self.site)
257            .bind(id.to_string())
258            .fetch_optional(&self.pool)
259            .await
260            .map_err(store_error)?;
261        row.map(|row| {
262            let text: String = row.try_get("quote").map_err(store_error)?;
263            serde_json::from_str(&text).map_err(store_error)
264        })
265        .transpose()
266    }
267
268    async fn place_order(&self, order: &Order) -> Result<Order> {
269        sqlx::query(
270            "INSERT INTO website_orders (site, id, status, placed_at, record) VALUES (?, ?, ?, ?, ?)
271             ON CONFLICT (site, id) DO NOTHING",
272        )
273        .bind(&self.site)
274        .bind(&order.id)
275        .bind(&order.status)
276        .bind(order.placed_at.to_rfc3339())
277        .bind(Self::encode(order)?)
278        .execute(&self.pool)
279        .await
280        .map_err(store_error)?;
281        self.order(&order.id)
282            .await?
283            .ok_or_else(|| store_error(format!("order {} was not kept", order.id)))
284    }
285
286    async fn order(&self, id: &str) -> Result<Option<Order>> {
287        let row = sqlx::query("SELECT record FROM website_orders WHERE site = ? AND id = ?")
288            .bind(&self.site)
289            .bind(id)
290            .fetch_optional(&self.pool)
291            .await
292            .map_err(store_error)?;
293        row.map(|row| {
294            let text: String = row.try_get("record").map_err(store_error)?;
295            serde_json::from_str(&text).map_err(store_error)
296        })
297        .transpose()
298    }
299
300    async fn set_order_status(&self, id: &str, status: &str) -> Result<Option<Order>> {
301        let Some(mut order) = self.order(id).await? else { return Ok(None) };
302        order.status = status.to_string();
303        sqlx::query("UPDATE website_orders SET status = ?, record = ? WHERE site = ? AND id = ?")
304            .bind(status)
305            .bind(Self::encode(&order)?)
306            .bind(&self.site)
307            .bind(id)
308            .execute(&self.pool)
309            .await
310            .map_err(store_error)?;
311        Ok(Some(order))
312    }
313
314    async fn transition_order(&self, id: &str, from: &str, to: &str) -> Result<Option<Order>> {
315        let Some(mut order) = self.order(id).await?.filter(|order| order.status == from) else {
316            return Ok(None);
317        };
318        order.status = to.to_string();
319        // The status is compared again in the update, so of two concurrent transitions out of
320        // `from` only one moves the order.
321        let done = sqlx::query(
322            "UPDATE website_orders SET status = ?, record = ?
323             WHERE site = ? AND id = ? AND status = ?",
324        )
325        .bind(to)
326        .bind(Self::encode(&order)?)
327        .bind(&self.site)
328        .bind(id)
329        .bind(from)
330        .execute(&self.pool)
331        .await
332        .map_err(store_error)?;
333        Ok((done.rows_affected() == 1).then_some(order))
334    }
335
336    async fn book(&self, slot: &str, key: &str) -> Result<bool> {
337        sqlx::query(
338            "INSERT INTO website_bookings (site, slot, key, at) VALUES (?, ?, ?, ?)
339             ON CONFLICT (site, slot) DO NOTHING",
340        )
341        .bind(&self.site)
342        .bind(slot)
343        .bind(key)
344        .bind(Utc::now().to_rfc3339())
345        .execute(&self.pool)
346        .await
347        .map_err(store_error)?;
348        let holder: String =
349            sqlx::query("SELECT key FROM website_bookings WHERE site = ? AND slot = ?")
350                .bind(&self.site)
351                .bind(slot)
352                .fetch_one(&self.pool)
353                .await
354                .map_err(store_error)?
355                .try_get("key")
356                .map_err(store_error)?;
357        Ok(holder == key)
358    }
359
360    async fn bookings(&self) -> Result<BTreeMap<String, String>> {
361        let rows = sqlx::query("SELECT slot, key FROM website_bookings WHERE site = ?")
362            .bind(&self.site)
363            .fetch_all(&self.pool)
364            .await
365            .map_err(store_error)?;
366        rows.iter()
367            .map(|row| {
368                Ok((
369                    row.try_get::<String, _>("slot").map_err(store_error)?,
370                    row.try_get::<String, _>("key").map_err(store_error)?,
371                ))
372            })
373            .collect()
374    }
375}
376
377/// The slots a site offers, booked in a [`CommerceStore`] (spec 3.5 §7.16 `booking`): the
378/// served site's calendar for the slots of `calendar.json`, so a booking survives a restart.
379///
380/// # Example
381///
382/// ```rust
383/// use std::sync::Arc;
384/// use adk_website::edge::commerce::{InMemoryCommerceStore, StoredCalendar};
385/// use adk_website::edge::handlers::{Calendar, Slot};
386///
387/// # #[tokio::main(flavor = "current_thread")]
388/// # async fn main() -> adk_core::Result<()> {
389/// let at = chrono::Utc::now();
390/// let slot = Slot { id: "s1".into(), starts_at: at, minutes: 30, price: Some(2_000) };
391/// let calendar = StoredCalendar::new([slot], Arc::new(InMemoryCommerceStore::default()));
392/// assert!(calendar.take("s1", "booking-1").await?);
393/// assert!(calendar.open(at, at + chrono::Duration::hours(1)).await?.is_empty());
394/// assert_eq!(calendar.price("s1"), Some(2_000));
395/// # Ok(())
396/// # }
397/// ```
398pub struct StoredCalendar {
399    slots: BTreeMap<String, Slot>,
400    store: Arc<dyn CommerceStore>,
401}
402
403impl StoredCalendar {
404    /// `slots`, booked in `store`.
405    pub fn new(slots: impl IntoIterator<Item = Slot>, store: Arc<dyn CommerceStore>) -> Self {
406        Self { slots: slots.into_iter().map(|slot| (slot.id.clone(), slot)).collect(), store }
407    }
408}
409
410#[async_trait]
411impl Calendar for StoredCalendar {
412    async fn open(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<Slot>> {
413        let taken = self.store.bookings().await?;
414        Ok(self
415            .slots
416            .values()
417            .filter(|slot| {
418                !taken.contains_key(&slot.id) && slot.starts_at >= from && slot.starts_at < to
419            })
420            .cloned()
421            .collect())
422    }
423
424    async fn take(&self, id: &str, key: &str) -> Result<bool> {
425        if !self.slots.contains_key(id) {
426            return Ok(false);
427        }
428        self.store.book(id, key).await
429    }
430
431    fn price(&self, id: &str) -> Option<u64> {
432        self.slots.get(id)?.price
433    }
434}
435
436/// The conformance check every [`CommerceStore`] passes (spec 3.5 §7.5, §7.9).
437pub mod conformance {
438    use std::sync::Arc;
439
440    use awp_types::{LineItem, QuoteDocument};
441    use chrono::Utc;
442    use uuid::Uuid;
443
444    use super::CommerceStore;
445    use crate::edge::handlers::{AWAITING_PAYMENT, Order, PAID, PAYING};
446
447    fn quote(total: u64) -> QuoteDocument {
448        let now = Utc::now();
449        QuoteDocument {
450            id: Uuid::new_v4(),
451            capability: "get_quote".into(),
452            requester: None,
453            lines: vec![LineItem {
454                sku: "loaf".into(),
455                description: Some("Sourdough".into()),
456                quantity: 2,
457                unit_amount: total / 2,
458            }],
459            total,
460            currency: "KES".into(),
461            release_seq: 3,
462            issued_at: now,
463            valid_until: now + chrono::Duration::days(7),
464            proof: None,
465        }
466    }
467
468    /// Quotes read back as kept; an order is placed once, its status moves by
469    /// compare-and-set, and a slot is booked once (spec 3.5 §7.5, A-I7, A-I25). `open` gives
470    /// a new handle over the same data, as a restarted process would.
471    ///
472    /// # Panics
473    ///
474    /// When the store breaks its contract.
475    pub async fn commerce_store<F, Fut>(open: F)
476    where
477        F: Fn() -> Fut,
478        Fut: std::future::Future<Output = Arc<dyn CommerceStore>>,
479    {
480        let issued = quote(800);
481        open().await.put_quote(&issued).await.unwrap();
482        assert_eq!(open().await.quote(issued.id).await.unwrap(), Some(issued.clone()));
483        assert_eq!(open().await.quote(Uuid::new_v4()).await.unwrap(), None);
484
485        let order = Order {
486            id: format!("order-{}", Uuid::new_v4().simple()),
487            quote: issued.clone(),
488            status: AWAITING_PAYMENT.into(),
489            placed_at: Utc::now(),
490        };
491        assert_eq!(open().await.place_order(&order).await.unwrap(), order);
492        let again = Order { status: PAID.into(), ..order.clone() };
493        assert_eq!(
494            open().await.place_order(&again).await.unwrap(),
495            order,
496            "a second placement keeps the first order"
497        );
498        assert_eq!(open().await.order(&order.id).await.unwrap(), Some(order.clone()));
499        assert_eq!(open().await.order("order-none").await.unwrap(), None);
500
501        let paying = open().await.transition_order(&order.id, AWAITING_PAYMENT, PAYING).await;
502        assert_eq!(paying.unwrap().map(|order| order.status), Some(PAYING.to_string()));
503        assert_eq!(
504            open().await.transition_order(&order.id, AWAITING_PAYMENT, PAYING).await.unwrap(),
505            None,
506            "an order not in `from` does not move"
507        );
508        assert_eq!(open().await.order(&order.id).await.unwrap().unwrap().status, PAYING);
509        let paid = open().await.set_order_status(&order.id, PAID).await.unwrap();
510        assert_eq!(paid.map(|order| order.status), Some(PAID.to_string()));
511        assert_eq!(open().await.set_order_status("order-none", PAID).await.unwrap(), None);
512
513        // Concurrent transitions out of one status: exactly one moves the order.
514        let contested = Order { id: format!("order-{}", Uuid::new_v4().simple()), ..order.clone() };
515        let contested = Order { status: AWAITING_PAYMENT.into(), ..contested };
516        open().await.place_order(&contested).await.unwrap();
517        let mut tasks = Vec::new();
518        for _ in 0..8 {
519            let store = open().await;
520            let id = contested.id.clone();
521            tasks.push(tokio::spawn(async move {
522                store.transition_order(&id, AWAITING_PAYMENT, PAYING).await.unwrap().is_some()
523            }));
524        }
525        let mut moved = 0;
526        for task in tasks {
527            moved += usize::from(task.await.unwrap());
528        }
529        assert_eq!(moved, 1);
530
531        let slot = format!("slot-{}", Uuid::new_v4().simple());
532        assert!(open().await.book(&slot, "key-a").await.unwrap());
533        assert!(open().await.book(&slot, "key-a").await.unwrap(), "the same booking again");
534        assert!(!open().await.book(&slot, "key-b").await.unwrap(), "taken by another");
535        assert_eq!(
536            open().await.bookings().await.unwrap().get(&slot).map(String::as_str),
537            Some("key-a")
538        );
539    }
540}