lib

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

order_state.rs (10421B)


      1 //! Current order selectors are derived cache data, never business authority.
      2 use super::*;
      3 use radroots_domain::{OperationId, OrderId, PublicKey};
      4 use radroots_storage::command::OperationError;
      5 use sqlx::Row;
      6 
      7 #[derive(Clone, Copy, Eq, PartialEq)]
      8 pub(super) enum Phase {
      9     Prepared,
     10     Installed,
     11     Aborted,
     12 }
     13 impl Phase {
     14     fn code(self) -> i64 {
     15         match self {
     16             Self::Prepared => 0,
     17             Self::Installed => 1,
     18             Self::Aborted => 2,
     19         }
     20     }
     21 }
     22 #[derive(Clone, Copy, Eq, PartialEq)]
     23 pub(super) struct Marker {
     24     pub order: OrderId,
     25     pub actor: PublicKey,
     26     pub operation: OperationId,
     27     pub entry: OperationId,
     28     pub revision: Sequence,
     29     pub phase: Phase,
     30 }
     31 impl Marker {
     32     /// Called only with a completely authenticated family-specific entry.
     33     pub fn from_history(entry: &ledger::HistoryEntry) -> Result<Option<Self>, OperationError> {
     34         let phase = match entry.header.family {
     35             ledger::Family::Acceptance => Phase::Prepared,
     36             ledger::Family::Installation => Phase::Installed,
     37             ledger::Family::AbortedPreparation => Phase::Aborted,
     38             _ => return Ok(None),
     39         };
     40         Self::from_header(&entry.header, phase).map(Some)
     41     }
     42     pub fn from_header(header: &ledger::Header, phase: Phase) -> Result<Self, OperationError> {
     43         let family = match phase {
     44             Phase::Prepared => 2,
     45             Phase::Installed => 6,
     46             Phase::Aborted => 7,
     47         };
     48         if header.family.code() != family {
     49             return Err(OperationError::RecoveryRequired);
     50         }
     51         let operation = match phase {
     52             Phase::Prepared => header.operation,
     53             Phase::Installed | Phase::Aborted => header
     54                 .related_operation
     55                 .ok_or(OperationError::RecoveryRequired)?,
     56         };
     57         Ok(Self {
     58             order: header.order.ok_or(OperationError::RecoveryRequired)?,
     59             actor: header.actor.participant(),
     60             operation,
     61             entry: header.operation,
     62             revision: header.revision,
     63             phase,
     64         })
     65     }
     66 }
     67 
     68 pub(super) struct Witness {
     69     pub order: OrderId,
     70     pub expected: Option<Marker>,
     71 }
     72 impl Witness {
     73     /// Compare the complete selected raw cache row after all provider IO.
     74     pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> {
     75         let row = sqlx::query("SELECT actor,operation_id,entry_id,revision,phase FROM stock_order_states WHERE order_id=?")
     76             .bind(self.order.as_bytes().as_slice()).fetch_optional(connection).await
     77             .map_err(|_| OperationError::RecoveryRequired)?;
     78         let actual = if let Some(row) = row {
     79             let bytes = |column| {
     80                 row.try_get::<Vec<u8>, _>(column)
     81                     .map_err(|_| OperationError::RecoveryRequired)?
     82                     .try_into()
     83                     .map_err(|_| OperationError::RecoveryRequired)
     84             };
     85             let revision: i64 = row
     86                 .try_get(3)
     87                 .map_err(|_| OperationError::RecoveryRequired)?;
     88             let phase: i64 = row
     89                 .try_get(4)
     90                 .map_err(|_| OperationError::RecoveryRequired)?;
     91             if revision <= 0 {
     92                 return Err(OperationError::RecoveryRequired);
     93             }
     94             Some(Marker {
     95                 order: self.order,
     96                 actor: PublicKey::from_bytes(bytes(0)?)
     97                     .map_err(|_| OperationError::RecoveryRequired)?,
     98                 operation: OperationId::from_bytes(bytes(1)?),
     99                 entry: OperationId::from_bytes(bytes(2)?),
    100                 revision: Sequence::new(revision as u64)
    101                     .map_err(|_| OperationError::RecoveryRequired)?,
    102                 phase: match phase {
    103                     0 => Phase::Prepared,
    104                     1 => Phase::Installed,
    105                     2 => Phase::Aborted,
    106                     _ => return Err(OperationError::RecoveryRequired),
    107                 },
    108             })
    109         } else {
    110             None
    111         };
    112         if actual != self.expected {
    113             return Err(OperationError::RecoveryRequired);
    114         }
    115         Ok(())
    116     }
    117     /// The owning BEGIN IMMEDIATE transaction must retain the bound history
    118     /// and root witnesses as well. This row supplies no independent authority.
    119     pub async fn advance(
    120         &self,
    121         connection: &mut SqliteConnection,
    122         next: Marker,
    123     ) -> Result<(), OperationError> {
    124         if next.order != self.order
    125             || self
    126                 .expected
    127                 .is_some_and(|old| next.revision <= old.revision)
    128         {
    129             return Err(OperationError::RecoveryRequired);
    130         }
    131         let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
    132             .fetch_one(&mut *connection)
    133             .await
    134             .map_err(|_| OperationError::RecoveryRequired)?;
    135         let legal = match self.expected {
    136             None => next.phase == Phase::Prepared,
    137             Some(old) if old.actor == next.actor => match (old.phase, next.phase) {
    138                 (Phase::Prepared, Phase::Installed | Phase::Aborted) => {
    139                     old.operation == next.operation
    140                 }
    141                 (Phase::Aborted, Phase::Prepared) => old.operation != next.operation,
    142                 (Phase::Installed, Phase::Prepared) if catalog >= 20 => {
    143                     old.operation != next.operation
    144                 }
    145                 _ => false,
    146             },
    147             Some(_) => false,
    148         };
    149         if !legal {
    150             return Err(OperationError::RecoveryRequired);
    151         }
    152         self.confirm(connection).await?;
    153         let result = if let Some(old) = self.expected {
    154             sqlx::query("UPDATE stock_order_states SET actor=?,operation_id=?,entry_id=?,revision=?,phase=? WHERE order_id=? AND actor=? AND operation_id=? AND entry_id=? AND revision=? AND phase=?")
    155                 .bind(next.actor.as_bytes().as_slice()).bind(next.operation.as_bytes().as_slice())
    156                 .bind(next.entry.as_bytes().as_slice()).bind(next.revision.get() as i64)
    157                 .bind(next.phase.code()).bind(self.order.as_bytes().as_slice())
    158                 .bind(old.actor.as_bytes().as_slice()).bind(old.operation.as_bytes().as_slice())
    159                 .bind(old.entry.as_bytes().as_slice()).bind(old.revision.get() as i64)
    160                 .bind(old.phase.code()).execute(connection).await
    161         } else {
    162             sqlx::query("INSERT INTO stock_order_states(order_id,actor,operation_id,entry_id,revision,phase) VALUES(?,?,?,?,?,?)")
    163                 .bind(next.order.as_bytes().as_slice()).bind(next.actor.as_bytes().as_slice())
    164                 .bind(next.operation.as_bytes().as_slice()).bind(next.entry.as_bytes().as_slice())
    165                 .bind(next.revision.get() as i64).bind(next.phase.code()).execute(connection).await
    166         }.map_err(|_| OperationError::StorageFailure)?;
    167         if result.rows_affected() != 1 {
    168             return Err(OperationError::RecoveryRequired);
    169         }
    170         Ok(())
    171     }
    172 }
    173 
    174 /// Constant-memory backward validation of retained decision transitions. Each
    175 /// original preparation remains independently recoverable after a later abort.
    176 pub(super) struct Chain {
    177     pub latest: Option<Marker>,
    178     previous: Previous,
    179     replacements: bool,
    180 }
    181 enum Previous {
    182     Latest,
    183     Preparation(OperationId),
    184     AbortOrGenesis(OperationId),
    185 }
    186 impl Chain {
    187     pub const fn new(catalog: i64) -> Self {
    188         Self {
    189             latest: None,
    190             previous: Previous::Latest,
    191             replacements: catalog >= 20,
    192         }
    193     }
    194     pub fn observe(&mut self, marker: Marker) -> Result<(), OperationError> {
    195         if self.latest.is_none() {
    196             self.latest = Some(marker);
    197         }
    198         match self.previous {
    199             Previous::Latest => {}
    200             Previous::Preparation(operation)
    201                 if marker.phase == Phase::Prepared && marker.operation == operation => {}
    202             Previous::AbortOrGenesis(operation)
    203                 if (marker.phase == Phase::Aborted
    204                     || (self.replacements && marker.phase == Phase::Installed))
    205                     && marker.operation != operation => {}
    206             _ => return Err(OperationError::RecoveryRequired),
    207         }
    208         self.previous = match marker.phase {
    209             Phase::Prepared => Previous::AbortOrGenesis(marker.operation),
    210             Phase::Installed | Phase::Aborted => Previous::Preparation(marker.operation),
    211         };
    212         Ok(())
    213     }
    214     pub fn complete(&self) -> Result<(), OperationError> {
    215         match self.previous {
    216             Previous::Latest | Previous::AbortOrGenesis(_) => Ok(()),
    217             Previous::Preparation(_) => Err(OperationError::RecoveryRequired),
    218         }
    219     }
    220 }
    221 
    222 pub(super) struct Checked {
    223     pub witness: Witness,
    224     pub ancestry: inventory::checkpoint::MinimumProof,
    225 }
    226 impl Checked {
    227     pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> {
    228         Box::pin(self.ancestry.confirm(connection)).await?;
    229         self.witness.confirm(connection).await
    230     }
    231     pub async fn advance(
    232         &self,
    233         connection: &mut SqliteConnection,
    234         next: Marker,
    235     ) -> Result<(), OperationError> {
    236         self.confirm(connection).await?;
    237         self.witness.advance(connection, next).await
    238     }
    239 }
    240 
    241 /// Order history eligibility only. The caller still confirms current consent,
    242 /// exact intent, deadline, provider capability and this proof before dispatch.
    243 pub(super) async fn signing_state(
    244     turn: &mut inventory::Turn<'_>,
    245     access: &inventory::Access,
    246     order: OrderId,
    247     operation: OperationId,
    248     allow_installed_copy: bool,
    249 ) -> Result<Option<Checked>, OperationError> {
    250     if access.authority.catalog < 13 {
    251         return Ok(None);
    252     }
    253     let checked = Box::pin(inventory::checkpoint::authenticate_order_state(
    254         turn.connection,
    255         turn.selected,
    256         turn.crypto,
    257         &access.current,
    258         &access.authority,
    259         order,
    260     ))
    261     .await?;
    262     if checked.witness.expected.is_none_or(|value| {
    263         value.operation != operation
    264             || !(value.phase == Phase::Prepared
    265                 || (allow_installed_copy && value.phase == Phase::Installed))
    266     }) {
    267         return Err(OperationError::StaleState);
    268     }
    269     Ok(Some(checked))
    270 }