lib

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

client.rs (11751B)


      1 use super::{HostFuture, Session, SessionHost, SessionState, SignerSession, host::Shared};
      2 use core::num::NonZeroU16;
      3 use radroots_signing::provider::{ProviderError, SignerHandle};
      4 use std::{
      5     boxed::Box,
      6     sync::{Mutex, MutexGuard},
      7 };
      8 
      9 #[cfg(feature = "workspace_session")]
     10 #[path = "client_commands.rs"]
     11 mod commands;
     12 
     13 #[cfg(feature = "workspace_session")]
     14 #[path = "client_inventory.rs"]
     15 mod inventory;
     16 
     17 #[cfg(feature = "workspace_session")]
     18 #[path = "client_commerce.rs"]
     19 mod commerce;
     20 
     21 #[cfg(feature = "workspace_session")]
     22 #[path = "client_rewrap.rs"]
     23 mod rewrap;
     24 
     25 struct Resources<H> {
     26     host: H,
     27     signer: Shared<Mutex<Option<SignerSession>>>,
     28     #[cfg(feature = "workspace_session")]
     29     workspaces: WorkspaceScopes,
     30     #[cfg(feature = "workspace_session")]
     31     stock_captures: Shared<super::stock_evidence::Owner>,
     32     host_quiesced: Mutex<bool>,
     33     host_drained: Mutex<bool>,
     34 }
     35 #[cfg(feature = "workspace_session")]
     36 type WorkspaceScopes = Shared<Mutex<std::vec::Vec<crate::workspace::WorkspaceSession>>>;
     37 #[cfg(feature = "workspace_session")]
     38 const MAX_WORKSPACE_SCOPES: usize = 16;
     39 fn signer_lock(value: &Mutex<Option<SignerSession>>) -> MutexGuard<'_, Option<SignerSession>> {
     40     value
     41         .lock()
     42         .unwrap_or_else(std::sync::PoisonError::into_inner)
     43 }
     44 impl<H: SessionHost> SessionHost for Resources<H> {
     45     fn start(&self) -> HostFuture<'_, crate::Result<()>> {
     46         self.host.start()
     47     }
     48     fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> {
     49         Box::pin(async move {
     50             #[cfg(feature = "workspace_session")]
     51             {
     52                 let scopes = self
     53                     .workspaces
     54                     .lock()
     55                     .unwrap_or_else(std::sync::PoisonError::into_inner);
     56                 for scope in scopes.iter() {
     57                     scope.close();
     58                 }
     59             }
     60             let quiesced = *self
     61                 .host_quiesced
     62                 .lock()
     63                 .unwrap_or_else(std::sync::PoisonError::into_inner);
     64             if !quiesced {
     65                 self.host.quiesce().await?;
     66                 *self
     67                     .host_quiesced
     68                     .lock()
     69                     .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
     70             }
     71             let signer = signer_lock(&self.signer).clone();
     72             if let Some(signer) = signer {
     73                 signer.quiesce().await?;
     74             }
     75             Ok(())
     76         })
     77     }
     78     fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> {
     79         self.host.disconnect()
     80     }
     81     fn drain(&self) -> HostFuture<'_, crate::Result<()>> {
     82         Box::pin(async move {
     83             let drained = *self
     84                 .host_drained
     85                 .lock()
     86                 .unwrap_or_else(std::sync::PoisonError::into_inner);
     87             if !drained {
     88                 // The host may drive its accepted futures here. They must reach
     89                 // settlement before retrying captures whose locks they retain.
     90                 self.host.drain().await?;
     91                 *self
     92                     .host_drained
     93                     .lock()
     94                     .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
     95             }
     96             #[cfg(feature = "workspace_session")]
     97             self.stock_captures.drain().await?;
     98             Ok(())
     99         })
    100     }
    101     fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> {
    102         Box::pin(async move {
    103             let signer = signer_lock(&self.signer).clone();
    104             if let Some(signer) = signer {
    105                 signer.close().await?;
    106             }
    107             self.host.dispose_callbacks().await
    108         })
    109     }
    110     fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> {
    111         self.host.close_storage()
    112     }
    113 }
    114 
    115 /// Shared client resource ownership and one explicitly attached signer scope.
    116 ///
    117 /// No observed identity establishes workspace, command or stock authority.
    118 /// The concrete facade supplies its actual resources through `SessionHost`.
    119 pub struct ClientSession<H: SessionHost> {
    120     session: Session<Resources<H>>,
    121     signer: Shared<Mutex<Option<SignerSession>>>,
    122     #[cfg(feature = "workspace_session")]
    123     workspaces: WorkspaceScopes,
    124     #[cfg(feature = "workspace_session")]
    125     pub(crate) task_host: Option<Shared<dyn super::tasks::TaskHost>>,
    126     #[cfg(feature = "workspace_session")]
    127     pub(crate) task_budget: super::tasks::TaskBudget,
    128     #[cfg(feature = "workspace_session")]
    129     pub(crate) commands: Option<Shared<super::command::CommandRuntime>>,
    130     #[cfg(feature = "workspace_session")]
    131     stock_captures: Shared<super::stock_evidence::Owner>,
    132 }
    133 impl<H: SessionHost> Clone for ClientSession<H> {
    134     fn clone(&self) -> Self {
    135         Self {
    136             session: self.session.clone(),
    137             signer: self.signer.clone(),
    138             #[cfg(feature = "workspace_session")]
    139             workspaces: self.workspaces.clone(),
    140             #[cfg(feature = "workspace_session")]
    141             task_host: self.task_host.clone(),
    142             #[cfg(feature = "workspace_session")]
    143             task_budget: self.task_budget.clone(),
    144             #[cfg(feature = "workspace_session")]
    145             commands: self.commands.clone(),
    146             #[cfg(feature = "workspace_session")]
    147             stock_captures: self.stock_captures.clone(),
    148         }
    149     }
    150 }
    151 impl<H: SessionHost> ClientSession<H> {
    152     /// Owns resources without starting workers, observing a signer or networking.
    153     pub fn new(host: H, maximum_in_flight: NonZeroU16) -> Self {
    154         let signer = Shared::new(Mutex::new(None));
    155         #[cfg(feature = "workspace_session")]
    156         let workspaces = Shared::new(Mutex::new(std::vec::Vec::new()));
    157         #[cfg(feature = "workspace_session")]
    158         let stock_captures = Shared::new(super::stock_evidence::Owner::default());
    159         Self {
    160             session: Session::new(
    161                 Resources {
    162                     host,
    163                     signer: signer.clone(),
    164                     #[cfg(feature = "workspace_session")]
    165                     workspaces: workspaces.clone(),
    166                     #[cfg(feature = "workspace_session")]
    167                     stock_captures: stock_captures.clone(),
    168                     host_quiesced: Mutex::new(false),
    169                     host_drained: Mutex::new(false),
    170                 },
    171                 maximum_in_flight,
    172             ),
    173             signer,
    174             #[cfg(feature = "workspace_session")]
    175             workspaces,
    176             #[cfg(feature = "workspace_session")]
    177             task_host: None,
    178             #[cfg(feature = "workspace_session")]
    179             task_budget: super::tasks::TaskBudget::new(),
    180             #[cfg(feature = "workspace_session")]
    181             commands: None,
    182             #[cfg(feature = "workspace_session")]
    183             stock_captures,
    184         }
    185     }
    186     /// Pairs an explicit target task host with its owning lifecycle host. The
    187     /// lifecycle must drain accepted tasks and retain failed captures through
    188     /// recovery before allowing storage disposal. This is a host trust boundary;
    189     /// supplying an implementation is not execution qualification.
    190     #[cfg(feature = "workspace_session")]
    191     pub fn new_with_task_host(
    192         host: H,
    193         maximum_in_flight: NonZeroU16,
    194         task_host: Shared<dyn super::tasks::TaskHost>,
    195     ) -> Self {
    196         let mut client = Self::new(host, maximum_in_flight);
    197         client.task_host = Some(task_host);
    198         client
    199     }
    200     /// Pairs the workflow's obtained-material owner with the lifecycle host
    201     /// which must drain that same owner before closing resources.
    202     #[cfg(feature = "workspace_session")]
    203     pub fn with_command_runtime(mut self, runtime: Shared<super::command::CommandRuntime>) -> Self {
    204         self.commands = Some(runtime);
    205         self
    206     }
    207     /// Reports resource lifecycle independently of business authority.
    208     pub fn state(&self) -> SessionState {
    209         self.session.state()
    210     }
    211     /// Starts the explicitly configured resource host on the caller's executor.
    212     pub async fn start(&self) -> crate::Result<()> {
    213         self.session.start().await
    214     }
    215     /// Retains the provider before awaiting its first actual observation.
    216     /// Failed or cancelled attachment remains owned and may be inspected/closed
    217     /// through `signer_session`; replacing a live scope is explicitly refused.
    218     pub async fn attach_signer(&self, handle: SignerHandle) -> crate::Result<SignerSession> {
    219         let _permit = self.session.retain_resource()?;
    220         let (scope, retired) = {
    221             let mut current = signer_lock(&self.signer);
    222             // Insertion and the close hook share this lock. Rechecking resource
    223             // admission here prevents an attachment being missed by quiesce.
    224             if matches!(self.state(), SessionState::Closing | SessionState::Closed) {
    225                 return Err(crate::Error::signer_unavailable());
    226             }
    227             if current
    228                 .as_ref()
    229                 .is_some_and(|scope| scope.state() != SessionState::Closed)
    230             {
    231                 return Err(crate::Error::signer_unavailable());
    232             }
    233             let scope = SignerSession::new(handle);
    234             let retired = current.replace(scope.clone());
    235             (scope, retired)
    236         };
    237         drop(retired);
    238         scope.observe().await.map_err(|error| {
    239             if error == ProviderError::IdentityChanged {
    240                 crate::Error::identity_changed()
    241             } else {
    242                 crate::Error::signer_unavailable()
    243             }
    244         })?;
    245         Ok(scope)
    246     }
    247     /// Returns the owned scope, including failed/cancelled first observations.
    248     /// It grants no workspace access and cannot reopen closed admission.
    249     pub fn signer_session(&self) -> Option<SignerSession> {
    250         signer_lock(&self.signer).clone()
    251     }
    252     /// Authenticates attachment while sharing the client's permanent resource
    253     /// admission gate. The concrete client owns the store through actual close.
    254     #[cfg(feature = "workspace_session")]
    255     pub async fn attach_workspace(
    256         &self,
    257         store: Shared<dyn radroots_storage::workspace::WorkspaceStore>,
    258         input: radroots_storage::workspace::AttachmentInput,
    259         proof: radroots_storage::workspace::AttachmentProof,
    260     ) -> crate::Result<crate::workspace::WorkspaceSession> {
    261         let _permit = self.session.retain_resource()?;
    262         let scope = crate::workspace::WorkspaceSession::attach(store, input, proof).await?;
    263         // Retired adapter roots may run host Drop code. Keep them alive until
    264         // after the registry guard is released, including every error return.
    265         let mut retired = std::vec::Vec::new();
    266         let mut scopes = self
    267             .workspaces
    268             .lock()
    269             .unwrap_or_else(std::sync::PoisonError::into_inner);
    270         retired.extend(scopes.extract_if(.., |scope| scope.is_closed()));
    271         if matches!(self.state(), SessionState::Closing | SessionState::Closed) {
    272             scope.close();
    273             return Err(crate::Error::workspace(
    274                 radroots_storage::workspace::WorkspaceError::Closed,
    275                 None,
    276             ));
    277         }
    278         if scopes.len() >= MAX_WORKSPACE_SCOPES {
    279             scope.close();
    280             return Err(crate::Error::session_unavailable(crate::Reason::OutOfRange));
    281         }
    282         scopes.push(scope.clone());
    283         drop(scopes);
    284         drop(retired);
    285         Ok(scope)
    286     }
    287     /// Stops admission, quiesces callbacks, drains work, disconnects transports,
    288     /// disposes callbacks and closes storage last. Cancellation is resumable.
    289     pub async fn close(&self) -> crate::Result<()> {
    290         self.session.close().await
    291     }
    292 }