lib

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

observations.rs (7148B)


      1 //! Synthetic normalized facts prove storage linkage, not remote execution.
      2 use super::{WorkspaceFixture, copied};
      3 use core::num::NonZeroU64;
      4 use futures::FutureExt;
      5 use radroots_domain::OperationId;
      6 use radroots_storage::{
      7     command::{DeliveryObservation, DeliveryObservationOutcome},
      8     workspace::{AttachmentProof, WorkspaceBinding},
      9 };
     10 use radroots_transport::{
     11     outcome::{DeliveryOutcome, Retryability},
     12     sink::{DeliveryRequestId, DeliveryTargetReceipt},
     13 };
     14 use serde_json::{Value, json};
     15 use wasm_bindgen::prelude::*;
     16 
     17 fn summary(value: &DeliveryObservation) -> Value {
     18     let target = value.target_receipt();
     19     let outcome = target.outcome();
     20     json!({"request":value.request_id().as_str(),"event":value.event_id().to_string(),"digest":hex::encode(value.envelope_digest()),"recipient":value.work().private().unwrap().recipient().to_string(),"capture":value.work().evidence().transaction_id().to_string(),"work":value.work().transaction_id().to_string(),"target":target.target().uri().as_str(),"fingerprint":target.target().fingerprint().as_str(),"attempted":target.was_attempted(),"class":value.kind().code(),"ordinal":value.target_ordinal(),"at":value.observed_at_unix_ms().map(|t|t.get()),"code":outcome.code(),"message":outcome.message()})
     21 }
     22 fn result(value: DeliveryObservationOutcome) -> String {
     23     match value {
     24         DeliveryObservationOutcome::Committed(value) => {
     25             json!({"kind":"committed","report":summary(&value)})
     26         }
     27         DeliveryObservationOutcome::Unknown(value) => {
     28             json!({"kind":"unknown","report":summary(&value)})
     29         }
     30     }
     31     .to_string()
     32 }
     33 #[wasm_bindgen]
     34 pub struct ObtainedObservation {
     35     binding: WorkspaceBinding,
     36     value: DeliveryObservation,
     37 }
     38 #[wasm_bindgen]
     39 impl ObtainedObservation {
     40     pub fn original(&self) -> String {
     41         summary(&self.value).to_string()
     42     }
     43 }
     44 #[wasm_bindgen]
     45 impl WorkspaceFixture {
     46     pub async fn observation(
     47         &self,
     48         n: u8,
     49         index: u8,
     50         id: u8,
     51         target: u8,
     52         kind: u8,
     53         time: u32,
     54     ) -> Result<ObtainedObservation, JsValue> {
     55         let request = self.request(n, false).await?;
     56         let mut recipients = vec![
     57             self.input.participant(),
     58             request.chat_command().unwrap().peer(),
     59         ];
     60         recipients.sort_unstable();
     61         recipients.dedup();
     62         let attempt = self
     63             .journal()
     64             .delivery_attempt(
     65                 request.binding().clone(),
     66                 OperationId::from_bytes([n; 32]),
     67                 request.command().digest(),
     68                 recipients[index as usize].into(),
     69                 DeliveryRequestId::parse(hex::encode([id; 32])).unwrap(),
     70                 copied(&self.proof),
     71             )
     72             .await
     73             .map_err(|e| JsValue::from_str(e.code()))?
     74             .ok_or(JsValue::from_str("missing_attempt"))?;
     75         let endpoint = attempt.intent().targets().targets()[target as usize].clone();
     76         let outcome = match kind {
     77             1 => DeliveryOutcome::accepted(),
     78             2 => DeliveryOutcome::rejected(),
     79             7 => DeliveryOutcome::delivered(),
     80             _ => DeliveryOutcome::failed(Retryability::Retryable).unwrap(),
     81         };
     82         let code = match kind {
     83             3 => "timeout",
     84             4 => "disconnected",
     85             _ => "synthetic_result",
     86         };
     87         let outcome = outcome
     88             .with_detail(code, format!("synthetic normalized detail {time}"))
     89             .unwrap();
     90         let report = if kind == 6 {
     91             DeliveryTargetReceipt::skipped(endpoint, outcome).unwrap()
     92         } else {
     93             DeliveryTargetReceipt::attempted(endpoint, outcome)
     94         };
     95         let value =
     96             DeliveryObservation::from_store_report(&attempt, &report, NonZeroU64::new(time as u64))
     97                 .map_err(|e| JsValue::from_str(e.code()))?;
     98         Ok(ObtainedObservation {
     99             binding: request.binding().clone(),
    100             value,
    101         })
    102     }
    103     pub async fn retain_observation(
    104         &self,
    105         original: &ObtainedObservation,
    106         wrong_proof: bool,
    107     ) -> Result<String, JsValue> {
    108         let proof = if wrong_proof {
    109             AttachmentProof::from_protected_input(&[0x31; 32]).unwrap()
    110         } else {
    111             copied(&self.proof)
    112         };
    113         self.journal()
    114             .record_delivery_observation(original.binding.clone(), proof, original.value.clone())
    115             .await
    116             .map(result)
    117             .map_err(|e| JsValue::from_str(e.code()))
    118     }
    119     pub async fn retain_observation_unknown(
    120         &self,
    121         original: &ObtainedObservation,
    122         hook: js_sys::Function,
    123     ) -> Result<String, JsValue> {
    124         hook.call0(&JsValue::NULL)?;
    125         self.journal()
    126             .record_delivery_observation(
    127                 original.binding.clone(),
    128                 copied(&self.proof),
    129                 original.value.clone(),
    130             )
    131             .await
    132             .map(result)
    133             .map_err(|e| JsValue::from_str(e.code()))
    134     }
    135     pub fn abandon_observation(&self, original: &ObtainedObservation) -> Result<(), JsValue> {
    136         if self
    137             .journal()
    138             .record_delivery_observation(
    139                 original.binding.clone(),
    140                 copied(&self.proof),
    141                 original.value.clone(),
    142             )
    143             .now_or_never()
    144             .is_some()
    145         {
    146             return Err(JsValue::from_str("unexpected_immediate_observation"));
    147         }
    148         Ok(())
    149     }
    150     pub async fn query_observations(&self, n: u8, index: u8, id: u8) -> Result<String, JsValue> {
    151         let request = self.request(n, false).await?;
    152         let mut recipients = vec![
    153             self.input.participant(),
    154             request.chat_command().unwrap().peer(),
    155         ];
    156         recipients.sort_unstable();
    157         recipients.dedup();
    158         self.journal()
    159             .delivery_observations(
    160                 request.binding().clone(),
    161                 OperationId::from_bytes([n; 32]),
    162                 request.command().digest(),
    163                 recipients[index as usize].into(),
    164                 DeliveryRequestId::parse(hex::encode([id; 32])).unwrap(),
    165                 copied(&self.proof),
    166             )
    167             .await
    168             .map(|values| values.iter().map(summary).collect::<Vec<_>>())
    169             .map(|v| json!(v).to_string())
    170             .map_err(|e| JsValue::from_str(e.code()))
    171     }
    172     pub async fn query_observation_scope(
    173         &self,
    174         original: &ObtainedObservation,
    175     ) -> Result<String, JsValue> {
    176         let evidence = original.value.work().evidence();
    177         self.journal()
    178             .delivery_observations(
    179                 original.binding.clone(),
    180                 evidence.operation_id(),
    181                 evidence.command_digest(),
    182                 evidence.target(),
    183                 original.value.request_id().clone(),
    184                 copied(&self.proof),
    185             )
    186             .await
    187             .map(|values| json!(values.iter().map(summary).collect::<Vec<_>>()).to_string())
    188             .map_err(|e| JsValue::from_str(e.code()))
    189     }
    190 }