lib

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

client_inventory.rs (16849B)


      1 //! Owned calls into the explicitly selected private inventory store.
      2 use super::{ClientSession, SessionHost, Shared};
      3 use crate::{
      4     Error, OperationContext,
      5     session::{HostBound, HostFuture},
      6     workspace::{CommandContext, WorkspaceSession},
      7 };
      8 use alloc::boxed::Box;
      9 use radroots_domain::{
     10     CommandDigest, OperationId, PoolId,
     11     stock::{OptionMappingKey, OptionPoolMapping, PoolView},
     12 };
     13 use radroots_protocol::command::{
     14     AcceptOrderInput, CapturedInventoryCommand, CapturedOptionMapping, CapturedOrderAcceptance,
     15     CapturedPoolCorrection, CapturedPoolCreation, CreatePoolInput, MapOptionInput,
     16     PoolCorrectionInput,
     17 };
     18 use radroots_storage::{
     19     command::OperationError,
     20     inventory::{
     21         InventoryCheckpointRef, InventoryOutcome, InventoryReceipt, InventoryRequest,
     22         InventoryStore, StockAbortOutcome, StockAbortReceipt, StockAbortRequest,
     23         StockAcceptanceOutcome, StockAcceptanceRequest, StockEvidenceOutcome, StockEvidenceRequest,
     24     },
     25     workspace::{AttachmentProof, WorkspaceBinding},
     26 };
     27 
     28 impl<H: SessionHost + 'static> ClientSession<H> {
     29     /// Owns already obtained original material until a matching durable append.
     30     /// The borrowed original survives preflight/host refusal. Accepted work and
     31     /// failed captures retain bytes, credentials and resource/byte leases after
     32     /// observer loss. This signs nothing and supplies no installation right.
     33     pub async fn capture_stock_evidence(
     34         &self,
     35         store: Shared<dyn InventoryStore>,
     36         scope: &WorkspaceSession,
     37         request: &StockEvidenceRequest,
     38     ) -> crate::Result<StockEvidenceOutcome> {
     39         let proposed = OperationContext::proposed(Some(request.operation_id()));
     40         let permit = self
     41             .session
     42             .admit()
     43             .map_err(|error| error.with_context(proposed))?;
     44         let budget = self
     45             .task_budget
     46             .reserve()
     47             .map_err(|error| error.with_context(proposed))?;
     48         {
     49             let scopes = self
     50                 .workspaces
     51                 .lock()
     52                 .unwrap_or_else(std::sync::PoisonError::into_inner);
     53             if !scopes.iter().any(|owned| owned.same_scope(scope)) {
     54                 return Err(Error::operation(OperationError::Unauthorized, proposed));
     55             }
     56         }
     57         let host = self
     58             .task_host
     59             .as_ref()
     60             .ok_or_else(|| Error::operation(OperationError::UnsupportedOperation, proposed))?;
     61         let (binding, proof) = scope
     62             .captured_input()
     63             .map_err(|error| Error::operation(error.into(), proposed))?;
     64         if !radroots_storage::workspace::seller_stock::SellerAuthoritySelection::from_attachment(
     65             binding.input(),
     66         )
     67         .matches_attachment(request.binding().input())
     68             || binding.scope() != request.binding().scope()
     69             || binding.actor() != request.binding().actor()
     70         {
     71             return Err(Error::operation(OperationError::Unauthorized, proposed));
     72         }
     73         // Refresh only non-authorizing host observations. Immutable namespace,
     74         // original actor/selectors and exact obtained bytes cannot be rebound.
     75         let retained = request
     76             .with_json(|raw| {
     77                 StockEvidenceRequest::from_obtained_wire(
     78                     binding,
     79                     request.operation_id(),
     80                     request.command_digest(),
     81                     request.signing_attempt_id(),
     82                     request.recipient(),
     83                     *request.intent_digest(),
     84                     raw,
     85                     request.observed_at_unix_ms(),
     86                 )
     87             })
     88             .map_err(|error| Error::operation(error, proposed))?;
     89         let owner = self.stock_captures.clone();
     90         let lease: Shared<dyn HostBound> = Shared::new((permit, budget));
     91         let (reply, observed) = futures::channel::oneshot::channel();
     92         host.submit(Box::pin(async move {
     93             let entry = owner.retain(store, retained, proof, lease);
     94             let result = owner.capture(&entry).await;
     95             let _ = reply.send(result);
     96         }))
     97         .map_err(|error| error.with_context(proposed))?;
     98         observed
     99             .await
    100             .unwrap_or_else(|_| Err(Error::operation(OperationError::RecoveryRequired, proposed)))
    101     }
    102 
    103     /// Retries only retained original captures. This remains available during
    104     /// closing; unresolved material keeps callbacks, keys and storage owned.
    105     pub async fn drain_stock_evidence(&self) -> crate::Result<()> {
    106         self.stock_captures.drain().await
    107     }
    108 
    109     /// Captures original acceptance and owns its T0 admission until settlement.
    110     /// A preparation report claims no signature, installed agreement or delivery.
    111     /// Concrete store authentication/consent and actual atomic effects remain
    112     /// authoritative; supplied minima and command metadata grant nothing.
    113     #[allow(clippy::too_many_arguments)]
    114     pub async fn prepare_stock_acceptance(
    115         &self,
    116         store: Shared<dyn InventoryStore>,
    117         scope: &WorkspaceSession,
    118         context: CommandContext,
    119         minimum: InventoryCheckpointRef,
    120         sources: radroots_storage::workspace::seller_stock::StockSourceCheckpointRef,
    121         listings: radroots_storage::workspace::seller_stock::StockListingCheckpointRef,
    122         input: AcceptOrderInput,
    123     ) -> crate::Result<StockAcceptanceOutcome> {
    124         let operation = context.data().operation_id();
    125         let proposed = OperationContext::proposed(Some(operation));
    126         self.stock_captures
    127             .ensure_ready()
    128             .map_err(|error| Error::operation(error, proposed))?;
    129         if !scope.owns_context(&context) {
    130             return Err(Error::operation(OperationError::Unauthorized, proposed));
    131         }
    132         let stock_captures = self.stock_captures.clone();
    133         self.run_stock_with_loss(
    134             scope,
    135             proposed,
    136             Error::admission_uncertain(operation),
    137             move |binding, proof| {
    138                 // Capture only after reserving work and byte capacity, before
    139                 // submission. No store, signer or transport runs in capture.
    140                 let request = CapturedOrderAcceptance::new(context.data().clone(), input)
    141                     .map_err(|_| OperationError::InvalidCommand)
    142                     .and_then(|command| {
    143                         StockAcceptanceRequest::capture(
    144                             binding, minimum, sources, listings, &command,
    145                         )
    146                     });
    147                 Box::pin(async move {
    148                     stock_captures.ensure_ready()?;
    149                     store.prepare_stock_acceptance(request?, proof).await
    150                 })
    151             },
    152         )
    153         .await
    154     }
    155 
    156     /// Captures pool creation from this client's own selected attachment.
    157     /// Actual authority, conservation and commit remain the store's obligation.
    158     pub async fn create_stock_pool(
    159         &self,
    160         store: Shared<dyn InventoryStore>,
    161         scope: &WorkspaceSession,
    162         context: CommandContext,
    163         minimum: InventoryCheckpointRef,
    164         input: CreatePoolInput,
    165     ) -> crate::Result<InventoryOutcome> {
    166         self.submit_inventory(store, scope, context, minimum, |data| {
    167             CapturedPoolCreation::new(data, input).map(Into::into)
    168         })
    169         .await
    170     }
    171 
    172     /// Captures an exact available-stock correction or spoilage command.
    173     pub async fn correct_stock_pool(
    174         &self,
    175         store: Shared<dyn InventoryStore>,
    176         scope: &WorkspaceSession,
    177         context: CommandContext,
    178         minimum: InventoryCheckpointRef,
    179         input: PoolCorrectionInput,
    180     ) -> crate::Result<InventoryOutcome> {
    181         self.submit_inventory(store, scope, context, minimum, |data| {
    182             CapturedPoolCorrection::new(data, input).map(Into::into)
    183         })
    184         .await
    185     }
    186 
    187     /// Captures a private option-to-pool mapping without signing or transport.
    188     pub async fn map_stock_option(
    189         &self,
    190         store: Shared<dyn InventoryStore>,
    191         scope: &WorkspaceSession,
    192         context: CommandContext,
    193         minimum: InventoryCheckpointRef,
    194         input: MapOptionInput,
    195     ) -> crate::Result<InventoryOutcome> {
    196         self.submit_inventory(store, scope, context, minimum, |data| {
    197             CapturedOptionMapping::new(data, input).map(Into::into)
    198         })
    199         .await
    200     }
    201 
    202     async fn submit_inventory(
    203         &self,
    204         store: Shared<dyn InventoryStore>,
    205         scope: &WorkspaceSession,
    206         context: CommandContext,
    207         minimum: InventoryCheckpointRef,
    208         capture: impl FnOnce(
    209             radroots_domain::CommandContextData,
    210         ) -> Result<
    211             CapturedInventoryCommand,
    212             radroots_protocol::command::CommandError,
    213         >,
    214     ) -> crate::Result<InventoryOutcome> {
    215         let proposed = OperationContext::proposed(Some(context.data().operation_id()));
    216         self.stock_captures
    217             .ensure_ready()
    218             .map_err(|error| Error::operation(error, proposed))?;
    219         if !scope.owns_context(&context) {
    220             return Err(Error::operation(OperationError::Unauthorized, proposed));
    221         }
    222         let stock_captures = self.stock_captures.clone();
    223         self.run_stock_with_loss(
    224             scope,
    225             proposed,
    226             Error::admission_uncertain(context.data().operation_id()),
    227             move |binding, proof| {
    228                 // Capture only after resource and byte reservations. This closure
    229                 // performs no store, signer or transport call before submission.
    230                 let request = capture(context.data().clone())
    231                     .map_err(|_| OperationError::InvalidCommand)
    232                     .and_then(|command| InventoryRequest::new(binding, minimum, command));
    233                 Box::pin(async move {
    234                     stock_captures.ensure_ready()?;
    235                     store.execute_inventory(request?, proof).await
    236                 })
    237             },
    238         )
    239         .await
    240     }
    241 
    242     /// Explicitly asks the selected store to prove original nonissuance and
    243     /// replay absence, then atomically release only that preparation.
    244     /// Selectors are never proof.
    245     pub async fn abort_proven_unissued(
    246         &self,
    247         store: Shared<dyn InventoryStore>,
    248         scope: &WorkspaceSession,
    249         minimum: InventoryCheckpointRef,
    250         operation: OperationId,
    251         digest: CommandDigest,
    252     ) -> crate::Result<StockAbortOutcome> {
    253         self.run_stock(
    254             scope,
    255             OperationContext::proposed(Some(operation)),
    256             move |binding, proof| {
    257                 let request = StockAbortRequest::new(binding, minimum, operation, digest);
    258                 Box::pin(async move { store.abort_proven_unissued(request, proof).await })
    259             },
    260         )
    261         .await
    262     }
    263 
    264     /// Reads an original abort without inferring safe nonissuance from absence.
    265     pub async fn stock_preparation_abort(
    266         &self,
    267         store: Shared<dyn InventoryStore>,
    268         scope: &WorkspaceSession,
    269         minimum: InventoryCheckpointRef,
    270         operation: OperationId,
    271         digest: CommandDigest,
    272     ) -> crate::Result<Option<StockAbortReceipt>> {
    273         self.run_stock(
    274             scope,
    275             OperationContext::proposed(Some(operation)),
    276             move |binding, proof| {
    277                 let request = StockAbortRequest::new(binding, minimum, operation, digest);
    278                 Box::pin(async move { store.stock_preparation_abort(request, proof).await })
    279             },
    280         )
    281         .await
    282     }
    283 
    284     /// Reads the original private inventory effect under an independent minimum.
    285     pub async fn inventory_operation(
    286         &self,
    287         store: Shared<dyn InventoryStore>,
    288         scope: &WorkspaceSession,
    289         minimum: InventoryCheckpointRef,
    290         operation: OperationId,
    291         digest: Option<CommandDigest>,
    292     ) -> crate::Result<Option<InventoryReceipt>> {
    293         self.run_stock(
    294             scope,
    295             OperationContext::proposed(Some(operation)),
    296             move |binding, proof| {
    297                 Box::pin(async move {
    298                     store
    299                         .inventory_operation(binding, minimum, operation, digest, proof)
    300                         .await
    301                 })
    302             },
    303         )
    304         .await
    305     }
    306 
    307     /// Reads current physical and installed backing/deficit together. This
    308     /// starts no signer, command capture or physical stock effect.
    309     pub async fn inspect_stock_pool(
    310         &self,
    311         store: Shared<dyn InventoryStore>,
    312         scope: &WorkspaceSession,
    313         minimum: InventoryCheckpointRef,
    314         pool: PoolId,
    315     ) -> crate::Result<Option<radroots_storage::inventory::StockSnapshot>> {
    316         self.run_stock(
    317             scope,
    318             OperationContext::proposed(None),
    319             move |binding, proof| {
    320                 Box::pin(async move { store.inspect_stock(binding, minimum, pool, proof).await })
    321             },
    322         )
    323         .await
    324     }
    325     /// Reads a private pool; a missing row never constructs stock or authority.
    326     pub async fn stock_pool(
    327         &self,
    328         store: Shared<dyn InventoryStore>,
    329         scope: &WorkspaceSession,
    330         minimum: InventoryCheckpointRef,
    331         pool: PoolId,
    332     ) -> crate::Result<Option<PoolView>> {
    333         self.run_stock(
    334             scope,
    335             OperationContext::proposed(None),
    336             move |binding, proof| {
    337                 Box::pin(async move { store.pool(binding, minimum, pool, proof).await })
    338             },
    339         )
    340         .await
    341     }
    342 
    343     /// Reads the actual private mapping under current owner access.
    344     pub async fn stock_option_mapping(
    345         &self,
    346         store: Shared<dyn InventoryStore>,
    347         scope: &WorkspaceSession,
    348         minimum: InventoryCheckpointRef,
    349         key: OptionMappingKey,
    350     ) -> crate::Result<Option<OptionPoolMapping>> {
    351         self.run_stock(
    352             scope,
    353             OperationContext::proposed(None),
    354             move |binding, proof| {
    355                 Box::pin(async move { store.option_mapping(binding, minimum, key, proof).await })
    356             },
    357         )
    358         .await
    359     }
    360 
    361     pub(super) async fn run_stock<T: HostBound + 'static>(
    362         &self,
    363         scope: &WorkspaceSession,
    364         proposed: OperationContext,
    365         work: impl FnOnce(
    366             WorkspaceBinding,
    367             AttachmentProof,
    368         ) -> HostFuture<'static, Result<T, OperationError>>,
    369     ) -> crate::Result<T> {
    370         self.run_stock_with_loss(
    371             scope,
    372             proposed,
    373             Error::operation(OperationError::RecoveryRequired, proposed),
    374             work,
    375         )
    376         .await
    377     }
    378 
    379     async fn run_stock_with_loss<T: HostBound + 'static>(
    380         &self,
    381         scope: &WorkspaceSession,
    382         proposed: OperationContext,
    383         lost_observation: Error,
    384         work: impl FnOnce(
    385             WorkspaceBinding,
    386             AttachmentProof,
    387         ) -> HostFuture<'static, Result<T, OperationError>>,
    388     ) -> crate::Result<T> {
    389         let permit = self
    390             .session
    391             .admit()
    392             .map_err(|error| error.with_context(proposed))?;
    393         let budget = self
    394             .task_budget
    395             .reserve()
    396             .map_err(|error| error.with_context(proposed))?;
    397         {
    398             let scopes = self
    399                 .workspaces
    400                 .lock()
    401                 .unwrap_or_else(std::sync::PoisonError::into_inner);
    402             if !scopes.iter().any(|owned| owned.same_scope(scope)) {
    403                 return Err(Error::operation(OperationError::Unauthorized, proposed));
    404             }
    405         }
    406         let host = self
    407             .task_host
    408             .as_ref()
    409             .ok_or_else(|| Error::operation(OperationError::UnsupportedOperation, proposed))?;
    410         let (binding, proof) = scope
    411             .captured_input()
    412             .map_err(|error| Error::operation(error.into(), proposed))?;
    413         let future = work(binding, proof);
    414         let lease: Shared<dyn HostBound> = Shared::new((permit, budget));
    415         let (reply, observed) = futures::channel::oneshot::channel();
    416         host.submit(Box::pin(async move {
    417             let result = future
    418                 .await
    419                 .map_err(|error| Error::operation(error, proposed));
    420             let _ = reply.send(result);
    421             // Observer loss cannot drop the permit before the store settles.
    422             drop(lease);
    423         }))
    424         .map_err(|error| error.with_context(proposed))?;
    425         // An accepted admission task lost before its reply has unknown T0;
    426         // reads/recovery cannot manufacture a confirmed business phase either.
    427         observed.await.unwrap_or(Err(lost_observation))
    428     }
    429 }