observation_operations.rs (9003B)
1 //! Capture obtained original outcomes, including after clock loss or revocation. 2 use super::*; 3 use graph::{Graph, SelectObservation}; 4 5 pub(in crate::workspace) async fn capture_observation( 6 turn: &mut Turn<'_>, 7 binding: WorkspaceBinding, 8 proof: AttachmentProof, 9 supplied: StockDeliveryObservation, 10 ) -> Result<StockDeliveryObservationOutcome, OperationError> { 11 if *turn.uncertain { 12 return Err(OperationError::RecoveryRequired); 13 } 14 turn.namespace.validate()?; 15 let input = binding.input(); 16 if !SellerAuthoritySelection::from_attachment(turn.selected).matches_attachment(input) { 17 return Err(OperationError::Unauthorized); 18 } 19 let (authority, credential, root, grant) = 20 super::super::read(turn.connection, input, turn.crypto).await?; 21 if !matches!(authority.catalog, 17..=20) { 22 return Err(OperationError::UnsupportedOperation); 23 } 24 credential.authenticate_retained_capture(input, &proof)?; 25 let original = supplied.source().attempt(); 26 let source = StockEnvelopeRequest::new( 27 binding.clone(), 28 InventoryCheckpointRef::from_host_metadata( 29 input.authority(), 30 Sequence::new(0).map_err(|_| OperationError::RecoveryRequired)?, 31 None, 32 )?, 33 original.operation_id(), 34 original.command_digest(), 35 supplied.source().recipient(), 36 None, 37 )?; 38 let source = if authority.catalog >= 18 { 39 source.with_envelope(supplied.source().event_id()) 40 } else { 41 source 42 }; 43 let witness = Box::pin(envelope::full_proof(turn, &source, &authority)).await?; 44 let mut graph = Box::pin(Graph::read( 45 turn, 46 &source, 47 &authority, 48 Some(supplied.request_id()), 49 Some(SelectObservation { 50 request: supplied.request_id(), 51 target: supplied.target_receipt().target().fingerprint(), 52 kind: supplied.kind(), 53 }), 54 )) 55 .await?; 56 let attempt = graph 57 .found_attempt 58 .as_ref() 59 .ok_or(OperationError::InvalidEvidence)?; 60 if attempt.frame.header.actor != binding.actor() 61 || attempt.frame.header.actor.grant_id() != Some(input.grant_id()) 62 { 63 return Err(OperationError::Unauthorized); 64 } 65 let checked = StockDeliveryObservation::from_store_report( 66 &attempt.report, 67 supplied.target_receipt(), 68 supplied.observed_at_unix_ms(), 69 )?; 70 if checked != supplied { 71 return Err(OperationError::InvalidEvidence); 72 } 73 let prepared = if graph.found_observation.is_none() { 74 let body = wire::encode(&observation::Wire::new(attempt, &supplied), OBSERVATION_MAX)?; 75 let projection = Projection::Observation { 76 operation: source.operation_id(), 77 recipient: source.recipient(), 78 request: request_key(supplied.request_id()), 79 target: target_key(supplied.target_receipt().target().fingerprint()), 80 kind: supplied.kind().code(), 81 }; 82 let prepared = Box::pin(Prepared::new( 83 turn, 84 &authority, 85 Append { 86 actor: attempt.frame.header.actor, 87 original: source.operation_id(), 88 digest: source.command_digest(), 89 order: attempt 90 .frame 91 .header 92 .order 93 .ok_or(OperationError::RecoveryRequired)?, 94 family: ledger::Family::DeliveryObservation, 95 projection, 96 }, 97 &body, 98 )) 99 .await?; 100 let receipt = StockDeliveryObservationReceipt::from_store_report( 101 supplied, 102 prepared.frame.header.transaction, 103 prepared.checkpoint(&authority)?, 104 )?; 105 Some((prepared, receipt)) 106 } else { 107 None 108 }; 109 let mut tx = turn 110 .connection 111 .begin_with("BEGIN IMMEDIATE") 112 .await 113 .map_err(|_| OperationError::StorageFailure)?; 114 let changed: Result<(), OperationError> = async { 115 turn.namespace.validate()?; 116 super::super::unchanged(&mut tx, input, authority.catalog, &root, &grant).await?; 117 credential.authenticate_retained_capture(input, &proof)?; 118 inventory::check_head( 119 &mut tx, 120 authority 121 .inventory 122 .ok_or(OperationError::RecoveryRequired)?, 123 ) 124 .await?; 125 witness.confirm(&mut tx).await?; 126 attempt.confirm(&mut tx).await?; 127 if let Some(old) = &graph.found_observation { 128 old.confirm(&mut tx).await?; 129 } 130 if let Some((prepared, _)) = &prepared { 131 prepared.insert(&mut tx, &root).await?; 132 } 133 turn.namespace.validate()?; 134 Ok(()) 135 } 136 .await; 137 let unknown = || { 138 StockDeliveryObservationOutcome::Unknown(radroots_storage::command::CommitAttempt::new( 139 input.workspace_id(), 140 source.operation_id(), 141 source.command_digest(), 142 prepared 143 .as_ref() 144 .map(|(prepared, _)| prepared.frame.header.transaction), 145 )) 146 }; 147 if let Err(error) = changed { 148 if tx.rollback().await.is_err() { 149 *turn.uncertain = true; 150 return Ok(unknown()); 151 } 152 return Err(error); 153 } 154 let completed = if prepared.is_some() { 155 tx.commit().await 156 } else { 157 tx.rollback().await 158 }; 159 if completed.is_err() { 160 *turn.uncertain = true; 161 return Ok(unknown()); 162 } 163 match prepared { 164 Some((_, receipt)) => Ok(StockDeliveryObservationOutcome::Committed(Box::new( 165 receipt, 166 ))), 167 None => Ok(StockDeliveryObservationOutcome::Committed(Box::new( 168 graph 169 .found_observation 170 .take() 171 .ok_or(OperationError::RecoveryRequired)? 172 .receipt, 173 ))), 174 } 175 } 176 177 pub(in crate::workspace) async fn page( 178 turn: &mut Turn<'_>, 179 source: StockEnvelopeRequest, 180 after: Option<Sequence>, 181 proof: AttachmentProof, 182 ) -> Result<StockDeliveryObservationPage, OperationError> { 183 let (auth, witness, graph) = Box::pin(operations::read(turn, &source, &proof, None)).await?; 184 let selected_event = graph 185 .source(source.recipient()) 186 .ok() 187 .map(|value| value.source.receipt().event_id()); 188 let current = auth 189 .access 190 .authority 191 .inventory 192 .ok_or(OperationError::RecoveryRequired)?; 193 if after.is_some_and(|after| after > current.revision) { 194 return Err(WorkspaceError::StaleCheckpoint.into()); 195 } 196 let rows = sqlx::query("SELECT d.entry_id 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=? AND d.recipient=? AND o.revision>? ORDER BY o.revision LIMIT 2305") 197 .bind(turn.selected.participant().as_bytes().as_slice()).bind(source.operation_id().as_bytes().as_slice()) 198 .bind(source.recipient().as_bytes().as_slice()).bind(after.map_or(0, |value| value.get()) as i64) 199 .fetch_all(&mut *turn.connection).await.map_err(|_|OperationError::RecoveryRequired)?; 200 if rows.len() > OBSERVATION_COUNT_MAX { 201 return Err(OperationError::RecoveryRequired); 202 } 203 // The protected history is globally bounded and already authenticated. 204 // Filter by the actual attempt source, never an unauthenticated event index. 205 // Retain at most one extra matching descriptor to establish continuation. 206 let mut entries = Vec::with_capacity(PAGE_MAX + 1); 207 for row in rows { 208 let bytes: Vec<u8> = row 209 .try_get(0) 210 .map_err(|_| OperationError::RecoveryRequired)?; 211 let entry = OperationId::from_bytes( 212 bytes 213 .try_into() 214 .map_err(|_| OperationError::RecoveryRequired)?, 215 ); 216 let value = Box::pin(observation::read_entry( 217 turn.connection, 218 turn.selected, 219 turn.crypto, 220 source.binding(), 221 auth.access.authority.input.grant_id(), 222 entry, 223 )) 224 .await? 225 .ok_or(OperationError::RecoveryRequired)?; 226 if selected_event == Some(value.receipt.observation().source().event_id()) { 227 entries.push(value.receipt); 228 if entries.len() > PAGE_MAX { 229 break; 230 } 231 } 232 } 233 let more = entries.len() > PAGE_MAX; 234 entries.truncate(PAGE_MAX); 235 Box::pin(operations::confirm_read(turn, &auth, &witness, &proof)).await?; 236 StockDeliveryObservationPage::from_store_report( 237 &source, 238 entries, 239 more, 240 InventoryCheckpointRef::from_host_metadata( 241 turn.selected.authority(), 242 current.revision, 243 current.head, 244 )? 245 .with_optional_authorization(auth.access.authority.authorization), 246 ) 247 }