graph.rs (13996B)
1 //! Constant-memory reduction of bounded original per-recipient transport history. 2 use super::*; 3 4 struct Endpoint { 5 fingerprint: TargetFingerprint, 6 attempts: u8, 7 accepted: bool, 8 last: Option<DeliveryObservationKind>, 9 observed: Option<NonZeroU64>, 10 } 11 struct Recipient { 12 participant: PublicKey, 13 source: Option<envelope::Retained>, 14 original: Option<radroots_storage::inventory::StockEnvelopeReceipt>, 15 first: Option<DeliveryIntent>, 16 first_source: Option<radroots_storage::inventory::StockEnvelopeReceipt>, 17 attempts: u16, 18 selected_attempts: u16, 19 endpoints: Vec<Endpoint>, 20 } 21 impl Recipient { 22 fn observe_attempt(&mut self, value: &StockDeliveryAttempt) -> Result<(), OperationError> { 23 if self.original.as_ref().is_none_or(|source| { 24 source.evidence() != value.source().receipt().evidence() 25 || source.installation_transaction_id() 26 != value.source().receipt().installation_transaction_id() 27 }) { 28 return Err(OperationError::RecoveryRequired); 29 } 30 if let Some(original) = &self.first { 31 if original.publication_policy_digest() != value.intent().publication_policy_digest() { 32 return Err(OperationError::RecoveryRequired); 33 } 34 } else { 35 self.first = Some(value.intent().clone()); 36 self.first_source = Some(value.source().receipt()); 37 self.endpoints = value 38 .intent() 39 .targets() 40 .targets() 41 .iter() 42 .map(|target| Endpoint { 43 fingerprint: target.fingerprint().clone(), 44 attempts: 0, 45 accepted: false, 46 last: None, 47 observed: None, 48 }) 49 .collect(); 50 } 51 for (fingerprint, ordinal) in value 52 .intent() 53 .selection() 54 .iter() 55 .zip(value.target_ordinals()) 56 { 57 let endpoint = self 58 .endpoints 59 .iter_mut() 60 .find(|endpoint| &endpoint.fingerprint == fingerprint) 61 .ok_or(OperationError::RecoveryRequired)?; 62 if endpoint.attempts >= 12 || *ordinal != endpoint.attempts + 1 { 63 return Err(OperationError::RecoveryRequired); 64 } 65 endpoint.attempts = *ordinal; 66 } 67 self.attempts = self 68 .attempts 69 .checked_add(1) 70 .ok_or(OperationError::RecoveryRequired)?; 71 if self.source.as_ref().is_some_and(|source| { 72 source.source.receipt().event_id() == value.source().receipt().event_id() 73 }) { 74 self.selected_attempts = self 75 .selected_attempts 76 .checked_add(1) 77 .ok_or(OperationError::RecoveryRequired)?; 78 } 79 if self.attempts > 16 * 12 { 80 return Err(OperationError::RecoveryRequired); 81 } 82 Ok(()) 83 } 84 fn observe(&mut self, value: &StockDeliveryObservation) -> Result<(), OperationError> { 85 let endpoint = self 86 .endpoints 87 .iter_mut() 88 .find(|endpoint| endpoint.fingerprint == *value.target_receipt().target().fingerprint()) 89 .ok_or(OperationError::RecoveryRequired)?; 90 if value.target_ordinal() == 0 || value.target_ordinal() > endpoint.attempts { 91 return Err(OperationError::RecoveryRequired); 92 } 93 if self 94 .source 95 .as_ref() 96 .is_none_or(|source| source.source.receipt().event_id() != value.source().event_id()) 97 { 98 return Ok(()); 99 } 100 endpoint.accepted |= value.kind() == DeliveryObservationKind::Accepted; 101 endpoint.last = Some(value.kind()); 102 endpoint.observed = value.observed_at_unix_ms(); 103 Ok(()) 104 } 105 } 106 pub(super) struct SelectObservation<'a> { 107 pub request: &'a DeliveryRequestId, 108 pub target: &'a TargetFingerprint, 109 pub kind: DeliveryObservationKind, 110 } 111 pub(super) struct Graph { 112 recipients: [Recipient; 2], 113 pub found_attempt: Option<attempt::Retained>, 114 pub found_observation: Option<observation::Retained>, 115 pub last_at: Option<UnixSeconds>, 116 } 117 impl Graph { 118 pub(super) async fn read( 119 turn: &mut Turn<'_>, 120 request: &StockEnvelopeRequest, 121 authority: &Authority, 122 wanted: Option<&DeliveryRequestId>, 123 observed: Option<SelectObservation<'_>>, 124 ) -> Result<Self, OperationError> { 125 let original = Box::pin(inventory::acceptance::codec::read( 126 turn.connection, 127 turn.selected, 128 turn.crypto, 129 request.operation_id(), 130 )) 131 .await? 132 .ok_or(OperationError::MissingHistory)?; 133 if original.receipt.attempt().command_digest() != request.command_digest() 134 || !original 135 .receipt 136 .rumor() 137 .recipients() 138 .contains(&request.recipient()) 139 { 140 return Err(OperationError::InvalidEvidence); 141 } 142 let mut recipients = Vec::with_capacity(2); 143 for participant in original.receipt.rumor().recipients() { 144 let selector = StockEnvelopeRequest::new( 145 request.binding().clone(), 146 request.minimum_checkpoint(), 147 request.operation_id(), 148 request.command_digest(), 149 *participant, 150 None, 151 )?; 152 let original_source = Box::pin(envelope::lookup(turn, &selector)).await?; 153 let original = original_source.as_ref().map(|value| value.source.receipt()); 154 let source = if *participant == request.recipient() { 155 if let Some(event) = request.envelope_event_id() { 156 Some( 157 Box::pin(envelope::lookup(turn, &selector.with_envelope(event))) 158 .await? 159 .ok_or(OperationError::MissingHistory)?, 160 ) 161 } else { 162 original_source 163 } 164 } else { 165 original_source 166 }; 167 recipients.push(Recipient { 168 participant: *participant, 169 source, 170 original, 171 first: None, 172 first_source: None, 173 attempts: 0, 174 selected_attempts: 0, 175 endpoints: vec![], 176 }); 177 } 178 let mut result = Self { 179 recipients: recipients 180 .try_into() 181 .map_err(|_| OperationError::RecoveryRequired)?, 182 found_attempt: None, 183 found_observation: None, 184 last_at: None, 185 }; 186 let rows = sqlx::query("SELECT CASE WHEN length(d.entry_id)=32 THEN d.entry_id END FROM stock_delivery_attempts d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.entry_id WHERE d.actor=? AND d.operation_id=? ORDER BY o.revision LIMIT 385") 187 .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()) 188 .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; 189 if rows.len() > ATTEMPT_COUNT_MAX { 190 return Err(OperationError::RecoveryRequired); 191 } 192 // Exact natural-key constraints and each body-derived projection prove 193 // uniqueness; retaining another history-sized identity set is unnecessary. 194 for row in rows { 195 let entry = entry(&row)?; 196 let value = Box::pin(attempt::read_entry( 197 turn.connection, 198 turn.selected, 199 turn.crypto, 200 request.binding(), 201 authority.input.grant_id(), 202 entry, 203 )) 204 .await? 205 .ok_or(OperationError::RecoveryRequired)?; 206 let source = value.report.source().receipt(); 207 if source.attempt().operation_id() != request.operation_id() 208 || source.attempt().command_digest() != request.command_digest() 209 || result 210 .last_at 211 .is_some_and(|at| value.report.retained_at() < at) 212 { 213 return Err(OperationError::RecoveryRequired); 214 } 215 result.last_at = Some(value.report.retained_at()); 216 result 217 .recipient_mut(source.recipient())? 218 .observe_attempt(&value.report)?; 219 if source.recipient() == request.recipient() 220 && wanted.is_some_and(|wanted| wanted == value.report.intent().request_id()) 221 { 222 result.found_attempt = Some(value); 223 } 224 } 225 let rows = sqlx::query("SELECT CASE WHEN length(d.entry_id)=32 THEN d.entry_id END FROM stock_delivery_observations d JOIN stock_operations o ON o.actor=d.actor AND o.operation_id=d.entry_id WHERE d.actor=? AND d.operation_id=? ORDER BY o.revision LIMIT 2305") 226 .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()) 227 .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; 228 if rows.len() > OBSERVATION_COUNT_MAX { 229 return Err(OperationError::RecoveryRequired); 230 } 231 for row in rows { 232 let value = Box::pin(observation::read_entry( 233 turn.connection, 234 turn.selected, 235 turn.crypto, 236 request.binding(), 237 authority.input.grant_id(), 238 entry(&row)?, 239 )) 240 .await? 241 .ok_or(OperationError::RecoveryRequired)?; 242 let report = value.receipt.observation(); 243 let source = report.source(); 244 let target = report.target_receipt().target().fingerprint(); 245 if source.attempt().operation_id() != request.operation_id() 246 || source.attempt().command_digest() != request.command_digest() 247 { 248 return Err(OperationError::RecoveryRequired); 249 } 250 result.recipient_mut(source.recipient())?.observe(report)?; 251 if source.recipient() == request.recipient() 252 && observed.as_ref().is_some_and(|selected| { 253 selected.request == report.request_id() 254 && selected.target == target 255 && selected.kind == report.kind() 256 }) 257 { 258 result.found_observation = Some(value); 259 } 260 } 261 Ok(result) 262 } 263 fn recipient(&self, participant: PublicKey) -> Result<&Recipient, OperationError> { 264 self.recipients 265 .iter() 266 .find(|value| value.participant == participant) 267 .ok_or(OperationError::InvalidEvidence) 268 } 269 fn recipient_mut(&mut self, participant: PublicKey) -> Result<&mut Recipient, OperationError> { 270 self.recipients 271 .iter_mut() 272 .find(|value| value.participant == participant) 273 .ok_or(OperationError::RecoveryRequired) 274 } 275 pub(super) fn source( 276 &self, 277 recipient: PublicKey, 278 ) -> Result<&envelope::Retained, OperationError> { 279 self.recipient(recipient)? 280 .source 281 .as_ref() 282 .ok_or(OperationError::MissingHistory) 283 } 284 pub(super) fn ordinals( 285 &self, 286 recipient: PublicKey, 287 intent: &DeliveryIntent, 288 ) -> Result<Vec<u8>, OperationError> { 289 let original = self.recipient(recipient)?; 290 if original.first.as_ref().is_some_and(|first| { 291 first.publication_policy_digest() != intent.publication_policy_digest() 292 }) { 293 return Err(OperationError::IdempotencyConflict); 294 } 295 intent 296 .selection() 297 .iter() 298 .map(|fingerprint| { 299 let count = original 300 .endpoints 301 .iter() 302 .find(|value| &value.fingerprint == fingerprint) 303 .map_or(0, |value| value.attempts); 304 if count >= 12 { 305 Err(OperationError::DeliveryAttemptLimit) 306 } else { 307 Ok(count + 1) 308 } 309 }) 310 .collect() 311 } 312 pub(super) fn attempt_count(&self, recipient: PublicKey) -> Result<u16, OperationError> { 313 Ok(self.recipient(recipient)?.attempts) 314 } 315 pub(super) fn summary( 316 &self, 317 request: &StockEnvelopeRequest, 318 checkpoint: InventoryCheckpointRef, 319 ) -> Result<StockDeliverySummary, OperationError> { 320 let value = self.recipient(request.recipient())?; 321 let targets = value 322 .endpoints 323 .iter() 324 .map(|target| { 325 StockDeliveryTargetProgress::from_store_report( 326 target.fingerprint.clone(), 327 target.attempts, 328 target.accepted, 329 target.last, 330 target.observed, 331 ) 332 }) 333 .collect::<Result<Vec<_>, _>>()?; 334 StockDeliverySummary::from_store_report_with_policy_source( 335 request, 336 value.source.as_ref().map(|source| source.source.receipt()), 337 value.first_source, 338 value.first.clone(), 339 value.attempts, 340 value.selected_attempts, 341 targets, 342 checkpoint, 343 ) 344 } 345 } 346 fn entry(row: &sqlx::sqlite::SqliteRow) -> Result<OperationId, OperationError> { 347 let bytes: Vec<u8> = row 348 .try_get(0) 349 .map_err(|_| OperationError::RecoveryRequired)?; 350 Ok(OperationId::from_bytes( 351 bytes 352 .try_into() 353 .map_err(|_| OperationError::RecoveryRequired)?, 354 )) 355 }