lib

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

sink.rs (23552B)


      1 //! Outbound event delivery SPI and bounded request models.
      2 
      3 use crate::{
      4     Error,
      5     outcome::{DeliveryOutcome, Retryability, validate_delivery_code, validate_delivery_message},
      6     policy::{SatisfactionPolicy, SatisfactionState, evaluate_satisfaction},
      7     source::BoxFuture,
      8     target::{Target, TargetSet},
      9 };
     10 use alloc::{
     11     boxed::Box,
     12     collections::{BTreeMap, BTreeSet},
     13     string::{String, ToString},
     14     vec::Vec,
     15 };
     16 use radroots_event::SignedEvent;
     17 use sha2::{Digest, Sha256};
     18 
     19 pub use crate::status::SinkStatus;
     20 
     21 /// Maximum encoded delivery request identity length.
     22 pub const DELIVERY_REQUEST_ID_MAX_BYTES: usize = 256;
     23 
     24 /// Sink-wide typed failure retaining safe retry and partial-target evidence.
     25 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
     26 #[derive(Clone, Debug, Eq, PartialEq)]
     27 pub struct SinkFailure {
     28     request_id: DeliveryRequestId,
     29     exact_payload_sha256: [u8; 32],
     30     target_set: TargetSet,
     31     code: String,
     32     retryability: Retryability,
     33     retry_after_unix_ms: Option<u64>,
     34     message: Option<String>,
     35     partial_evidence: Vec<DeliveryTargetReceipt>,
     36 }
     37 
     38 /// Validated caller identity for one delivery operation.
     39 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
     40 pub struct DeliveryRequestId(String);
     41 
     42 impl DeliveryRequestId {
     43     /// Parses a non-empty, bounded, printable request identity.
     44     pub fn parse(value: impl Into<String>) -> Result<Self, Error> {
     45         let value = value.into();
     46         if value.is_empty() {
     47             return Err(Error::EmptyDeliveryRequestId);
     48         }
     49         if value.len() > DELIVERY_REQUEST_ID_MAX_BYTES
     50             || value != value.trim()
     51             || value.chars().any(char::is_control)
     52         {
     53             return Err(Error::InvalidDeliveryRequestId);
     54         }
     55         Ok(Self(value))
     56     }
     57 
     58     /// Returns the validated request identity.
     59     pub fn as_str(&self) -> &str {
     60         self.0.as_str()
     61     }
     62 }
     63 
     64 /// Transport-neutral outbound event payload.
     65 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
     66 #[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
     67 #[derive(Clone, Debug, Eq, PartialEq)]
     68 pub struct DeliveryPayload {
     69     event: SignedEvent,
     70 }
     71 
     72 impl DeliveryPayload {
     73     /// Wraps an ID-checked signed event for delivery.
     74     pub const fn new(event: SignedEvent) -> Self {
     75         Self { event }
     76     }
     77 
     78     /// Returns the signed event. Signature verification remains a caller concern.
     79     pub const fn event(&self) -> &SignedEvent {
     80         &self.event
     81     }
     82 }
     83 
     84 /// Bounded multi-target delivery request.
     85 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
     86 #[derive(Clone, Debug, Eq, PartialEq)]
     87 pub struct DeliveryRequest {
     88     request_id: DeliveryRequestId,
     89     payload: DeliveryPayload,
     90     target_set: TargetSet,
     91     satisfaction: SatisfactionPolicy,
     92     deadline_unix_ms: u64,
     93 }
     94 
     95 impl DeliveryRequest {
     96     /// Creates and validates one explicit delivery request.
     97     pub fn new(
     98         request_id: impl Into<String>,
     99         payload: DeliveryPayload,
    100         target_set: TargetSet,
    101         satisfaction: SatisfactionPolicy,
    102         deadline_unix_ms: u64,
    103     ) -> Result<Self, Error> {
    104         if deadline_unix_ms == 0 {
    105             return Err(Error::InvalidDeliveryDeadline);
    106         }
    107         satisfaction.validate_for(&target_set)?;
    108         Ok(Self {
    109             request_id: DeliveryRequestId::parse(request_id)?,
    110             payload,
    111             target_set,
    112             satisfaction,
    113             deadline_unix_ms,
    114         })
    115     }
    116 
    117     /// Returns the request identity.
    118     pub const fn request_id(&self) -> &DeliveryRequestId {
    119         &self.request_id
    120     }
    121 
    122     /// Returns the signed event payload.
    123     pub const fn payload(&self) -> &DeliveryPayload {
    124         &self.payload
    125     }
    126 
    127     /// Returns the exact non-empty target set.
    128     pub const fn target_set(&self) -> &TargetSet {
    129         &self.target_set
    130     }
    131 
    132     /// Returns the requested success and target policy.
    133     pub const fn satisfaction(&self) -> &SatisfactionPolicy {
    134         &self.satisfaction
    135     }
    136 
    137     /// Returns the absolute Unix deadline in milliseconds.
    138     pub const fn deadline_unix_ms(&self) -> u64 {
    139         self.deadline_unix_ms
    140     }
    141 
    142     /// Validates a nonempty bounded subset of the exact original targets.
    143     /// Selection never changes this request's payload, policy or identity.
    144     pub fn validate_target_selection(&self, selected: &TargetSet) -> Result<(), Error> {
    145         if selected
    146             .targets()
    147             .iter()
    148             .all(|target| self.target_set.targets().contains(target))
    149         {
    150             Ok(())
    151         } else {
    152             Err(Error::InvalidDeliveryTargetSelection)
    153         }
    154     }
    155 }
    156 
    157 /// Normalized result for one requested target.
    158 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    159 #[derive(Clone, Debug, Eq, PartialEq)]
    160 pub struct DeliveryTargetReceipt {
    161     target: Target,
    162     attempted: bool,
    163     outcome: DeliveryOutcome,
    164 }
    165 
    166 impl DeliveryTargetReceipt {
    167     /// Records the outcome of an attempted target.
    168     pub const fn attempted(target: Target, outcome: DeliveryOutcome) -> Self {
    169         Self {
    170             target,
    171             attempted: true,
    172             outcome,
    173         }
    174     }
    175 
    176     /// Records an unattempted target and its normalized failure reason.
    177     pub fn skipped(target: Target, outcome: DeliveryOutcome) -> Result<Self, Error> {
    178         if outcome.satisfies(crate::policy::SatisfactionClass::Accepted) {
    179             return Err(Error::DeliveryTargetReceiptAttemptMismatch);
    180         }
    181         Ok(Self {
    182             target,
    183             attempted: false,
    184             outcome,
    185         })
    186     }
    187 
    188     /// Returns the exact target.
    189     pub const fn target(&self) -> &Target {
    190         &self.target
    191     }
    192 
    193     /// Whether the adapter attempted remote publication.
    194     pub const fn was_attempted(&self) -> bool {
    195         self.attempted
    196     }
    197 
    198     /// Returns normalized target outcome data.
    199     pub const fn outcome(&self) -> &DeliveryOutcome {
    200         &self.outcome
    201     }
    202 
    203     fn validate(&self) -> Result<(), Error> {
    204         self.outcome.validate()?;
    205         if !self.attempted
    206             && self
    207                 .outcome
    208                 .satisfies(crate::policy::SatisfactionClass::Accepted)
    209         {
    210             return Err(Error::DeliveryTargetReceiptAttemptMismatch);
    211         }
    212         Ok(())
    213     }
    214 }
    215 
    216 /// Request-bound per-target delivery receipt.
    217 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    218 #[derive(Clone, Debug, Eq, PartialEq)]
    219 pub struct DeliveryReceipt {
    220     request_id: DeliveryRequestId,
    221     exact_payload_sha256: [u8; 32],
    222     target_set: TargetSet,
    223     target_receipts: Vec<DeliveryTargetReceipt>,
    224 }
    225 
    226 impl DeliveryReceipt {
    227     /// Creates a complete result set in the original request target order.
    228     pub fn for_request(
    229         request: &DeliveryRequest,
    230         target_receipts: Vec<DeliveryTargetReceipt>,
    231     ) -> Result<Self, Error> {
    232         Self::new(
    233             request.request_id.clone(),
    234             exact_payload_sha256(request),
    235             request.target_set.clone(),
    236             target_receipts,
    237         )
    238     }
    239 
    240     fn new(
    241         request_id: DeliveryRequestId,
    242         exact_payload_sha256: [u8; 32],
    243         target_set: TargetSet,
    244         target_receipts: Vec<DeliveryTargetReceipt>,
    245     ) -> Result<Self, Error> {
    246         let mut by_fingerprint = BTreeMap::new();
    247         for receipt in target_receipts {
    248             receipt.validate()?;
    249             let fingerprint = receipt.target().fingerprint().as_str().to_string();
    250             if !target_set
    251                 .targets()
    252                 .iter()
    253                 .any(|target| target.fingerprint().as_str() == fingerprint)
    254             {
    255                 return Err(Error::UnexpectedDeliveryTargetReceipt);
    256             }
    257             if by_fingerprint.insert(fingerprint, receipt).is_some() {
    258                 return Err(Error::DuplicateDeliveryTargetReceipt);
    259             }
    260         }
    261 
    262         let mut ordered = Vec::with_capacity(target_set.len());
    263         for target in target_set.targets() {
    264             let Some(receipt) = by_fingerprint.remove(target.fingerprint().as_str()) else {
    265                 return Err(Error::MissingDeliveryTargetReceipt);
    266             };
    267             ordered.push(receipt);
    268         }
    269         Ok(Self {
    270             request_id,
    271             exact_payload_sha256,
    272             target_set,
    273             target_receipts: ordered,
    274         })
    275     }
    276 
    277     /// Validates the original request identity, exact payload bytes and targets.
    278     pub fn validate_for_request(&self, request: &DeliveryRequest) -> Result<(), Error> {
    279         if &self.request_id != request.request_id() {
    280             return Err(Error::DeliveryReceiptRequestIdMismatch);
    281         }
    282         if self.exact_payload_sha256 != exact_payload_sha256(request) {
    283             return Err(Error::DeliveryReceiptPayloadMismatch);
    284         }
    285         if self.target_set != *request.target_set() {
    286             return Err(Error::DeliveryReceiptTargetSetMismatch);
    287         }
    288         let rebuilt = Self::for_request(request, self.target_receipts.clone())?;
    289         if rebuilt != *self {
    290             return Err(Error::DeliveryReceiptTargetSetMismatch);
    291         }
    292         Ok(())
    293     }
    294 
    295     /// Returns whether the receipt satisfies the request's exact policy.
    296     pub fn is_satisfied(&self, request: &DeliveryRequest) -> Result<bool, Error> {
    297         Ok(matches!(
    298             self.satisfaction(request)?,
    299             SatisfactionState::Satisfied
    300         ))
    301     }
    302 
    303     /// Evaluates this receipt as satisfied, pending, or exhausted.
    304     pub fn satisfaction(&self, request: &DeliveryRequest) -> Result<SatisfactionState, Error> {
    305         self.validate_for_request(request)?;
    306         evaluate_satisfaction(
    307             request.satisfaction(),
    308             request.target_set(),
    309             self.target_receipts
    310                 .iter()
    311                 .map(|receipt| (receipt.target().fingerprint(), receipt.outcome())),
    312         )
    313     }
    314 
    315     /// Returns the request identity.
    316     pub const fn request_id(&self) -> &DeliveryRequestId {
    317         &self.request_id
    318     }
    319 
    320     /// Returns per-target results in request order.
    321     pub fn target_receipts(&self) -> &[DeliveryTargetReceipt] {
    322         self.target_receipts.as_slice()
    323     }
    324 }
    325 
    326 impl SinkFailure {
    327     /// Refuses a request after admission closed, retaining an unattempted row for every target.
    328     pub fn transport_closed(request: &DeliveryRequest) -> Self {
    329         Self::unattempted(
    330             request,
    331             "transport_closed",
    332             Retryability::Terminal,
    333             DeliveryOutcome::rejected()
    334                 .with_detail("transport_closed", "transport admission is closed")
    335                 .expect("static closed outcome is valid"),
    336         )
    337     }
    338 
    339     /// Refuses work during a lifecycle transition without losing per-target attempt certainty.
    340     pub fn transport_unavailable(request: &DeliveryRequest) -> Self {
    341         Self::unattempted(
    342             request,
    343             "transport_unavailable",
    344             Retryability::Retryable,
    345             DeliveryOutcome::unavailable()
    346                 .with_detail(
    347                     "transport_unavailable",
    348                     "transport is temporarily unavailable",
    349                 )
    350                 .expect("static unavailable outcome is valid"),
    351         )
    352     }
    353 
    354     fn unattempted(
    355         request: &DeliveryRequest,
    356         code: &str,
    357         retry: Retryability,
    358         outcome: DeliveryOutcome,
    359     ) -> Self {
    360         let evidence = request
    361             .target_set()
    362             .targets()
    363             .iter()
    364             .map(|target| {
    365                 DeliveryTargetReceipt::skipped(target.clone(), outcome.clone())
    366                     .expect("validated target and unattempted outcome are valid")
    367             })
    368             .collect();
    369         Self::for_request(request, code, retry, None, None, evidence)
    370             .expect("complete static unattempted delivery evidence is valid")
    371     }
    372 
    373     /// Creates a request-bound sink-wide failure with validated partial evidence.
    374     pub fn for_request(
    375         request: &DeliveryRequest,
    376         code: impl Into<String>,
    377         retryability: Retryability,
    378         retry_after_unix_ms: Option<u64>,
    379         message: Option<String>,
    380         partial_evidence: Vec<DeliveryTargetReceipt>,
    381     ) -> Result<Self, Error> {
    382         let failure = Self {
    383             request_id: request.request_id.clone(),
    384             exact_payload_sha256: exact_payload_sha256(request),
    385             target_set: request.target_set.clone(),
    386             code: code.into(),
    387             retryability,
    388             retry_after_unix_ms,
    389             message,
    390             partial_evidence,
    391         };
    392         failure.validate_for_request(request)?;
    393         Ok(failure)
    394     }
    395 
    396     /// Returns a terminal adapter-contract failure for an exact request.
    397     pub fn invalid_contract(request: &DeliveryRequest) -> Self {
    398         Self::for_request(
    399             request,
    400             "invalid_transport_contract",
    401             Retryability::Terminal,
    402             None,
    403             Some("transport adapter returned invalid evidence".to_string()),
    404             Vec::new(),
    405         )
    406         .expect("static sink failure is valid")
    407     }
    408 
    409     /// Validates identity, exact payload bytes, retry timing and partial evidence.
    410     pub fn validate_for_request(&self, request: &DeliveryRequest) -> Result<(), Error> {
    411         if self.request_id != *request.request_id() {
    412             return Err(Error::DeliveryReceiptRequestIdMismatch);
    413         }
    414         if self.exact_payload_sha256 != exact_payload_sha256(request) {
    415             return Err(Error::DeliveryReceiptPayloadMismatch);
    416         }
    417         if self.target_set != *request.target_set() {
    418             return Err(Error::DeliveryReceiptTargetSetMismatch);
    419         }
    420         validate_delivery_code(self.code.as_str())?;
    421         if matches!(self.retryability, Retryability::NotApplicable)
    422             || matches!(self.retry_after_unix_ms, Some(0))
    423             || (self.retry_after_unix_ms.is_some()
    424                 && !matches!(self.retryability, Retryability::Retryable))
    425         {
    426             return Err(Error::InvalidDeliveryOutcome);
    427         }
    428         if let Some(message) = &self.message {
    429             validate_delivery_message(message)?;
    430         }
    431         let mut observed = BTreeSet::new();
    432         for receipt in &self.partial_evidence {
    433             receipt.validate()?;
    434             if !request
    435                 .target_set()
    436                 .contains(receipt.target().fingerprint())
    437             {
    438                 return Err(Error::UnexpectedDeliveryTargetReceipt);
    439             }
    440             if !observed.insert(receipt.target().fingerprint().as_str()) {
    441                 return Err(Error::DuplicateDeliveryTargetReceipt);
    442             }
    443         }
    444         Ok(())
    445     }
    446 
    447     /// Returns the stable normalized failure code.
    448     pub fn code(&self) -> &str {
    449         self.code.as_str()
    450     }
    451 
    452     /// Returns whether retrying the same request may be useful.
    453     pub const fn retryability(&self) -> Retryability {
    454         self.retryability
    455     }
    456 
    457     /// Returns the earliest absolute Unix millisecond retry time, when supplied.
    458     pub const fn retry_after_unix_ms(&self) -> Option<u64> {
    459         self.retry_after_unix_ms
    460     }
    461 
    462     /// Returns bounded caller-safe diagnostic detail.
    463     pub fn message(&self) -> Option<&str> {
    464         self.message.as_deref()
    465     }
    466 
    467     /// Returns safe target evidence collected before the sink-wide failure.
    468     pub fn partial_evidence(&self) -> &[DeliveryTargetReceipt] {
    469         self.partial_evidence.as_slice()
    470     }
    471 }
    472 
    473 fn exact_payload_sha256(request: &DeliveryRequest) -> [u8; 32] {
    474     Sha256::digest(request.payload().event().raw_json().as_bytes()).into()
    475 }
    476 
    477 /// Host SPI for outbound event delivery.
    478 ///
    479 /// This trait supports external implementations and is dyn-compatible. Its
    480 /// futures are native `Send` or browser-local; implementations must not borrow request data after a
    481 /// future completes. `status` observes sink state and does not initiate
    482 /// delivery. `deliver` performs only the attempts authorized by its request,
    483 /// returns partial success per target, and owns no hidden retry loop.
    484 ///
    485 /// Dropping a returned future requests cancellation. If it is dropped before
    486 /// a remote request is published, the implementation must leave no remote
    487 /// operation behind. Once publication may have occurred, cancellation cannot
    488 /// claim rollback; a later observation may report the remote outcome. An
    489 /// explicit request deadline bounds work independently of future cancellation.
    490 pub trait EventSink: crate::host::HostBound {
    491     /// Returns the sink's current runtime status.
    492     fn status(&self) -> BoxFuture<'_, Result<SinkStatus, Error>>;
    493 
    494     /// Delivers an event according to the request's bounded target policy.
    495     fn deliver(
    496         &self,
    497         request: DeliveryRequest,
    498     ) -> BoxFuture<'_, Result<DeliveryReceipt, SinkFailure>>;
    499 
    500     /// Attempts only selected targets while retaining the full request binding.
    501     ///
    502     /// Implementations must validate the exact subset before I/O, keep every
    503     /// original target in successful receipts, and report unselected targets as
    504     /// unattempted. The default supports only a selection of every target; a
    505     /// proper subset fails closed without calling ordinary delivery.
    506     fn deliver_selected(
    507         &self,
    508         request: DeliveryRequest,
    509         selected: TargetSet,
    510     ) -> BoxFuture<'_, Result<DeliveryReceipt, SinkFailure>> {
    511         Box::pin(async move {
    512             if request.validate_target_selection(&selected).is_err() {
    513                 return Err(SinkFailure::invalid_contract(&request));
    514             }
    515             if selected.len() == request.target_set().len() {
    516                 return self.deliver(request).await;
    517             }
    518             Err(SinkFailure::for_request(
    519                 &request,
    520                 "target_selection_unsupported",
    521                 Retryability::Terminal,
    522                 None,
    523                 None,
    524                 Vec::new(),
    525             )
    526             .expect("static unsupported selection failure is valid"))
    527         })
    528     }
    529 }
    530 
    531 #[cfg(feature = "serde")]
    532 mod serde_impl {
    533     use super::*;
    534 
    535     impl serde::Serialize for DeliveryRequestId {
    536         fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    537         where
    538             S: serde::Serializer,
    539         {
    540             serializer.serialize_str(self.as_str())
    541         }
    542     }
    543 
    544     impl<'de> serde::Deserialize<'de> for DeliveryRequestId {
    545         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    546         where
    547             D: serde::Deserializer<'de>,
    548         {
    549             let value = <String as serde::Deserialize>::deserialize(deserializer)?;
    550             Self::parse(value).map_err(serde::de::Error::custom)
    551         }
    552     }
    553 
    554     #[derive(serde::Deserialize)]
    555     #[serde(deny_unknown_fields)]
    556     struct DeliveryRequestWire {
    557         request_id: String,
    558         payload: DeliveryPayload,
    559         target_set: TargetSet,
    560         satisfaction: SatisfactionPolicy,
    561         deadline_unix_ms: u64,
    562     }
    563 
    564     impl<'de> serde::Deserialize<'de> for DeliveryRequest {
    565         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    566         where
    567             D: serde::Deserializer<'de>,
    568         {
    569             let wire = DeliveryRequestWire::deserialize(deserializer)?;
    570             Self::new(
    571                 wire.request_id,
    572                 wire.payload,
    573                 wire.target_set,
    574                 wire.satisfaction,
    575                 wire.deadline_unix_ms,
    576             )
    577             .map_err(serde::de::Error::custom)
    578         }
    579     }
    580 
    581     #[derive(serde::Deserialize)]
    582     #[serde(deny_unknown_fields)]
    583     struct DeliveryTargetReceiptWire {
    584         target: Target,
    585         attempted: bool,
    586         outcome: DeliveryOutcome,
    587     }
    588 
    589     impl<'de> serde::Deserialize<'de> for DeliveryTargetReceipt {
    590         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    591         where
    592             D: serde::Deserializer<'de>,
    593         {
    594             let wire = DeliveryTargetReceiptWire::deserialize(deserializer)?;
    595             let receipt = Self {
    596                 target: wire.target,
    597                 attempted: wire.attempted,
    598                 outcome: wire.outcome,
    599             };
    600             receipt.validate().map_err(serde::de::Error::custom)?;
    601             Ok(receipt)
    602         }
    603     }
    604 
    605     #[derive(serde::Deserialize)]
    606     #[serde(deny_unknown_fields)]
    607     struct DeliveryReceiptWire {
    608         request_id: DeliveryRequestId,
    609         exact_payload_sha256: [u8; 32],
    610         target_set: TargetSet,
    611         target_receipts: Vec<DeliveryTargetReceipt>,
    612     }
    613 
    614     impl<'de> serde::Deserialize<'de> for DeliveryReceipt {
    615         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    616         where
    617             D: serde::Deserializer<'de>,
    618         {
    619             let wire = DeliveryReceiptWire::deserialize(deserializer)?;
    620             Self::new(
    621                 wire.request_id,
    622                 wire.exact_payload_sha256,
    623                 wire.target_set,
    624                 wire.target_receipts,
    625             )
    626             .map_err(serde::de::Error::custom)
    627         }
    628     }
    629 
    630     #[derive(serde::Deserialize)]
    631     #[serde(deny_unknown_fields)]
    632     struct SinkFailureWire {
    633         request_id: DeliveryRequestId,
    634         exact_payload_sha256: [u8; 32],
    635         target_set: TargetSet,
    636         code: String,
    637         retryability: Retryability,
    638         retry_after_unix_ms: Option<u64>,
    639         message: Option<String>,
    640         partial_evidence: Vec<DeliveryTargetReceipt>,
    641     }
    642 
    643     impl<'de> serde::Deserialize<'de> for SinkFailure {
    644         fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    645         where
    646             D: serde::Deserializer<'de>,
    647         {
    648             let wire = SinkFailureWire::deserialize(deserializer)?;
    649             let failure = Self {
    650                 request_id: wire.request_id,
    651                 exact_payload_sha256: wire.exact_payload_sha256,
    652                 target_set: wire.target_set,
    653                 code: wire.code,
    654                 retryability: wire.retryability,
    655                 retry_after_unix_ms: wire.retry_after_unix_ms,
    656                 message: wire.message,
    657                 partial_evidence: wire.partial_evidence,
    658             };
    659             validate_delivery_code(failure.code.as_str()).map_err(serde::de::Error::custom)?;
    660             if matches!(failure.retryability, Retryability::NotApplicable)
    661                 || matches!(failure.retry_after_unix_ms, Some(0))
    662                 || (failure.retry_after_unix_ms.is_some()
    663                     && !matches!(failure.retryability, Retryability::Retryable))
    664             {
    665                 return Err(serde::de::Error::custom(Error::InvalidDeliveryOutcome));
    666             }
    667             if let Some(message) = &failure.message {
    668                 validate_delivery_message(message).map_err(serde::de::Error::custom)?;
    669             }
    670             let mut observed = BTreeSet::new();
    671             for receipt in &failure.partial_evidence {
    672                 receipt.validate().map_err(serde::de::Error::custom)?;
    673                 if !failure.target_set.contains(receipt.target().fingerprint()) {
    674                     return Err(serde::de::Error::custom(
    675                         Error::UnexpectedDeliveryTargetReceipt,
    676                     ));
    677                 }
    678                 if !observed.insert(receipt.target().fingerprint().as_str()) {
    679                     return Err(serde::de::Error::custom(
    680                         Error::DuplicateDeliveryTargetReceipt,
    681                     ));
    682                 }
    683             }
    684             Ok(failure)
    685         }
    686     }
    687 }