lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

source.rs (48142B)


      1 //! Inbound event source SPI and bounded page models.
      2 
      3 use crate::{
      4     Error, TransportId,
      5     outcome::FetchTargetOutcome,
      6     target::{TargetFingerprint, TargetSet},
      7 };
      8 use alloc::{
      9     boxed::Box,
     10     collections::{BTreeMap, BTreeSet},
     11     string::String,
     12     vec::Vec,
     13 };
     14 use core::{fmt, future::Future, pin::Pin};
     15 use radroots_event::SignedEvent;
     16 use radroots_identity::PublicKey;
     17 
     18 #[cfg(feature = "serde")]
     19 use crate::target::TARGET_SET_MAX_ITEMS;
     20 
     21 pub use crate::status::SourceStatus;
     22 
     23 /// Maximum encoded request identity length.
     24 pub const FETCH_REQUEST_ID_MAX_BYTES: usize = 256;
     25 /// Maximum opaque cursor length.
     26 pub const FETCH_CURSOR_MAX_BYTES: usize = 2_048;
     27 /// Maximum number of events one page may request.
     28 pub const FETCH_PAGE_MAX_EVENTS: u16 = 1_000;
     29 /// Maximum distinct event kinds in one source selector.
     30 pub const FETCH_SELECTOR_MAX_KINDS: usize = 64;
     31 /// Maximum distinct event authors in one source selector.
     32 pub const FETCH_SELECTOR_MAX_AUTHORS: usize = 256;
     33 /// Maximum distinct exact single-letter tag keys in one source selector.
     34 pub const FETCH_SELECTOR_MAX_TAG_KEYS: usize = 26;
     35 /// Maximum exact tag values across one source selector.
     36 pub const FETCH_SELECTOR_MAX_TAG_VALUES: usize = 256;
     37 /// Maximum UTF-8 bytes in one exact tag value.
     38 pub const FETCH_SELECTOR_TAG_VALUE_MAX_BYTES: usize = 4_096;
     39 
     40 // Deliberate representation indirection keeps every selector-bearing request
     41 // and terminal value compact while allocating nothing for the common no-tag
     42 // case. The map itself still owns its bounded tree nodes.
     43 #[allow(clippy::box_collection)]
     44 type ExactTagFilters = Box<BTreeMap<char, Vec<String>>>;
     45 
     46 /// Maximum encoded live-subscription request identity length.
     47 pub const SUBSCRIPTION_REQUEST_ID_MAX_BYTES: usize = 256;
     48 /// Maximum number of events one live subscription may emit.
     49 pub const SUBSCRIPTION_MAX_EVENTS: u16 = 1_000;
     50 
     51 /// Heap-backed future returned by transport SPIs.
     52 #[cfg(not(target_arch = "wasm32"))]
     53 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
     54 /// Heap-backed future local to a browser main thread or worker.
     55 #[cfg(target_arch = "wasm32")]
     56 pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>;
     57 
     58 /// Validated caller identity for one fetch operation.
     59 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     60 pub struct FetchRequestId(String);
     61 
     62 impl FetchRequestId {
     63     /// Parses a non-empty, bounded, printable request identity.
     64     pub fn parse(value: impl Into<String>) -> Result<Self, Error> {
     65         let value = value.into();
     66         if value.is_empty() {
     67             return Err(Error::EmptyFetchRequestId);
     68         }
     69         if value.len() > FETCH_REQUEST_ID_MAX_BYTES
     70             || value != value.trim()
     71             || value.chars().any(char::is_control)
     72         {
     73             return Err(Error::InvalidFetchRequestId);
     74         }
     75         Ok(Self(value))
     76     }
     77 
     78     /// Returns the validated request identity.
     79     pub fn as_str(&self) -> &str {
     80         self.0.as_str()
     81     }
     82 }
     83 
     84 impl fmt::Display for FetchRequestId {
     85     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     86         formatter.write_str(self.as_str())
     87     }
     88 }
     89 
     90 /// Opaque adapter-owned continuation token.
     91 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     92 pub struct FetchCursor(String);
     93 
     94 impl FetchCursor {
     95     /// Parses a bounded printable cursor without interpreting its contents.
     96     pub fn parse(value: impl Into<String>) -> Result<Self, Error> {
     97         let value = value.into();
     98         if value.is_empty() {
     99             return Err(Error::EmptyFetchCursor);
    100         }
    101         if value.len() > FETCH_CURSOR_MAX_BYTES
    102             || value != value.trim()
    103             || value.chars().any(char::is_control)
    104         {
    105             return Err(Error::InvalidFetchCursor);
    106         }
    107         Ok(Self(value))
    108     }
    109 
    110     /// Returns the opaque cursor exactly as supplied by its adapter.
    111     pub fn as_str(&self) -> &str {
    112         self.0.as_str()
    113     }
    114 }
    115 
    116 impl fmt::Display for FetchCursor {
    117     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    118         formatter.write_str(self.as_str())
    119     }
    120 }
    121 
    122 /// Validated caller identity for one bounded live subscription.
    123 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
    124 pub struct SubscriptionRequestId(String);
    125 
    126 impl SubscriptionRequestId {
    127     /// Parses a non-empty, bounded, printable request identity.
    128     pub fn parse(value: impl AsRef<str>) -> Result<Self, Error> {
    129         let value = value.as_ref();
    130         if value.is_empty() {
    131             return Err(Error::EmptySubscriptionRequestId);
    132         }
    133         if value.len() > SUBSCRIPTION_REQUEST_ID_MAX_BYTES
    134             || value != value.trim()
    135             || value.chars().any(char::is_control)
    136         {
    137             return Err(Error::InvalidSubscriptionRequestId);
    138         }
    139         Ok(Self(String::from(value)))
    140     }
    141 
    142     /// Returns the validated request identity.
    143     pub fn as_str(&self) -> &str {
    144         self.0.as_str()
    145     }
    146 }
    147 
    148 impl fmt::Display for SubscriptionRequestId {
    149     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
    150         formatter.write_str(self.as_str())
    151     }
    152 }
    153 
    154 /// Hard bounds for one source operation.
    155 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    156 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    157 pub struct FetchBounds {
    158     limit: u16,
    159     deadline_unix_ms: u64,
    160 }
    161 
    162 impl FetchBounds {
    163     /// Creates bounds with a non-zero page limit and absolute deadline.
    164     pub const fn new(limit: u16, deadline_unix_ms: u64) -> Result<Self, Error> {
    165         if limit == 0 || limit > FETCH_PAGE_MAX_EVENTS {
    166             return Err(Error::InvalidFetchLimit);
    167         }
    168         if deadline_unix_ms == 0 {
    169             return Err(Error::InvalidFetchDeadline);
    170         }
    171         Ok(Self {
    172             limit,
    173             deadline_unix_ms,
    174         })
    175     }
    176 
    177     /// Maximum number of events the adapter may return.
    178     pub const fn limit(self) -> u16 {
    179         self.limit
    180     }
    181 
    182     /// Absolute Unix deadline in milliseconds.
    183     pub const fn deadline_unix_ms(self) -> u64 {
    184         self.deadline_unix_ms
    185     }
    186 }
    187 
    188 /// Hard bounds for one live-subscription operation.
    189 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    190 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    191 pub struct SubscriptionBounds {
    192     event_limit: u16,
    193     deadline_unix_ms: u64,
    194 }
    195 
    196 impl SubscriptionBounds {
    197     /// Creates bounds with a non-zero event limit and absolute deadline.
    198     pub const fn new(event_limit: u16, deadline_unix_ms: u64) -> Result<Self, Error> {
    199         if event_limit == 0 || event_limit > SUBSCRIPTION_MAX_EVENTS {
    200             return Err(Error::InvalidSubscriptionLimit);
    201         }
    202         if deadline_unix_ms == 0 {
    203             return Err(Error::InvalidSubscriptionDeadline);
    204         }
    205         Ok(Self {
    206             event_limit,
    207             deadline_unix_ms,
    208         })
    209     }
    210 
    211     /// Maximum number of events the adapter may emit.
    212     pub const fn event_limit(self) -> u16 {
    213         self.event_limit
    214     }
    215 
    216     /// Absolute Unix deadline in milliseconds.
    217     pub const fn deadline_unix_ms(self) -> u64 {
    218         self.deadline_unix_ms
    219     }
    220 }
    221 
    222 /// Transport-neutral constraints applied before a source page is bounded.
    223 ///
    224 /// An empty kind, author, or tag collection means "any" for that dimension.
    225 /// Values for one tag key are alternatives, while distinct tag keys are
    226 /// conjunctive. Time bounds are inclusive Unix seconds. Adapters must apply
    227 /// every configured dimension remotely when their protocol supports it and
    228 /// must defensively exclude non-matching events before returning a page.
    229 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    230 #[derive(Clone, Debug, Default, Eq, PartialEq)]
    231 pub struct FetchSelector {
    232     kinds: Vec<u32>,
    233     authors: Vec<PublicKey>,
    234     #[cfg_attr(
    235         feature = "serde",
    236         serde(serialize_with = "serde_impl::serialize_exact_tags")
    237     )]
    238     exact_tags: Option<ExactTagFilters>,
    239     since_unix_seconds: Option<u64>,
    240     until_unix_seconds: Option<u64>,
    241 }
    242 
    243 impl FetchSelector {
    244     /// Creates a selector that accepts every event within request bounds.
    245     #[must_use]
    246     pub const fn all() -> Self {
    247         Self {
    248             kinds: Vec::new(),
    249             authors: Vec::new(),
    250             exact_tags: None,
    251             since_unix_seconds: None,
    252             until_unix_seconds: None,
    253         }
    254     }
    255 
    256     /// Restricts the selector to exact, unique event kinds.
    257     pub fn with_kinds(mut self, mut kinds: Vec<u32>) -> Result<Self, Error> {
    258         if kinds.len() > FETCH_SELECTOR_MAX_KINDS {
    259             return Err(Error::FetchSelectorTooLarge);
    260         }
    261         kinds.sort_unstable();
    262         if kinds.windows(2).any(|pair| pair[0] == pair[1]) {
    263             return Err(Error::DuplicateFetchKind);
    264         }
    265         self.kinds = kinds;
    266         Ok(self)
    267     }
    268 
    269     /// Restricts the selector to exact, unique canonical authors.
    270     pub fn with_authors(mut self, mut authors: Vec<PublicKey>) -> Result<Self, Error> {
    271         if authors.len() > FETCH_SELECTOR_MAX_AUTHORS {
    272             return Err(Error::FetchSelectorTooLarge);
    273         }
    274         authors.sort();
    275         if authors.windows(2).any(|pair| pair[0] == pair[1]) {
    276             return Err(Error::DuplicateFetchAuthor);
    277         }
    278         self.authors = authors;
    279         Ok(self)
    280     }
    281 
    282     /// Requires one exact indexed single-letter tag value.
    283     ///
    284     /// Repeating a key adds an alternative value for that key. Different keys
    285     /// are conjunctive. Keys are lowercase ASCII letters and values are
    286     /// non-empty bounded UTF-8 strings.
    287     pub fn with_exact_tag_value(
    288         mut self,
    289         key: char,
    290         value: impl AsRef<str>,
    291     ) -> Result<Self, Error> {
    292         if !key.is_ascii_lowercase() {
    293             return Err(Error::InvalidFetchTagKey);
    294         }
    295         let value = value.as_ref();
    296         if value.is_empty()
    297             || value.len() > FETCH_SELECTOR_TAG_VALUE_MAX_BYTES
    298             || value.chars().any(char::is_control)
    299         {
    300             return Err(Error::InvalidFetchTagValue);
    301         }
    302         let exact_tags = self.exact_tags.as_deref();
    303         let total_values = exact_tags
    304             .into_iter()
    305             .flat_map(BTreeMap::values)
    306             .map(Vec::len)
    307             .sum::<usize>();
    308         if (!exact_tags.is_some_and(|tags| tags.contains_key(&key))
    309             && exact_tags.is_some_and(|tags| tags.len() == FETCH_SELECTOR_MAX_TAG_KEYS))
    310             || total_values == FETCH_SELECTOR_MAX_TAG_VALUES
    311         {
    312             return Err(Error::FetchSelectorTooLarge);
    313         }
    314         let values = self
    315             .exact_tags
    316             .get_or_insert_with(|| Box::new(BTreeMap::new()))
    317             .entry(key)
    318             .or_default();
    319         match values.binary_search_by(|candidate| candidate.as_str().cmp(value)) {
    320             Ok(_) => return Err(Error::DuplicateFetchTagValue),
    321             Err(position) => values.insert(position, String::from(value)),
    322         }
    323         Ok(self)
    324     }
    325 
    326     /// Sets an inclusive lower event-time bound.
    327     pub fn with_since_unix_seconds(mut self, since: u64) -> Result<Self, Error> {
    328         if self.until_unix_seconds.is_some_and(|until| since > until) {
    329             return Err(Error::InvalidFetchTimeRange);
    330         }
    331         self.since_unix_seconds = Some(since);
    332         Ok(self)
    333     }
    334 
    335     /// Sets an inclusive upper event-time bound.
    336     pub fn with_until_unix_seconds(mut self, until: u64) -> Result<Self, Error> {
    337         if self.since_unix_seconds.is_some_and(|since| since > until) {
    338             return Err(Error::InvalidFetchTimeRange);
    339         }
    340         self.until_unix_seconds = Some(until);
    341         Ok(self)
    342     }
    343 
    344     /// Returns sorted exact event kinds, or an empty slice for any kind.
    345     pub fn kinds(&self) -> &[u32] {
    346         self.kinds.as_slice()
    347     }
    348 
    349     /// Returns sorted exact authors, or an empty slice for any author.
    350     pub fn authors(&self) -> &[PublicKey] {
    351         self.authors.as_slice()
    352     }
    353 
    354     /// Returns exact tag filters in canonical key order.
    355     pub fn exact_tag_filters(&self) -> impl Iterator<Item = (char, &[String])> + '_ {
    356         self.exact_tags
    357             .iter()
    358             .flat_map(|tags| tags.iter())
    359             .map(|(key, values)| (*key, values.as_slice()))
    360     }
    361 
    362     /// Returns the inclusive lower event-time bound.
    363     pub const fn since_unix_seconds(&self) -> Option<u64> {
    364         self.since_unix_seconds
    365     }
    366 
    367     /// Returns the inclusive upper event-time bound.
    368     pub const fn until_unix_seconds(&self) -> Option<u64> {
    369         self.until_unix_seconds
    370     }
    371 
    372     /// Returns whether one canonical signed event satisfies every dimension.
    373     #[must_use]
    374     pub fn matches(&self, event: &SignedEvent) -> bool {
    375         (self.kinds.is_empty() || self.kinds.binary_search(&event.kind()).is_ok())
    376             && (self.authors.is_empty() || self.authors.binary_search(event.pubkey()).is_ok())
    377             && self.exact_tags.as_deref().is_none_or(|tags| {
    378                 tags.iter().all(|(key, values)| {
    379                     event.envelope().tag_slices().iter().any(|tag| {
    380                         let elements = tag.as_slice();
    381                         elements.first().is_some_and(|candidate| {
    382                             candidate.len() == 1 && candidate.starts_with(*key)
    383                         }) && elements.get(1).is_some_and(|value| {
    384                             values
    385                                 .binary_search_by(|candidate| candidate.as_str().cmp(value))
    386                                 .is_ok()
    387                         })
    388                     })
    389                 })
    390             })
    391             && self
    392                 .since_unix_seconds
    393                 .is_none_or(|since| event.created_at() >= since)
    394             && self
    395                 .until_unix_seconds
    396                 .is_none_or(|until| event.created_at() <= until)
    397     }
    398 }
    399 
    400 /// Bounded request for one page from one or more transport targets.
    401 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    402 #[derive(Clone, Debug, Eq, PartialEq)]
    403 pub struct FetchRequest {
    404     request_id: FetchRequestId,
    405     target_set: TargetSet,
    406     bounds: FetchBounds,
    407     cursor: Option<FetchCursor>,
    408     selector: FetchSelector,
    409 }
    410 
    411 impl FetchRequest {
    412     /// Creates a first-page request.
    413     pub fn new(
    414         request_id: impl Into<String>,
    415         target_set: TargetSet,
    416         bounds: FetchBounds,
    417     ) -> Result<Self, Error> {
    418         Ok(Self {
    419             request_id: FetchRequestId::parse(request_id)?,
    420             target_set,
    421             bounds,
    422             cursor: None,
    423             selector: FetchSelector::all(),
    424         })
    425     }
    426 
    427     /// Sets the adapter-owned cursor for a continuation request.
    428     #[must_use]
    429     pub fn with_cursor(mut self, cursor: FetchCursor) -> Self {
    430         self.cursor = Some(cursor);
    431         self
    432     }
    433 
    434     /// Applies explicit transport-neutral event constraints.
    435     #[must_use]
    436     pub fn with_selector(mut self, selector: FetchSelector) -> Self {
    437         self.selector = selector;
    438         self
    439     }
    440 
    441     /// Returns the request identity.
    442     pub fn request_id(&self) -> &FetchRequestId {
    443         &self.request_id
    444     }
    445 
    446     /// Returns the exact requested target set.
    447     pub fn target_set(&self) -> &TargetSet {
    448         &self.target_set
    449     }
    450 
    451     /// Returns the hard operation bounds.
    452     pub const fn bounds(&self) -> FetchBounds {
    453         self.bounds
    454     }
    455 
    456     /// Returns the continuation cursor, when this is not a first-page request.
    457     pub fn cursor(&self) -> Option<&FetchCursor> {
    458         self.cursor.as_ref()
    459     }
    460 
    461     /// Returns the exact event constraints for this request.
    462     pub const fn selector(&self) -> &FetchSelector {
    463         &self.selector
    464     }
    465 }
    466 
    467 /// Transport observation attached to one inbound event.
    468 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    469 #[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
    470 #[derive(Clone, Debug, Eq, PartialEq)]
    471 pub struct EventProvenance {
    472     transport_id: TransportId,
    473     target: TargetFingerprint,
    474     observed_at_unix_ms: u64,
    475     cursor: Option<FetchCursor>,
    476 }
    477 
    478 impl EventProvenance {
    479     /// Creates provenance for an event observed from one exact target.
    480     pub fn new(
    481         transport_id: TransportId,
    482         target: TargetFingerprint,
    483         observed_at_unix_ms: u64,
    484     ) -> Result<Self, Error> {
    485         if observed_at_unix_ms == 0 {
    486             return Err(Error::InvalidObservedAt);
    487         }
    488         Ok(Self {
    489             transport_id,
    490             target,
    491             observed_at_unix_ms,
    492             cursor: None,
    493         })
    494     }
    495 
    496     /// Attaches the adapter cursor that located this event.
    497     #[must_use]
    498     pub fn with_cursor(mut self, cursor: FetchCursor) -> Self {
    499         self.cursor = Some(cursor);
    500         self
    501     }
    502 
    503     /// Returns the transport that produced this observation.
    504     pub const fn transport_id(&self) -> TransportId {
    505         self.transport_id
    506     }
    507 
    508     /// Returns the exact target fingerprint that produced this observation.
    509     pub const fn target(&self) -> &TargetFingerprint {
    510         &self.target
    511     }
    512 
    513     /// Returns the host-recorded observation time.
    514     pub const fn observed_at_unix_ms(&self) -> u64 {
    515         self.observed_at_unix_ms
    516     }
    517 
    518     /// Returns the optional adapter cursor at the observation point.
    519     pub const fn cursor(&self) -> Option<&FetchCursor> {
    520         self.cursor.as_ref()
    521     }
    522 }
    523 
    524 /// ID-checked signed event plus transport provenance.
    525 ///
    526 /// Signature verification, contract validation, canonical admission, storage,
    527 /// and projection results intentionally remain outside this transport model.
    528 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    529 #[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
    530 #[derive(Clone, Debug, Eq, PartialEq)]
    531 pub struct ObservedEvent {
    532     event: SignedEvent,
    533     provenance: EventProvenance,
    534 }
    535 
    536 impl ObservedEvent {
    537     /// Attaches provenance to an inbound signed event.
    538     pub const fn new(event: SignedEvent, provenance: EventProvenance) -> Self {
    539         Self { event, provenance }
    540     }
    541 
    542     /// Returns the unverified signed event payload.
    543     pub const fn event(&self) -> &SignedEvent {
    544         &self.event
    545     }
    546 
    547     /// Returns the transport observation.
    548     pub const fn provenance(&self) -> &EventProvenance {
    549         &self.provenance
    550     }
    551 }
    552 
    553 /// State required to continue or conclude a bounded fetch.
    554 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    555 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    556 #[derive(Clone, Debug, Eq, PartialEq)]
    557 pub enum NextPage {
    558     /// Every requested target reached its current end.
    559     Complete,
    560     /// More results are available from this exact cursor.
    561     Cursor(FetchCursor),
    562     /// The operation was cancelled and may optionally be resumed.
    563     Cancelled { resume_from: Option<FetchCursor> },
    564 }
    565 
    566 /// One validated, request-bound page of inbound observations.
    567 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    568 #[derive(Clone, Debug, Eq, PartialEq)]
    569 pub struct FetchPage {
    570     request_id: FetchRequestId,
    571     target_set: TargetSet,
    572     limit: u16,
    573     selector: FetchSelector,
    574     events: Vec<ObservedEvent>,
    575     target_outcomes: Vec<FetchTargetOutcome>,
    576     next_page: NextPage,
    577 }
    578 
    579 impl FetchPage {
    580     /// Creates and validates one page against its originating request.
    581     pub fn for_request(
    582         request: &FetchRequest,
    583         events: Vec<ObservedEvent>,
    584         target_outcomes: Vec<FetchTargetOutcome>,
    585         next_page: NextPage,
    586     ) -> Result<Self, Error> {
    587         let page = Self {
    588             request_id: request.request_id.clone(),
    589             target_set: request.target_set.clone(),
    590             limit: request.bounds.limit,
    591             selector: request.selector.clone(),
    592             events,
    593             target_outcomes,
    594             next_page,
    595         };
    596         page.validate()?;
    597         Ok(page)
    598     }
    599 
    600     /// Validates internal cardinality, target provenance, and outcome identity.
    601     pub fn validate(&self) -> Result<(), Error> {
    602         if self.limit == 0 || self.limit > FETCH_PAGE_MAX_EVENTS {
    603             return Err(Error::InvalidFetchLimit);
    604         }
    605         if self.events.len() > usize::from(self.limit) {
    606             return Err(Error::FetchPageLimitExceeded);
    607         }
    608 
    609         for observed in &self.events {
    610             if !self.selector.matches(observed.event()) {
    611                 return Err(Error::UnexpectedFetchEvent);
    612             }
    613             let provenance = observed.provenance();
    614             let Some(target) = self
    615                 .target_set
    616                 .targets()
    617                 .iter()
    618                 .find(|target| target.fingerprint() == provenance.target())
    619             else {
    620                 return Err(Error::UnexpectedFetchProvenance);
    621             };
    622             if *target.kind() != provenance.transport_id() {
    623                 return Err(Error::UnexpectedFetchProvenance);
    624             }
    625         }
    626 
    627         let requested: BTreeSet<&str> = self
    628             .target_set
    629             .targets()
    630             .iter()
    631             .map(|target| target.fingerprint().as_str())
    632             .collect();
    633         let mut outcomes = BTreeSet::new();
    634         for outcome in &self.target_outcomes {
    635             if !requested.contains(outcome.target().as_str()) {
    636                 return Err(Error::UnexpectedFetchTargetOutcome);
    637             }
    638             if !outcomes.insert(outcome.target().as_str()) {
    639                 return Err(Error::DuplicateFetchTargetOutcome);
    640             }
    641         }
    642         Ok(())
    643     }
    644 
    645     /// Validates that this page is bound to the exact originating request.
    646     pub fn validate_for_request(&self, request: &FetchRequest) -> Result<(), Error> {
    647         self.validate()?;
    648         if &self.request_id != request.request_id()
    649             || self.target_set != *request.target_set()
    650             || self.limit != request.bounds().limit()
    651             || self.selector != *request.selector()
    652         {
    653             return Err(Error::FetchPageRequestMismatch);
    654         }
    655         Ok(())
    656     }
    657 
    658     /// Returns the request identity.
    659     pub const fn request_id(&self) -> &FetchRequestId {
    660         &self.request_id
    661     }
    662 
    663     /// Returns the observations in adapter order.
    664     pub fn events(&self) -> &[ObservedEvent] {
    665         self.events.as_slice()
    666     }
    667 
    668     /// Returns zero or more target-specific outcomes; omitted targets remain unreported.
    669     pub fn target_outcomes(&self) -> &[FetchTargetOutcome] {
    670         self.target_outcomes.as_slice()
    671     }
    672 
    673     /// Returns continuation, completion, or cancellation state.
    674     pub const fn next_page(&self) -> &NextPage {
    675         &self.next_page
    676     }
    677 }
    678 
    679 /// Per-target continuation point for a live subscription.
    680 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    681 #[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
    682 #[derive(Clone, Debug, Eq, PartialEq)]
    683 pub struct SubscriptionCheckpoint {
    684     target: TargetFingerprint,
    685     cursor: FetchCursor,
    686 }
    687 
    688 impl SubscriptionCheckpoint {
    689     /// Binds an opaque adapter cursor to one exact target.
    690     pub const fn new(target: TargetFingerprint, cursor: FetchCursor) -> Self {
    691         Self { target, cursor }
    692     }
    693 
    694     /// Returns the exact target fingerprint.
    695     pub const fn target(&self) -> &TargetFingerprint {
    696         &self.target
    697     }
    698 
    699     /// Returns the opaque adapter cursor.
    700     pub const fn cursor(&self) -> &FetchCursor {
    701         &self.cursor
    702     }
    703 }
    704 
    705 /// Bounded request for a live stream from one or more transport targets.
    706 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    707 #[derive(Clone, Debug, Eq, PartialEq)]
    708 pub struct SubscriptionRequest {
    709     request_id: SubscriptionRequestId,
    710     target_set: TargetSet,
    711     bounds: SubscriptionBounds,
    712     selector: FetchSelector,
    713     checkpoints: Vec<SubscriptionCheckpoint>,
    714 }
    715 
    716 impl SubscriptionRequest {
    717     /// Creates a live request with no prior target checkpoints.
    718     pub fn new(
    719         request_id: impl AsRef<str>,
    720         target_set: TargetSet,
    721         bounds: SubscriptionBounds,
    722     ) -> Result<Self, Error> {
    723         Ok(Self {
    724             request_id: SubscriptionRequestId::parse(request_id)?,
    725             target_set,
    726             bounds,
    727             selector: FetchSelector::all(),
    728             checkpoints: Vec::new(),
    729         })
    730     }
    731 
    732     /// Applies explicit transport-neutral event constraints.
    733     #[must_use]
    734     pub fn with_selector(mut self, selector: FetchSelector) -> Self {
    735         self.selector = selector;
    736         self
    737     }
    738 
    739     /// Applies a bounded, unique checkpoint subset in canonical target order.
    740     pub fn with_checkpoints<I>(mut self, checkpoints: I) -> Result<Self, Error>
    741     where
    742         I: IntoIterator<Item = SubscriptionCheckpoint>,
    743     {
    744         self.checkpoints = normalize_subscription_checkpoints(&self.target_set, checkpoints)?;
    745         Ok(self)
    746     }
    747 
    748     /// Returns the request identity.
    749     pub const fn request_id(&self) -> &SubscriptionRequestId {
    750         &self.request_id
    751     }
    752 
    753     /// Returns the exact requested target set.
    754     pub const fn target_set(&self) -> &TargetSet {
    755         &self.target_set
    756     }
    757 
    758     /// Returns the hard operation bounds.
    759     pub const fn bounds(&self) -> SubscriptionBounds {
    760         self.bounds
    761     }
    762 
    763     /// Returns the exact event constraints for this request.
    764     pub const fn selector(&self) -> &FetchSelector {
    765         &self.selector
    766     }
    767 
    768     /// Returns prior per-target checkpoints in canonical target order.
    769     pub fn checkpoints(&self) -> &[SubscriptionCheckpoint] {
    770         self.checkpoints.as_slice()
    771     }
    772 }
    773 
    774 /// One request-bound live event and its resulting per-target checkpoint.
    775 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    776 #[derive(Clone, Debug, Eq, PartialEq)]
    777 pub struct SubscriptionEvent {
    778     request: SubscriptionRequest,
    779     observed: ObservedEvent,
    780     checkpoint: SubscriptionCheckpoint,
    781 }
    782 
    783 impl SubscriptionEvent {
    784     /// Creates and validates one live event against its originating request.
    785     pub fn for_request(
    786         request: &SubscriptionRequest,
    787         observed: ObservedEvent,
    788         checkpoint: SubscriptionCheckpoint,
    789     ) -> Result<Self, Error> {
    790         let event = Self {
    791             request: request.clone(),
    792             observed,
    793             checkpoint,
    794         };
    795         event.validate_for_request(request)?;
    796         Ok(event)
    797     }
    798 
    799     /// Validates target, transport, selector, cursor, and request identity.
    800     pub fn validate_for_request(&self, request: &SubscriptionRequest) -> Result<(), Error> {
    801         if self.request != *request {
    802             return Err(Error::UnexpectedSubscriptionEvent);
    803         }
    804         let provenance = self.observed.provenance();
    805         let Some(target) = request
    806             .target_set
    807             .targets()
    808             .iter()
    809             .find(|target| target.fingerprint() == provenance.target())
    810         else {
    811             return Err(Error::UnexpectedSubscriptionEvent);
    812         };
    813         if *target.kind() != provenance.transport_id()
    814             || !request.selector.matches(self.observed.event())
    815         {
    816             return Err(Error::UnexpectedSubscriptionEvent);
    817         }
    818         if self.checkpoint.target() != provenance.target()
    819             || provenance.cursor() != Some(self.checkpoint.cursor())
    820         {
    821             return Err(Error::SubscriptionEventCheckpointMismatch);
    822         }
    823         Ok(())
    824     }
    825 
    826     /// Returns the request identity.
    827     pub const fn request_id(&self) -> &SubscriptionRequestId {
    828         self.request.request_id()
    829     }
    830 
    831     /// Returns the exact originating request.
    832     pub const fn request(&self) -> &SubscriptionRequest {
    833         &self.request
    834     }
    835 
    836     /// Returns the observed event.
    837     pub const fn observed(&self) -> &ObservedEvent {
    838         &self.observed
    839     }
    840 
    841     /// Returns the checkpoint established by this event.
    842     pub const fn checkpoint(&self) -> &SubscriptionCheckpoint {
    843         &self.checkpoint
    844     }
    845 }
    846 
    847 /// Stable terminal reason for a bounded live subscription.
    848 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    849 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    850 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    851 pub enum SubscriptionEndReason {
    852     /// The requested maximum event count was emitted.
    853     EventLimit,
    854     /// The absolute request deadline was reached.
    855     Deadline,
    856     /// Explicit or future-drop cancellation was observed.
    857     Cancelled,
    858     /// The underlying source closed before another event was available.
    859     SourceClosed,
    860 }
    861 
    862 /// Request-bound terminal result for a live subscription.
    863 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    864 #[derive(Clone, Debug, Eq, PartialEq)]
    865 pub struct SubscriptionEnd {
    866     request: SubscriptionRequest,
    867     event_count: u16,
    868     checkpoints: Vec<SubscriptionCheckpoint>,
    869     reason: SubscriptionEndReason,
    870 }
    871 
    872 impl SubscriptionEnd {
    873     /// Creates a terminal result with canonical final checkpoints.
    874     pub fn for_request<I>(
    875         request: &SubscriptionRequest,
    876         event_count: u16,
    877         checkpoints: I,
    878         reason: SubscriptionEndReason,
    879     ) -> Result<Self, Error>
    880     where
    881         I: IntoIterator<Item = SubscriptionCheckpoint>,
    882     {
    883         if event_count > request.bounds.event_limit {
    884             return Err(Error::SubscriptionEndLimitExceeded);
    885         }
    886         if reason == SubscriptionEndReason::EventLimit && event_count != request.bounds.event_limit
    887         {
    888             return Err(Error::InvalidSubscriptionEnd);
    889         }
    890         Ok(Self {
    891             request: request.clone(),
    892             event_count,
    893             checkpoints: normalize_subscription_checkpoints(&request.target_set, checkpoints)?,
    894             reason,
    895         })
    896     }
    897 
    898     /// Validates that this result belongs to the exact originating request.
    899     pub fn validate_for_request(&self, request: &SubscriptionRequest) -> Result<(), Error> {
    900         if self.request != *request || self.event_count > request.bounds.event_limit {
    901             return Err(Error::SubscriptionEndRequestMismatch);
    902         }
    903         normalize_subscription_checkpoints(&request.target_set, self.checkpoints.clone())?;
    904         Ok(())
    905     }
    906 
    907     /// Returns the exact originating request.
    908     pub const fn request(&self) -> &SubscriptionRequest {
    909         &self.request
    910     }
    911 
    912     /// Returns the number of events emitted before termination.
    913     pub const fn event_count(&self) -> u16 {
    914         self.event_count
    915     }
    916 
    917     /// Returns final per-target checkpoints in canonical target order.
    918     pub fn checkpoints(&self) -> &[SubscriptionCheckpoint] {
    919         self.checkpoints.as_slice()
    920     }
    921 
    922     /// Returns why the bounded operation terminated.
    923     pub const fn reason(&self) -> SubscriptionEndReason {
    924         self.reason
    925     }
    926 }
    927 
    928 /// One event or the stable terminal result from a live subscription.
    929 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    930 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
    931 #[derive(Clone, Debug, Eq, PartialEq)]
    932 pub enum SubscriptionNext {
    933     /// One request-bound event was observed.
    934     Event(Box<SubscriptionEvent>),
    935     /// The subscription reached its stable terminal state.
    936     End(SubscriptionEnd),
    937 }
    938 
    939 fn normalize_subscription_checkpoints<I>(
    940     target_set: &TargetSet,
    941     checkpoints: I,
    942 ) -> Result<Vec<SubscriptionCheckpoint>, Error>
    943 where
    944     I: IntoIterator<Item = SubscriptionCheckpoint>,
    945 {
    946     let maximum = target_set.len();
    947     let mut checkpoints: Vec<_> = checkpoints.into_iter().take(maximum + 1).collect();
    948     if checkpoints.len() > maximum {
    949         return Err(Error::SubscriptionCheckpointSetTooLarge);
    950     }
    951 
    952     let mut seen = BTreeSet::new();
    953     for checkpoint in &checkpoints {
    954         if target_position(target_set, checkpoint.target()).is_none() {
    955             return Err(Error::UnexpectedSubscriptionCheckpoint);
    956         }
    957         if !seen.insert(checkpoint.target().as_str()) {
    958             return Err(Error::DuplicateSubscriptionCheckpoint);
    959         }
    960     }
    961     checkpoints.sort_by_key(|checkpoint| {
    962         target_position(target_set, checkpoint.target()).expect("checkpoint target validated")
    963     });
    964     Ok(checkpoints)
    965 }
    966 
    967 fn target_position(target_set: &TargetSet, fingerprint: &TargetFingerprint) -> Option<usize> {
    968     target_set
    969         .targets()
    970         .iter()
    971         .position(|target| target.fingerprint() == fingerprint)
    972 }
    973 
    974 /// Host SPI for inbound event retrieval.
    975 ///
    976 /// This trait supports external implementations and is dyn-compatible. Its
    977 /// futures are native `Send` or browser-local; implementations must not borrow request data after a
    978 /// future completes. `status` observes source state and does not initiate a
    979 /// fetch. `fetch` performs at most the work bounded by its request and owns no
    980 /// hidden retry loop.
    981 ///
    982 /// Dropping a returned future requests cancellation. If it is dropped before
    983 /// a remote request is published, the implementation must leave no remote
    984 /// operation behind. Once publication may have occurred, cancellation cannot
    985 /// claim rollback; a later observation may report the remote outcome. The
    986 /// explicit request deadline bounds work independently of future cancellation.
    987 pub trait EventSource: crate::host::HostBound {
    988     /// Returns the source's current runtime status.
    989     fn status(&self) -> BoxFuture<'_, Result<SourceStatus, Error>>;
    990 
    991     /// Fetches one bounded page of transport-neutral events.
    992     fn fetch(&self, request: FetchRequest) -> BoxFuture<'_, Result<FetchPage, Error>>;
    993 }
    994 
    995 /// One active, bounded live-subscription operation.
    996 ///
    997 /// Implementations must enforce the request's event limit and absolute
    998 /// deadline without hidden retries. Once [`SubscriptionNext::End`] has been
    999 /// returned, every later `next` or `cancel` call must return the exact same
   1000 /// terminal result. Dropping a pending future requests cancellation but does
   1001 /// not claim that an already-observed remote event was rolled back.
   1002 pub trait EventSubscription: crate::host::MoveBound {
   1003     /// Returns the exact request governing this operation.
   1004     fn request(&self) -> &SubscriptionRequest;
   1005 
   1006     /// Returns the next request-bound event or stable terminal result.
   1007     fn next(&mut self) -> BoxFuture<'_, Result<SubscriptionNext, Error>>;
   1008 
   1009     /// Requests cancellation and returns the stable terminal result.
   1010     fn cancel(&mut self) -> BoxFuture<'_, Result<SubscriptionEnd, Error>>;
   1011 }
   1012 
   1013 /// Heap-owned live-subscription capability returned by adapters.
   1014 pub type BoxSubscription = Box<dyn EventSubscription>;
   1015 
   1016 /// Host SPI for beginning bounded live subscriptions.
   1017 ///
   1018 /// This is separate from [`EventSource`] so existing bounded-fetch producers
   1019 /// remain source-compatible until they explicitly adopt live delivery.
   1020 pub trait EventSubscriber: crate::host::HostBound {
   1021     /// Begins one exact bounded live-subscription request.
   1022     fn subscribe(
   1023         &self,
   1024         request: SubscriptionRequest,
   1025     ) -> BoxFuture<'_, Result<BoxSubscription, Error>>;
   1026 }
   1027 
   1028 #[cfg(feature = "serde")]
   1029 mod serde_impl {
   1030     use super::*;
   1031 
   1032     pub(super) fn serialize_exact_tags<S>(
   1033         exact_tags: &Option<ExactTagFilters>,
   1034         serializer: S,
   1035     ) -> Result<S::Ok, S::Error>
   1036     where
   1037         S: serde::Serializer,
   1038     {
   1039         match exact_tags {
   1040             Some(exact_tags) => serde::Serialize::serialize(exact_tags, serializer),
   1041             None => serde::Serialize::serialize(&BTreeMap::<char, Vec<String>>::new(), serializer),
   1042         }
   1043     }
   1044 
   1045     impl serde::Serialize for FetchRequestId {
   1046         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   1047         where
   1048             S: serde::Serializer,
   1049         {
   1050             serializer.serialize_str(self.as_str())
   1051         }
   1052     }
   1053 
   1054     impl<'de> serde::Deserialize<'de> for FetchRequestId {
   1055         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1056         where
   1057             D: serde::Deserializer<'de>,
   1058         {
   1059             let value = <String as serde::Deserialize>::deserialize(deserializer)?;
   1060             Self::parse(value).map_err(serde::de::Error::custom)
   1061         }
   1062     }
   1063 
   1064     impl serde::Serialize for FetchCursor {
   1065         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   1066         where
   1067             S: serde::Serializer,
   1068         {
   1069             serializer.serialize_str(self.as_str())
   1070         }
   1071     }
   1072 
   1073     impl<'de> serde::Deserialize<'de> for FetchCursor {
   1074         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1075         where
   1076             D: serde::Deserializer<'de>,
   1077         {
   1078             let value = <String as serde::Deserialize>::deserialize(deserializer)?;
   1079             Self::parse(value).map_err(serde::de::Error::custom)
   1080         }
   1081     }
   1082 
   1083     impl serde::Serialize for SubscriptionRequestId {
   1084         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
   1085         where
   1086             S: serde::Serializer,
   1087         {
   1088             serializer.serialize_str(self.as_str())
   1089         }
   1090     }
   1091 
   1092     impl<'de> serde::Deserialize<'de> for SubscriptionRequestId {
   1093         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1094         where
   1095             D: serde::Deserializer<'de>,
   1096         {
   1097             let value = <String as serde::Deserialize>::deserialize(deserializer)?;
   1098             Self::parse(value.as_str()).map_err(serde::de::Error::custom)
   1099         }
   1100     }
   1101 
   1102     #[derive(serde::Deserialize)]
   1103     #[serde(deny_unknown_fields)]
   1104     struct FetchBoundsWire {
   1105         limit: u16,
   1106         deadline_unix_ms: u64,
   1107     }
   1108 
   1109     impl<'de> serde::Deserialize<'de> for FetchBounds {
   1110         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1111         where
   1112             D: serde::Deserializer<'de>,
   1113         {
   1114             let wire = FetchBoundsWire::deserialize(deserializer)?;
   1115             Self::new(wire.limit, wire.deadline_unix_ms).map_err(serde::de::Error::custom)
   1116         }
   1117     }
   1118 
   1119     #[derive(serde::Deserialize)]
   1120     #[serde(deny_unknown_fields)]
   1121     struct SubscriptionBoundsWire {
   1122         event_limit: u16,
   1123         deadline_unix_ms: u64,
   1124     }
   1125 
   1126     impl<'de> serde::Deserialize<'de> for SubscriptionBounds {
   1127         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1128         where
   1129             D: serde::Deserializer<'de>,
   1130         {
   1131             let wire = SubscriptionBoundsWire::deserialize(deserializer)?;
   1132             Self::new(wire.event_limit, wire.deadline_unix_ms).map_err(serde::de::Error::custom)
   1133         }
   1134     }
   1135 
   1136     #[derive(Default)]
   1137     struct ExactTagsWire(Vec<(char, Vec<String>)>);
   1138 
   1139     impl<'de> serde::Deserialize<'de> for ExactTagsWire {
   1140         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1141         where
   1142             D: serde::Deserializer<'de>,
   1143         {
   1144             struct ExactTagsVisitor;
   1145 
   1146             impl<'de> serde::de::Visitor<'de> for ExactTagsVisitor {
   1147                 type Value = ExactTagsWire;
   1148 
   1149                 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
   1150                     formatter.write_str("a map of unique exact single-letter tag filters")
   1151                 }
   1152 
   1153                 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
   1154                 where
   1155                     A: serde::de::MapAccess<'de>,
   1156                 {
   1157                     let mut entries = Vec::<(char, Vec<String>)>::new();
   1158                     while let Some((key, values)) = map.next_entry::<char, Vec<String>>()? {
   1159                         if entries.iter().any(|(candidate, _)| *candidate == key) {
   1160                             return Err(serde::de::Error::custom(
   1161                                 "transport fetch selector contains a duplicate tag key",
   1162                             ));
   1163                         }
   1164                         entries.push((key, values));
   1165                     }
   1166                     Ok(ExactTagsWire(entries))
   1167                 }
   1168             }
   1169 
   1170             deserializer.deserialize_map(ExactTagsVisitor)
   1171         }
   1172     }
   1173 
   1174     #[derive(serde::Deserialize)]
   1175     #[serde(deny_unknown_fields)]
   1176     struct FetchRequestWire {
   1177         request_id: String,
   1178         target_set: TargetSet,
   1179         bounds: FetchBounds,
   1180         cursor: Option<FetchCursor>,
   1181         #[serde(default)]
   1182         selector: FetchSelector,
   1183     }
   1184 
   1185     impl<'de> serde::Deserialize<'de> for FetchRequest {
   1186         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1187         where
   1188             D: serde::Deserializer<'de>,
   1189         {
   1190             let wire = FetchRequestWire::deserialize(deserializer)?;
   1191             Self::new(wire.request_id, wire.target_set, wire.bounds)
   1192                 .map(|request| request.with_selector(wire.selector))
   1193                 .map(|request| match wire.cursor {
   1194                     Some(cursor) => request.with_cursor(cursor),
   1195                     None => request,
   1196                 })
   1197                 .map_err(serde::de::Error::custom)
   1198         }
   1199     }
   1200 
   1201     #[derive(serde::Deserialize)]
   1202     #[serde(deny_unknown_fields)]
   1203     struct SubscriptionRequestWire {
   1204         request_id: String,
   1205         target_set: TargetSet,
   1206         bounds: SubscriptionBounds,
   1207         #[serde(default)]
   1208         selector: FetchSelector,
   1209         #[serde(default)]
   1210         #[serde(deserialize_with = "deserialize_subscription_checkpoints")]
   1211         checkpoints: Vec<SubscriptionCheckpoint>,
   1212     }
   1213 
   1214     impl<'de> serde::Deserialize<'de> for SubscriptionRequest {
   1215         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1216         where
   1217             D: serde::Deserializer<'de>,
   1218         {
   1219             let wire = SubscriptionRequestWire::deserialize(deserializer)?;
   1220             Self::new(wire.request_id.as_str(), wire.target_set, wire.bounds)
   1221                 .map(|request| request.with_selector(wire.selector))
   1222                 .and_then(|request| request.with_checkpoints(wire.checkpoints))
   1223                 .map_err(serde::de::Error::custom)
   1224         }
   1225     }
   1226 
   1227     impl<'de> serde::Deserialize<'de> for FetchSelector {
   1228         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1229         where
   1230             D: serde::Deserializer<'de>,
   1231         {
   1232             #[derive(serde::Deserialize)]
   1233             #[serde(deny_unknown_fields)]
   1234             struct Wire {
   1235                 #[serde(default)]
   1236                 kinds: Vec<u32>,
   1237                 #[serde(default)]
   1238                 authors: Vec<PublicKey>,
   1239                 #[serde(default)]
   1240                 exact_tags: ExactTagsWire,
   1241                 since_unix_seconds: Option<u64>,
   1242                 until_unix_seconds: Option<u64>,
   1243             }
   1244 
   1245             let wire = Wire::deserialize(deserializer)?;
   1246             let selector = FetchSelector::all()
   1247                 .with_kinds(wire.kinds)
   1248                 .and_then(|selector| selector.with_authors(wire.authors))
   1249                 .and_then(|selector| {
   1250                     wire.exact_tags
   1251                         .0
   1252                         .into_iter()
   1253                         .try_fold(selector, |selector, (key, values)| {
   1254                             values.into_iter().try_fold(selector, |selector, value| {
   1255                                 selector.with_exact_tag_value(key, value)
   1256                             })
   1257                         })
   1258                 })
   1259                 .and_then(|selector| match wire.since_unix_seconds {
   1260                     Some(since) => selector.with_since_unix_seconds(since),
   1261                     None => Ok(selector),
   1262                 })
   1263                 .and_then(|selector| match wire.until_unix_seconds {
   1264                     Some(until) => selector.with_until_unix_seconds(until),
   1265                     None => Ok(selector),
   1266                 });
   1267             selector.map_err(serde::de::Error::custom)
   1268         }
   1269     }
   1270 
   1271     #[derive(serde::Deserialize)]
   1272     #[serde(deny_unknown_fields)]
   1273     struct EventProvenanceWire {
   1274         transport_id: TransportId,
   1275         target: TargetFingerprint,
   1276         observed_at_unix_ms: u64,
   1277         cursor: Option<FetchCursor>,
   1278     }
   1279 
   1280     impl<'de> serde::Deserialize<'de> for EventProvenance {
   1281         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1282         where
   1283             D: serde::Deserializer<'de>,
   1284         {
   1285             let wire = EventProvenanceWire::deserialize(deserializer)?;
   1286             Self::new(wire.transport_id, wire.target, wire.observed_at_unix_ms)
   1287                 .map(|provenance| match wire.cursor {
   1288                     Some(cursor) => provenance.with_cursor(cursor),
   1289                     None => provenance,
   1290                 })
   1291                 .map_err(serde::de::Error::custom)
   1292         }
   1293     }
   1294 
   1295     #[derive(serde::Deserialize)]
   1296     #[serde(deny_unknown_fields)]
   1297     struct FetchPageWire {
   1298         request_id: FetchRequestId,
   1299         target_set: TargetSet,
   1300         limit: u16,
   1301         #[serde(default)]
   1302         selector: FetchSelector,
   1303         events: Vec<ObservedEvent>,
   1304         target_outcomes: Vec<FetchTargetOutcome>,
   1305         next_page: NextPage,
   1306     }
   1307 
   1308     impl<'de> serde::Deserialize<'de> for FetchPage {
   1309         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1310         where
   1311             D: serde::Deserializer<'de>,
   1312         {
   1313             let wire = FetchPageWire::deserialize(deserializer)?;
   1314             let page = Self {
   1315                 request_id: wire.request_id,
   1316                 target_set: wire.target_set,
   1317                 limit: wire.limit,
   1318                 selector: wire.selector,
   1319                 events: wire.events,
   1320                 target_outcomes: wire.target_outcomes,
   1321                 next_page: wire.next_page,
   1322             };
   1323             page.validate().map_err(serde::de::Error::custom)?;
   1324             Ok(page)
   1325         }
   1326     }
   1327 
   1328     #[derive(serde::Deserialize)]
   1329     #[serde(deny_unknown_fields)]
   1330     struct SubscriptionEventWire {
   1331         request: SubscriptionRequest,
   1332         observed: ObservedEvent,
   1333         checkpoint: SubscriptionCheckpoint,
   1334     }
   1335 
   1336     impl<'de> serde::Deserialize<'de> for SubscriptionEvent {
   1337         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1338         where
   1339             D: serde::Deserializer<'de>,
   1340         {
   1341             let wire = SubscriptionEventWire::deserialize(deserializer)?;
   1342             Self::for_request(&wire.request, wire.observed, wire.checkpoint)
   1343                 .map_err(serde::de::Error::custom)
   1344         }
   1345     }
   1346 
   1347     #[derive(serde::Deserialize)]
   1348     #[serde(deny_unknown_fields)]
   1349     struct SubscriptionEndWire {
   1350         request: SubscriptionRequest,
   1351         event_count: u16,
   1352         #[serde(deserialize_with = "deserialize_subscription_checkpoints")]
   1353         checkpoints: Vec<SubscriptionCheckpoint>,
   1354         reason: SubscriptionEndReason,
   1355     }
   1356 
   1357     impl<'de> serde::Deserialize<'de> for SubscriptionEnd {
   1358         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
   1359         where
   1360             D: serde::Deserializer<'de>,
   1361         {
   1362             let wire = SubscriptionEndWire::deserialize(deserializer)?;
   1363             Self::for_request(
   1364                 &wire.request,
   1365                 wire.event_count,
   1366                 wire.checkpoints,
   1367                 wire.reason,
   1368             )
   1369             .map_err(serde::de::Error::custom)
   1370         }
   1371     }
   1372 
   1373     fn deserialize_subscription_checkpoints<'de, D>(
   1374         deserializer: D,
   1375     ) -> Result<Vec<SubscriptionCheckpoint>, D::Error>
   1376     where
   1377         D: serde::Deserializer<'de>,
   1378     {
   1379         struct CheckpointVisitor;
   1380 
   1381         impl<'de> serde::de::Visitor<'de> for CheckpointVisitor {
   1382             type Value = Vec<SubscriptionCheckpoint>;
   1383 
   1384             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
   1385                 formatter.write_str("a bounded transport subscription checkpoint sequence")
   1386             }
   1387 
   1388             fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
   1389             where
   1390                 A: serde::de::SeqAccess<'de>,
   1391             {
   1392                 let capacity = sequence.size_hint().unwrap_or(0).min(TARGET_SET_MAX_ITEMS);
   1393                 let mut checkpoints = Vec::with_capacity(capacity);
   1394                 while let Some(checkpoint) = sequence.next_element()? {
   1395                     if checkpoints.len() == TARGET_SET_MAX_ITEMS {
   1396                         return Err(serde::de::Error::custom(
   1397                             Error::SubscriptionCheckpointSetTooLarge,
   1398                         ));
   1399                     }
   1400                     checkpoints.push(checkpoint);
   1401                 }
   1402                 Ok(checkpoints)
   1403             }
   1404         }
   1405 
   1406         deserializer.deserialize_seq(CheckpointVisitor)
   1407     }
   1408 }