delivery.rs (12123B)
1 //! Stock-owned original delivery reports. Data construction grants no dispatch. 2 use super::*; 3 use crate::command::{DeliveryIntent, DeliveryObservationKind}; 4 use core::{fmt, num::NonZeroU64}; 5 use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; 6 use radroots_protocol::intent::ArtifactRole; 7 use radroots_transport::{ 8 DeliveryReceipt, SinkFailure, 9 sink::{DeliveryPayload, DeliveryRequest, DeliveryRequestId, DeliveryTargetReceipt}, 10 target::TargetFingerprint, 11 }; 12 use std::sync::Arc; 13 14 /// Exact original operation/recipient selectors and one requested transport intent. 15 pub struct StockDeliveryRequest { 16 source: StockEnvelopeRequest, 17 intent: DeliveryIntent, 18 expected_attempts: Option<u16>, 19 } 20 impl StockDeliveryRequest { 21 pub fn new( 22 binding: WorkspaceBinding, 23 minimum: InventoryCheckpointRef, 24 operation: OperationId, 25 digest: CommandDigest, 26 recipient: PublicKey, 27 intent: DeliveryIntent, 28 ) -> Result<Self, OperationError> { 29 if intent.role() != ArtifactRole::GiftWrap { 30 return Err(OperationError::InvalidCommand); 31 } 32 Ok(Self { 33 source: StockEnvelopeRequest::new( 34 binding, minimum, operation, digest, recipient, None, 35 )?, 36 intent, 37 expected_attempts: None, 38 }) 39 } 40 /// Requires a fresh claim to observe this exact per-recipient attempt count. 41 /// Ordinary execution supplies its authenticated snapshot count to prevent 42 /// concurrent clients from dispatching twice from the same observation. 43 /// An exact existing request remains a read without dispatch permission. 44 pub fn with_expected_attempt_count(mut self, count: u16) -> Result<Self, OperationError> { 45 if count > 16 * 12 { 46 return Err(OperationError::InvalidCommand); 47 } 48 self.expected_attempts = Some(count); 49 Ok(self) 50 } 51 pub const fn expected_attempt_count(&self) -> Option<u16> { 52 self.expected_attempts 53 } 54 /// Selects exact retained bytes for this intent without obtaining another 55 /// outer or renewing the recipient's cumulative invocation budget. 56 pub fn with_envelope(mut self, event: EnvelopeEventId) -> Result<Self, OperationError> { 57 if event != self.intent.event_id() { 58 return Err(OperationError::InvalidCommand); 59 } 60 self.source = self.source.with_envelope(event); 61 Ok(self) 62 } 63 pub const fn source(&self) -> &StockEnvelopeRequest { 64 &self.source 65 } 66 pub const fn intent(&self) -> &DeliveryIntent { 67 &self.intent 68 } 69 pub fn attempt(&self) -> CommitAttempt { 70 self.source.attempt() 71 } 72 } 73 impl fmt::Debug for StockDeliveryRequest { 74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 75 f.write_str("StockDeliveryRequest(<redacted>)") 76 } 77 } 78 79 /// Original retained intent and exact outer. Queries of this report cannot 80 /// authorize transport; only a qualified owner's fresh confirmed claim can. 81 pub struct StockDeliveryAttempt { 82 source: Arc<StockEnvelopeSource>, 83 intent: DeliveryIntent, 84 transaction: TransactionId, 85 retained_at: UnixSeconds, 86 checkpoint: InventoryCheckpointRef, 87 ordinals: Box<[u8]>, 88 } 89 impl StockDeliveryAttempt { 90 /// Checks report shape and the actual carrier. The concrete owner must 91 /// authenticate the original stock graph and observe transaction completion. 92 pub fn from_store_report( 93 source: Arc<StockEnvelopeSource>, 94 intent: DeliveryIntent, 95 transaction: TransactionId, 96 retained_at: UnixSeconds, 97 checkpoint: InventoryCheckpointRef, 98 ordinals: Vec<u8>, 99 ) -> Result<Self, OperationError> { 100 if intent.role() != ArtifactRole::GiftWrap 101 || intent.event_id() != source.receipt().event_id() 102 || checkpoint.authority() != source.receipt().checkpoint().authority() 103 || checkpoint.revision() <= source.receipt().checkpoint().revision() 104 || ordinals.len() != intent.selection().len() 105 || ordinals.iter().any(|n| !(1..=12).contains(n)) 106 || retained_at 107 .get() 108 .checked_mul(1000) 109 .is_none_or(|at| at >= intent.deadline_unix_ms().get()) 110 { 111 return Err(OperationError::RecoveryRequired); 112 } 113 let outer = source.with_json(|raw| { 114 crate::command::verified_private_outer(raw, source.receipt().recipient()) 115 })?; 116 if outer.envelope().created_at_u64() > retained_at.get() { 117 return Err(OperationError::RecoveryRequired); 118 } 119 Ok(Self { 120 source, 121 intent, 122 transaction, 123 retained_at, 124 checkpoint, 125 ordinals: ordinals.into_boxed_slice(), 126 }) 127 } 128 pub fn source(&self) -> &StockEnvelopeSource { 129 &self.source 130 } 131 pub const fn intent(&self) -> &DeliveryIntent { 132 &self.intent 133 } 134 pub const fn transaction_id(&self) -> TransactionId { 135 self.transaction 136 } 137 pub const fn retained_at(&self) -> UnixSeconds { 138 self.retained_at 139 } 140 pub const fn checkpoint(&self) -> InventoryCheckpointRef { 141 self.checkpoint 142 } 143 pub fn target_ordinals(&self) -> &[u8] { 144 &self.ordinals 145 } 146 /// Reconstructs the original request without supplying a dispatch permit. 147 pub fn transport_request(&self) -> Result<DeliveryRequest, OperationError> { 148 let outer = self.source.with_json(|raw| { 149 crate::command::verified_private_outer(raw, self.source.receipt().recipient()) 150 })?; 151 DeliveryRequest::new( 152 self.intent.request_id().as_str(), 153 DeliveryPayload::new(outer), 154 self.intent.targets().clone(), 155 self.intent.policy().clone(), 156 self.intent.deadline_unix_ms().get(), 157 ) 158 .map_err(|_| OperationError::RecoveryRequired) 159 } 160 } 161 impl fmt::Debug for StockDeliveryAttempt { 162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 163 f.write_str("StockDeliveryAttempt(<redacted>)") 164 } 165 } 166 167 /// Actual store outcome; public construction does not qualify an arbitrary host. 168 pub enum StockDeliveryAttemptOutcome { 169 /// Newly confirmed potential invocation; its qualified owner may proceed once. 170 Claimed(Box<StockDeliveryAttempt>), 171 /// Original existing request, without another dispatch right. 172 Retained(Box<StockDeliveryAttempt>), 173 /// Uncertain transaction, without any dispatch right. 174 Unknown { 175 operation: CommitAttempt, 176 request: DeliveryRequestId, 177 }, 178 } 179 impl fmt::Debug for StockDeliveryAttemptOutcome { 180 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 181 f.write_str("StockDeliveryAttemptOutcome(<redacted>)") 182 } 183 } 184 185 /// Independent exact attempt/target outcome, never buyer receipt or stock effect. 186 #[derive(Clone, Eq, PartialEq)] 187 pub struct StockDeliveryObservation { 188 source: StockEnvelopeReceipt, 189 request: DeliveryRequestId, 190 attempt: TransactionId, 191 checkpoint: InventoryCheckpointRef, 192 target: DeliveryTargetReceipt, 193 kind: DeliveryObservationKind, 194 ordinal: u8, 195 observed: Option<NonZeroU64>, 196 } 197 impl StockDeliveryObservation { 198 pub fn from_receipt( 199 attempt: &StockDeliveryAttempt, 200 receipt: &DeliveryReceipt, 201 target: &TargetFingerprint, 202 observed: Option<NonZeroU64>, 203 ) -> Result<Self, OperationError> { 204 receipt 205 .validate_for_request(&attempt.transport_request()?) 206 .map_err(|_| OperationError::InvalidEvidence)?; 207 let report = receipt 208 .target_receipts() 209 .iter() 210 .find(|report| report.target().fingerprint() == target) 211 .ok_or(OperationError::InvalidEvidence)?; 212 Self::from_store_report(attempt, report, observed) 213 } 214 pub fn from_failure( 215 attempt: &StockDeliveryAttempt, 216 failure: &SinkFailure, 217 target: &TargetFingerprint, 218 observed: Option<NonZeroU64>, 219 ) -> Result<Self, OperationError> { 220 failure 221 .validate_for_request(&attempt.transport_request()?) 222 .map_err(|_| OperationError::InvalidEvidence)?; 223 let report = failure 224 .partial_evidence() 225 .iter() 226 .find(|report| report.target().fingerprint() == target) 227 .ok_or(OperationError::InvalidEvidence)?; 228 Self::from_store_report(attempt, report, observed) 229 } 230 /// Normalizes bounded data only. The native owner authenticates the actual 231 /// original attempt and preserves the first observation of each class. 232 pub fn from_store_report( 233 attempt: &StockDeliveryAttempt, 234 report: &DeliveryTargetReceipt, 235 observed: Option<NonZeroU64>, 236 ) -> Result<Self, OperationError> { 237 let (kind, ordinal) = crate::command::normalize_delivery_observation( 238 attempt.intent(), 239 attempt.target_ordinals(), 240 report, 241 observed, 242 )?; 243 Ok(Self { 244 source: attempt.source().receipt(), 245 request: attempt.intent().request_id().clone(), 246 attempt: attempt.transaction_id(), 247 checkpoint: attempt.checkpoint(), 248 target: report.clone(), 249 kind, 250 ordinal, 251 observed, 252 }) 253 } 254 pub const fn source(&self) -> StockEnvelopeReceipt { 255 self.source 256 } 257 pub const fn request_id(&self) -> &DeliveryRequestId { 258 &self.request 259 } 260 pub const fn event_id(&self) -> EnvelopeEventId { 261 self.source.event_id() 262 } 263 pub const fn attempt_transaction_id(&self) -> TransactionId { 264 self.attempt 265 } 266 pub const fn attempt_checkpoint(&self) -> InventoryCheckpointRef { 267 self.checkpoint 268 } 269 pub const fn target_receipt(&self) -> &DeliveryTargetReceipt { 270 &self.target 271 } 272 pub const fn kind(&self) -> DeliveryObservationKind { 273 self.kind 274 } 275 pub const fn target_ordinal(&self) -> u8 { 276 self.ordinal 277 } 278 pub const fn observed_at_unix_ms(&self) -> Option<NonZeroU64> { 279 self.observed 280 } 281 } 282 impl fmt::Debug for StockDeliveryObservation { 283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 284 f.write_str("StockDeliveryObservation(<redacted>)") 285 } 286 } 287 288 /// Actual original observation append metadata, with no remote delivery claim. 289 #[derive(Clone, Eq, PartialEq)] 290 pub struct StockDeliveryObservationReceipt { 291 observation: StockDeliveryObservation, 292 transaction: TransactionId, 293 checkpoint: InventoryCheckpointRef, 294 } 295 impl StockDeliveryObservationReceipt { 296 pub fn from_store_report( 297 observation: StockDeliveryObservation, 298 transaction: TransactionId, 299 checkpoint: InventoryCheckpointRef, 300 ) -> Result<Self, OperationError> { 301 if checkpoint.authority() != observation.attempt_checkpoint().authority() 302 || checkpoint.revision() <= observation.attempt_checkpoint().revision() 303 { 304 return Err(OperationError::RecoveryRequired); 305 } 306 Ok(Self { 307 observation, 308 transaction, 309 checkpoint, 310 }) 311 } 312 pub const fn observation(&self) -> &StockDeliveryObservation { 313 &self.observation 314 } 315 pub const fn transaction_id(&self) -> TransactionId { 316 self.transaction 317 } 318 pub const fn checkpoint(&self) -> InventoryCheckpointRef { 319 self.checkpoint 320 } 321 } 322 impl fmt::Debug for StockDeliveryObservationReceipt { 323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 324 f.write_str("StockDeliveryObservationReceipt(<redacted>)") 325 } 326 } 327 328 /// Confirmed original append or unresolved capture of the borrowed original. 329 pub enum StockDeliveryObservationOutcome { 330 Committed(Box<StockDeliveryObservationReceipt>), 331 Unknown(CommitAttempt), 332 } 333 impl fmt::Debug for StockDeliveryObservationOutcome { 334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 335 f.write_str("StockDeliveryObservationOutcome(<redacted>)") 336 } 337 }