Skip to main content

adk_server/awp/
events.rs

1//! Events: Standard Webhooks subscriptions, delivery with retries and suspension, replay and
2//! coalesced catalogue changes (spec 3.5 §7.5, §7.8.3; AWP 2.0 §9).
3//!
4//! | Route | Does |
5//! |---|---|
6//! | `POST /awp/v2/events` | Creates a subscription owned by the caller; answers `201` with its signing secret, once |
7//! | `GET`, `PATCH`, `DELETE /awp/v2/events/{id}` | Reads, changes (types, URL, reactivation) or ends the caller's subscription |
8//! | `POST /awp/v2/events/replay` | Redelivers retained events under their original ids; answers `202` with `{accepted}` |
9//! | `GET /awp/v2/events/changes/{seq}/{page}` | Further item ids of release `seq`'s `catalog.changed`, from page 2 |
10//!
11//! Subscription routes need tier `known` or above through Web Bot Auth or OAuth; a
12//! subscription belongs to the requester that created it. Delivery URLs must be `https` and
13//! public: the edge refuses loopback, private and link-local addresses when it registers a URL
14//! and when it connects. An edge whose delivery client cannot be built with that check does
15//! not build.
16//!
17//! Each delivery is a Standard Webhooks message — `webhook-id` (the event id),
18//! `webhook-timestamp`, `webhook-signature` — with `AWP-Version: 2.0`. A failed delivery is
19//! retried after 1 s, 5 s, 30 s, 5 min, 30 min and 2 h with jitter; six consecutive failures
20//! suspend the subscription, which receives one final `subscription.suspended`. Events are
21//! retained 72 hours for replay. A release's `catalog.changed` carries at most 1,000 item ids
22//! and a `next` URL for the rest.
23//!
24//! An [`EventLog`] that keeps catalogue pages, the consent-reference index and pending
25//! deliveries — the SQLite, PostgreSQL and Redis edge stores do — makes them survive a
26//! restart: a retry the process was waiting on is resumed by
27//! [`AwpEdge::spawn_delivery_resumer`](super::AwpEdge::spawn_delivery_resumer) once its lease
28//! passes. A log that keeps none leaves them in the process, as before.
29
30use std::collections::{BTreeMap, BTreeSet, HashMap};
31use std::sync::{Arc, Mutex};
32use std::time::Duration;
33
34use adk_awp::v2::response::awp_json;
35use adk_awp::v2::store::{
36    StoreError, StoreResult, SubscriptionRecord, SubscriptionStore, SubscriptionUpdate,
37};
38use adk_core::egress::{EgressPolicy, GuardedClient};
39use adk_core::webhook::{WebhookSecret, WebhookSigner};
40use async_trait::async_trait;
41use awp_types::{
42    CatalogChanged, CatalogChangesPage, ContentId, ErrorBody, ErrorCode, EventCatalog,
43    EventEnvelope, EventSubscription, EventType, IdentityMethod, OrderUpdated, ReleasePublished,
44    RequesterId, StatusChanged, SubscriptionState, SubscriptionSuspended, TrustTier,
45};
46use axum::extract::{Path, State};
47use axum::http::{HeaderValue, StatusCode, header};
48use axum::response::{IntoResponse, Response};
49use axum::routing::{get, post};
50use axum::{Extension, Json, Router};
51use chrono::{DateTime, Utc};
52use serde::Deserialize;
53use serde_json::{Value, json};
54
55use super::tiers::EdgeCaller;
56
57/// The subscription routes' base path.
58pub const EVENTS_PATH: &str = "/awp/v2/events";
59/// The longest delivery body, 64 KiB (AWP 2.0 §9.3).
60pub const MAX_EVENT_BODY: usize = 64 * 1024;
61
62/// How the edge delivers and retains events (spec 3.5 §7.5).
63#[derive(Debug, Clone)]
64#[non_exhaustive]
65pub struct EventsConfig {
66    /// The event types the site emits, listed in its contract.
67    pub catalog: EventCatalog,
68    /// The waits before each retry of a failed delivery.
69    pub retry_schedule: Vec<Duration>,
70    /// How long events are kept for replay.
71    pub retention: chrono::Duration,
72    /// Which delivery URLs the edge may reach.
73    pub egress: EgressPolicy,
74    /// The bound on one delivery attempt.
75    pub attempt_timeout: Duration,
76    /// How long a delivery's next attempt stays its process's before a resumer may take it
77    /// from a durable [`EventLog`].
78    pub delivery_lease: Duration,
79}
80
81impl Default for EventsConfig {
82    /// The six AWP 2.0 event types; retries after 1 s, 5 s, 30 s, 5 min, 30 min and 2 h;
83    /// 72 hours' retention; public `https` URLs only; ten seconds per attempt; a 70-second
84    /// delivery lease.
85    fn default() -> Self {
86        Self {
87            catalog: EventCatalog(vec![
88                EventType::SiteReleasePublished,
89                EventType::SiteStatusChanged,
90                EventType::CatalogChanged,
91                EventType::OrderUpdated,
92                EventType::ConsentRevoked,
93                EventType::SubscriptionSuspended,
94            ]),
95            retry_schedule: [1, 5, 30, 300, 1_800, 7_200].map(Duration::from_secs).to_vec(),
96            retention: chrono::Duration::hours(72),
97            egress: EgressPolicy::default(),
98            attempt_timeout: Duration::from_secs(10),
99            delivery_lease: Duration::from_secs(70),
100        }
101    }
102}
103
104impl EventsConfig {
105    /// Sets the event catalogue.
106    #[must_use]
107    pub fn catalog(mut self, catalog: EventCatalog) -> Self {
108        self.catalog = catalog;
109        self
110    }
111
112    /// Sets the retry waits.
113    #[must_use]
114    pub fn retry_schedule(mut self, schedule: Vec<Duration>) -> Self {
115        self.retry_schedule = schedule;
116        self
117    }
118
119    /// Sets the egress policy; [`EgressPolicy::allow_private_networks`] only where every
120    /// subscriber is trusted, such as in tests.
121    #[must_use]
122    pub fn egress(mut self, egress: EgressPolicy) -> Self {
123        self.egress = egress;
124        self
125    }
126}
127
128/// An event kept for replay and who may receive it (spec 3.5 §7.5).
129#[derive(Debug, Clone, PartialEq)]
130pub struct RetainedEvent {
131    /// The event.
132    pub event: EventEnvelope,
133    /// The requesters whose subscriptions receive it; `None` for every subscription naming
134    /// its type.
135    pub audience: Option<BTreeSet<RequesterId>>,
136}
137
138/// A delivery waiting for its next attempt, kept so a restart resumes it (spec 3.5 §7.5).
139#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
140#[serde(rename_all = "camelCase")]
141pub struct PendingDelivery {
142    /// The subscription it goes to.
143    pub subscription: String,
144    /// The retained event it carries.
145    pub event_id: String,
146    /// The failed attempts so far.
147    pub failures: u32,
148    /// When it is due if nobody holds it: the next attempt's time plus a lease, so a live
149    /// process finishes its own retries and a restart resumes the ones a stopped process left.
150    pub due: DateTime<Utc>,
151}
152
153/// Events retained for replay, and what their delivery needs across a restart (spec 3.5
154/// §7.5, §7.8.3, §7.9).
155///
156/// [`append`](Self::append), [`between`](Self::between) and
157/// [`purge_before`](Self::purge_before) are required. The provided methods keep nothing: the
158/// edge then holds catalogue pages and consent references in the process, and retries last
159/// as long as it does. A durable log overrides them;
160/// [`edge_log_conformance_tests!`](crate::edge_log_conformance_tests) checks every method.
161#[async_trait]
162pub trait EventLog: Send + Sync {
163    /// Retains `event`.
164    async fn append(&self, event: RetainedEvent) -> StoreResult<()>;
165
166    /// The events at or after `since` and before `until`, oldest first.
167    async fn between(
168        &self,
169        since: DateTime<Utc>,
170        until: Option<DateTime<Utc>>,
171    ) -> StoreResult<Vec<RetainedEvent>>;
172
173    /// Drops the events, and the catalogue pages, kept before `cutoff`; returns how many
174    /// events.
175    async fn purge_before(&self, cutoff: DateTime<Utc>) -> StoreResult<usize>;
176
177    /// The retained event `id`.
178    ///
179    /// The provided method scans [`between`](Self::between); a durable log looks it up.
180    async fn event(&self, id: &str) -> StoreResult<Option<RetainedEvent>> {
181        Ok(self
182            .between(DateTime::<Utc>::MIN_UTC, None)
183            .await?
184            .into_iter()
185            .find(|retained| retained.event.id == id))
186    }
187
188    /// Keeps the further pages of release `seq`'s `catalog.changed`, page 2 first, stored at
189    /// `at`; returns whether the log keeps them. The provided method keeps none.
190    async fn put_catalog_pages(
191        &self,
192        seq: u64,
193        at: DateTime<Utc>,
194        pages: &[CatalogChangesPage],
195    ) -> StoreResult<bool> {
196        let _ = (seq, at, pages);
197        Ok(false)
198    }
199
200    /// Page `page` (from 2) of release `seq`'s changed items.
201    async fn catalog_page(&self, seq: u64, page: usize) -> StoreResult<Option<CatalogChangesPage>> {
202        let _ = (seq, page);
203        Ok(None)
204    }
205
206    /// Notes that `requester` referenced consent receipt `receipt`, so `consent.revoked`
207    /// reaches it (AWP 2.0 §9.2); returns whether the log keeps the note. The provided
208    /// method keeps none.
209    async fn note_consent_reference(
210        &self,
211        receipt: uuid::Uuid,
212        requester: &RequesterId,
213    ) -> StoreResult<bool> {
214        let _ = (receipt, requester);
215        Ok(false)
216    }
217
218    /// The requesters that referenced consent receipt `receipt`.
219    async fn consent_references(&self, receipt: uuid::Uuid) -> StoreResult<BTreeSet<RequesterId>> {
220        let _ = receipt;
221        Ok(BTreeSet::new())
222    }
223
224    /// Keeps `delivery`, replacing the one for the same subscription and event. The provided
225    /// method keeps none.
226    async fn save_delivery(&self, delivery: &PendingDelivery) -> StoreResult<()> {
227        let _ = delivery;
228        Ok(())
229    }
230
231    /// Takes the deliveries due at `now`, atomically: each is returned to one caller with its
232    /// `due` moved to `now + lease`, so no other caller takes it while this one delivers.
233    async fn claim_deliveries(
234        &self,
235        now: DateTime<Utc>,
236        lease: chrono::Duration,
237    ) -> StoreResult<Vec<PendingDelivery>> {
238        let _ = (now, lease);
239        Ok(Vec::new())
240    }
241
242    /// Forgets the delivery of `event_id` to `subscription`: it succeeded or ended.
243    async fn finish_delivery(&self, subscription: &str, event_id: &str) -> StoreResult<()> {
244        let _ = (subscription, event_id);
245        Ok(())
246    }
247}
248
249/// An in-memory [`EventLog`]: what it keeps lasts the process.
250#[derive(Debug, Clone, Default)]
251pub struct InMemoryEventLog {
252    events: Arc<Mutex<Vec<RetainedEvent>>>,
253    pages: Arc<Mutex<CatalogPages>>,
254    references: Arc<Mutex<HashMap<uuid::Uuid, BTreeSet<RequesterId>>>>,
255    deliveries: Arc<Mutex<BTreeMap<(String, String), PendingDelivery>>>,
256}
257
258fn locked<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
259    mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
260}
261
262impl InMemoryEventLog {
263    /// An empty log.
264    pub fn new() -> Self {
265        Self::default()
266    }
267}
268
269#[async_trait]
270impl EventLog for InMemoryEventLog {
271    async fn append(&self, event: RetainedEvent) -> StoreResult<()> {
272        self.events.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(event);
273        Ok(())
274    }
275
276    async fn between(
277        &self,
278        since: DateTime<Utc>,
279        until: Option<DateTime<Utc>>,
280    ) -> StoreResult<Vec<RetainedEvent>> {
281        let mut found: Vec<RetainedEvent> = locked(&self.events)
282            .iter()
283            .filter(|retained| {
284                retained.event.timestamp >= since
285                    && until.is_none_or(|until| retained.event.timestamp < until)
286            })
287            .cloned()
288            .collect();
289        found.sort_by(|a, b| {
290            (a.event.timestamp, &a.event.id).cmp(&(b.event.timestamp, &b.event.id))
291        });
292        Ok(found)
293    }
294
295    async fn purge_before(&self, cutoff: DateTime<Utc>) -> StoreResult<usize> {
296        locked(&self.pages).retain(|_, (at, _)| *at >= cutoff);
297        let mut events = locked(&self.events);
298        let before = events.len();
299        events.retain(|retained| retained.event.timestamp >= cutoff);
300        Ok(before - events.len())
301    }
302
303    async fn event(&self, id: &str) -> StoreResult<Option<RetainedEvent>> {
304        Ok(locked(&self.events).iter().find(|retained| retained.event.id == id).cloned())
305    }
306
307    async fn put_catalog_pages(
308        &self,
309        seq: u64,
310        at: DateTime<Utc>,
311        pages: &[CatalogChangesPage],
312    ) -> StoreResult<bool> {
313        let mut stored = locked(&self.pages);
314        for (index, page) in pages.iter().enumerate() {
315            stored.insert((seq, index + 2), (at, page.clone()));
316        }
317        Ok(true)
318    }
319
320    async fn catalog_page(&self, seq: u64, page: usize) -> StoreResult<Option<CatalogChangesPage>> {
321        Ok(locked(&self.pages).get(&(seq, page)).map(|(_, page)| page.clone()))
322    }
323
324    async fn note_consent_reference(
325        &self,
326        receipt: uuid::Uuid,
327        requester: &RequesterId,
328    ) -> StoreResult<bool> {
329        locked(&self.references).entry(receipt).or_default().insert(requester.clone());
330        Ok(true)
331    }
332
333    async fn consent_references(&self, receipt: uuid::Uuid) -> StoreResult<BTreeSet<RequesterId>> {
334        Ok(locked(&self.references).get(&receipt).cloned().unwrap_or_default())
335    }
336
337    async fn save_delivery(&self, delivery: &PendingDelivery) -> StoreResult<()> {
338        locked(&self.deliveries)
339            .insert((delivery.subscription.clone(), delivery.event_id.clone()), delivery.clone());
340        Ok(())
341    }
342
343    async fn claim_deliveries(
344        &self,
345        now: DateTime<Utc>,
346        lease: chrono::Duration,
347    ) -> StoreResult<Vec<PendingDelivery>> {
348        let mut claimed = Vec::new();
349        for delivery in locked(&self.deliveries).values_mut().filter(|d| d.due <= now) {
350            delivery.due = now + lease;
351            claimed.push(delivery.clone());
352        }
353        Ok(claimed)
354    }
355
356    async fn finish_delivery(&self, subscription: &str, event_id: &str) -> StoreResult<()> {
357        locked(&self.deliveries).remove(&(subscription.to_owned(), event_id.to_owned()));
358        Ok(())
359    }
360}
361
362/// Who referenced which consent receipt, so `consent.revoked` reaches them (AWP 2.0 §9.2):
363/// in the event log when it keeps them, else in the process.
364#[derive(Clone)]
365pub(crate) struct ConsentReferences {
366    log: Arc<dyn EventLog>,
367    by_receipt: Arc<Mutex<HashMap<uuid::Uuid, BTreeSet<RequesterId>>>>,
368}
369
370impl ConsentReferences {
371    pub(crate) async fn note(&self, receipts: &[uuid::Uuid], requester: &RequesterId) {
372        for receipt in receipts {
373            match self.log.note_consent_reference(*receipt, requester).await {
374                Ok(true) => {}
375                Ok(false) => {
376                    locked(&self.by_receipt).entry(*receipt).or_default().insert(requester.clone());
377                }
378                Err(error) => {
379                    tracing::warn!(error = %error, "awp consent reference kept in the process only");
380                    locked(&self.by_receipt).entry(*receipt).or_default().insert(requester.clone());
381                }
382            }
383        }
384    }
385
386    pub(crate) async fn of(&self, receipt: uuid::Uuid) -> BTreeSet<RequesterId> {
387        let mut found = locked(&self.by_receipt).get(&receipt).cloned().unwrap_or_default();
388        match self.log.consent_references(receipt).await {
389            Ok(kept) => found.extend(kept),
390            Err(error) => tracing::warn!(error = %error, "awp consent references not read"),
391        }
392        found
393    }
394}
395
396/// The further pages of each release's `catalog.changed`, by release and page, with when
397/// they were stored.
398type CatalogPages = HashMap<(u64, usize), (DateTime<Utc>, CatalogChangesPage)>;
399
400struct Inner {
401    subscriptions: Arc<dyn SubscriptionStore>,
402    log: Arc<dyn EventLog>,
403    config: EventsConfig,
404    client: GuardedClient,
405    base_url: String,
406    pages: Mutex<CatalogPages>,
407    references: Arc<Mutex<HashMap<uuid::Uuid, BTreeSet<RequesterId>>>>,
408    last_purge: Mutex<DateTime<Utc>>,
409}
410
411/// The edge's event publisher (spec 3.5 §7.5). Cheap to clone.
412///
413/// The edge publishes `site.status.changed` and `consent.revoked` itself; the site's release
414/// pipeline publishes releases and catalogue changes, and its commerce capabilities publish
415/// order updates, through this handle ([`AwpEdge::events`](super::AwpEdge::events)).
416#[derive(Clone)]
417pub struct EdgeEvents {
418    inner: Arc<Inner>,
419}
420
421impl std::fmt::Debug for EdgeEvents {
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        f.debug_struct("EdgeEvents").field("catalog", &self.inner.config.catalog).finish()
424    }
425}
426
427fn jittered(wait: Duration) -> Duration {
428    // ±20 %, from a fresh random value.
429    let permille = (uuid::Uuid::new_v4().as_u128() % 401) as u32 + 800;
430    wait * permille / 1_000
431}
432
433impl EdgeEvents {
434    /// The edge's events over `subscriptions` and `log`.
435    ///
436    /// # Errors
437    ///
438    /// `awp.events.client_unavailable` when the delivery client cannot be built; a default
439    /// client in its place would skip the egress check.
440    pub(crate) fn new(
441        subscriptions: Arc<dyn SubscriptionStore>,
442        log: Arc<dyn EventLog>,
443        config: EventsConfig,
444        base_url: &str,
445    ) -> adk_core::Result<Self> {
446        let client = GuardedClient::builder(config.egress.clone())
447            .timeout(config.attempt_timeout)
448            .redirects(0)
449            .user_agent(concat!("adk-awp-edge/", env!("CARGO_PKG_VERSION")))
450            .build()
451            .map_err(|error| {
452                adk_core::AdkError::new(
453                    adk_core::ErrorComponent::Server,
454                    adk_core::ErrorCategory::Internal,
455                    "awp.events.client_unavailable",
456                    format!("AWP event delivery is unavailable: {error}"),
457                )
458            })?;
459        Ok(Self {
460            inner: Arc::new(Inner {
461                subscriptions,
462                log,
463                config,
464                client,
465                base_url: base_url.trim_end_matches('/').to_owned(),
466                pages: Mutex::new(HashMap::new()),
467                references: Arc::default(),
468                last_purge: Mutex::new(Utc::now()),
469            }),
470        })
471    }
472
473    /// The consent-reference index, kept beside the events.
474    pub(crate) fn references(&self) -> ConsentReferences {
475        ConsentReferences {
476            log: Arc::clone(&self.inner.log),
477            by_receipt: Arc::clone(&self.inner.references),
478        }
479    }
480
481    /// The catalogue the edge emits.
482    pub fn catalog(&self) -> &EventCatalog {
483        &self.inner.config.catalog
484    }
485
486    /// The retained events published at or after `since` and before `until`, oldest first,
487    /// each with its audience (spec 3.5 §7.5): the site's own read of what its edge
488    /// announced, for the back office and the owner's views. Subscribers read events through
489    /// their subscriptions and replay; the edge serves no route for this read.
490    ///
491    /// # Example
492    ///
493    /// ```rust,ignore
494    /// let day = chrono::Utc::now() - chrono::Duration::days(1);
495    /// for retained in edge.events().retained(day, None).await? {
496    ///     println!("{} {}", retained.event.event_type, retained.event.id);
497    /// }
498    /// ```
499    ///
500    /// # Errors
501    ///
502    /// [`StoreError`] when the event log cannot be read.
503    pub async fn retained(
504        &self,
505        since: DateTime<Utc>,
506        until: Option<DateTime<Utc>>,
507    ) -> StoreResult<Vec<RetainedEvent>> {
508        self.inner.log.between(since, until).await
509    }
510
511    /// Publishes `site.release.published`; returns the event id.
512    ///
513    /// # Errors
514    ///
515    /// [`StoreError`] when the event cannot be retained or the subscriptions read.
516    pub async fn release_published(&self, release: ReleasePublished) -> StoreResult<String> {
517        self.emit(EventType::SiteReleasePublished, json_of(&release), None).await
518    }
519
520    /// Publishes one `catalog.changed` for a release's changed items: the first 1,000 ids, the
521    /// total, and a `next` URL, `/awp/v2/events/changes/{seq}/2`, for the rest (spec 3.5
522    /// §7.8.3). Returns the event id.
523    ///
524    /// # Errors
525    ///
526    /// [`StoreError`] when the event cannot be retained or the subscriptions read.
527    pub async fn catalog_changed(
528        &self,
529        release_seq: u64,
530        items: Vec<ContentId>,
531    ) -> StoreResult<String> {
532        let chunks: Vec<&[ContentId]> = items.chunks(CatalogChanged::PAGE_SIZE).collect();
533        let url = |page: usize| (page <= chunks.len()).then(|| self.changes_url(release_seq, page));
534        let catalog = CatalogChanged {
535            release_seq,
536            items: chunks.first().map(|chunk| chunk.to_vec()).unwrap_or_default(),
537            total: items.len() as u64,
538            next: url(2),
539        };
540        let pages = chunks
541            .iter()
542            .enumerate()
543            .skip(1)
544            .map(|(index, chunk)| CatalogChangesPage {
545                items: chunk.to_vec(),
546                next: url(index + 2),
547            })
548            .collect();
549        self.announce_catalog(catalog, pages).await
550    }
551
552    /// Publishes a release's `catalog.changed` as the site pipeline built it, and serves its
553    /// further pages, page 2 onwards, at `/awp/v2/events/changes/{seq}/{page}` (spec 3.5
554    /// §7.8.3): the edge half of `adk-site`'s `Announcement`. Returns the event id.
555    ///
556    /// # Errors
557    ///
558    /// [`StoreError`] when the event cannot be retained or the subscriptions read.
559    pub async fn announce_catalog(
560        &self,
561        catalog: CatalogChanged,
562        pages: Vec<CatalogChangesPage>,
563    ) -> StoreResult<String> {
564        let now = Utc::now();
565        let kept = match self.inner.log.put_catalog_pages(catalog.release_seq, now, &pages).await {
566            Ok(kept) => kept,
567            Err(error) => {
568                tracing::warn!(error = %error, "awp catalogue pages kept in the process only");
569                false
570            }
571        };
572        if !kept {
573            let mut stored = locked(&self.inner.pages);
574            for (index, page) in pages.into_iter().enumerate() {
575                stored.insert((catalog.release_seq, index + 2), (now, page));
576            }
577        }
578        self.emit(EventType::CatalogChanged, json_of(&catalog), None).await
579    }
580
581    /// The URL of page `page` of release `seq`'s changed items.
582    pub fn changes_url(&self, seq: u64, page: usize) -> String {
583        format!("{}{EVENTS_PATH}/changes/{seq}/{page}", self.inner.base_url)
584    }
585
586    /// Publishes `order.updated` to the subscriptions of `requester`, the requester that
587    /// placed the order. Returns the event id.
588    ///
589    /// # Errors
590    ///
591    /// [`StoreError`] when the event cannot be retained or the subscriptions read.
592    pub async fn order_updated(
593        &self,
594        requester: &RequesterId,
595        update: OrderUpdated,
596    ) -> StoreResult<String> {
597        let audience = BTreeSet::from([requester.clone()]);
598        self.emit(EventType::OrderUpdated, json_of(&update), Some(audience)).await
599    }
600
601    pub(crate) async fn status_changed(&self, change: StatusChanged) -> StoreResult<String> {
602        self.emit(EventType::SiteStatusChanged, json_of(&change), None).await
603    }
604
605    pub(crate) async fn consent_revoked(
606        &self,
607        revoked: awp_types::ConsentRevoked,
608        audience: BTreeSet<RequesterId>,
609    ) -> StoreResult<String> {
610        self.emit(EventType::ConsentRevoked, json_of(&revoked), Some(audience)).await
611    }
612
613    /// Publishes an event of `event_type` with `data` to every subscription naming it, or only
614    /// those of `audience`; returns the event id.
615    ///
616    /// # Errors
617    ///
618    /// [`StoreError`] when the event cannot be retained or the subscriptions read.
619    pub async fn emit(
620        &self,
621        event_type: EventType,
622        data: Value,
623        audience: Option<BTreeSet<RequesterId>>,
624    ) -> StoreResult<String> {
625        self.emit_with_id(new_event_id(), event_type, data, audience).await
626    }
627
628    async fn emit_with_id(
629        &self,
630        id: String,
631        event_type: EventType,
632        data: Value,
633        audience: Option<BTreeSet<RequesterId>>,
634    ) -> StoreResult<String> {
635        self.purge_if_due().await;
636        let event = EventEnvelope::new(id.clone(), event_type.clone(), Utc::now(), data);
637        let retained = RetainedEvent { event, audience };
638        self.inner.log.append(retained.clone()).await?;
639        let targets = self.inner.subscriptions.active_for(&event_type).await?;
640        for record in targets {
641            if admits(&retained, &record.owner) {
642                self.spawn_delivery(record, retained.event.clone(), 0);
643            }
644        }
645        tracing::debug!(event.id = %id, event.kind = %event_type, "awp event published");
646        Ok(id)
647    }
648
649    async fn purge_if_due(&self) {
650        let now = Utc::now();
651        {
652            let mut last =
653                self.inner.last_purge.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
654            if now - *last < chrono::Duration::minutes(10) {
655                return;
656            }
657            *last = now;
658        }
659        let cutoff = now - self.inner.config.retention;
660        if let Err(error) = self.inner.log.purge_before(cutoff).await {
661            tracing::warn!(error = %error, "awp event log purge failed");
662        }
663        self.inner
664            .pages
665            .lock()
666            .unwrap_or_else(std::sync::PoisonError::into_inner)
667            .retain(|_, (at, _)| *at >= cutoff);
668    }
669
670    /// One POST of `event` to `subscription`; `Err` with the reason on failure.
671    async fn post(
672        &self,
673        subscription: &EventSubscription,
674        event: &EventEnvelope,
675    ) -> Result<(), String> {
676        let request = self.inner.client.post(&subscription.url).map_err(|e| e.to_string())?;
677        let secret = subscription
678            .secret
679            .as_deref()
680            .ok_or_else(|| "the subscription has no signing secret".to_owned())
681            .and_then(|secret| {
682                WebhookSecret::from_base64(secret).map_err(|error| error.to_string())
683            })?;
684        let body = serde_json::to_vec(event).map_err(|error| error.to_string())?;
685        if body.len() > MAX_EVENT_BODY {
686            return Err("the event is over 64 KiB".to_owned());
687        }
688        let signed = WebhookSigner::new(secret).sign_now(&event.id, &body);
689        let mut request = request
690            .header(header::CONTENT_TYPE, "application/json")
691            .header("awp-version", "2.0")
692            .body(body);
693        for (name, value) in signed.header_pairs() {
694            request = request.header(name, value);
695        }
696        match request.send().await {
697            Ok(response) if response.status().is_success() => Ok(()),
698            Ok(response) => Err(format!("the endpoint answered {}", response.status().as_u16())),
699            Err(error) => Err(error.without_url().to_string()),
700        }
701    }
702
703    fn spawn_delivery(&self, record: SubscriptionRecord, event: EventEnvelope, failures: u32) {
704        let events = self.clone();
705        tokio::spawn(async move { events.deliver(record, event, failures).await });
706    }
707
708    /// How long a delivery is held by the process attempting it before another may take it.
709    fn lease(&self) -> chrono::Duration {
710        chrono::Duration::from_std(self.inner.config.delivery_lease)
711            .unwrap_or_else(|_| chrono::Duration::seconds(70))
712    }
713
714    /// Keeps the delivery's state in the log, so a restart resumes it.
715    async fn keep(&self, subscription: &str, event: &str, failures: u32, due: DateTime<Utc>) {
716        let delivery = PendingDelivery {
717            subscription: subscription.to_owned(),
718            event_id: event.to_owned(),
719            failures,
720            due,
721        };
722        if let Err(error) = self.inner.log.save_delivery(&delivery).await {
723            tracing::warn!(error = %error, "awp delivery kept in the process only");
724        }
725    }
726
727    async fn finish(&self, subscription: &str, event: &str) {
728        if let Err(error) = self.inner.log.finish_delivery(subscription, event).await {
729            tracing::warn!(error = %error, "awp finished delivery not cleared");
730        }
731    }
732
733    /// Delivers `event` with the retry schedule, after `failures` failed attempts; suspends
734    /// the subscription after six consecutive failures and makes one final
735    /// `subscription.suspended` attempt.
736    async fn deliver(&self, record: SubscriptionRecord, event: EventEnvelope, failures: u32) {
737        let id = record.subscription.id.clone();
738        let mut failures = failures;
739        let mut subscription = record.subscription;
740        self.keep(&id, &event.id, failures, Utc::now() + self.lease()).await;
741        loop {
742            match self.post(&subscription, &event).await {
743                Ok(()) => {
744                    self.finish(&id, &event.id).await;
745                    if let Err(error) = self.inner.subscriptions.record_delivery(&id, true).await {
746                        tracing::warn!(error = %error, "awp delivery outcome not recorded");
747                    }
748                    return;
749                }
750                Err(reason) => {
751                    tracing::debug!(subscription.id = %id, event.id = %event.id, reason = %reason, "awp delivery failed");
752                    let after = match self.inner.subscriptions.record_delivery(&id, false).await {
753                        Ok(after) => after,
754                        Err(error) => {
755                            tracing::warn!(error = %error, "awp delivery outcome not recorded");
756                            return;
757                        }
758                    };
759                    if after.subscription.state == SubscriptionState::Suspended {
760                        tracing::warn!(subscription.id = %id, "awp subscription suspended after six failed deliveries");
761                        let suspended = SubscriptionSuspended {
762                            subscription: id.clone(),
763                            failures: after.subscription.failures,
764                            last_error: Some(reason.chars().take(200).collect()),
765                        };
766                        let notice = EventEnvelope::new(
767                            new_event_id(),
768                            EventType::SubscriptionSuspended,
769                            Utc::now(),
770                            json_of(&suspended),
771                        );
772                        if let Err(reason) = self.post(&after.subscription, &notice).await {
773                            tracing::debug!(reason = %reason, "awp final suspension notice not delivered");
774                        }
775                        self.finish(&id, &event.id).await;
776                        return;
777                    }
778                    subscription = after.subscription;
779                    let schedule = &self.inner.config.retry_schedule;
780                    let Some(wait) = schedule.get(failures as usize).copied() else {
781                        self.finish(&id, &event.id).await;
782                        return;
783                    };
784                    failures += 1;
785                    let wait = jittered(wait);
786                    let wake = Utc::now()
787                        + chrono::Duration::from_std(wait)
788                            .unwrap_or_else(|_| chrono::Duration::zero());
789                    self.keep(&id, &event.id, failures, wake + self.lease()).await;
790                    tokio::time::sleep(wait).await;
791                }
792            }
793        }
794    }
795
796    /// Redelivers the retained events `owner`'s subscription `id` may receive, between
797    /// `since` and `until`, of `types` (default: the subscription's); returns how many.
798    async fn replay(
799        &self,
800        owner: &RequesterId,
801        id: &str,
802        since: DateTime<Utc>,
803        until: Option<DateTime<Utc>>,
804        types: Option<Vec<EventType>>,
805    ) -> StoreResult<usize> {
806        let record = self
807            .inner
808            .subscriptions
809            .get(owner, id)
810            .await?
811            .ok_or_else(|| StoreError::NotFound(format!("subscription {id}")))?;
812        let wanted = types.unwrap_or_else(|| record.subscription.types.clone());
813        let events: Vec<RetainedEvent> = self
814            .inner
815            .log
816            .between(since.max(Utc::now() - self.inner.config.retention), until)
817            .await?
818            .into_iter()
819            .filter(|retained| {
820                record.subscription.types.contains(&retained.event.event_type)
821                    && wanted.contains(&retained.event.event_type)
822                    && admits(retained, owner)
823            })
824            .collect();
825        let accepted = events.len();
826        let events_handle = self.clone();
827        tokio::spawn(async move {
828            for retained in events {
829                events_handle.deliver(record.clone(), retained.event, 0).await;
830            }
831        });
832        Ok(accepted)
833    }
834
835    async fn page(&self, seq: u64, page: usize) -> StoreResult<Option<CatalogChangesPage>> {
836        if let Some((_, found)) = locked(&self.inner.pages).get(&(seq, page)) {
837            return Ok(Some(found.clone()));
838        }
839        self.inner.log.catalog_page(seq, page).await
840    }
841
842    /// Resumes the deliveries a stopped process left: each delivery whose lease passed is
843    /// taken from the log and attempted again where its retries stood, if its subscription
844    /// is still active and its event retained (spec 3.5 §7.5). Returns how many resumed.
845    ///
846    /// [`AwpEdge::spawn_delivery_resumer`](super::AwpEdge::spawn_delivery_resumer) calls it
847    /// on an interval.
848    ///
849    /// # Errors
850    ///
851    /// [`StoreError`] when the log cannot be read.
852    pub async fn resume_deliveries(&self) -> StoreResult<usize> {
853        let mut resumed = 0;
854        for delivery in self.inner.log.claim_deliveries(Utc::now(), self.lease()).await? {
855            let Some(retained) = self.inner.log.event(&delivery.event_id).await? else {
856                self.finish(&delivery.subscription, &delivery.event_id).await;
857                continue;
858            };
859            let record = self
860                .inner
861                .subscriptions
862                .active_for(&retained.event.event_type)
863                .await?
864                .into_iter()
865                .find(|record| record.subscription.id == delivery.subscription)
866                .filter(|record| admits(&retained, &record.owner));
867            let Some(record) = record else {
868                self.finish(&delivery.subscription, &delivery.event_id).await;
869                continue;
870            };
871            tracing::info!(
872                subscription.id = %delivery.subscription,
873                event.id = %delivery.event_id,
874                failures = delivery.failures,
875                "awp delivery resumed after a restart"
876            );
877            self.spawn_delivery(record, retained.event, delivery.failures);
878            resumed += 1;
879        }
880        Ok(resumed)
881    }
882}
883
884fn admits(retained: &RetainedEvent, owner: &RequesterId) -> bool {
885    retained.audience.as_ref().is_none_or(|audience| audience.contains(owner))
886}
887
888fn json_of<T: serde::Serialize>(value: &T) -> Value {
889    serde_json::to_value(value).unwrap_or(Value::Null)
890}
891
892fn new_event_id() -> String {
893    format!("evt_{}", uuid::Uuid::new_v4().simple())
894}
895
896// --- routes --------------------------------------------------------------------------------
897
898fn refuse(code: ErrorCode, message: &str) -> Response {
899    super::envelope(ErrorBody::new(code, message), None)
900}
901
902/// The subscriber a subscription route serves: `known` or above through Web Bot Auth or OAuth.
903fn subscriber(caller: &EdgeCaller) -> Result<RequesterId, Response> {
904    let Some(requester) = caller.requester.clone().filter(|_| caller.tier >= TrustTier::Known)
905    else {
906        return Err(refuse(
907            ErrorCode::Unauthorized,
908            "subscriptions need a Web Bot Auth signature or an OAuth token",
909        ));
910    };
911    match requester.method() {
912        Some(IdentityMethod::WebBotAuth | IdentityMethod::Oauth2ClientCredentials) => Ok(requester),
913        _ => Err(refuse(
914            ErrorCode::Forbidden,
915            "subscriptions are authenticated by Web Bot Auth or OAuth",
916        )),
917    }
918}
919
920fn caller_of(caller: Option<Extension<EdgeCaller>>) -> EdgeCaller {
921    caller.map_or_else(|| EdgeCaller::public("ip:unknown"), |Extension(caller)| caller)
922}
923
924fn without_secret(mut subscription: EventSubscription) -> EventSubscription {
925    subscription.secret = None;
926    subscription
927}
928
929impl EdgeEvents {
930    fn check_types(&self, types: &[EventType]) -> Result<(), Response> {
931        if types.is_empty() {
932            return Err(refuse(ErrorCode::InvalidRequest, "name at least one event type"));
933        }
934        match types.iter().find(|kind| !self.inner.config.catalog.contains(kind)) {
935            Some(kind) => Err(refuse(
936                ErrorCode::InvalidRequest,
937                &format!("`{kind}` is not in the site's event catalogue"),
938            )),
939            None => Ok(()),
940        }
941    }
942
943    fn check_url(&self, url: &str) -> Result<(), Response> {
944        self.inner
945            .config
946            .egress
947            .check_url(url)
948            .map(|_| ())
949            .map_err(|denial| refuse(ErrorCode::InvalidRequest, &denial.to_string()))
950    }
951
952    pub(crate) fn router(&self) -> Router {
953        Router::new()
954            .route(EVENTS_PATH, post(create))
955            .route(&format!("{EVENTS_PATH}/replay"), post(replay))
956            .route(&format!("{EVENTS_PATH}/changes/{{seq}}/{{page}}"), get(changes))
957            .route(&format!("{EVENTS_PATH}/{{id}}"), get(read).patch(update).delete(remove))
958            .with_state(self.clone())
959    }
960}
961
962#[derive(Deserialize)]
963struct NewSubscription {
964    types: Vec<EventType>,
965    url: String,
966}
967
968fn store_failed(error: &StoreError) -> Response {
969    match error {
970        StoreError::NotFound(_) => refuse(ErrorCode::ResourceNotFound, "no such subscription"),
971        StoreError::Conflict(message) => refuse(ErrorCode::InvalidRequest, message),
972        _ => {
973            tracing::error!(error = %error, "awp subscription store failed");
974            refuse(ErrorCode::InternalError, "the subscription could not be stored")
975        }
976    }
977}
978
979async fn create(
980    State(events): State<EdgeEvents>,
981    caller: Option<Extension<EdgeCaller>>,
982    Json(body): Json<NewSubscription>,
983) -> Response {
984    let owner = match subscriber(&caller_of(caller)) {
985        Ok(owner) => owner,
986        Err(response) => return response,
987    };
988    if let Err(response) =
989        events.check_types(&body.types).and_then(|()| events.check_url(&body.url))
990    {
991        return response;
992    }
993    let mut key = [0_u8; 32];
994    key[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
995    key[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
996    let secret = match WebhookSecret::from_bytes(key.to_vec()) {
997        Ok(secret) => secret.to_whsec(),
998        Err(error) => {
999            tracing::error!(error = %error, "awp subscription secret not generated");
1000            return refuse(ErrorCode::InternalError, "the subscription could not be created");
1001        }
1002    };
1003    let subscription = EventSubscription {
1004        id: format!("sub_{}", uuid::Uuid::new_v4().simple()),
1005        types: body.types,
1006        url: body.url,
1007        state: SubscriptionState::Active,
1008        created_at: Utc::now(),
1009        failures: 0,
1010        secret: Some(secret),
1011    };
1012    let record = SubscriptionRecord { owner, subscription: subscription.clone() };
1013    if let Err(error) = events.inner.subscriptions.create(record).await {
1014        return store_failed(&error);
1015    }
1016    let mut response = awp_json(StatusCode::CREATED, &subscription);
1017    if let Ok(location) = HeaderValue::from_str(&format!("{EVENTS_PATH}/{}", subscription.id)) {
1018        response.headers_mut().insert(header::LOCATION, location);
1019    }
1020    response
1021}
1022
1023async fn read(
1024    State(events): State<EdgeEvents>,
1025    caller: Option<Extension<EdgeCaller>>,
1026    Path(id): Path<String>,
1027) -> Response {
1028    let owner = match subscriber(&caller_of(caller)) {
1029        Ok(owner) => owner,
1030        Err(response) => return response,
1031    };
1032    match events.inner.subscriptions.get(&owner, &id).await {
1033        Ok(Some(record)) => awp_json(StatusCode::OK, &without_secret(record.subscription)),
1034        Ok(None) => refuse(ErrorCode::ResourceNotFound, "no such subscription"),
1035        Err(error) => store_failed(&error),
1036    }
1037}
1038
1039async fn update(
1040    State(events): State<EdgeEvents>,
1041    caller: Option<Extension<EdgeCaller>>,
1042    Path(id): Path<String>,
1043    Json(change): Json<SubscriptionUpdate>,
1044) -> Response {
1045    let owner = match subscriber(&caller_of(caller)) {
1046        Ok(owner) => owner,
1047        Err(response) => return response,
1048    };
1049    if let Some(types) = &change.types
1050        && let Err(response) = events.check_types(types)
1051    {
1052        return response;
1053    }
1054    if let Some(url) = &change.url
1055        && let Err(response) = events.check_url(url)
1056    {
1057        return response;
1058    }
1059    match events.inner.subscriptions.update(&owner, &id, change).await {
1060        Ok(record) => awp_json(StatusCode::OK, &without_secret(record.subscription)),
1061        Err(error) => store_failed(&error),
1062    }
1063}
1064
1065async fn remove(
1066    State(events): State<EdgeEvents>,
1067    caller: Option<Extension<EdgeCaller>>,
1068    Path(id): Path<String>,
1069) -> Response {
1070    let owner = match subscriber(&caller_of(caller)) {
1071        Ok(owner) => owner,
1072        Err(response) => return response,
1073    };
1074    match events.inner.subscriptions.delete(&owner, &id).await {
1075        Ok(true) => StatusCode::NO_CONTENT.into_response(),
1076        Ok(false) => refuse(ErrorCode::ResourceNotFound, "no such subscription"),
1077        Err(error) => store_failed(&error),
1078    }
1079}
1080
1081#[derive(Deserialize)]
1082struct ReplayRequest {
1083    subscription: String,
1084    since: DateTime<Utc>,
1085    #[serde(default)]
1086    until: Option<DateTime<Utc>>,
1087    #[serde(default)]
1088    types: Option<Vec<EventType>>,
1089}
1090
1091async fn replay(
1092    State(events): State<EdgeEvents>,
1093    caller: Option<Extension<EdgeCaller>>,
1094    Json(body): Json<ReplayRequest>,
1095) -> Response {
1096    let owner = match subscriber(&caller_of(caller)) {
1097        Ok(owner) => owner,
1098        Err(response) => return response,
1099    };
1100    match events.replay(&owner, &body.subscription, body.since, body.until, body.types).await {
1101        Ok(accepted) => awp_json(StatusCode::ACCEPTED, &json!({ "accepted": accepted })),
1102        Err(error) => store_failed(&error),
1103    }
1104}
1105
1106async fn changes(
1107    State(events): State<EdgeEvents>,
1108    caller: Option<Extension<EdgeCaller>>,
1109    Path((seq, page)): Path<(u64, usize)>,
1110) -> Response {
1111    let owner = match subscriber(&caller_of(caller)) {
1112        Ok(owner) => owner,
1113        Err(response) => return response,
1114    };
1115    // Only a subscriber to catalogue changes reads their pages.
1116    match events.inner.subscriptions.list(&owner).await {
1117        Ok(records)
1118            if records
1119                .iter()
1120                .any(|record| record.subscription.types.contains(&EventType::CatalogChanged)) => {}
1121        Ok(_) => return refuse(ErrorCode::ResourceNotFound, "no such page"),
1122        Err(error) => return store_failed(&error),
1123    }
1124    match events.page(seq, page).await {
1125        Ok(Some(page)) => awp_json(StatusCode::OK, &page),
1126        Ok(None) => refuse(ErrorCode::ResourceNotFound, "no such page"),
1127        Err(error) => store_failed(&error),
1128    }
1129}