1use 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#[async_trait]
54pub trait CommerceStore: Send + Sync {
55 async fn put_quote(&self, quote: &QuoteDocument) -> Result<()>;
61
62 async fn quote(&self, id: Uuid) -> Result<Option<QuoteDocument>>;
68
69 async fn place_order(&self, order: &Order) -> Result<Order>;
75
76 async fn order(&self, id: &str) -> Result<Option<Order>>;
82
83 async fn set_order_status(&self, id: &str, status: &str) -> Result<Option<Order>>;
89
90 async fn transition_order(&self, id: &str, from: &str, to: &str) -> Result<Option<Order>>;
97
98 async fn book(&self, slot: &str, key: &str) -> Result<bool>;
105
106 async fn bookings(&self) -> Result<BTreeMap<String, String>>;
112}
113
114#[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#[derive(Debug, Clone)]
193pub struct SqliteCommerceStore {
194 pool: sqlx::SqlitePool,
195 site: String,
196}
197
198impl SqliteCommerceStore {
199 pub fn new(pool: sqlx::SqlitePool) -> Self {
201 Self { pool, site: "default".into() }
202 }
203
204 #[must_use]
206 pub fn with_site(mut self, site: impl Into<String>) -> Self {
207 self.site = site.into();
208 self
209 }
210
211 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 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
377pub struct StoredCalendar {
399 slots: BTreeMap<String, Slot>,
400 store: Arc<dyn CommerceStore>,
401}
402
403impl StoredCalendar {
404 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
436pub 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 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 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}