1use std::collections::BTreeMap;
18use std::sync::{Arc, OnceLock};
19
20use adk_awp::signing::jws::DocumentSigner;
21use adk_awp::v2::store::{ConsentRecord, LeadStore};
22use adk_core::{AdkError, Result};
23use adk_harness::website::{SIGNAL_FIELD_MAX_CHARS, screen_bounded};
24use adk_kernel::charter::SignalSink;
25use adk_server::awp::{EdgeEvents, SignalEmitter, SiteHit, SiteSearch, SubjectData, ThreadSink};
26use adk_site::live::{LiveStore, LiveValue};
27use adk_site::pipeline::{Announcement, Announcer};
28use async_trait::async_trait;
29use awp_types::{Bounded, ContentId, PublicKeyJwk, Signal, SignalKind, ThreadRef};
30use serde_json::{Value, json};
31use tokio::sync::RwLock;
32use tracing::Instrument as _;
33use uuid::Uuid;
34
35use super::handlers::ContactBook;
36
37async fn screened(text: &Bounded) -> Bounded {
38 screen_bounded(text.as_str(), SIGNAL_FIELD_MAX_CHARS).await
39}
40
41pub struct KernelSignals {
46 sink: std::sync::RwLock<SignalSink>,
47}
48
49impl KernelSignals {
50 pub fn new(sink: SignalSink) -> Self {
52 Self { sink: std::sync::RwLock::new(sink) }
53 }
54
55 pub fn attach(&self, sink: SignalSink) {
60 *self.sink.write().unwrap_or_else(std::sync::PoisonError::into_inner) = sink;
61 }
62}
63
64#[async_trait]
65impl SignalEmitter for KernelSignals {
66 async fn emit(&self, signal: Signal) -> Result<()> {
67 let span = tracing::info_span!(
68 crate::observability::spans::KERNEL_SIGNAL,
69 signal.kind = signal.kind.name(),
70 signal.id = %signal.id,
71 signal.emitted_by = %signal.emitted_by,
72 );
73 self.file(signal).instrument(span).await
74 }
75}
76
77impl KernelSignals {
78 async fn file(&self, mut signal: Signal) -> Result<()> {
79 match &mut signal.kind {
80 SignalKind::LeadCaptured { answers, .. } => {
81 for value in answers.values_mut() {
82 *value = screened(value).await;
83 }
84 }
85 SignalKind::ContentGap { topic, samples, .. } => {
86 *topic = screened(topic).await;
87 for sample in samples.iter_mut() {
88 *sample = screened(sample).await;
89 }
90 }
91 SignalKind::ReviewSeen { excerpt, .. } => *excerpt = screened(excerpt).await,
92 _ => {}
93 }
94 let sink = self.sink.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone();
95 sink.emit(signal).await.map(|_| ()).map_err(|e| AdkError::config(e.to_string()))
96 }
97}
98
99pub struct ReleaseSearch {
101 index: Arc<adk_harness::website::SiteSearch>,
102}
103
104impl ReleaseSearch {
105 pub fn new(index: Arc<adk_harness::website::SiteSearch>) -> Self {
107 Self { index }
108 }
109}
110
111#[async_trait]
112impl SiteSearch for ReleaseSearch {
113 async fn search(&self, query: &str, limit: usize) -> Result<Vec<SiteHit>> {
114 Ok(self
115 .index
116 .search(query, limit)
117 .into_iter()
118 .map(|hit| SiteHit { path: hit.url, title: hit.title, snippet: hit.snippet })
119 .collect())
120 }
121}
122
123pub struct InboxThreads {
125 reply: Arc<adk_drivers::ReplyInThread>,
126 template: String,
127}
128
129impl InboxThreads {
130 pub fn new(reply: Arc<adk_drivers::ReplyInThread>, template: impl Into<String>) -> Self {
133 Self { reply, template: template.into() }
134 }
135}
136
137#[async_trait]
138impl ThreadSink for InboxThreads {
139 async fn reply(&self, thread: &ThreadRef, text: &str) -> Result<()> {
140 let fields = BTreeMap::from([("body".to_string(), text.to_string())]);
141 self.reply
142 .reply(&thread.0, &self.template, &fields)
143 .await
144 .map(|_| ())
145 .map_err(|e| AdkError::config(e.to_string()))
146 }
147}
148
149pub struct SiteSubjectData {
152 leads: Arc<dyn LeadStore>,
153 contacts: Arc<dyn ContactBook>,
154}
155
156impl SiteSubjectData {
157 pub fn new(leads: Arc<dyn LeadStore>, contacts: Arc<dyn ContactBook>) -> Self {
159 Self { leads, contacts }
160 }
161}
162
163fn receipt_ids(receipts: &[ConsentRecord]) -> Vec<Uuid> {
164 receipts.iter().map(|record| record.receipt.id).collect()
165}
166
167#[async_trait]
168impl SubjectData for SiteSubjectData {
169 async fn export(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<Value> {
170 let ids = receipt_ids(receipts);
171 let leads: Vec<Value> = self
172 .leads
173 .since(chrono::DateTime::<chrono::Utc>::MIN_UTC)
174 .await
175 .map_err(|e| AdkError::config(e.to_string()))?
176 .into_iter()
177 .filter(|lead| lead.consent.iter().any(|r| ids.contains(&r.0)))
178 .map(|lead| json!(lead))
179 .collect();
180 let contacts = self.contacts.by_receipts(&ids).await?;
181 Ok(json!({ "leads": leads, "contacts": contacts }))
182 }
183
184 async fn erase(&self, _subject: &str, receipts: &[ConsentRecord]) -> Result<usize> {
185 self.contacts.erase(&receipt_ids(receipts)).await
187 }
188}
189
190pub struct EdgeAnnouncer {
192 events: EdgeEvents,
193}
194
195impl EdgeAnnouncer {
196 pub fn new(events: EdgeEvents) -> Self {
198 Self { events }
199 }
200}
201
202#[async_trait]
203impl Announcer for EdgeAnnouncer {
204 async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
205 let fail = |e: adk_awp::v2::store::StoreError| adk_site::SiteError::Pipeline(e.to_string());
206 self.events.release_published(announcement.release.clone()).await.map_err(fail)?;
207 if let Some(catalog) = &announcement.catalog {
208 self.events
209 .announce_catalog(catalog.clone(), announcement.catalog_pages.clone())
210 .await
211 .map_err(fail)?;
212 }
213 Ok(())
214 }
215}
216
217#[derive(Default)]
232pub struct DeferredAnnouncer {
233 target: OnceLock<Arc<dyn Announcer>>,
234}
235
236impl DeferredAnnouncer {
237 pub fn set(&self, target: Arc<dyn Announcer>) -> bool {
239 self.target.set(target).is_ok()
240 }
241
242 pub fn is_set(&self) -> bool {
244 self.target.get().is_some()
245 }
246}
247
248#[async_trait]
249impl Announcer for DeferredAnnouncer {
250 async fn announce(&self, announcement: &Announcement) -> adk_site::Result<()> {
251 match self.target.get() {
252 Some(target) => target.announce(announcement).await,
253 None => {
254 tracing::debug!(
255 release = announcement.release.seq,
256 "no edge yet; release not announced"
257 );
258 Ok(())
259 }
260 }
261 }
262}
263
264#[derive(Default)]
282pub struct DeferredFetcher {
283 target: OnceLock<Arc<dyn adk_awp::verify::fetch::Fetcher>>,
284}
285
286impl DeferredFetcher {
287 pub fn set(&self, target: Arc<dyn adk_awp::verify::fetch::Fetcher>) -> bool {
289 self.target.set(target).is_ok()
290 }
291}
292
293#[async_trait]
294impl adk_awp::verify::fetch::Fetcher for DeferredFetcher {
295 async fn get(
296 &self,
297 url: &str,
298 headers: &axum::http::HeaderMap,
299 ) -> std::result::Result<adk_awp::verify::fetch::Fetched, adk_awp::verify::fetch::FetchError>
300 {
301 match self.target.get() {
302 Some(target) => target.get(url, headers).await,
303 None => Err(adk_awp::verify::fetch::FetchError {
304 url: url.to_string(),
305 reason: "the site's edge is not serving yet".into(),
306 }),
307 }
308 }
309}
310
311#[derive(Debug, Default)]
314pub struct EdgeLiveStore {
315 values: RwLock<BTreeMap<ContentId, BTreeMap<String, LiveValue>>>,
316}
317
318#[async_trait]
319impl LiveStore for EdgeLiveStore {
320 async fn set(
321 &self,
322 id: &ContentId,
323 values: BTreeMap<String, LiveValue>,
324 ) -> adk_site::Result<()> {
325 self.values.write().await.entry(id.clone()).or_default().extend(values);
326 Ok(())
327 }
328
329 async fn get(&self, id: &ContentId) -> adk_site::Result<BTreeMap<String, LiveValue>> {
330 Ok(self.values.read().await.get(id).cloned().unwrap_or_default())
331 }
332}
333
334pub struct ReceiptEntrySigner {
336 signer: Arc<dyn DocumentSigner>,
337}
338
339impl ReceiptEntrySigner {
340 pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
342 Self { signer }
343 }
344}
345
346#[async_trait]
347impl adk_site::stream::EntrySigner for ReceiptEntrySigner {
348 fn kid(&self) -> &str {
349 self.signer.kid()
350 }
351
352 fn public_key(&self) -> PublicKeyJwk {
353 self.signer.public_key()
354 }
355
356 async fn sign(&self, message: &[u8]) -> adk_site::Result<Vec<u8>> {
357 self.signer.sign(message).await.map_err(|e| adk_site::SiteError::Pipeline(e.to_string()))
358 }
359}
360
361pub struct ReceiptKey {
383 signer: Arc<dyn DocumentSigner>,
384}
385
386impl ReceiptKey {
387 pub fn new(signer: Arc<dyn DocumentSigner>) -> Self {
389 Self { signer }
390 }
391}
392
393fn receipt_error(code: &'static str, error: impl std::fmt::Display) -> AdkError {
394 AdkError::new(
395 adk_core::ErrorComponent::Tool,
396 adk_core::ErrorCategory::Unauthorized,
397 code,
398 format!("the receipt's signature: {error}"),
399 )
400}
401
402#[async_trait]
403impl adk_payments::wallet::ReceiptSigner for ReceiptKey {
404 async fn sign(&self, document: &Value) -> Result<awp_types::Proof> {
405 adk_awp::signing::jws::sign(document, self.signer.as_ref())
406 .await
407 .map_err(|error| receipt_error("website.receipt.unsigned", error))
408 }
409}
410
411#[async_trait]
412impl adk_payments::wallet::ReceiptVerifier for ReceiptKey {
413 async fn verify(&self, document: &Value, proof: &awp_types::Proof) -> Result<()> {
414 adk_awp::signing::jws::verify(document, proof, &self.signer.public_key())
415 .map_err(|error| receipt_error("website.receipt.invalid", error))
416 }
417}