use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use adk_awp::signing::jws::DocumentSigner;
use adk_awp::v2::store::{ConsentRecord, LeadStore};
use adk_core::{AdkError, Result};
use adk_harness::website::{SIGNAL_FIELD_MAX_CHARS, screen_bounded};
use adk_kernel::charter::SignalSink;
use adk_server::awp::{EdgeEvents, SignalEmitter, SiteHit, SiteSearch, SubjectData, ThreadSink};
use adk_site::live::{LiveStore, LiveValue};
use adk_site::pipeline::{Announcement, Announcer};
use async_trait::async_trait;
use awp_types::{Bounded, ContentId, PublicKeyJwk, Signal, SignalKind, ThreadRef};
use serde_json::{Value, json};
use tokio::sync::RwLock;
use tracing::Instrument as _;
use uuid::Uuid;
use super::handlers::ContactBook;
async fn screened(text: &Bounded) -> Bounded {
screen_bounded(text.as_str(), SIGNAL_FIELD_MAX_CHARS).await
}
pub struct KernelSignals {
sink: std::sync::RwLock<SignalSink>,
}
impl KernelSignals {
pub fn new(sink: SignalSink) -> Self {
Self { sink: std::sync::RwLock::new(sink) }
}
pub fn attach(&self, sink: SignalSink) {
*self.sink.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
}
}
#[async_trait]
impl SignalEmitter for KernelSignals {
async fn emit(&self, signal: Signal) -> Result<()> {
let span = tracing::info_span!(
crate::observability::spans::KERNEL_SIGNAL,
signal.kind = signal.kind.name(),
signal.id = %signal.id,
signal.emitted_by = %signal.emitted_by,
);
self.file(signal).instrument(span).await
}
}
impl KernelSignals {
async fn file(&self, mut signal: Signal) -> Result<()> {
match &mut signal.kind {
SignalKind::LeadCaptured { answers, .. } => {
for value in answers.values_mut() {
*value = screened(value).await;
}
}
SignalKind::ContentGap { topic, samples, .. } => {
*topic = screened(topic).await;
for sample in samples.iter_mut() {
*sample = screened(sample).await;
}
}
SignalKind::ReviewSeen { excerpt, .. } => *excerpt = screened(excerpt).await,
_ => {}
}
let sink = self.sink.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
sink.emit(signal).await.map(|_| ()).map_err(|e| AdkError::config(e.to_string()))
}
}
pub struct ReleaseSearch {
index: Arc<adk_harness::website::SiteSearch>,
}
impl ReleaseSearch {
pub fn new(index: Arc<adk_harness::website::SiteSearch>) -> Self {
Self { index }
}
}
#[async_trait]
impl SiteSearch for ReleaseSearch {
async fn search(&self, query: &str, limit: usize) -> Result<Vec<SiteHit>> {
Ok(self
.index
.search(query, limit)
.into_iter()
.map(|hit| SiteHit { path: hit.url, title: hit.title, snippet: hit.snippet })
.collect())
}
}
pub struct InboxThreads {
reply: Arc<adk_drivers::ReplyInThread>,
template: String,
}
impl InboxThreads {
pub fn new(reply: Arc<adk_drivers::ReplyInThread>, template: impl Into<String>) -> Self {
Self { reply, template: template.into() }
}
}
#[async_trait]
impl ThreadSink for InboxThreads {
async fn reply(&self, thread: &ThreadRef, text: &str) -> Result<()> {
let fields = BTreeMap::from([("body".to_string(), text.to_string())]);
self.reply
.reply(&thread.0, &self.template, &fields)
.await
.map(|_| ())
.map_err(|e| AdkError::config(e.to_string()))
}
}
pub struct SiteSubjectData {
leads: Arc<dyn LeadStore>,
contacts: Arc<dyn ContactBook>,
}
impl SiteSubjectData {
pub fn new(leads: Arc<dyn LeadStore>, contacts: Arc<dyn ContactBook>) -> Self {
Self { leads, contacts }
}
}
fn receipt_ids(receipts: &[ConsentRecord]) -> Vec<Uuid> {
receipts.iter().map(|record| record.receipt.id).collect()
}
#[async_trait]
impl SubjectData for SiteSubjectData {
async fn export(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<Value> {
let ids = receipt_ids(receipts);
let leads: Vec<Value> = self
.leads
.since(chrono::DateTime::<chrono::Utc>::MIN_UTC)
.await
.map_err(|e| AdkError::config(e.to_string()))?
.into_iter()
.filter(|lead| lead.consent.iter().any(|r| ids.contains(&r.0)))
.map(|lead| json!(lead))
.collect();
let contacts = self.contacts.by_receipts(&ids).await?;
Ok(json!({ "leads": leads, "contacts": contacts }))
}
async fn erase(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<usize> {
self.contacts.erase(&receipt_ids(receipts)).await
}
}
pub struct EdgeAnnouncer {
events: EdgeEvents,
}
impl EdgeAnnouncer {
pub fn new(events: EdgeEvents) -> Self {
Self { events }
}
}
#[async_trait]
impl Announcer for EdgeAnnouncer {
async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
let fail = |e: adk_awp::v2::store::StoreError| adk_site::SiteError::Pipeline(e.to_string());
self.events.release_published(announcement.release.clone()).await.map_err(fail)?;
if let Some(catalog) = &announcement.catalog {
self.events
.announce_catalog(catalog.clone(), announcement.catalog_pages.clone())
.await
.map_err(fail)?;
}
Ok(())
}
}
#[derive(Default)]
pub struct DeferredAnnouncer {
target: OnceLock<Arc<dyn Announcer>>,
}
impl DeferredAnnouncer {
pub fn set(&self, target: Arc<dyn Announcer>) -> bool {
self.target.set(target).is_ok()
}
pub fn is_set(&self) -> bool {
self.target.get().is_some()
}
}
#[async_trait]
impl Announcer for DeferredAnnouncer {
async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
match self.target.get() {
Some(target) => target.announce(announcement).await,
None => {
tracing::debug!(
release = announcement.release.seq,
"no edge yet; release not announced"
);
Ok(())
}
}
}
}
#[derive(Default)]
pub struct DeferredFetcher {
target: OnceLock<Arc<dyn adk_awp::verify::fetch::Fetcher>>,
}
impl DeferredFetcher {
pub fn set(&self, target: Arc<dyn adk_awp::verify::fetch::Fetcher>) -> bool {
self.target.set(target).is_ok()
}
}
#[async_trait]
impl adk_awp::verify::fetch::Fetcher for DeferredFetcher {
async fn get(
&self,
url: &str,
headers: &axum::http::HeaderMap,
) -> std::result::Result<adk_awp::verify::fetch::Fetched, adk_awp::verify::fetch::FetchError>
{
match self.target.get() {
Some(target) => target.get(url, headers).await,
None => Err(adk_awp::verify::fetch::FetchError {
url: url.to_string(),
reason: "the site's edge is not serving yet".into(),
}),
}
}
}
#[derive(Debug, Default)]
pub struct EdgeLiveStore {
values: RwLock<BTreeMap<ContentId, BTreeMap<String, LiveValue>>>,
}
#[async_trait]
impl LiveStore for EdgeLiveStore {
async fn set(
&self,
id: &ContentId,
values: BTreeMap<String, LiveValue>,
) -> adk_site::Result<()> {
self.values.write().await.entry(id.clone()).or_default().extend(values);
Ok(())
}
async fn get(&self, id: &ContentId) -> adk_site::Result<BTreeMap<String, LiveValue>> {
Ok(self.values.read().await.get(id).cloned().unwrap_or_default())
}
}
pub struct ReceiptEntrySigner {
signer: Arc<dyn DocumentSigner>,
}
impl ReceiptEntrySigner {
pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
Self { signer }
}
}
#[async_trait]
impl adk_site::stream::EntrySigner for ReceiptEntrySigner {
fn kid(&self) -> &str {
self.signer.kid()
}
fn public_key(&self) -> PublicKeyJwk {
self.signer.public_key()
}
async fn sign(&self, message: &[u8]) -> adk_site::Result<Vec<u8>> {
self.signer.sign(message).await.map_err(|e| adk_site::SiteError::Pipeline(e.to_string()))
}
}
pub struct ReceiptKey {
signer: Arc<dyn DocumentSigner>,
}
impl ReceiptKey {
pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
Self { signer }
}
}
fn receipt_error(code: &'static str, error: impl std::fmt::Display) -> AdkError {
AdkError::new(
adk_core::ErrorComponent::Tool,
adk_core::ErrorCategory::Unauthorized,
code,
format!("the receipt's signature: {error}"),
)
}
#[async_trait]
impl adk_payments::wallet::ReceiptSigner for ReceiptKey {
async fn sign(&self, document: &Value) -> Result<awp_types::Proof> {
adk_awp::signing::jws::sign(document, self.signer.as_ref())
.await
.map_err(|error| receipt_error("website.receipt.unsigned", error))
}
}
#[async_trait]
impl adk_payments::wallet::ReceiptVerifier for ReceiptKey {
async fn verify(&self, document: &Value, proof: &awp_types::Proof) -> Result<()> {
adk_awp::signing::jws::verify(document, proof, &self.signer.public_key())
.map_err(|error| receipt_error("website.receipt.invalid", error))
}
}