lib

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

observation.rs (8176B)


      1 //! Bounded observations of an already retained exact transport attempt.
      2 
      3 use super::{DeliveryAttempt, OperationError, PublicationArtifact};
      4 use core::{fmt, num::NonZeroU64};
      5 use radroots_domain::EnvelopeEventId;
      6 use radroots_transport::{
      7     DeliveryReceipt, SinkFailure,
      8     outcome::DeliveryOutcomeKind,
      9     sink::{DeliveryRequestId, DeliveryTargetReceipt},
     10     target::TargetFingerprint,
     11 };
     12 
     13 /// Mechanical target normalization shared by independently authenticated owners.
     14 pub(crate) fn normalize(
     15     intent: &super::DeliveryIntent,
     16     ordinals: &[u8],
     17     report: &DeliveryTargetReceipt,
     18     observed_at: Option<NonZeroU64>,
     19 ) -> Result<(DeliveryObservationKind, u8), OperationError> {
     20     if observed_at.is_some_and(|time| time.get() > 253_402_300_799_999)
     21         || !intent.targets().targets().contains(report.target())
     22         || report.outcome().kind() == DeliveryOutcomeKind::Delivered
     23     {
     24         return Err(OperationError::InvalidEvidence);
     25     }
     26     let kind = if !report.was_attempted() {
     27         DeliveryObservationKind::NotAttempted
     28     } else {
     29         match report.outcome().kind() {
     30             DeliveryOutcomeKind::Accepted => DeliveryObservationKind::Accepted,
     31             DeliveryOutcomeKind::Rejected => DeliveryObservationKind::Rejected,
     32             DeliveryOutcomeKind::Failed | DeliveryOutcomeKind::Unavailable => {
     33                 match report.outcome().code() {
     34                     Some("timeout" | "deadline_exceeded") => DeliveryObservationKind::TimedOut,
     35                     Some("connection_failed" | "disconnected") => {
     36                         DeliveryObservationKind::Disconnected
     37                     }
     38                     _ => DeliveryObservationKind::Unknown,
     39                 }
     40             }
     41             DeliveryOutcomeKind::Delivered => return Err(OperationError::InvalidEvidence),
     42         }
     43     };
     44     let index = intent
     45         .selection()
     46         .iter()
     47         .position(|target| target == report.target().fingerprint())
     48         .ok_or(OperationError::InvalidEvidence)?;
     49     let ordinal = *ordinals.get(index).ok_or(OperationError::InvalidEvidence)?;
     50     Ok((kind, ordinal))
     51 }
     52 
     53 /// Independent append-only outcome classes. Each actual attempt/target has at
     54 /// most one original observation of each class; a later class never erases it.
     55 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     56 pub enum DeliveryObservationKind {
     57     /// The relay accepted this exact outer event, not recipient delivery.
     58     Accepted,
     59     /// The relay refused the event.
     60     Rejected,
     61     /// The bounded attempt ended without an acknowledgement before its deadline.
     62     TimedOut,
     63     /// The connection failed without establishing acceptance.
     64     Disconnected,
     65     /// The target result is uncertain or another normalized failure occurred.
     66     Unknown,
     67     /// The adapter explicitly reports that it did not attempt this target.
     68     NotAttempted,
     69 }
     70 impl DeliveryObservationKind {
     71     /// Fixed protected-record discriminator, never an authorization token.
     72     pub const fn code(self) -> u8 {
     73         match self {
     74             Self::Accepted => 1,
     75             Self::Rejected => 2,
     76             Self::TimedOut => 3,
     77             Self::Disconnected => 4,
     78             Self::Unknown => 5,
     79             Self::NotAttempted => 6,
     80         }
     81     }
     82 }
     83 
     84 /// Exact attempt-bound normalized data. Construction authenticates no adapter
     85 /// or storage. The native owner independently checks actual protected linkage.
     86 #[derive(Clone, Eq, PartialEq)]
     87 pub struct DeliveryObservation {
     88     work: PublicationArtifact,
     89     request: DeliveryRequestId,
     90     event: EnvelopeEventId,
     91     envelope_digest: [u8; 32],
     92     target: DeliveryTargetReceipt,
     93     kind: DeliveryObservationKind,
     94     ordinal: u8,
     95     observed_at: Option<NonZeroU64>,
     96 }
     97 impl DeliveryObservation {
     98     /// Selects one exact target only after checking the complete receipt's
     99     /// original request, target set and exact payload binding.
    100     pub fn from_receipt(
    101         attempt: &DeliveryAttempt,
    102         receipt: &DeliveryReceipt,
    103         target: &TargetFingerprint,
    104         observed_at_unix_ms: Option<NonZeroU64>,
    105     ) -> Result<Self, OperationError> {
    106         receipt
    107             .validate_for_request(&attempt.transport_request()?)
    108             .map_err(|_| OperationError::InvalidEvidence)?;
    109         let report = receipt
    110             .target_receipts()
    111             .iter()
    112             .find(|report| report.target().fingerprint() == target)
    113             .ok_or(OperationError::InvalidEvidence)?;
    114         Self::from_store_report(attempt, report, observed_at_unix_ms)
    115     }
    116 
    117     /// Selects actual partial evidence from a request-bound sink failure.
    118     /// Missing target evidence remains absent; it is never invented as failure.
    119     pub fn from_failure(
    120         attempt: &DeliveryAttempt,
    121         failure: &SinkFailure,
    122         target: &TargetFingerprint,
    123         observed_at_unix_ms: Option<NonZeroU64>,
    124     ) -> Result<Self, OperationError> {
    125         failure
    126             .validate_for_request(&attempt.transport_request()?)
    127             .map_err(|_| OperationError::InvalidEvidence)?;
    128         let report = failure
    129             .partial_evidence()
    130             .iter()
    131             .find(|report| report.target().fingerprint() == target)
    132             .ok_or(OperationError::InvalidEvidence)?;
    133         Self::from_store_report(attempt, report, observed_at_unix_ms)
    134     }
    135 
    136     /// Reconstructs bounded data against an original attempt. This is not proof
    137     /// of execution, remote acknowledgement, current access or a durable row.
    138     pub fn from_store_report(
    139         attempt: &DeliveryAttempt,
    140         report: &DeliveryTargetReceipt,
    141         observed_at_unix_ms: Option<NonZeroU64>,
    142     ) -> Result<Self, OperationError> {
    143         let (kind, ordinal) = normalize(
    144             attempt.intent(),
    145             attempt.target_ordinals(),
    146             report,
    147             observed_at_unix_ms,
    148         )?;
    149         Ok(Self {
    150             work: attempt.work(),
    151             request: attempt.intent().request_id().clone(),
    152             event: attempt.intent().event_id(),
    153             envelope_digest: *attempt.envelope_digest(),
    154             target: report.clone(),
    155             kind,
    156             ordinal,
    157             observed_at: observed_at_unix_ms,
    158         })
    159     }
    160     /// Original publication scope, independently checked by the native owner.
    161     pub const fn work(&self) -> PublicationArtifact {
    162         self.work
    163     }
    164     /// Full original potential invocation identity.
    165     pub const fn request_id(&self) -> &DeliveryRequestId {
    166         &self.request
    167     }
    168     /// Actual outer identity, separate from logical message and recipient seal.
    169     pub const fn event_id(&self) -> EnvelopeEventId {
    170         self.event
    171     }
    172     /// Digest of the exact original retained signed representation.
    173     pub const fn envelope_digest(&self) -> &[u8; 32] {
    174         &self.envelope_digest
    175     }
    176     /// Original normalized target evidence, for protected handling only.
    177     pub const fn target_receipt(&self) -> &DeliveryTargetReceipt {
    178         &self.target
    179     }
    180     /// Independent observation class; it changes no command installation fact.
    181     pub const fn kind(&self) -> DeliveryObservationKind {
    182         self.kind
    183     }
    184     /// Original potential invocation number for this exact selected endpoint.
    185     pub const fn target_ordinal(&self) -> u8 {
    186         self.ordinal
    187     }
    188     /// First original optional observation time. No ambient clock is consulted.
    189     pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> {
    190         self.observed_at
    191     }
    192 }
    193 impl fmt::Debug for DeliveryObservation {
    194     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    195         f.write_str("DeliveryObservation(<redacted>)")
    196     }
    197 }
    198 
    199 /// Actual owner outcome, separate from the observation's remote meaning.
    200 pub enum DeliveryObservationOutcome {
    201     /// Confirmed append or matching original first observation.
    202     Committed(DeliveryObservation),
    203     /// Reconcile this original observation before inferring durable capture.
    204     Unknown(DeliveryObservation),
    205 }
    206 impl fmt::Debug for DeliveryObservationOutcome {
    207     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    208         f.write_str("DeliveryObservationOutcome(<redacted>)")
    209     }
    210 }