lib

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

client.rs (12493B)


      1 //! Concrete browser resources with the shared command and shutdown owner.
      2 use crate::{
      3     CommandContext, InquireInput, OperationId, OperationReceipt, Result, SessionState, StartMode,
      4     WorkspaceSession,
      5 };
      6 use crate::{
      7     commands::{BrowserCommands, unix_seconds},
      8     tasks::OwnedTasks,
      9 };
     10 use radroots_domain::{ChatMessage, CommandDigest, UnixSeconds};
     11 use radroots_execution::{
     12     Code, Error, OperationContext, RetryClass,
     13     session::{ClientSession, HostFuture, SessionHost, SignerSession, command::CommandRuntime},
     14 };
     15 use radroots_secrets::{SecretId, SecretRef, browser::BrowserProvider, provider::AccessPolicy};
     16 use radroots_signing::provider::SignerHandle;
     17 use radroots_storage::{
     18     command::OperationError,
     19     workspace::{AttachmentInput, AttachmentProof, WorkspaceClock, WorkspaceError},
     20 };
     21 use radroots_storage_indexeddb::workspace::BrowserWorkspace;
     22 use std::{cell::Cell, num::NonZeroU16, rc::Rc};
     23 
     24 fn storage_failure() -> Error {
     25     Error::new(
     26         Code::StorageFailure,
     27         OperationContext::proposed(None),
     28         RetryClass::Never,
     29         None,
     30     )
     31     .unwrap_or_else(|_| unreachable!("valid constant storage error"))
     32 }
     33 fn operation(error: OperationError) -> Error {
     34     Error::operation(error, OperationContext::proposed(None))
     35 }
     36 
     37 /// Exact existing protected namespace and independently retained authority.
     38 /// Constructing configuration opens no database and observes no participant.
     39 pub struct BrowserConfig {
     40     namespace: SecretId,
     41     reference: SecretRef,
     42     fingerprint: [u8; 32],
     43     input: AttachmentInput,
     44     proof: AttachmentProof,
     45     policy: AccessPolicy,
     46     commands: Option<Rc<BrowserCommands>>,
     47 }
     48 impl BrowserConfig {
     49     /// Selects an existing key and workspace only. Missing/damaged state is an
     50     /// error; it never triggers automatic enrollment or replacement key creation.
     51     pub fn existing(
     52         namespace: SecretId,
     53         reference: SecretRef,
     54         fingerprint: [u8; 32],
     55         input: AttachmentInput,
     56         proof: AttachmentProof,
     57         policy: AccessPolicy,
     58     ) -> Self {
     59         Self {
     60             namespace,
     61             reference,
     62             fingerprint,
     63             input,
     64             proof,
     65             policy,
     66             commands: None,
     67         }
     68     }
     69     /// Adds explicit destinations and a relay acceptance criterion. No I/O.
     70     pub fn with_nostr(
     71         mut self,
     72         config: radroots_transport_nostr::Config,
     73         policy: radroots_transport::policy::SatisfactionPolicy,
     74     ) -> Result<Self> {
     75         self.commands = Some(Rc::new(
     76             BrowserCommands::new(config, policy).map_err(operation)?,
     77         ));
     78         Ok(self)
     79     }
     80 }
     81 struct WallClock;
     82 impl WorkspaceClock for WallClock {
     83     fn now(&self) -> std::result::Result<UnixSeconds, WorkspaceError> {
     84         unix_seconds().map_err(|_| WorkspaceError::Unavailable)
     85     }
     86 }
     87 struct Resources {
     88     workspace: Rc<BrowserWorkspace>,
     89     provider: Rc<BrowserProvider>,
     90     tasks: Rc<OwnedTasks>,
     91     commands: Option<Rc<CommandRuntime>>,
     92     io: Option<Rc<BrowserCommands>>,
     93     storage_closed: Rc<Cell<bool>>,
     94 }
     95 impl SessionHost for Resources {
     96     fn start(&self) -> HostFuture<'_, Result<()>> {
     97         Box::pin(async move { self.tasks.start(wasm_bindgen_futures::spawn_local) })
     98     }
     99     fn quiesce(&self) -> HostFuture<'_, Result<()>> {
    100         Box::pin(async move { self.tasks.quiesce() })
    101     }
    102     fn drain(&self) -> HostFuture<'_, Result<()>> {
    103         Box::pin(async move {
    104             self.tasks.drain().await?;
    105             if let Some(commands) = &self.commands {
    106                 commands.drain().await?;
    107             }
    108             Ok(())
    109         })
    110     }
    111     fn disconnect(&self) -> HostFuture<'_, Result<()>> {
    112         Box::pin(async move {
    113             if let Some(io) = &self.io {
    114                 io.disconnect().await;
    115             }
    116             Ok(())
    117         })
    118     }
    119     fn dispose_callbacks(&self) -> HostFuture<'_, Result<()>> {
    120         Box::pin(async move {
    121             if let Some(io) = &self.io {
    122                 io.dispose().await.map_err(operation)?;
    123             }
    124             Ok(())
    125         })
    126     }
    127     fn close_storage(&self) -> HostFuture<'_, Result<()>> {
    128         Box::pin(async move {
    129             self.tasks.close().await?;
    130             self.workspace
    131                 .close()
    132                 .await
    133                 .map_err(|_| storage_failure())?;
    134             self.provider.close().await.map_err(|_| storage_failure())?;
    135             self.storage_closed.set(true);
    136             Ok(())
    137         })
    138     }
    139 }
    140 /// Confirmation that this client's actual protected resources completed close.
    141 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    142 pub struct CloseReceipt {
    143     storage_closed: bool,
    144 }
    145 impl CloseReceipt {
    146     /// Actual workspace/provider close completed after owned work and callbacks.
    147     pub const fn storage_closed(self) -> bool {
    148         self.storage_closed
    149     }
    150 }
    151 /// Cloneable origin-thread ownership of one actual browser resource session.
    152 /// Clones share lifecycle, journal, signer scope and permanent close admission.
    153 #[derive(Clone)]
    154 pub struct Client {
    155     session: ClientSession<Resources>,
    156     workspace: Rc<BrowserWorkspace>,
    157     io: Option<Rc<BrowserCommands>>,
    158     storage_closed: Rc<Cell<bool>>,
    159 }
    160 impl Client {
    161     /// Authenticates and opens the real existing IndexedDB key/workspace. It
    162     /// neither attaches a signer/scope nor starts network work or replays writes.
    163     pub async fn open(config: BrowserConfig) -> Result<Self> {
    164         let provider = Rc::new(
    165             BrowserProvider::open(
    166                 config.namespace,
    167                 SecretRef::new(
    168                     config.reference.id().clone(),
    169                     config.reference.backend(),
    170                     config.reference.key_version(),
    171                 ),
    172                 config.fingerprint,
    173             )
    174             .await
    175             .map_err(|_| storage_failure())?,
    176         );
    177         let workspace = match BrowserWorkspace::open_existing(
    178             config.input,
    179             config.proof,
    180             provider.clone(),
    181             config.reference,
    182             config.policy,
    183             Rc::new(WallClock),
    184         )
    185         .await
    186         {
    187             Ok(workspace) => Rc::new(workspace),
    188             Err(error) => {
    189                 provider.close().await.map_err(|_| storage_failure())?;
    190                 return Err(operation(OperationError::Workspace(error)));
    191             }
    192         };
    193         let tasks = Rc::new(OwnedTasks::default());
    194         let commands = config
    195             .commands
    196             .as_ref()
    197             .map(|io| Rc::new(CommandRuntime::new(io.clone())));
    198         let storage_closed = Rc::new(Cell::new(false));
    199         let host = Resources {
    200             workspace: workspace.clone(),
    201             provider,
    202             tasks: tasks.clone(),
    203             commands: commands.clone(),
    204             io: config.commands.clone(),
    205             storage_closed: storage_closed.clone(),
    206         };
    207         const MAX: NonZeroU16 = match NonZeroU16::new(32) {
    208             Some(value) => value,
    209             None => panic!("nonzero constant"),
    210         };
    211         let session = ClientSession::new_with_task_host(host, MAX, tasks);
    212         let session = match commands {
    213             Some(commands) => session.with_command_runtime(commands),
    214             None => session,
    215         };
    216         Ok(Self {
    217             session,
    218             workspace,
    219             io: config.commands,
    220             storage_closed,
    221         })
    222     }
    223     /// Passive lifecycle observation; no backend probe or authority acquisition.
    224     pub fn state(&self) -> SessionState {
    225         self.session.state()
    226     }
    227     /// Explicitly observes and retains one participant signer/callback scope.
    228     pub async fn attach_signer(&self, handle: SignerHandle) -> Result<SignerSession> {
    229         self.session.attach_signer(handle).await
    230     }
    231     /// Retains access to a failed/cancelled first signer observation for close.
    232     pub fn signer_session(&self) -> Option<SignerSession> {
    233         self.session.signer_session()
    234     }
    235     /// Authenticates a client-owned workspace scope separately from key opening.
    236     pub async fn attach(
    237         &self,
    238         input: AttachmentInput,
    239         proof: AttachmentProof,
    240     ) -> Result<WorkspaceSession> {
    241         self.session
    242             .attach_workspace(self.workspace.clone(), input, proof)
    243             .await
    244     }
    245     /// Starts bounded Rust tasks. Online permits only subsequent explicit calls;
    246     /// startup performs no query, publication or implicit resume.
    247     pub async fn start(&self, mode: StartMode) -> Result<SessionState> {
    248         if let Some(io) = &self.io {
    249             io.select(mode == StartMode::Online).map_err(operation)?;
    250         } else if mode == StartMode::Online {
    251             return Err(operation(OperationError::Unauthorized));
    252         }
    253         self.session.start().await?;
    254         Ok(self.state())
    255     }
    256     /// Borrows the ordinary private inquiry entry point without performing I/O.
    257     pub const fn inbox(&self) -> Inbox<'_> {
    258         Inbox { client: self }
    259     }
    260     /// Borrows initial public listing execution through the same shared owner.
    261     pub const fn listings(&self) -> Listings<'_> {
    262         Listings { client: self }
    263     }
    264     /// Selects an explicitly authenticated scope for retained operation reads.
    265     pub fn operations(&self, scope: &WorkspaceSession) -> Operations<'_> {
    266         Operations {
    267             client: self,
    268             scope: scope.clone(),
    269         }
    270     }
    271     /// Permanently stops admission and resumes original ordered closure after
    272     /// cancellation. A receipt requires actual storage close, never Drop.
    273     pub async fn close(&self) -> Result<CloseReceipt> {
    274         self.session.close().await?;
    275         if !self.storage_closed.get() {
    276             return Err(storage_failure());
    277         }
    278         Ok(CloseReceipt {
    279             storage_closed: true,
    280         })
    281     }
    282 }
    283 /// Private inquiry access through the actual protected browser journal.
    284 pub struct Inbox<'a> {
    285     client: &'a Client,
    286 }
    287 impl Inbox<'_> {
    288     /// Runs the shared durable inquiry. Losing observation does not cancel an
    289     /// accepted command, issued artifact or committed browser transaction.
    290     pub async fn inquire(
    291         &self,
    292         context: CommandContext,
    293         input: InquireInput,
    294     ) -> radroots_execution::ExecutionResult<OperationReceipt<ChatMessage>> {
    295         self.client
    296             .session
    297             .inquire(self.client.workspace.clone(), context, input)
    298             .await
    299     }
    300 }
    301 /// Public listing access through the actual protected browser journal.
    302 pub struct Listings<'a> {
    303     client: &'a Client,
    304 }
    305 impl Listings<'_> {
    306     /// Captures initial publication under an authenticated seller attachment.
    307     /// Shared execution owns signing, installation, delivery and retained work;
    308     /// losing this observer never grants rollback or automatic redispatch.
    309     pub async fn publish(
    310         &self,
    311         context: CommandContext,
    312         input: radroots_protocol::listing::PublishInput,
    313     ) -> radroots_execution::ExecutionResult<OperationReceipt<radroots_domain::listing::Listing>>
    314     {
    315         self.client
    316             .session
    317             .publish_listing(self.client.workspace.clone(), context, input)
    318             .await
    319     }
    320 }
    321 /// Authenticated original-operation reads and explicit delivery resumption.
    322 pub struct Operations<'a> {
    323     client: &'a Client,
    324     scope: WorkspaceSession,
    325 }
    326 impl Operations<'_> {
    327     /// Reads original retained progress; absence proves no safe nonissuance.
    328     pub async fn get(
    329         &self,
    330         id: OperationId,
    331     ) -> Result<Option<radroots_execution::OperationStatus>> {
    332         self.get_matching(id, None).await
    333     }
    334     /// Requires the original command digest in addition to operation identity.
    335     pub async fn get_matching(
    336         &self,
    337         id: OperationId,
    338         expected: Option<CommandDigest>,
    339     ) -> Result<Option<radroots_execution::OperationStatus>> {
    340         self.client
    341             .session
    342             .operation(self.client.workspace.clone(), &self.scope, id, expected)
    343             .await
    344     }
    345     /// Resumes only original retained work; it never reissues a signing claim.
    346     pub async fn resume(
    347         &self,
    348         id: OperationId,
    349         expected: Option<CommandDigest>,
    350     ) -> radroots_execution::ExecutionResult<radroots_execution::OperationStatus> {
    351         self.client
    352             .session
    353             .resume_command(self.client.workspace.clone(), &self.scope, id, expected)
    354             .await
    355     }
    356 }