lib

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

delivery.rs (8863B)


      1 //! Stock-owned protected dispatch history. Transport stays outside transactions.
      2 use super::*;
      3 use inventory::{Turn, checkpoint};
      4 use radroots_domain::{
      5     ActorRef, CheckpointDigest, CommandDigest, EnvelopeEventId, OperationId, OrderId, PublicKey,
      6     UnixSeconds,
      7 };
      8 use radroots_storage::{
      9     command::{DeliveryIntent, DeliveryObservationKind, OperationError, SignedDmRelaySource},
     10     inventory::{
     11         InventoryCheckpointRef, StockDeliveryAttempt, StockDeliveryAttemptOutcome,
     12         StockDeliveryObservation, StockDeliveryObservationOutcome, StockDeliveryObservationPage,
     13         StockDeliveryObservationReceipt, StockDeliveryRequest, StockDeliverySummary,
     14         StockDeliveryTargetProgress, StockEnvelopeRequest,
     15     },
     16 };
     17 use radroots_transport::{
     18     TargetSet,
     19     policy::SatisfactionPolicy,
     20     sink::{DeliveryRequestId, DeliveryTargetReceipt},
     21     target::TargetFingerprint,
     22 };
     23 use sha2::{Digest, Sha256};
     24 use sqlx::Row;
     25 use std::{num::NonZeroU64, sync::Arc};
     26 
     27 pub(in crate::workspace::stock) mod attempt;
     28 mod graph;
     29 pub(in crate::workspace::stock) mod observation;
     30 mod observation_operations;
     31 mod operations;
     32 mod projection;
     33 mod wire;
     34 pub(in crate::workspace) use observation_operations::{capture_observation, page};
     35 pub(in crate::workspace) use operations::{prepare, query_attempt, summary};
     36 pub(in crate::workspace::stock) use projection::{Projection, raw_projection};
     37 
     38 const ATTEMPT_MAX: usize = 65536;
     39 const OBSERVATION_MAX: usize = 16384;
     40 const ATTEMPT_COUNT_MAX: usize = 384;
     41 const OBSERVATION_COUNT_MAX: usize = 2304;
     42 const PAGE_MAX: usize = 16;
     43 
     44 pub(in crate::workspace::stock) async fn snapshot(
     45     turn: &mut Turn<'_>,
     46     request: StockEnvelopeRequest,
     47     authority: &Authority,
     48 ) -> Result<[StockDeliverySummary; 2], OperationError> {
     49     let graph = Box::pin(graph::Graph::read(turn, &request, authority, None, None)).await?;
     50     let original = Box::pin(inventory::acceptance::codec::read(
     51         turn.connection,
     52         turn.selected,
     53         turn.crypto,
     54         request.operation_id(),
     55     ))
     56     .await?
     57     .ok_or(OperationError::RecoveryRequired)?;
     58     let checkpoint = authority
     59         .inventory
     60         .ok_or(OperationError::RecoveryRequired)?;
     61     let checkpoint = InventoryCheckpointRef::from_host_metadata(
     62         turn.selected.authority(),
     63         checkpoint.revision,
     64         checkpoint.head,
     65     )?
     66     .with_optional_authorization(authority.authorization);
     67     let reports = original
     68         .receipt
     69         .rumor()
     70         .recipients()
     71         .each_ref()
     72         .map(|recipient| {
     73             let source = StockEnvelopeRequest::new(
     74                 request.binding().clone(),
     75                 request.minimum_checkpoint(),
     76                 request.operation_id(),
     77                 request.command_digest(),
     78                 *recipient,
     79                 None,
     80             )?;
     81             graph.summary(&source, checkpoint)
     82         });
     83     let [first, second] = reports;
     84     Ok([first?, second?])
     85 }
     86 
     87 fn request_key(request: &DeliveryRequestId) -> [u8; 32] {
     88     Sha256::digest(request.as_str().as_bytes()).into()
     89 }
     90 fn target_key(target: &TargetFingerprint) -> [u8; 32] {
     91     Sha256::digest(target.as_str().as_bytes()).into()
     92 }
     93 fn validate_request(request: &DeliveryRequestId) -> Result<(), OperationError> {
     94     let raw = request.as_str();
     95     if raw.len() != 64
     96         || !raw
     97             .bytes()
     98             .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
     99     {
    100         return Err(OperationError::InvalidCommand);
    101     }
    102     Ok(())
    103 }
    104 async fn confirm_record(
    105     connection: &mut SqliteConnection,
    106     frame: &ledger::Retained,
    107     projection: Projection,
    108 ) -> Result<(), OperationError> {
    109     if !matches!(
    110         (frame.header.family, projection),
    111         (ledger::Family::DeliveryAttempt, Projection::Attempt { .. })
    112             | (
    113                 ledger::Family::DeliveryObservation,
    114                 Projection::Observation { .. }
    115             )
    116     ) {
    117         return Err(OperationError::RecoveryRequired);
    118     }
    119     ledger::confirm_header(connection, &frame.header, &frame.protected).await?;
    120     ledger::confirm_parts(
    121         connection,
    122         frame.header.actor,
    123         frame.header.operation,
    124         frame.parts_witness,
    125         frame.header.parts,
    126     )
    127     .await?;
    128     projection
    129         .confirm(
    130             connection,
    131             frame.header.actor.participant(),
    132             frame.header.operation,
    133         )
    134         .await?;
    135     let movements: i64 =
    136         sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?")
    137             .bind(frame.header.actor.participant().as_bytes().as_slice())
    138             .bind(frame.header.operation.as_bytes().as_slice())
    139             .fetch_one(connection)
    140             .await
    141             .map_err(|_| OperationError::RecoveryRequired)?;
    142     if movements != 0 {
    143         return Err(OperationError::RecoveryRequired);
    144     }
    145     Ok(())
    146 }
    147 fn history(frame: ledger::Retained, projection: Projection) -> ledger::HistoryEntry {
    148     ledger::HistoryEntry {
    149         deficit: None,
    150         delivery: Some(projection),
    151         envelope: None,
    152         aborted: None,
    153         preparation: None,
    154         header: frame.header,
    155         protected: frame.protected,
    156         parts_witness: frame.parts_witness,
    157         pools: vec![],
    158         mapping: None,
    159         movements: vec![],
    160         signing: None,
    161         installation: None,
    162         local_record: None,
    163     }
    164 }
    165 struct Append {
    166     actor: ActorRef,
    167     original: OperationId,
    168     digest: CommandDigest,
    169     order: OrderId,
    170     family: ledger::Family,
    171     projection: Projection,
    172 }
    173 struct Prepared {
    174     frame: ledger::Prepared,
    175     projection: Projection,
    176     root: Vec<u8>,
    177 }
    178 impl Prepared {
    179     async fn new(
    180         turn: &Turn<'_>,
    181         authority: &Authority,
    182         append: Append,
    183         body: &[u8],
    184     ) -> Result<Self, OperationError> {
    185         if !matches!(authority.catalog, 17..=20) {
    186             return Err(OperationError::UnsupportedOperation);
    187         }
    188         let before = authority
    189             .inventory
    190             .ok_or(OperationError::RecoveryRequired)?;
    191         let revision = Sequence::new(
    192             before
    193                 .revision
    194                 .get()
    195                 .checked_add(1)
    196                 .ok_or(WorkspaceError::Capacity)?,
    197         )
    198         .map_err(|_| WorkspaceError::Capacity)?;
    199         let mut header = ledger::Header {
    200             version: 5,
    201             family: append.family,
    202             namespace: SellerAuthoritySelection::from_attachment(turn.selected),
    203             actor: append.actor,
    204             operation: OperationId::from_bytes(super::super::random()?),
    205             digest: append.digest,
    206             transaction: TransactionId::from_bytes(super::super::random()?),
    207             revision,
    208             previous: before.head,
    209             head: CheckpointDigest::from_bytes([0; 32]),
    210             pool: None,
    211             order: Some(append.order),
    212             related_operation: Some(append.original),
    213             subject_grant: None,
    214             bytes: 0,
    215             parts: 0,
    216             body_digest: [0; 32],
    217         };
    218         header.head = wire::head(&header, body);
    219         let frame = Box::pin(ledger::prepare(turn.crypto, turn.selected, header, body)).await?;
    220         let mut next = authority.clone();
    221         next.inventory = Some(InventoryCheckpoint {
    222             revision,
    223             head: Some(frame.header.head),
    224             ..before
    225         });
    226         let root = Box::pin(turn.crypto.seal_stock_root(
    227             turn.selected,
    228             next.catalog,
    229             &next.encode()?,
    230         ))
    231         .await?;
    232         Ok(Self {
    233             frame,
    234             projection: append.projection,
    235             root,
    236         })
    237     }
    238     fn checkpoint(&self, authority: &Authority) -> Result<InventoryCheckpointRef, OperationError> {
    239         Ok(InventoryCheckpointRef::from_host_metadata(
    240             authority.input.authority(),
    241             self.frame.header.revision,
    242             Some(self.frame.header.head),
    243         )?)
    244     }
    245     async fn insert(
    246         &self,
    247         connection: &mut SqliteConnection,
    248         original_root: &[u8],
    249     ) -> Result<(), OperationError> {
    250         self.frame.insert_record(connection).await?;
    251         self.projection
    252             .insert(
    253                 connection,
    254                 self.frame.header.actor.participant(),
    255                 self.frame.header.operation,
    256             )
    257             .await?;
    258         let result =
    259             sqlx::query("UPDATE stock_authority SET protected=? WHERE singleton=1 AND protected=?")
    260                 .bind(&self.root)
    261                 .bind(original_root)
    262                 .execute(connection)
    263                 .await
    264                 .map_err(|_| OperationError::StorageFailure)?;
    265         if result.rows_affected() != 1 {
    266             return Err(OperationError::RecoveryRequired);
    267         }
    268         Ok(())
    269     }
    270 }