lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

workspace_commands.rs (15774B)


      1 // Port-model orchestration tests, not native persistence/authentication evidence.
      2 use super::*;
      3 use radroots_execution::inbox::InquireInput;
      4 use radroots_execution::{Admission, Code, OperationContext, RetryClass};
      5 use radroots_storage::command::*;
      6 type BoxFuture<'a, T> = radroots_storage::event::BoxFuture<'a, T>;
      7 
      8 type Stored = Option<(WorkspaceBinding, Vec<u8>)>;
      9 struct Journal {
     10     model: Shared<Model>,
     11     trace: Mutex<Vec<&'static str>>,
     12     stored: Mutex<Stored>,
     13     uncertain: AtomicBool,
     14     absent: AtomicBool,
     15     admission_error: Mutex<Option<OperationError>>,
     16     query_error: Mutex<Option<OperationError>>,
     17 }
     18 impl WorkspaceStore for Journal {
     19     fn authenticate(
     20         &self,
     21         input: AttachmentInput,
     22         proof: AttachmentProof,
     23     ) -> BoxFuture<'_, Result<WorkspaceBinding, WorkspaceError>> {
     24         self.model.authenticate(input, proof)
     25     }
     26     fn close_workspace(&self) -> BoxFuture<'_, Result<(), WorkspaceError>> {
     27         Box::pin(async { Ok(()) })
     28     }
     29 }
     30 fn prepared(request: AdmissionRequest) -> PreparedOperation {
     31     PreparedOperation::from_committed_store(
     32         request,
     33         TransactionId::from_bytes([21; 32]),
     34         Sequence::new(1).unwrap(),
     35         IssuanceWindow::new(
     36             UnixSeconds::new(100).unwrap(),
     37             UnixSeconds::new(150).unwrap(),
     38         )
     39         .unwrap(),
     40     )
     41     .unwrap()
     42 }
     43 fn journal() -> Shared<Journal> {
     44     Shared::new(Journal {
     45         model: new_model(),
     46         trace: Mutex::new(Vec::new()),
     47         stored: Mutex::new(None),
     48         uncertain: AtomicBool::new(false),
     49         absent: AtomicBool::new(false),
     50         admission_error: Mutex::new(None),
     51         query_error: Mutex::new(None),
     52     })
     53 }
     54 fn context(scope: &WorkspaceSession) -> radroots_execution::workspace::CommandContext {
     55     scope
     56         .command_context(
     57             OperationId::from_bytes([22; 32]),
     58             None,
     59             None,
     60             UnixSeconds::new(150).unwrap(),
     61         )
     62         .unwrap()
     63 }
     64 fn inquiry() -> InquireInput {
     65     InquireInput::new(
     66         ThreadId::from_bytes([23; 32]),
     67         key(),
     68         None,
     69         "private model text",
     70     )
     71     .unwrap()
     72 }
     73 async fn attached(journal: &Shared<Journal>) -> (ClientSession<Host>, WorkspaceSession) {
     74     let client = ClientSession::new(Host, core::num::NonZeroU16::MIN);
     75     let scope = client
     76         .attach_workspace(journal.clone(), input(5), proof())
     77         .await
     78         .unwrap();
     79     client.start().await.unwrap();
     80     (client, scope)
     81 }
     82 impl OperationJournal for Journal {
     83     fn record_delivery_observation(
     84         &self,
     85         _binding: WorkspaceBinding,
     86         _proof: AttachmentProof,
     87         _observation: DeliveryObservation,
     88     ) -> BoxFuture<'_, Result<DeliveryObservationOutcome, OperationError>> {
     89         panic!("unexpected journal effect")
     90     }
     91     fn delivery_observations(
     92         &self,
     93         _binding: WorkspaceBinding,
     94         _operation: radroots_domain::OperationId,
     95         _digest: radroots_domain::CommandDigest,
     96         _target: radroots_storage::command::SigningTarget,
     97         _request: radroots_transport::sink::DeliveryRequestId,
     98         _proof: AttachmentProof,
     99     ) -> BoxFuture<'_, Result<Vec<DeliveryObservation>, OperationError>> {
    100         panic!("unexpected journal effect")
    101     }
    102     fn prepare_delivery_attempt<'a>(
    103         &'a self,
    104         _request: DeliveryAttemptRequest,
    105         _proof: AttachmentProof,
    106         _candidate: Option<&'a EnvelopeCandidate>,
    107     ) -> BoxFuture<'a, Result<DeliveryAttemptOutcome, OperationError>> {
    108         panic!("unexpected journal effect")
    109     }
    110     fn delivery_attempt(
    111         &self,
    112         _binding: WorkspaceBinding,
    113         _operation: OperationId,
    114         _digest: CommandDigest,
    115         _target: radroots_storage::command::SigningTarget,
    116         _request: radroots_transport::sink::DeliveryRequestId,
    117         _proof: AttachmentProof,
    118     ) -> BoxFuture<'_, Result<Option<DeliveryAttempt>, OperationError>> {
    119         panic!("unexpected journal effect")
    120     }
    121     fn install_transition_and_outbox(
    122         &self,
    123         _request: InstallationRequest,
    124         _proof: AttachmentProof,
    125     ) -> BoxFuture<'_, Result<InstallationOutcome, OperationError>> {
    126         panic!("unexpected journal effect")
    127     }
    128     fn operation_snapshot(
    129         &self,
    130         _binding: WorkspaceBinding,
    131         operation_id: OperationId,
    132         expected_digest: Option<CommandDigest>,
    133         _proof: AttachmentProof,
    134     ) -> BoxFuture<'_, Result<Option<OperationSnapshot>, OperationError>> {
    135         Box::pin(async move {
    136             self.trace.lock().unwrap().push("query");
    137             if let Some(error) = *self.query_error.lock().unwrap() {
    138                 return Err(error);
    139             }
    140             if self.absent.load(Ordering::SeqCst) {
    141                 return Ok(None);
    142             }
    143             let retained = self.stored.lock().unwrap();
    144             let Some((binding, bytes)) = retained.as_ref() else {
    145                 return Ok(None);
    146             };
    147             let request = AdmissionRequest::from_protected_wire(binding.clone(), bytes).unwrap();
    148             assert_eq!(operation_id, request.command().context().operation_id());
    149             assert!(expected_digest.is_none_or(|digest| digest == request.command().digest()));
    150             let snapshot = OperationSnapshot::from_store_report(
    151                 RetainedOperation::Prepared(prepared(request)),
    152                 vec![ArtifactSnapshot::from_store_report(key(), None, None, None)],
    153                 UnixSeconds::new(101).unwrap(),
    154             )
    155             .unwrap();
    156             Ok(Some(snapshot))
    157         })
    158     }
    159     fn claim_attempt(
    160         &self,
    161         _request: ClaimAttemptRequest,
    162         _proof: AttachmentProof,
    163     ) -> BoxFuture<'_, Result<ClaimAttemptOutcome, OperationError>> {
    164         panic!("unexpected journal effect")
    165     }
    166     fn signing_attempt(
    167         &self,
    168         _request: ClaimAttemptRequest,
    169         _proof: AttachmentProof,
    170     ) -> BoxFuture<'_, Result<Option<SigningAttempt>, OperationError>> {
    171         panic!("unexpected journal effect")
    172     }
    173     fn capture_evidence<'a>(
    174         &'a self,
    175         _input: radroots_storage::workspace::AttachmentInput,
    176         _proof: &'a AttachmentProof,
    177         _evidence: &'a ArtifactEvidence,
    178     ) -> BoxFuture<'a, Result<EvidenceCaptureOutcome, OperationError>> {
    179         panic!("unexpected journal effect")
    180     }
    181     fn obtained_evidence(
    182         &self,
    183         _request: ClaimAttemptRequest,
    184         _proof: AttachmentProof,
    185     ) -> BoxFuture<'_, Result<Option<CapturedArtifact>, OperationError>> {
    186         panic!("unexpected journal effect")
    187     }
    188     fn bind_signing_intents(
    189         &self,
    190         _binding: WorkspaceBinding,
    191         _plan: CapturedSigningPlan,
    192         _proof: AttachmentProof,
    193     ) -> BoxFuture<'_, Result<PlanBindingOutcome, OperationError>> {
    194         panic!("unexpected journal effect")
    195     }
    196     fn signing_plan(
    197         &self,
    198         _binding: WorkspaceBinding,
    199         _operation_id: OperationId,
    200         _expected_digest: CommandDigest,
    201         _proof: AttachmentProof,
    202     ) -> BoxFuture<'_, Result<Option<BoundSigningPlan>, OperationError>> {
    203         panic!("unexpected journal effect")
    204     }
    205     fn admit_command_and_hold(
    206         &self,
    207         request: AdmissionRequest,
    208         _proof: AttachmentProof,
    209     ) -> BoxFuture<'_, Result<AdmissionOutcome, OperationError>> {
    210         Box::pin(async move {
    211             self.trace.lock().unwrap().push("admit");
    212             let operation = request.command().context().operation_id();
    213             let digest = request.command().digest();
    214             if self.uncertain.load(Ordering::SeqCst) {
    215                 return Ok(AdmissionOutcome::Unknown(CommitAttempt::new(
    216                     request.binding().input().workspace_id(),
    217                     operation,
    218                     digest,
    219                     None,
    220                 )));
    221             }
    222             if let Some(error) = *self.admission_error.lock().unwrap() {
    223                 return Err(error);
    224             }
    225             *self.stored.lock().unwrap() = Some((
    226                 request.binding().clone(),
    227                 request.command().protected_wire().to_vec(),
    228             ));
    229             Ok(AdmissionOutcome::Committed(prepared(request)))
    230         })
    231     }
    232     fn operation(
    233         &self,
    234         _binding: WorkspaceBinding,
    235         _operation_id: OperationId,
    236         _expected_digest: Option<CommandDigest>,
    237         _proof: AttachmentProof,
    238     ) -> BoxFuture<'_, Result<Option<PreparedOperation>, OperationError>> {
    239         panic!("unexpected journal effect")
    240     }
    241 }
    242 
    243 #[test]
    244 fn only_confirmed_admission_reaches_query_and_unknown_preserves_original_id() {
    245     block_on(async {
    246         let journal = journal();
    247         let (client, scope) = attached(&journal).await;
    248         journal.uncertain.store(true, Ordering::SeqCst);
    249         let error = client
    250             .inquire(journal.clone(), context(&scope), inquiry())
    251             .await
    252             .unwrap_err();
    253         assert_eq!(error.code(), Code::CommitUnknown);
    254         assert_eq!(
    255             error.context(),
    256             OperationContext::admission_unknown(OperationId::from_bytes([22; 32]))
    257         );
    258         assert_eq!(error.retry(), RetryClass::ManualReconciliation);
    259         assert_eq!(*journal.trace.lock().unwrap(), vec!["admit"]);
    260         journal.uncertain.store(false, Ordering::SeqCst);
    261         journal.trace.lock().unwrap().clear();
    262         let receipt = client
    263             .inquire(journal.clone(), context(&scope), inquiry())
    264             .await
    265             .unwrap();
    266         assert!(receipt.durable());
    267         assert!(receipt.business_result().is_none());
    268         assert_eq!(*journal.trace.lock().unwrap(), vec!["admit", "query"]);
    269         journal.trace.lock().unwrap().clear();
    270         let queried = client
    271             .operation(
    272                 journal.clone(),
    273                 &scope,
    274                 OperationId::from_bytes([22; 32]),
    275                 Some(receipt.command_digest()),
    276             )
    277             .await
    278             .unwrap()
    279             .unwrap();
    280         assert_eq!(
    281             queried.operation_checkpoint(),
    282             receipt.operation_checkpoint()
    283         );
    284         assert_eq!(*journal.trace.lock().unwrap(), vec!["query"]);
    285         journal.absent.store(true, Ordering::SeqCst);
    286         assert!(
    287             client
    288                 .operation(
    289                     journal.clone(),
    290                     &scope,
    291                     OperationId::from_bytes([22; 32]),
    292                     None
    293                 )
    294                 .await
    295                 .unwrap()
    296                 .is_none()
    297         );
    298         let error = client
    299             .inquire(journal.clone(), context(&scope), inquiry())
    300             .await
    301             .unwrap_err();
    302         assert_eq!(error.code(), Code::RecoveryRequired);
    303         assert_eq!(error.context().admission(), Admission::Confirmed);
    304         client.close().await.unwrap();
    305     });
    306 }
    307 
    308 #[test]
    309 fn port_failures_preserve_the_actual_admission_stage_and_fixed_error_contract() {
    310     block_on(async {
    311         let journal = journal();
    312         let (client, scope) = attached(&journal).await;
    313         for (port_error, code) in [
    314             (OperationError::InvalidCommand, Code::InvalidInput),
    315             (OperationError::InvalidEvidence, Code::RecoveryRequired),
    316             (OperationError::Unauthorized, Code::Unauthorized),
    317             (OperationError::UnverifiedApproval, Code::Unauthorized),
    318             (OperationError::MissingHistory, Code::MissingHistory),
    319             (OperationError::DeadlineExceeded, Code::DeadlineExceeded),
    320             (
    321                 OperationError::IdempotencyConflict,
    322                 Code::IdempotencyConflict,
    323             ),
    324             (OperationError::StorageFailure, Code::StorageFailure),
    325             (OperationError::RecoveryRequired, Code::RecoveryRequired),
    326             (OperationError::DeliveryAttemptLimit, Code::RecoveryRequired),
    327             (
    328                 OperationError::Workspace(WorkspaceError::GrantRevoked),
    329                 Code::GrantRevoked,
    330             ),
    331         ] {
    332             *journal.admission_error.lock().unwrap() = Some(port_error);
    333             let error = client
    334                 .inquire(journal.clone(), context(&scope), inquiry())
    335                 .await
    336                 .unwrap_err();
    337             assert_eq!(error.code(), code);
    338             assert_eq!(error.context().admission(), Admission::NotAdmitted);
    339             assert_eq!(
    340                 error.context().operation_id(),
    341                 Some(OperationId::from_bytes([22; 32]))
    342             );
    343             *journal.admission_error.lock().unwrap() = None;
    344             *journal.query_error.lock().unwrap() = Some(port_error);
    345             let error = client
    346                 .inquire(journal.clone(), context(&scope), inquiry())
    347                 .await
    348                 .unwrap_err();
    349             assert_eq!(error.code(), code);
    350             assert_eq!(error.context().admission(), Admission::Confirmed);
    351             assert!(!format!("{error:?}").contains("private model text"));
    352             let error = client
    353                 .operation(
    354                     journal.clone(),
    355                     &scope,
    356                     OperationId::from_bytes([22; 32]),
    357                     None,
    358                 )
    359                 .await
    360                 .unwrap_err();
    361             assert_eq!(error.code(), code);
    362             *journal.query_error.lock().unwrap() = None;
    363         }
    364         client.close().await.unwrap();
    365     });
    366 }
    367 
    368 #[test]
    369 fn closed_and_foreign_scopes_do_not_reach_journal_and_capacity_is_not_reopened() {
    370     block_on(async {
    371         let journal = journal();
    372         let (client, scope) = attached(&journal).await;
    373         let other = WorkspaceSession::attach(journal.clone(), input(5), proof())
    374             .await
    375             .unwrap();
    376         assert_eq!(
    377             client
    378                 .inquire(journal.clone(), context(&other), inquiry())
    379                 .await
    380                 .unwrap_err()
    381                 .code(),
    382             Code::Unauthorized
    383         );
    384         assert_eq!(
    385             client
    386                 .operation(
    387                     journal.clone(),
    388                     &other,
    389                     OperationId::from_bytes([22; 32]),
    390                     None
    391                 )
    392                 .await
    393                 .unwrap_err()
    394                 .code(),
    395             Code::Unauthorized
    396         );
    397         let captured = context(&scope);
    398         scope.close();
    399         assert_eq!(
    400             client
    401                 .inquire(journal.clone(), captured, inquiry())
    402                 .await
    403                 .unwrap_err()
    404                 .code(),
    405             Code::CapabilityUnavailable
    406         );
    407         assert_eq!(
    408             client
    409                 .operation(
    410                     journal.clone(),
    411                     &scope,
    412                     OperationId::from_bytes([22; 32]),
    413                     None
    414                 )
    415                 .await
    416                 .unwrap_err()
    417                 .code(),
    418             Code::CapabilityUnavailable
    419         );
    420         assert!(journal.trace.lock().unwrap().is_empty());
    421         let captured = context(&other);
    422         client.close().await.unwrap();
    423         assert_eq!(
    424             client
    425                 .inquire(journal.clone(), captured, inquiry())
    426                 .await
    427                 .unwrap_err()
    428                 .code(),
    429             Code::CapabilityUnavailable
    430         );
    431         assert_eq!(
    432             client
    433                 .operation(
    434                     journal.clone(),
    435                     &other,
    436                     OperationId::from_bytes([22; 32]),
    437                     None
    438                 )
    439                 .await
    440                 .unwrap_err()
    441                 .code(),
    442             Code::CapabilityUnavailable
    443         );
    444     });
    445 }