command.rs (22951B)
1 //! Typed authoritative admission/query transactions. The SPI is not a command 2 //! engine or a qualification claim. Concrete hosts must execute the specified 3 //! transactions and classify their actual completion; descriptors mint nothing. 4 5 use crate::workspace::{AttachmentProof, WorkspaceBinding, WorkspaceError, WorkspaceStore}; 6 use core::fmt; 7 use radroots_domain::{ 8 CommandDigest, IssuanceWindow, OperationId, Sequence, TransactionId, WorkspaceId, 9 }; 10 pub use radroots_protocol::chat::ChatSigningPlan; 11 use radroots_protocol::command::{CapturedChatCommand, CapturedCommand}; 12 pub use radroots_protocol::plan::{CapturedSigningPlan, SigningTarget}; 13 use radroots_transport::BoxFuture; 14 15 #[cfg(feature = "protected_outbox")] 16 pub mod protected; 17 18 mod delivery; 19 #[cfg(feature = "protected_outbox")] 20 pub(crate) use delivery::outer as verified_private_outer; 21 mod delivery_summary; 22 mod dm_source; 23 mod installation; 24 mod issuance; 25 mod observation; 26 #[cfg(feature = "protected_outbox")] 27 pub(crate) use observation::normalize as normalize_delivery_observation; 28 mod publication; 29 pub use publication::PublicationArtifact; 30 mod snapshot; 31 pub use delivery::{ 32 DeliveryAttempt, DeliveryAttemptOutcome, DeliveryAttemptRequest, DeliveryIntent, 33 EnvelopeCandidate, PrivateEnvelopeCandidate, 34 }; 35 pub use delivery_summary::DeliveryAttemptSummary; 36 pub use dm_source::SignedDmRelaySource; 37 pub use installation::{ 38 ChatInstallation, InstallationOutcome, InstallationRequest, ListingInstallation, 39 PublicPublicationWork, PublicationWork, 40 }; 41 pub use issuance::{ 42 ArtifactEvidence, CapturedArtifact, ClaimAttemptOutcome, ClaimAttemptRequest, 43 EvidenceCaptureOutcome, EvidenceReceipt, SigningAttempt, 44 }; 45 pub use observation::{DeliveryObservation, DeliveryObservationKind, DeliveryObservationOutcome}; 46 pub use snapshot::{ArtifactSnapshot, ClaimSnapshot, OperationSnapshot, RetainedOperation}; 47 48 /// Fixed operation-store failures known before a successful admission commit. 49 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 50 #[non_exhaustive] 51 pub enum OperationError { 52 /// Current workspace authentication or ownership failed. 53 Workspace(WorkspaceError), 54 /// Captured fields do not match the selected authenticated scope. 55 InvalidCommand, 56 /// Obtained bytes do not authenticate against the exact retained seal. 57 InvalidEvidence, 58 /// This concrete authority cannot execute the requested action. 59 Unauthorized, 60 /// This exact backend/family port cannot perform the requested operation. 61 UnsupportedOperation, 62 /// Required authenticated thread/order history is unavailable. 63 MissingHistory, 64 /// No qualified protected origin verifies the supplied approval descriptor. 65 UnverifiedApproval, 66 /// The first-admission deadline has passed; retained operations remain queryable. 67 DeadlineExceeded, 68 /// The retained operation identity binds a different command commitment. 69 IdempotencyConflict, 70 /// The selected state, pool version or retained decision has changed. 71 StaleState, 72 /// A known storage failure preceded writes or had confirmed rollback. 73 StorageFailure, 74 /// State, completion or decoding requires explicit reconciliation. 75 RecoveryRequired, 76 /// The retained target's twelve potential attempts require operator review. 77 DeliveryAttemptLimit, 78 } 79 impl OperationError { 80 /// Returns an input-free diagnostic code. 81 pub const fn code(self) -> &'static str { 82 match self { 83 Self::Workspace(e) => e.code(), 84 Self::InvalidCommand => "invalid_command", 85 Self::InvalidEvidence => "invalid_evidence", 86 Self::Unauthorized => "unauthorized", 87 Self::UnsupportedOperation => "capability_unavailable", 88 Self::MissingHistory => "missing_history", 89 Self::UnverifiedApproval => "unverified_approval", 90 Self::DeadlineExceeded => "deadline_exceeded", 91 Self::IdempotencyConflict => "idempotency_conflict", 92 Self::StaleState => "stale_state", 93 Self::StorageFailure => "storage_failure", 94 Self::RecoveryRequired => "recovery_required", 95 Self::DeliveryAttemptLimit => "delivery_attempt_limit", 96 } 97 } 98 } 99 impl fmt::Display for OperationError { 100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 101 f.write_str(self.code()) 102 } 103 } 104 impl core::error::Error for OperationError {} 105 impl From<WorkspaceError> for OperationError { 106 fn from(value: WorkspaceError) -> Self { 107 Self::Workspace(value) 108 } 109 } 110 111 /// Captured command and original authenticated binding. Construction compares 112 /// descriptors only. The separate protected proof must authenticate current 113 /// persisted state inside the actual admission transaction. 114 pub struct AdmissionRequest { 115 binding: WorkspaceBinding, 116 command: CapturedCommand, 117 } 118 impl AdmissionRequest { 119 /// Refuses substituted workspace, actor/grant, authority or route data. 120 /// Deadline and current grant checks belong to the concrete transaction; 121 /// an expired original command may still be queried/reconciled by identity. 122 pub fn new( 123 binding: WorkspaceBinding, 124 command: impl Into<CapturedCommand>, 125 ) -> Result<Self, OperationError> { 126 let command = command.into(); 127 let context = command.context(); 128 let input = binding.input(); 129 if context.actor() != binding.actor() 130 || context.workspace_id() != input.workspace_id() 131 || context.authority() != input.authority() 132 || context.route_digest() != input.route_digest() 133 { 134 return Err(OperationError::InvalidCommand); 135 } 136 Ok(Self { binding, command }) 137 } 138 /// Decodes protected retained command data and compares its captured scope. 139 /// This remains structural; current access is independently authenticated. 140 pub fn from_protected_wire( 141 binding: WorkspaceBinding, 142 wire: &[u8], 143 ) -> Result<Self, OperationError> { 144 let command = CapturedCommand::parse(wire).map_err(|_| OperationError::RecoveryRequired)?; 145 Self::new(binding, command) 146 } 147 /// Borrows the captured attachment observation, without claiming it is current. 148 pub const fn binding(&self) -> &WorkspaceBinding { 149 &self.binding 150 } 151 /// Borrows exact immutable command data. 152 pub const fn command(&self) -> &CapturedCommand { 153 &self.command 154 } 155 /// Borrows actual chat data only. A public operation has no invented peer, 156 /// rumor, text or parent and cannot enter a chat-only effect port. 157 pub fn chat_command(&self) -> Result<&CapturedChatCommand, OperationError> { 158 self.command 159 .chat() 160 .ok_or(OperationError::UnsupportedOperation) 161 } 162 /// Checks fresh non-stock payload preconditions after actual authentication. 163 /// This structural check supplies no current access, transaction or hold; 164 /// concrete owners must independently recheck their authoritative fences. 165 pub fn validate_fresh(&self, now: radroots_domain::UnixSeconds) -> Result<(), OperationError> { 166 if self.command.requires_history() { 167 return Err(OperationError::MissingHistory); 168 } 169 if self.command.context().approval().is_some() { 170 return Err(OperationError::UnverifiedApproval); 171 } 172 if let Some(listing) = self.command.listing() { 173 if self.binding.scope() != crate::workspace::WorkspaceScope::NewSellerOutbox { 174 return Err(OperationError::Unauthorized); 175 } 176 radroots_protocol::listing::ListingEvent::new( 177 listing.input(), 178 self.binding.actor().participant(), 179 now, 180 ) 181 .map_err(|_| OperationError::InvalidCommand)?; 182 } 183 Ok(()) 184 } 185 /// Transfers both owned descriptors to the concrete transaction owner. 186 pub fn into_parts(self) -> (WorkspaceBinding, CapturedCommand) { 187 (self.binding, self.command) 188 } 189 } 190 impl fmt::Debug for AdmissionRequest { 191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 192 f.write_str("AdmissionRequest(<redacted>)") 193 } 194 } 195 196 /// Immutable anchor for one attempted admission. It is not proof of commit. 197 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 198 pub struct CommitAttempt { 199 workspace_id: WorkspaceId, 200 operation_id: OperationId, 201 command_digest: CommandDigest, 202 transaction_id: Option<TransactionId>, 203 } 204 impl CommitAttempt { 205 /// Captures full original identities without creating an operation. 206 pub const fn new( 207 workspace_id: WorkspaceId, 208 operation_id: OperationId, 209 command_digest: CommandDigest, 210 transaction_id: Option<TransactionId>, 211 ) -> Self { 212 Self { 213 workspace_id, 214 operation_id, 215 command_digest, 216 transaction_id, 217 } 218 } 219 /// Returns the selected workspace. 220 pub const fn workspace_id(self) -> WorkspaceId { 221 self.workspace_id 222 } 223 /// Returns the original caller-provided operation identity. 224 pub const fn operation_id(self) -> OperationId { 225 self.operation_id 226 } 227 /// Returns its exact semantic command commitment. 228 pub const fn command_digest(self) -> CommandDigest { 229 self.command_digest 230 } 231 /// Returns the exact attempted transaction when observed. A lost owner 232 /// reply may leave only the original operation/digest anchor available. 233 pub const fn transaction_id(self) -> Option<TransactionId> { 234 self.transaction_id 235 } 236 } 237 238 /// Owned observation of actual retained Prepared state. It is not an installed 239 /// business result, signature, delivery fact, stock hold or readiness flag. 240 /// A custom adapter's report does not qualify that adapter's persistence. 241 pub struct PreparedOperation { 242 request: Box<AdmissionRequest>, 243 transaction_id: TransactionId, 244 revision: Sequence, 245 issuance_window: IssuanceWindow, 246 } 247 impl PreparedOperation { 248 /// Validates a concrete store's structural report. The adapter must first 249 /// confirm its real commit or read the matching committed row after reopen. 250 pub fn from_committed_store( 251 request: AdmissionRequest, 252 transaction_id: TransactionId, 253 revision: Sequence, 254 issuance_window: IssuanceWindow, 255 ) -> Result<Self, OperationError> { 256 if revision.get() == 0 257 || issuance_window.prepared_at() < request.binding().observed_at() 258 || issuance_window.first_issue_not_after() > request.command().context().not_after() 259 || issuance_window.first_issue_not_after() > request.binding().expires_at() 260 { 261 return Err(OperationError::RecoveryRequired); 262 } 263 Ok(Self { 264 request: Box::new(request), 265 transaction_id, 266 revision, 267 issuance_window, 268 }) 269 } 270 /// Borrows the captured original request, including its diagnostic correlation. 271 pub const fn request(&self) -> &AdmissionRequest { 272 &self.request 273 } 274 /// Returns the original confirmed admission transaction identity. 275 pub const fn transaction_id(&self) -> TransactionId { 276 self.transaction_id 277 } 278 /// Returns the retained monotonic operation revision. 279 pub const fn revision(&self) -> Sequence { 280 self.revision 281 } 282 /// Returns the original preparation observation and first-issue deadline. 283 /// It remains historical after expiry and never establishes nonissuance. 284 pub const fn issuance_window(&self) -> IssuanceWindow { 285 self.issuance_window 286 } 287 /// Returns the exact retained identity/commitment anchor. 288 pub fn identity(&self) -> CommitAttempt { 289 let context = self.request.command().context(); 290 CommitAttempt::new( 291 context.workspace_id(), 292 context.operation_id(), 293 self.request.command().digest(), 294 Some(self.transaction_id), 295 ) 296 } 297 } 298 impl fmt::Debug for PreparedOperation { 299 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 300 f.write_str("PreparedOperation(<redacted>)") 301 } 302 } 303 304 /// Actual initial transaction completion, separate from signing/installation. 305 pub enum AdmissionOutcome { 306 /// The exact row commit or an existing committed row was confirmed. 307 Committed(PreparedOperation), 308 /// Completion is unknown. Reconcile this original anchor after safe reopen; 309 /// never infer rollback, discard the ID or issue from another preparation. 310 Unknown(CommitAttempt), 311 } 312 impl fmt::Debug for AdmissionOutcome { 313 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 314 f.write_str(match self { 315 Self::Committed(_) => "AdmissionOutcome::Committed(<redacted>)", 316 Self::Unknown(_) => "AdmissionOutcome::Unknown(<retained>)", 317 }) 318 } 319 } 320 321 /// Typed transaction port, implemented by actual shared storage adapters. 322 /// Applications do not implement a second orchestration or stock engine here. 323 pub trait OperationJournal: WorkspaceStore { 324 /// Reconciles a failed/unknown capture of already obtained original seal 325 /// bytes. A qualified host must retain its namespace/writer identity, 326 /// verify the existing schema and original claim, and confirm capture before 327 /// clearing uncertainty. This grants no fresh issuance or replacement 328 /// authority. The current profile covers obtained chat evidence only. 329 fn reconcile_unknown<'a>( 330 &'a self, 331 _input: crate::workspace::AttachmentInput, 332 _proof: &'a AttachmentProof, 333 _evidence: &'a ArtifactEvidence, 334 ) -> BoxFuture<'a, Result<EvidenceCaptureOutcome, OperationError>> { 335 Box::pin(async { Err(OperationError::RecoveryRequired) }) 336 } 337 /// Appends obtained target evidence against the actual original retained 338 /// attempt. Original credential authentication is required; late capture 339 /// does not acquire a fresh lease, deadline, grant or dispatch permission. 340 fn record_delivery_observation( 341 &self, 342 binding: WorkspaceBinding, 343 proof: AttachmentProof, 344 observation: DeliveryObservation, 345 ) -> BoxFuture<'_, Result<DeliveryObservationOutcome, OperationError>>; 346 /// Returns original per-target observations under current access. Startup 347 /// and query never initiate delivery or imply a missing acknowledgement. 348 fn delivery_observations( 349 &self, 350 binding: WorkspaceBinding, 351 operation: radroots_domain::OperationId, 352 digest: radroots_domain::CommandDigest, 353 target: SigningTarget, 354 request: radroots_transport::sink::DeliveryRequestId, 355 proof: AttachmentProof, 356 ) -> BoxFuture<'_, Result<Vec<DeliveryObservation>, OperationError>>; 357 /// Atomically retains exact signed payload bytes and every selected target intent 358 /// before transport. A fresh actual commit may be dispatched once by its 359 /// qualified owner. Restored or unknown claims never permit replay. 360 fn prepare_delivery_attempt<'a>( 361 &'a self, 362 request: DeliveryAttemptRequest, 363 proof: AttachmentProof, 364 candidate: Option<&'a EnvelopeCandidate>, 365 ) -> BoxFuture<'a, Result<DeliveryAttemptOutcome, OperationError>>; 366 /// Reads an original attempt under current access, including after expiry; 367 /// the returned report supplies no dispatch or safe-nonissuance proof. 368 fn delivery_attempt( 369 &self, 370 binding: WorkspaceBinding, 371 operation: OperationId, 372 digest: CommandDigest, 373 target: SigningTarget, 374 request: radroots_transport::sink::DeliveryRequestId, 375 proof: AttachmentProof, 376 ) -> BoxFuture<'_, Result<Option<DeliveryAttempt>, OperationError>>; 377 /// Atomically installs the original chat result or initial listing revision 378 /// with publication work for actual obtained artifacts. Concrete hosts must 379 /// enforce the command's retained decision and current access. No signing or 380 /// transport occurs here; unknown completion retains claims and evidence. 381 fn install_transition_and_outbox( 382 &self, 383 request: InstallationRequest, 384 proof: AttachmentProof, 385 ) -> BoxFuture<'_, Result<InstallationOutcome, OperationError>>; 386 /// Queries one coherent original preparation/plan/per-artifact evidence 387 /// graph under current access. Reported absence grants no safe reissue. 388 fn operation_snapshot( 389 &self, 390 binding: WorkspaceBinding, 391 operation_id: OperationId, 392 expected_digest: Option<CommandDigest>, 393 proof: AttachmentProof, 394 ) -> BoxFuture<'_, Result<Option<OperationSnapshot>, OperationError>>; 395 /// Commits a first claim before dispatch. Retained/unknown outcomes never 396 /// authorize another invocation; the concrete executor owns that decision. 397 fn claim_attempt( 398 &self, 399 request: ClaimAttemptRequest, 400 proof: AttachmentProof, 401 ) -> BoxFuture<'_, Result<ClaimAttemptOutcome, OperationError>>; 402 /// Reads a retained potential invocation under current workspace access. 403 fn signing_attempt( 404 &self, 405 request: ClaimAttemptRequest, 406 proof: AttachmentProof, 407 ) -> BoxFuture<'_, Result<Option<SigningAttempt>, OperationError>>; 408 /// Appends matching authenticated obtained bytes to the actual original 409 /// claim, without a fresh-issuance deadline or observation clock. Borrowed 410 /// input remains caller-owned through error, lost wait or unknown completion. 411 fn capture_evidence<'a>( 412 &'a self, 413 input: crate::workspace::AttachmentInput, 414 proof: &'a AttachmentProof, 415 evidence: &'a ArtifactEvidence, 416 ) -> BoxFuture<'a, Result<EvidenceCaptureOutcome, OperationError>>; 417 /// Reads original exact captured bytes under current workspace access. 418 fn obtained_evidence( 419 &self, 420 request: ClaimAttemptRequest, 421 proof: AttachmentProof, 422 ) -> BoxFuture<'_, Result<Option<CapturedArtifact>, OperationError>>; 423 /// Atomically retains the complete immutable plan under current access and 424 /// the original first-issue window. No signer invocation happens here. 425 fn bind_signing_intents( 426 &self, 427 binding: WorkspaceBinding, 428 plan: CapturedSigningPlan, 429 proof: AttachmentProof, 430 ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>>; 431 /// Queries original complete plan bytes under current access, including 432 /// after expiry. The returned value grants no permission to dispatch. 433 fn signing_plan( 434 &self, 435 binding: WorkspaceBinding, 436 operation_id: OperationId, 437 expected_digest: CommandDigest, 438 proof: AttachmentProof, 439 ) -> BoxFuture<'_, Result<Option<BoundSigningPlan>, OperationError>>; 440 /// Authenticates current grant/fences, checks the original operation first, 441 /// and confirms atomic retained preparation before any signing. Chat has no 442 /// physical hold. Only confirmed rollback may return a known-failure error. 443 fn admit_command_and_hold( 444 &self, 445 request: AdmissionRequest, 446 proof: AttachmentProof, 447 ) -> BoxFuture<'_, Result<AdmissionOutcome, OperationError>>; 448 /// Queries original committed state under current access. Absence is not a 449 /// generic proof that an unknown external effect never happened. 450 fn operation( 451 &self, 452 binding: WorkspaceBinding, 453 operation_id: OperationId, 454 expected_digest: Option<CommandDigest>, 455 proof: AttachmentProof, 456 ) -> BoxFuture<'_, Result<Option<PreparedOperation>, OperationError>>; 457 } 458 459 /// Complete retained T1 observation, separate from issuance and installation. 460 /// A custom adapter's structural report does not qualify durable execution. 461 pub struct BoundSigningPlan { 462 prepared: PreparedOperation, 463 plan: Box<CapturedSigningPlan>, 464 transaction_id: TransactionId, 465 bound_at: radroots_domain::UnixSeconds, 466 } 467 impl BoundSigningPlan { 468 /// Compares exact original command and fixed first-issue window. 469 pub fn from_committed_store( 470 prepared: PreparedOperation, 471 plan: impl Into<CapturedSigningPlan>, 472 transaction_id: TransactionId, 473 bound_at: radroots_domain::UnixSeconds, 474 ) -> Result<Self, OperationError> { 475 let plan = plan.into(); 476 if plan.operation_id() != prepared.identity().operation_id() 477 || plan.command_digest() != prepared.identity().command_digest() 478 || bound_at < prepared.issuance_window().prepared_at() 479 || bound_at >= prepared.issuance_window().first_issue_not_after() 480 || plan.created_at() < prepared.issuance_window().prepared_at() 481 || plan.created_at() > bound_at 482 { 483 return Err(OperationError::RecoveryRequired); 484 } 485 // Reconstruct against the actually retained command, rather than trust 486 // a matching digest descriptor attached to unrelated plan fields. 487 let checked = 488 CapturedSigningPlan::parse(prepared.request().command(), plan.protected_wire()) 489 .map_err(|_| OperationError::RecoveryRequired)?; 490 Ok(Self { 491 prepared, 492 plan: Box::new(checked), 493 transaction_id, 494 bound_at, 495 }) 496 } 497 /// Transfers retained command and exact plan without changing their identities. 498 pub fn into_parts(self) -> (PreparedOperation, CapturedSigningPlan) { 499 (self.prepared, *self.plan) 500 } 501 pub const fn prepared(&self) -> &PreparedOperation { 502 &self.prepared 503 } 504 pub const fn plan(&self) -> &CapturedSigningPlan { 505 &self.plan 506 } 507 /// Borrows actual private preimages only; public plans never acquire an 508 /// invented seal, peer or message through a private effect port. 509 pub fn chat_plan(&self) -> Result<&ChatSigningPlan, OperationError> { 510 self.plan.chat().ok_or(OperationError::UnsupportedOperation) 511 } 512 pub const fn transaction_id(&self) -> TransactionId { 513 self.transaction_id 514 } 515 /// Returns the checked observation captured before protection; this is not 516 /// an independently measured wall-clock commit or signing time. 517 pub const fn bound_at(&self) -> radroots_domain::UnixSeconds { 518 self.bound_at 519 } 520 } 521 impl fmt::Debug for BoundSigningPlan { 522 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 523 f.write_str("BoundSigningPlan(<redacted>)") 524 } 525 } 526 /// Confirmed T1 completion or an original anchor requiring reconciliation. 527 pub enum PlanBindingOutcome { 528 Committed(BoundSigningPlan), 529 Unknown(CommitAttempt), 530 } 531 impl fmt::Debug for PlanBindingOutcome { 532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 533 f.write_str(match self { 534 Self::Committed(_) => "PlanBindingOutcome::Committed(<redacted>)", 535 Self::Unknown(_) => "PlanBindingOutcome::Unknown(<retained>)", 536 }) 537 } 538 }