operations.rs (11056B)
1 //! Concrete D admission and current-authorized reads on the stock connection. 2 use super::*; 3 use graph::Graph; 4 5 async fn authorized( 6 turn: &mut Turn<'_>, 7 source: &StockEnvelopeRequest, 8 proof: &AttachmentProof, 9 ) -> Result<signing_plan::Authorized, OperationError> { 10 let catalog: i64 = sqlx::query_scalar("PRAGMA user_version") 11 .fetch_one(&mut *turn.connection) 12 .await 13 .map_err(|_| OperationError::RecoveryRequired)?; 14 if !matches!(catalog, 17..=20) { 15 return Err(OperationError::UnsupportedOperation); 16 } 17 let loading = signing_plan::load( 18 turn, 19 source.binding(), 20 source.minimum_checkpoint(), 21 source.operation_id(), 22 source.command_digest(), 23 proof, 24 ); 25 let auth = Box::pin(loading).await?; 26 if !matches!(auth.access.authority.catalog, 17..=20) { 27 return Err(OperationError::UnsupportedOperation); 28 } 29 if !auth 30 .original 31 .receipt 32 .rumor() 33 .recipients() 34 .contains(&source.recipient()) 35 { 36 return Err(OperationError::InvalidEvidence); 37 } 38 Ok(auth) 39 } 40 pub(in crate::workspace) async fn prepare( 41 turn: &mut Turn<'_>, 42 request: StockDeliveryRequest, 43 proof: AttachmentProof, 44 ) -> Result<StockDeliveryAttemptOutcome, OperationError> { 45 if *turn.uncertain { 46 return Err(OperationError::RecoveryRequired); 47 } 48 let source = request.source(); 49 validate_request(request.intent().request_id())?; 50 let auth = Box::pin(authorized(turn, source, &proof)).await?; 51 Box::pin(prepare_authorized(turn, request, proof, auth)).await 52 } 53 // Authorization has its own polling frame, as in the stock snapshot reader. 54 async fn prepare_authorized( 55 turn: &mut Turn<'_>, 56 request: StockDeliveryRequest, 57 proof: AttachmentProof, 58 auth: signing_plan::Authorized, 59 ) -> Result<StockDeliveryAttemptOutcome, OperationError> { 60 let source = request.source(); 61 let witness = Box::pin(envelope::full_proof(turn, source, &auth.access.authority)).await?; 62 let mut graph = Box::pin(Graph::read( 63 turn, 64 source, 65 &auth.access.authority, 66 Some(request.intent().request_id()), 67 None, 68 )) 69 .await?; 70 71 let envelope = graph.source(source.recipient())?; 72 if request.intent().event_id() != envelope.source.receipt().event_id() { 73 return Err(OperationError::InvalidEvidence); 74 } 75 if graph 76 .found_attempt 77 .as_ref() 78 .is_some_and(|old| old.report.intent().digest() != request.intent().digest()) 79 { 80 return Err(OperationError::IdempotencyConflict); 81 } 82 let fresh = graph.found_attempt.is_none(); 83 if fresh 84 && request 85 .expected_attempt_count() 86 .is_some_and(|expected| graph.attempt_count(source.recipient()) != Ok(expected)) 87 { 88 return Err(OperationError::StaleState); 89 } 90 let now = auth.access.current.observed_at(); 91 let prepared = if fresh { 92 let installed = Box::pin(inventory::installation::read_entry( 93 turn.connection, 94 turn.selected, 95 turn.crypto, 96 envelope.installation_entry(), 97 )) 98 .await? 99 .ok_or(OperationError::RecoveryRequired)?; 100 if now < installed.receipt.installed_at() { 101 return Err(WorkspaceError::Unavailable.into()); 102 } 103 if graph.last_at.is_some_and(|at| now < at) || now < auth.consent.observed_at { 104 return Err(WorkspaceError::Unavailable.into()); 105 } 106 if now 107 .get() 108 .checked_mul(1000) 109 .is_none_or(|at| at >= request.intent().deadline_unix_ms().get()) 110 { 111 return Err(OperationError::DeadlineExceeded); 112 } 113 let ordinals = graph.ordinals(source.recipient(), request.intent())?; 114 let body = wire::encode( 115 &attempt::Wire::new(envelope, &auth, request.intent(), now, ordinals.clone())?, 116 ATTEMPT_MAX, 117 )?; 118 let projection = Projection::Attempt { 119 operation: source.operation_id(), 120 recipient: source.recipient(), 121 request: request_key(request.intent().request_id()), 122 }; 123 let prepared = Box::pin(Prepared::new( 124 turn, 125 &auth.access.authority, 126 Append { 127 actor: auth.access.current.actor(), 128 original: source.operation_id(), 129 digest: source.command_digest(), 130 order: auth.original.receipt.order_id(), 131 family: ledger::Family::DeliveryAttempt, 132 projection, 133 }, 134 &body, 135 )) 136 .await?; 137 138 let copied = envelope.source.with_json(|raw| { 139 radroots_storage::inventory::StockEnvelopeSource::from_retained_wire( 140 envelope.source.receipt(), 141 raw, 142 ) 143 })?; 144 145 let report = StockDeliveryAttempt::from_store_report( 146 Arc::new(copied), 147 request.intent().clone(), 148 prepared.frame.header.transaction, 149 now, 150 prepared.checkpoint(&auth.access.authority)?, 151 ordinals, 152 )?; 153 154 Some((prepared, report)) 155 } else { 156 None 157 }; 158 let mut tx = turn 159 .connection 160 .begin_with("BEGIN IMMEDIATE") 161 .await 162 .map_err(|_| OperationError::StorageFailure)?; 163 let changed: Result<(), OperationError> = async { 164 let current = auth 165 .confirm(&mut tx, turn.namespace, turn.clock, &proof, false) 166 .await?; 167 inventory::check_head( 168 &mut tx, 169 auth.access 170 .authority 171 .inventory 172 .ok_or(OperationError::RecoveryRequired)?, 173 ) 174 .await?; 175 witness.confirm(&mut tx).await?; 176 if let Some(old) = &graph.found_attempt { 177 old.confirm(&mut tx).await?; 178 } 179 if let Some((prepared, _)) = &prepared { 180 if current.observed_at() < now { 181 return Err(WorkspaceError::Unavailable.into()); 182 } 183 if current 184 .observed_at() 185 .get() 186 .checked_mul(1000) 187 .is_none_or(|at| at >= request.intent().deadline_unix_ms().get()) 188 { 189 return Err(OperationError::DeadlineExceeded); 190 } 191 prepared.insert(&mut tx, &auth.access.root).await?; 192 } 193 turn.namespace.validate()?; 194 Ok(()) 195 } 196 .await; 197 198 let unknown = || StockDeliveryAttemptOutcome::Unknown { 199 operation: radroots_storage::command::CommitAttempt::new( 200 source.binding().input().workspace_id(), 201 source.operation_id(), 202 source.command_digest(), 203 prepared 204 .as_ref() 205 .map(|(prepared, _)| prepared.frame.header.transaction), 206 ), 207 request: request.intent().request_id().clone(), 208 }; 209 if let Err(error) = changed { 210 if tx.rollback().await.is_err() { 211 *turn.uncertain = true; 212 return Ok(unknown()); 213 } 214 return Err(error); 215 } 216 let completed = if fresh { 217 tx.commit().await 218 } else { 219 tx.rollback().await 220 }; 221 if completed.is_err() { 222 *turn.uncertain = true; 223 return Ok(unknown()); 224 } 225 match prepared { 226 Some((_, report)) => Ok(StockDeliveryAttemptOutcome::Claimed(Box::new(report))), 227 None => Ok(StockDeliveryAttemptOutcome::Retained(Box::new( 228 graph 229 .found_attempt 230 .take() 231 .ok_or(OperationError::RecoveryRequired)? 232 .report, 233 ))), 234 } 235 } 236 pub(in crate::workspace) async fn summary( 237 turn: &mut Turn<'_>, 238 source: StockEnvelopeRequest, 239 proof: AttachmentProof, 240 ) -> Result<StockDeliverySummary, OperationError> { 241 let (auth, witness, graph) = Box::pin(read(turn, &source, &proof, None)).await?; 242 Box::pin(confirm_read(turn, &auth, &witness, &proof)).await?; 243 let current = auth 244 .access 245 .authority 246 .inventory 247 .ok_or(OperationError::RecoveryRequired)?; 248 graph.summary( 249 &source, 250 InventoryCheckpointRef::from_host_metadata( 251 turn.selected.authority(), 252 current.revision, 253 current.head, 254 )? 255 .with_optional_authorization(auth.access.authority.authorization), 256 ) 257 } 258 pub(in crate::workspace) async fn query_attempt( 259 turn: &mut Turn<'_>, 260 source: StockEnvelopeRequest, 261 request: DeliveryRequestId, 262 proof: AttachmentProof, 263 ) -> Result<Option<StockDeliveryAttempt>, OperationError> { 264 validate_request(&request)?; 265 let (auth, witness, mut graph) = Box::pin(read(turn, &source, &proof, Some(&request))).await?; 266 if graph.found_attempt.as_ref().is_some_and(|value| { 267 graph.source(source.recipient()).is_ok_and(|selected| { 268 selected.source.receipt().event_id() != value.report.source().receipt().event_id() 269 }) 270 }) { 271 return Err(OperationError::InvalidEvidence); 272 } 273 Box::pin(confirm_read(turn, &auth, &witness, &proof)).await?; 274 Ok(graph.found_attempt.take().map(|value| value.report)) 275 } 276 pub(super) async fn read( 277 turn: &mut Turn<'_>, 278 source: &StockEnvelopeRequest, 279 proof: &AttachmentProof, 280 request: Option<&DeliveryRequestId>, 281 ) -> Result<(signing_plan::Authorized, checkpoint::MinimumProof, Graph), OperationError> { 282 if *turn.uncertain { 283 return Err(OperationError::RecoveryRequired); 284 } 285 let auth = Box::pin(authorized(turn, source, proof)).await?; 286 let witness = Box::pin(envelope::full_proof(turn, source, &auth.access.authority)).await?; 287 let graph = Box::pin(Graph::read( 288 turn, 289 source, 290 &auth.access.authority, 291 request, 292 None, 293 )) 294 .await?; 295 Ok((auth, witness, graph)) 296 } 297 pub(super) async fn confirm_read( 298 turn: &mut Turn<'_>, 299 auth: &signing_plan::Authorized, 300 witness: &checkpoint::MinimumProof, 301 proof: &AttachmentProof, 302 ) -> Result<(), OperationError> { 303 let mut tx = turn 304 .connection 305 .begin_with("BEGIN IMMEDIATE") 306 .await 307 .map_err(|_| OperationError::StorageFailure)?; 308 let checked: Result<(), OperationError> = async { 309 auth.confirm(&mut tx, turn.namespace, turn.clock, proof, false) 310 .await?; 311 inventory::check_head( 312 &mut tx, 313 auth.access 314 .authority 315 .inventory 316 .ok_or(OperationError::RecoveryRequired)?, 317 ) 318 .await?; 319 witness.confirm(&mut tx).await?; 320 turn.namespace.validate()?; 321 Ok(()) 322 } 323 .await; 324 if let Err(error) = checked { 325 if tx.rollback().await.is_err() { 326 *turn.uncertain = true; 327 } 328 return Err(error); 329 } 330 if tx.rollback().await.is_err() { 331 *turn.uncertain = true; 332 return Err(OperationError::RecoveryRequired); 333 } 334 Ok(()) 335 }