use std::sync::Arc;
use adk_awp::v2::capability::{CapabilityCall, CapabilityError};
use adk_core::audit_log::{AuditRecordDraft, AuditRecorder};
use async_trait::async_trait;
use awp_types::ErrorCode;
use serde_json::{Value, json};
use super::project::PaymentLink;
use crate::edge::handlers::PaymentDesk;
pub use adk_site::gate::ReleaseDelegation;
pub fn preview_verification(
project: &adk_site::content::SiteProject,
host: Arc<dyn adk_site::host::SiteHost>,
edge: Arc<crate::edge::adapters::DeferredFetcher>,
) -> adk_site::gate::PreviewVerification {
use adk_awp::signing::anchor::{FixedTxtResolver, root_record, root_record_name};
let domain = project.config.domain.clone();
let keys = project
.documents
.get(".well-known/awp/keys.json")
.and_then(|bytes| serde_json::from_slice::<awp_types::KeySet>(bytes).ok());
let resolver = match keys {
Some(keys) => FixedTxtResolver::default()
.with(&root_record_name(&domain), &root_record(&keys.root.kid, &keys.root.public_key)),
None => FixedTxtResolver::default(),
};
adk_site::gate::PreviewVerification::new(domain, host, Arc::new(resolver)).with_fetcher(edge)
}
pub struct PaymentLinks {
links: Vec<PaymentLink>,
}
impl PaymentLinks {
pub fn new(links: Vec<PaymentLink>) -> Self {
Self { links }
}
}
#[async_trait]
impl PaymentDesk for PaymentLinks {
async fn take(&self, call: &CapabilityCall) -> Result<Value, CapabilityError> {
let wanted = call.input["rail"].as_str();
let link = match wanted {
Some(rail) => self.links.iter().find(|link| link.rail == rail),
None => self.links.first(),
}
.ok_or_else(|| CapabilityError::Refused {
code: ErrorCode::PaymentPolicyRejected,
message: format!(
"the site does not take payment by {}; it accepts {}",
wanted.unwrap_or("that rail"),
self.links.iter().map(|link| link.rail.as_str()).collect::<Vec<_>>().join(", ")
),
})?;
let reference = call.input["orderId"].as_str().map_or_else(
|| format!("{}-{}", call.capability, call.idempotency_key),
str::to_string,
);
Ok(json!({
"status": "awaiting_payment",
"reference": reference,
"rail": link.rail,
"instructions": link.instructions,
"url": link.url,
}))
}
}
#[derive(Debug, Default, Clone)]
pub struct LogRecorder;
#[async_trait]
impl AuditRecorder for LogRecorder {
fn digest(&self, value: &Value) -> String {
adk_core::json_digest(value)
}
async fn record(&self, draft: AuditRecordDraft) -> adk_core::Result<()> {
tracing::info!(audit.action = %draft.action, "audit record");
Ok(())
}
}
pub fn metered_trail(
recorder: Arc<dyn AuditRecorder>,
counts: Arc<dyn adk_server::awp::BeaconStore>,
) -> adk_core::audit_log::AuditTrail {
adk_core::audit_log::AuditTrail::new(Arc::new(crate::measurement::EdgeMeter::new(
recorder, counts,
)))
}
pub fn metered_audit(
counts: Arc<dyn adk_server::awp::BeaconStore>,
) -> adk_core::audit_log::AuditTrail {
adk_core::audit_log::AuditTrail::new(Arc::new(crate::measurement::EdgeMeter::new(
Arc::new(LogRecorder),
counts,
)))
}