request.rs (9124B)
1 //! Fresh initial request/source inspection. Execution rights, installed order 2 //! state, pending fences and actual atomic stock effects remain separate. 3 use super::*; 4 use radroots_domain::{ 5 CheckpointRef, Terms, TermsDigest, UnixSeconds, 6 causal::{CausalRecord, CausalScope, RequestClaimError}, 7 }; 8 use radroots_storage::workspace::seller_stock::StockListingCheckpointRef; 9 use std::collections::BTreeMap; 10 mod replacement; 11 pub(in crate::workspace::stock) use replacement::{ 12 Selected as ReplacementSource, prepare as prepare_terms, 13 }; 14 15 /// Explicit private request/source data under current administrative read access. 16 /// This does not authorize execution or promise a physical hold/agreement. 17 pub struct StockRequestSnapshot { 18 pub(super) scope: CausalScope, 19 pub(super) request: RecordId, 20 pub(super) terms: Box<Terms>, 21 pub(super) digest: TermsDigest, 22 pub(super) expires: UnixSeconds, 23 pub(super) quote: Option<RecordId>, 24 pub(super) checkpoint: CheckpointRef, 25 pub(super) sources: StockSourceCheckpointRef, 26 pub(super) listings: StockListingCheckpointRef, 27 pub(super) observed_at: UnixSeconds, 28 pub(super) inventory: radroots_storage::inventory::InventoryCheckpointRef, 29 } 30 impl StockRequestSnapshot { 31 /// Inventory progress included in the complete local causal read. 32 pub const fn inventory_checkpoint( 33 &self, 34 ) -> radroots_storage::inventory::InventoryCheckpointRef { 35 self.inventory 36 } 37 /// Exact selected scope derived from original authenticated request content. 38 pub const fn scope(&self) -> CausalScope { 39 self.scope 40 } 41 /// Exact original request identity, distinct from its transport envelopes. 42 pub const fn request(&self) -> RecordId { 43 self.request 44 } 45 /// Explicit private disclosure of complete original buyer-authorized terms. 46 pub fn terms(&self) -> &Terms { 47 &self.terms 48 } 49 /// Canonical complete terms identity; no approval is minted by this getter. 50 pub const fn terms_digest(&self) -> TermsDigest { 51 self.digest 52 } 53 /// Earliest request/quote deadline, excluding grant/approval/issuance bounds. 54 pub const fn expires_at(&self) -> UnixSeconds { 55 self.expires 56 } 57 /// Exact optional complete seller quote used for source permission. 58 pub const fn quote(&self) -> Option<RecordId> { 59 self.quote 60 } 61 /// Complete local causal data; not an installed order or decision fence. 62 pub const fn checkpoint(&self) -> &CheckpointRef { 63 &self.checkpoint 64 } 65 /// Independently acknowledged retained private source progress. 66 pub const fn source_checkpoint(&self) -> StockSourceCheckpointRef { 67 self.sources 68 } 69 /// Independently acknowledged retained public source progress. 70 pub const fn listing_checkpoint(&self) -> StockListingCheckpointRef { 71 self.listings 72 } 73 /// Final usable observation after transaction witnesses/current access checks. 74 pub const fn observed_at(&self) -> UnixSeconds { 75 self.observed_at 76 } 77 } 78 impl std::fmt::Debug for StockRequestSnapshot { 79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 80 f.write_str("StockRequestSnapshot(<private request>)") 81 } 82 } 83 pub(in crate::workspace::stock) struct Prepared { 84 pub scope: CausalScope, 85 pub authorization: RecordId, 86 pub digest: TermsDigest, 87 pub expires: UnixSeconds, 88 pub quote: Option<RecordId>, 89 pub replacement: Option<radroots_domain::causal::ReplacementTermsSelection>, 90 pub history: history::Prepared, 91 lookup: Option<checkpoint::Proof>, 92 views: BTreeMap<EnvelopeEventId, super::super::public_source::admission::ListingView>, 93 } 94 fn claim_error(error: RequestClaimError) -> OperationError { 95 match error { 96 RequestClaimError::MissingHistory => OperationError::MissingHistory, 97 RequestClaimError::Uninterpreted => OperationError::UnsupportedOperation, 98 RequestClaimError::Expired => OperationError::DeadlineExceeded, 99 RequestClaimError::ClockAhead => WorkspaceError::Unavailable.into(), 100 RequestClaimError::Conflicted 101 | RequestClaimError::Withdrawn 102 | RequestClaimError::Declined 103 | RequestClaimError::ConflictingAuthorizations 104 | RequestClaimError::RequiresReconciliation => OperationError::StaleState, 105 _ => OperationError::InvalidEvidence, 106 } 107 } 108 impl Prepared { 109 pub fn terms(&self) -> Result<&Terms, OperationError> { 110 match self 111 .history 112 .records 113 .get( 114 &self 115 .replacement 116 .map(|value| value.proposal()) 117 .unwrap_or(self.authorization), 118 ) 119 .map(|record| record.content().payload()) 120 { 121 Some(radroots_domain::CommercePayload::Request(request)) 122 if self.replacement.is_none() => 123 { 124 Ok(request.terms()) 125 } 126 Some(radroots_domain::CommercePayload::TermsProposed(proposal)) 127 if self.replacement.is_some() => 128 { 129 Ok(proposal.terms()) 130 } 131 _ => Err(OperationError::RecoveryRequired), 132 } 133 } 134 pub fn validate_at(&self, at: UnixSeconds) -> Result<(), OperationError> { 135 if at >= self.expires { 136 return Err(OperationError::DeadlineExceeded); 137 } 138 for line in self.terms()?.lines() { 139 self.views 140 .get(&line.source().event_id()) 141 .ok_or(OperationError::RecoveryRequired)? 142 .validate(line, self.quote.is_some() || self.replacement.is_some(), at)?; 143 } 144 Ok(()) 145 } 146 pub async fn confirm(&self, connection: &mut SqliteConnection) -> Result<(), OperationError> { 147 if let Some(lookup) = &self.lookup { 148 lookup.confirm(connection).await?; 149 } 150 self.history.confirm(connection).await?; 151 for view in self.views.values() { 152 view.confirm(connection).await?; 153 } 154 Ok(()) 155 } 156 } 157 pub(in crate::workspace::stock) async fn prepare( 158 connection: &mut SqliteConnection, 159 input: &AttachmentInput, 160 crypto: &WorkspaceCrypto, 161 inventory_read: history::InventoryRead<'_>, 162 request: RecordId, 163 listing_minimum: StockListingCheckpointRef, 164 observed_at: UnixSeconds, 165 ) -> Result<Prepared, OperationError> { 166 let authority = inventory_read.authority; 167 let raw = record::canonical(connection, input, crypto, request).await?; 168 let observed = raw 169 .as_ref() 170 .map(|(raw, _)| <[u8; 32]>::from(Sha256::digest(&**raw))); 171 let lookup = checkpoint::authenticate( 172 connection, 173 input, 174 crypto, 175 authority 176 .sources 177 .ok_or(OperationError::UnsupportedOperation)?, 178 checkpoint::Target::Record(request, observed), 179 ) 180 .await?; 181 let (raw, _) = raw.ok_or(OperationError::MissingHistory)?; 182 let decoded = 183 radroots_protocol::commerce::decode(&raw).map_err(|_| OperationError::RecoveryRequired)?; 184 let header = decoded.content().header(); 185 if decoded.content().record_type() != radroots_domain::CommerceType::Request { 186 return Err(OperationError::InvalidCommand); 187 } 188 let scope = CausalScope::new( 189 header.thread_id(), 190 header.order_id().ok_or(OperationError::InvalidEvidence)?, 191 header.buyer(), 192 header.seller(), 193 ) 194 .map_err(|_| OperationError::InvalidEvidence)?; 195 let history = Box::pin(history::prepare( 196 connection, 197 input, 198 crypto, 199 inventory_read, 200 scope, 201 listing_minimum, 202 )) 203 .await?; 204 let nodes: Vec<_> = history 205 .records 206 .iter() 207 .map(|(id, record)| CausalRecord::new(*id, record.content())) 208 .collect(); 209 let claim = radroots_domain::causal::prepare_initial_request( 210 scope, 211 request, 212 &nodes, 213 &history.external, 214 &history.uninterpreted, 215 observed_at, 216 ) 217 .map_err(claim_error)?; 218 let digest = radroots_protocol::terms::EncodedTerms::capture(claim.terms()) 219 .map_err(|_| OperationError::InvalidEvidence)? 220 .digest(); 221 let expires = claim.expires_at(); 222 let quote = claim.quote(); 223 let mut views = BTreeMap::new(); 224 for line in claim.terms().lines() { 225 if let std::collections::btree_map::Entry::Vacant(entry) = 226 views.entry(line.source().event_id()) 227 { 228 let view = super::super::public_source::admission::prepare( 229 connection, 230 input, 231 crypto, 232 authority, 233 line.source(), 234 observed_at, 235 ) 236 .await?; 237 entry.insert(view); 238 } 239 views[&line.source().event_id()].validate(line, claim.quote().is_some(), observed_at)?; 240 } 241 Ok(Prepared { 242 scope, 243 authorization: request, 244 digest, 245 expires, 246 quote, 247 replacement: None, 248 history, 249 lookup: Some(lookup), 250 views, 251 }) 252 }