use std::collections::BTreeMap;
use std::sync::{Arc, PoisonError};
use adk_core::audit_log::{AuditActor, AuditTrail};
use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler};
use adk_awp::v2::store::{Lead, LeadStore};
use adk_harness::website::SiteRuntime;
use adk_server::awp::{SignalEmitter, SiteSearch};
use async_trait::async_trait;
use awp_types::{
Bounded, Channel, ConsentReceiptRef, ContactRef, ContentItem, ContentKind, ContentState,
ErrorCode, LeadRef, LineItem, QuoteDocument, Signal, SignalKind,
};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use tokio::sync::Mutex;
use uuid::Uuid;
const ANSWER_MAX_CHARS: usize = 280;
fn failed(error: impl std::fmt::Display) -> CapabilityError {
CapabilityError::Failed(error.to_string())
}
fn refused(code: ErrorCode, message: impl Into<String>) -> CapabilityError {
CapabilityError::Refused { code, message: message.into() }
}
#[derive(Clone)]
pub struct PublishedContent {
runtime: Arc<SiteRuntime>,
}
impl PublishedContent {
pub fn new(runtime: Arc<SiteRuntime>) -> Self {
Self { runtime }
}
pub async fn items(&self, kind: ContentKind) -> Result<Vec<ContentItem>, CapabilityError> {
Ok(self
.runtime
.store()
.list()
.await
.map_err(failed)?
.into_iter()
.filter(|item| item.kind == kind && item.state == ContentState::Published)
.collect())
}
pub async fn release_seq(&self) -> u64 {
self.runtime.pipeline().previous().await.map_or(0, |previous| previous.manifest.seq)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Contact {
pub contact_ref: ContactRef,
pub email: Option<String>,
pub name: Option<String>,
pub consent: Vec<Uuid>,
pub at: DateTime<Utc>,
}
#[async_trait]
pub trait ContactBook: Send + Sync {
async fn put(&self, contact: Contact) -> adk_core::Result<()>;
async fn by_receipts(&self, receipts: &[Uuid]) -> adk_core::Result<Vec<Contact>>;
async fn erase(&self, receipts: &[Uuid]) -> adk_core::Result<usize>;
}
#[derive(Debug, Default)]
pub struct InMemoryContactBook {
contacts: Mutex<BTreeMap<String, Contact>>,
}
#[async_trait]
impl ContactBook for InMemoryContactBook {
async fn put(&self, contact: Contact) -> adk_core::Result<()> {
self.contacts.lock().await.insert(contact.contact_ref.0.clone(), contact);
Ok(())
}
async fn by_receipts(&self, receipts: &[Uuid]) -> adk_core::Result<Vec<Contact>> {
Ok(self
.contacts
.lock()
.await
.values()
.filter(|c| c.consent.iter().any(|r| receipts.contains(r)))
.cloned()
.collect())
}
async fn erase(&self, receipts: &[Uuid]) -> adk_core::Result<usize> {
let mut contacts = self.contacts.lock().await;
let before = contacts.len();
contacts.retain(|_, c| !c.consent.iter().any(|r| receipts.contains(r)));
Ok(before - contacts.len())
}
}
fn contact_ref(email: Option<&str>, key: &str) -> ContactRef {
let basis = email.map_or_else(|| key.to_string(), |e| e.trim().to_ascii_lowercase());
let digest = adk_site::release::file_digest(basis.as_bytes()).to_string();
ContactRef(format!("contact:{}", digest.trim_start_matches("sha256:").get(..16).unwrap_or("")))
}
pub struct FormHandler {
leads: Arc<dyn LeadStore>,
contacts: Arc<dyn ContactBook>,
signals: Arc<dyn SignalEmitter>,
emitted_by: String,
}
impl FormHandler {
pub fn new(
leads: Arc<dyn LeadStore>,
contacts: Arc<dyn ContactBook>,
signals: Arc<dyn SignalEmitter>,
emitted_by: impl Into<String>,
) -> Self {
Self { leads, contacts, signals, emitted_by: emitted_by.into() }
}
}
#[async_trait]
impl CapabilityHandler for FormHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let fields = call.input.as_object().cloned().unwrap_or_default();
let text = |key: &str| fields.get(key).and_then(Value::as_str).map(str::to_string);
let email = text("email");
let contact_ref = contact_ref(email.as_deref(), &call.idempotency_key);
let now = Utc::now();
self.contacts
.put(Contact {
contact_ref: contact_ref.clone(),
email: email.clone(),
name: text("name"),
consent: call.consent.clone(),
at: now,
})
.await
.map_err(failed)?;
let answers: BTreeMap<String, Bounded> = fields
.iter()
.filter(|(key, _)| !matches!(key.as_str(), "email" | "name"))
.filter_map(|(key, value)| {
let text = match value {
Value::String(text) => text.clone(),
Value::Null => return None,
other => other.to_string(),
};
Some((key.clone(), Bounded::truncated(&text, ANSWER_MAX_CHARS)))
})
.chain(std::iter::once((
"capability".to_string(),
Bounded::truncated(&call.capability, ANSWER_MAX_CHARS),
)))
.collect();
let consent: Vec<ConsentReceiptRef> =
call.consent.iter().map(|id| ConsentReceiptRef(*id)).collect();
let lead = Lead {
id: LeadRef(format!("lead-{}", Uuid::new_v4().simple())),
captured_at: now,
source: Channel::Http,
contact_ref,
consent: consent.clone(),
answers: answers.clone(),
thread_ref: None,
score: None,
};
self.leads.insert(lead.clone()).await.map_err(failed)?;
self.signals
.emit(Signal {
id: Uuid::new_v4(),
kind: SignalKind::LeadCaptured {
lead_ref: lead.id.clone(),
source: Channel::Http,
consent,
answers,
},
emitted_by: self.emitted_by.clone(),
emitted_at: now,
})
.await
.map_err(failed)?;
Ok(json!({ "received": true, "reference": lead.id.0, "receivedAt": now }))
}
}
pub struct QuoteBook {
store: Arc<dyn super::commerce::CommerceStore>,
}
impl Default for QuoteBook {
fn default() -> Self {
Self::new(Arc::new(super::commerce::InMemoryCommerceStore::default()))
}
}
impl std::fmt::Debug for QuoteBook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QuoteBook").finish_non_exhaustive()
}
}
impl QuoteBook {
pub fn new(store: Arc<dyn super::commerce::CommerceStore>) -> Self {
Self { store }
}
pub async fn get(&self, id: &Uuid) -> Option<QuoteDocument> {
self.store.quote(*id).await.unwrap_or_else(|error| {
tracing::warn!(quote = %id, error = %error, "a quote could not be read");
None
})
}
async fn insert(&self, quote: &QuoteDocument) -> Result<(), CapabilityError> {
self.store.put_quote(quote).await.map_err(failed)
}
}
pub struct QuoteHandler {
content: PublishedContent,
quotes: Arc<QuoteBook>,
validity: Duration,
}
impl QuoteHandler {
pub fn new(content: PublishedContent, quotes: Arc<QuoteBook>, validity: Duration) -> Self {
Self { content, quotes, validity }
}
}
#[async_trait]
impl CapabilityHandler for QuoteHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let products = self.content.items(ContentKind::Product).await?;
let wanted = call.input["items"].as_array().cloned().unwrap_or_default();
let mut lines = Vec::new();
let mut currency: Option<String> = None;
for line in &wanted {
let sku = line["sku"].as_str().unwrap_or_default();
let quantity = line["quantity"].as_u64().unwrap_or(1);
let product = products
.iter()
.find(|item| item.fields.get("sku").and_then(Value::as_str) == Some(sku))
.ok_or_else(|| {
refused(ErrorCode::InventoryUnavailable, format!("no product {sku}"))
})?;
let price = product.fields.get("price").and_then(Value::as_u64).ok_or_else(|| {
refused(ErrorCode::InventoryUnavailable, format!("{sku} has no published price"))
})?;
let line_currency =
product.fields.get("currency").and_then(Value::as_str).unwrap_or("USD").to_string();
if currency.as_ref().is_some_and(|c| *c != line_currency) {
return Err(refused(ErrorCode::InvalidRequest, "a quote is in one currency"));
}
currency = Some(line_currency);
lines.push(LineItem {
sku: sku.to_string(),
description: product
.fields
.get("title")
.and_then(Value::as_str)
.map(str::to_string),
quantity: u32::try_from(quantity).unwrap_or(u32::MAX),
unit_amount: price,
});
}
let total = lines
.iter()
.map(|line| line.unit_amount.saturating_mul(u64::from(line.quantity)))
.fold(0u64, u64::saturating_add);
let now = Utc::now();
let quote = QuoteDocument {
id: Uuid::new_v4(),
capability: call.capability.clone(),
requester: call.requester.clone(),
lines,
total,
currency: currency.unwrap_or_else(|| "USD".into()),
release_seq: self.content.release_seq().await,
issued_at: now,
valid_until: now + self.validity,
proof: None,
};
self.quotes.insert("e).await?;
serde_json::to_value(quote).map_err(failed)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Order {
pub id: String,
pub quote: QuoteDocument,
pub status: String,
pub placed_at: DateTime<Utc>,
}
pub const AWAITING_PAYMENT: &str = "awaiting_payment";
pub const PAYING: &str = "paying";
pub const PAID: &str = "paid";
pub struct OrderBook {
store: Arc<dyn super::commerce::CommerceStore>,
}
impl Default for OrderBook {
fn default() -> Self {
Self::new(Arc::new(super::commerce::InMemoryCommerceStore::default()))
}
}
impl std::fmt::Debug for OrderBook {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OrderBook").finish_non_exhaustive()
}
}
impl OrderBook {
pub fn new(store: Arc<dyn super::commerce::CommerceStore>) -> Self {
Self { store }
}
pub async fn get(&self, id: &str) -> Option<Order> {
self.order(id).await.unwrap_or_else(|error| {
tracing::warn!(order = id, error = %error, "an order could not be read");
None
})
}
pub async fn set_status(&self, id: &str, status: &str) -> Option<Order> {
self.store.set_order_status(id, status).await.unwrap_or_else(|error| {
tracing::warn!(order = id, error = %error, "an order's status could not be written");
None
})
}
async fn order(&self, id: &str) -> Result<Option<Order>, CapabilityError> {
self.store.order(id).await.map_err(failed)
}
async fn transition(
&self,
id: &str,
from: &str,
to: &str,
) -> Result<Option<Order>, CapabilityError> {
self.store.transition_order(id, from, to).await.map_err(failed)
}
async fn place(&self, order: &Order) -> Result<Order, CapabilityError> {
self.store.place_order(order).await.map_err(failed)
}
}
pub struct OrderHandler {
quotes: Arc<QuoteBook>,
orders: Arc<OrderBook>,
desk: Option<Arc<dyn PaymentDesk>>,
}
impl OrderHandler {
pub fn new(quotes: Arc<QuoteBook>, orders: Arc<OrderBook>) -> Self {
Self { quotes, orders, desk: None }
}
#[must_use]
pub fn with_payments(mut self, desk: Arc<dyn PaymentDesk>) -> Self {
self.desk = Some(desk);
self
}
}
#[async_trait]
impl CapabilityHandler for OrderHandler {
async fn amount(&self, input: &Value) -> Option<u64> {
if let Some(quote) = input["quoteId"].as_str() {
return self.quotes.get("e.parse().ok()?).await.map(|quote| quote.total);
}
let order = input["orderId"].as_str()?;
self.orders.get(order).await.map(|order| order.quote.total)
}
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let not_found = |what: &str| refused(ErrorCode::ResourceNotFound, format!("no {what}"));
match call.capability.as_str() {
"place_order" => {
let id = call.input["quoteId"]
.as_str()
.and_then(|id| id.parse::<Uuid>().ok())
.ok_or_else(|| not_found("quote"))?;
let quote = self.quotes.get(&id).await.ok_or_else(|| not_found("quote"))?;
if quote.requester.is_some() && quote.requester != call.requester {
return Err(not_found("quote"));
}
if !quote.is_open(Utc::now()) {
return Err(refused(ErrorCode::QuoteExpired, "the quote has expired"));
}
let id = format!("order-{}", call.idempotency_key);
let order = self.orders.order(&id).await?.unwrap_or_else(|| Order {
id,
quote,
status: AWAITING_PAYMENT.into(),
placed_at: Utc::now(),
});
let payment = match &self.desk {
Some(desk) => desk.checkout(&order).await?,
None => None,
};
let order = self.orders.place(&order).await?;
let mut placed = serde_json::to_value(order).map_err(failed)?;
if let Some(payment) = payment {
placed["payment"] = payment;
}
Ok(placed)
}
"order_status" | "request_return" => {
let id = call.input["orderId"].as_str().unwrap_or_default();
let order = self
.orders
.order(id)
.await?
.filter(|order| {
order.quote.requester.is_none() || order.quote.requester == call.requester
})
.ok_or_else(|| not_found("order"))?;
if call.capability == "order_status" {
return Ok(
json!({ "orderId": order.id, "status": order.status, "total": order.quote.total, "currency": order.quote.currency }),
);
}
let order = self
.orders
.set_status(&order.id, "return_approved")
.await
.ok_or_else(|| not_found("order"))?;
Ok(json!({ "orderId": order.id, "status": order.status }))
}
other => Err(failed(format!("{other} is not an order capability"))),
}
}
}
#[async_trait]
pub trait PaymentDesk: Send + Sync {
async fn take(&self, call: &CapabilityCall) -> Result<Value, CapabilityError>;
async fn take_for(
&self,
call: &CapabilityCall,
order: &Order,
) -> Result<Value, CapabilityError> {
let _ = order;
self.take(call).await
}
async fn checkout(&self, order: &Order) -> Result<Option<Value>, CapabilityError> {
let _ = order;
Ok(None)
}
}
pub const PAYMENT_CREATED: &str = "awp.payment.created";
pub const PAYMENT_SETTLED: &str = "awp.payment.settled";
pub const PAYMENT_REJECTED: &str = "awp.payment.rejected";
pub struct PaymentHandler {
desk: Option<Arc<dyn PaymentDesk>>,
orders: Option<Arc<OrderBook>>,
audit: Option<AuditTrail>,
}
impl PaymentHandler {
pub fn new(desk: Option<Arc<dyn PaymentDesk>>) -> Self {
Self { desk, orders: None, audit: None }
}
#[must_use]
pub fn with_audit(mut self, trail: AuditTrail) -> Self {
self.audit = Some(trail);
self
}
async fn record(&self, action: &str, call: &CapabilityCall, fields: Value) {
let mut fields = fields;
fields["capability"] = json!(call.capability);
fields["requester"] = json!(call.requester.as_ref().map(ToString::to_string));
fields["idempotencyKey"] = json!(call.idempotency_key);
crate::audit::record(self.audit.as_ref(), action, AuditActor::default(), fields).await;
}
async fn take(
&self,
desk: &Arc<dyn PaymentDesk>,
call: &CapabilityCall,
order: Option<&Order>,
) -> Result<Value, CapabilityError> {
let amount = match order {
Some(order) => Some(order.quote.total),
None => call.input.get("amount").and_then(Value::as_u64),
};
let currency = order.map(|order| order.quote.currency.clone());
let order_id = order.map(|order| order.id.clone());
let base = json!({ "order": order_id, "amount": amount, "currency": currency });
self.record(PAYMENT_CREATED, call, base.clone()).await;
let receipt = match order {
Some(order) => desk.take_for(call, order).await,
None => desk.take(call).await,
};
let mut fields = base;
match &receipt {
Ok(receipt) => {
fields["status"] = receipt["status"].clone();
if receipt["status"] == PAID {
self.record(PAYMENT_SETTLED, call, fields).await;
}
}
Err(error) => {
fields["error"] = json!(error.to_string());
self.record(PAYMENT_REJECTED, call, fields).await;
}
}
receipt
}
#[must_use]
pub fn with_orders(mut self, orders: Arc<OrderBook>) -> Self {
self.orders = Some(orders);
self
}
}
#[async_trait]
impl CapabilityHandler for PaymentHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let Some(desk) = &self.desk else {
return Err(refused(
ErrorCode::PaymentPolicyRejected,
"the site takes no payments until its owner connects a payment rail",
));
};
let (Some(orders), Some(id)) = (&self.orders, call.input["orderId"].as_str()) else {
return self.take(desk, &call, None).await;
};
let not_found = || refused(ErrorCode::ResourceNotFound, "no order");
let order = orders.order(id).await?.ok_or_else(not_found)?;
if order.quote.requester.is_some() && order.quote.requester != call.requester {
return Err(not_found());
}
let Some(paying) = orders.transition(&order.id, AWAITING_PAYMENT, PAYING).await? else {
let status = orders.order(&order.id).await?.map_or(order.status, |order| order.status);
return Err(refused(
ErrorCode::PaymentPolicyRejected,
format!("order {} is {status}, not awaiting payment", order.id),
));
};
let mut payment = Paying { orders: Some(orders.clone()), id: paying.id.clone() };
let receipt = self.take(desk, &call, Some(&paying)).await;
let settled = matches!(&receipt, Ok(receipt) if receipt["status"] == PAID);
payment.finish(settled).await;
receipt
}
async fn amount(&self, input: &Value) -> Option<u64> {
match (&self.orders, input["orderId"].as_str()) {
(Some(orders), Some(id)) => orders.get(id).await.map(|order| order.quote.total),
_ => input.get("amount").and_then(Value::as_u64),
}
}
}
struct Paying {
orders: Option<Arc<OrderBook>>,
id: String,
}
impl Paying {
async fn finish(&mut self, settled: bool) {
let Some(orders) = self.orders.take() else { return };
let next = if settled { PAID } else { AWAITING_PAYMENT };
if let Err(error) = orders.transition(&self.id, PAYING, next).await {
tracing::warn!(order = %self.id, error = %error, "an order's payment state could not be written");
}
}
}
impl Drop for Paying {
fn drop(&mut self) {
let Some(orders) = self.orders.take() else { return };
let id = std::mem::take(&mut self.id);
match tokio::runtime::Handle::try_current() {
Ok(runtime) => {
runtime.spawn(async move {
let _ = orders.transition(&id, PAYING, AWAITING_PAYMENT).await;
});
}
Err(_) => tracing::warn!(order = %id, "a dropped payment leaves its order paying"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Slot {
pub id: String,
pub starts_at: DateTime<Utc>,
pub minutes: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub price: Option<u64>,
}
#[async_trait]
pub trait Calendar: Send + Sync {
async fn open(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> adk_core::Result<Vec<Slot>>;
async fn take(&self, id: &str, key: &str) -> adk_core::Result<bool>;
fn price(&self, id: &str) -> Option<u64> {
let _ = id;
None
}
}
#[derive(Debug, Default)]
pub struct InMemoryCalendar {
slots: std::sync::Mutex<BTreeMap<String, (Slot, Option<String>)>>,
}
impl InMemoryCalendar {
pub fn new(slots: impl IntoIterator<Item = Slot>) -> Self {
Self {
slots: std::sync::Mutex::new(
slots.into_iter().map(|slot| (slot.id.clone(), (slot, None))).collect(),
),
}
}
}
#[async_trait]
impl Calendar for InMemoryCalendar {
async fn open(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> adk_core::Result<Vec<Slot>> {
Ok(self
.slots
.lock()
.unwrap_or_else(PoisonError::into_inner)
.values()
.filter(|(slot, taken)| {
taken.is_none() && slot.starts_at >= from && slot.starts_at < to
})
.map(|(slot, _)| slot.clone())
.collect())
}
async fn take(&self, id: &str, key: &str) -> adk_core::Result<bool> {
let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
Ok(match slots.get_mut(id) {
Some((_, taken @ None)) => {
*taken = Some(key.to_string());
true
}
Some((_, Some(holder))) => holder == key,
None => false,
})
}
fn price(&self, id: &str) -> Option<u64> {
self.slots.lock().unwrap_or_else(PoisonError::into_inner).get(id)?.0.price
}
}
pub struct BookingHandler {
calendar: Arc<dyn Calendar>,
forms: Arc<FormHandler>,
}
impl BookingHandler {
pub fn new(calendar: Arc<dyn Calendar>, forms: Arc<FormHandler>) -> Self {
Self { calendar, forms }
}
}
#[async_trait]
impl CapabilityHandler for BookingHandler {
fn call_amount(&self, input: &Value) -> Option<u64> {
self.calendar.price(input["slot"].as_str()?)
}
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let date = |key: &str| {
call.input[key]
.as_str()
.and_then(|d| d.parse::<chrono::NaiveDate>().ok())
.and_then(|d| d.and_hms_opt(0, 0, 0))
.map(|d| d.and_utc())
};
if call.capability == "check_availability" {
let from = date("from").unwrap_or_else(Utc::now);
let to = date("to").unwrap_or(from + Duration::days(14));
let open = self.calendar.open(from, to).await.map_err(failed)?;
return Ok(json!({ "slots": open }));
}
let slot = call.input["slot"].as_str().unwrap_or_default().to_string();
if !self.calendar.take(&slot, &call.idempotency_key).await.map_err(failed)? {
return Err(refused(ErrorCode::InventoryUnavailable, "that slot is no longer open"));
}
let mut booked = self.forms.handle(call).await?;
booked["slot"] = json!(slot);
booked["booked"] = json!(true);
Ok(booked)
}
}
pub struct SearchHandler {
search: Arc<dyn SiteSearch>,
}
impl SearchHandler {
pub fn new(search: Arc<dyn SiteSearch>) -> Self {
Self { search }
}
}
#[async_trait]
impl CapabilityHandler for SearchHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let query = call.input["query"].as_str().unwrap_or_default();
let hits = self.search.search(query, 10).await.map_err(failed)?;
Ok(
json!({ "results": hits.iter().map(|h| json!({ "path": h.path, "title": h.title, "snippet": h.snippet })).collect::<Vec<_>>() }),
)
}
}
pub struct ListingHandler {
content: PublishedContent,
kind: ContentKind,
}
impl ListingHandler {
pub fn new(content: PublishedContent, kind: ContentKind) -> Self {
Self { content, kind }
}
}
#[async_trait]
impl CapabilityHandler for ListingHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let query = call.input["query"].as_str().map(str::to_ascii_lowercase);
let items: Vec<Value> = self
.content
.items(self.kind)
.await?
.into_iter()
.filter(|item| {
query.as_ref().is_none_or(|q| {
item.fields.values().any(|v| v.as_str().is_some_and(|s| s.to_ascii_lowercase().contains(q)))
})
})
.map(|item| {
let mut entry = json!({ "id": item.id.0, "slug": item.slug, "language": item.language.as_str() });
for (key, value) in &item.fields {
if !item.volatile.contains(key) {
entry[key] = value.clone();
}
}
entry
})
.collect();
Ok(json!({ "items": items, "release": self.content.release_seq().await }))
}
}
pub struct StatusHandler {
leads: Arc<dyn LeadStore>,
}
impl StatusHandler {
pub fn new(leads: Arc<dyn LeadStore>) -> Self {
Self { leads }
}
}
#[async_trait]
impl CapabilityHandler for StatusHandler {
async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
let reference = call.input["reference"].as_str().unwrap_or_default();
let lead =
self.leads.get(&LeadRef(reference.to_string())).await.map_err(failed)?.ok_or_else(
|| refused(ErrorCode::ResourceNotFound, "no application has that reference"),
)?;
Ok(json!({ "reference": lead.id.0, "status": "received", "receivedAt": lead.captured_at }))
}
}