lib

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

client.rs (40716B)


      1 //! Client construction and lifecycle.
      2 
      3 use std::{
      4     collections::{BTreeMap, BTreeSet},
      5     sync::{
      6         Arc,
      7         atomic::{AtomicU8, Ordering},
      8     },
      9 };
     10 
     11 use radroots_signing::Signer;
     12 use radroots_storage::Storage;
     13 #[cfg(feature = "memory")]
     14 use radroots_storage::{event::SourceGeneration, memory::MemoryStorage};
     15 use radroots_transport::{EventSink, EventSource};
     16 
     17 use crate::{
     18     Error, Result,
     19     capability::{Availability, CapabilityId, CapabilityReport},
     20 };
     21 
     22 /// Cloneable handle to a composed Radroots client.
     23 #[derive(Clone)]
     24 pub struct Client {
     25     inner: Arc<ClientInner>,
     26 }
     27 
     28 /// Explicit composition boundary for a [`Client`].
     29 #[derive(Default)]
     30 pub struct ClientBuilder {
     31     storage: Option<Arc<dyn Storage>>,
     32     #[cfg(feature = "sync")]
     33     sync_storage: Option<Arc<dyn radroots_sync::policy::SyncStorage>>,
     34     signer: Option<Arc<dyn Signer>>,
     35     source: Option<Arc<dyn EventSource>>,
     36     sink: Option<Arc<dyn EventSink>>,
     37     #[cfg(feature = "sync")]
     38     sync: Option<radroots_sync::Engine>,
     39     #[cfg(feature = "sync")]
     40     host_sync: Option<crate::sync::HostPolicy>,
     41     #[cfg(feature = "nostr")]
     42     nostr: Option<crate::transport::NostrSlot>,
     43     #[cfg(feature = "blossom")]
     44     blossom: Option<crate::transport::BlossomSlot>,
     45     capability_availability: BTreeMap<CapabilityId, Availability>,
     46     explicitly_configured_capabilities: BTreeSet<CapabilityId>,
     47 }
     48 
     49 struct ClientInner {
     50     storage: Arc<dyn Storage>,
     51     signer: Option<Arc<dyn Signer>>,
     52     source: Option<Arc<dyn EventSource>>,
     53     sink: Option<Arc<dyn EventSink>>,
     54     #[cfg(feature = "sync")]
     55     sync: Option<radroots_sync::Engine>,
     56     #[cfg(feature = "nostr")]
     57     nostr: Option<crate::transport::NostrSlot>,
     58     #[cfg(feature = "blossom")]
     59     blossom: Option<crate::transport::BlossomSlot>,
     60     capability_availability: BTreeMap<CapabilityId, Availability>,
     61     explicitly_configured_capabilities: BTreeSet<CapabilityId>,
     62     lifecycle: AtomicU8,
     63 }
     64 
     65 const OPEN: u8 = 0;
     66 const CLOSING: u8 = 1;
     67 const CLOSE_RETRY_REQUIRED: u8 = 2;
     68 const CLOSED: u8 = 3;
     69 
     70 impl ClientBuilder {
     71     /// Creates an empty builder with no hidden storage, network, signing, or
     72     /// runtime side effects.
     73     #[must_use]
     74     pub fn new() -> Self {
     75         Self::default()
     76     }
     77 
     78     /// Creates a builder backed by deterministic in-process memory storage.
     79     #[cfg(feature = "memory")]
     80     #[must_use]
     81     pub fn memory(generation: SourceGeneration) -> Self {
     82         let storage = Arc::new(MemoryStorage::new(generation));
     83         let builder = Self::new().storage(storage.clone());
     84         #[cfg(feature = "sync")]
     85         {
     86             let mut builder = builder;
     87             builder.sync_storage = Some(storage);
     88             builder
     89         }
     90         #[cfg(not(feature = "sync"))]
     91         builder
     92     }
     93 
     94     /// Creates the ordinary deterministic in-process memory configuration.
     95     ///
     96     /// This performs no I/O and is intended for ephemeral local clients whose
     97     /// source-generation identity does not need to survive the process. Hosts
     98     /// that persist cursors should call [`Self::memory`] with their own
     99     /// generation instead.
    100     #[cfg(feature = "memory")]
    101     #[must_use]
    102     pub fn memory_default() -> Self {
    103         let storage = Arc::new(MemoryStorage::default());
    104         let builder = Self::new().storage(storage.clone());
    105         #[cfg(feature = "sync")]
    106         {
    107             let mut builder = builder;
    108             builder.sync_storage = Some(storage);
    109             builder
    110         }
    111         #[cfg(not(feature = "sync"))]
    112         builder
    113     }
    114 
    115     /// Explicitly opens canonical SQLite storage from validated host-owned
    116     /// configuration and returns a builder containing only the storage SPI.
    117     #[cfg(feature = "sqlite")]
    118     pub async fn sqlite(options: crate::storage::SqliteOptions) -> Result<Self> {
    119         let storage = radroots_storage_sqlite::SqliteStorage::open(options)
    120             .await
    121             .map_err(Error::storage_open_failed)?;
    122         let storage = Arc::new(storage);
    123         let builder = Self::new()
    124             .storage(storage.clone())
    125             .capability_availability(CapabilityId::PERSISTENT_STORAGE, Availability::Available);
    126         #[cfg(feature = "sync")]
    127         {
    128             let mut builder = builder;
    129             builder.sync_storage = Some(storage);
    130             Ok(builder)
    131         }
    132         #[cfg(not(feature = "sync"))]
    133         Ok(builder)
    134     }
    135 
    136     /// Injects the canonical storage capability.
    137     #[must_use]
    138     pub fn storage(mut self, storage: Arc<dyn Storage>) -> Self {
    139         self.storage = Some(storage);
    140         self
    141     }
    142 
    143     /// Injects an optional canonical signer capability.
    144     #[must_use]
    145     pub fn signer(mut self, signer: Arc<dyn Signer>) -> Self {
    146         self.signer = Some(signer);
    147         self
    148     }
    149 
    150     /// Installs a module-scoped signer provider over the canonical SPI and
    151     /// records its presentation-independent runtime capability.
    152     #[must_use]
    153     pub fn signing(mut self, provider: crate::signing::Provider) -> Self {
    154         let capability = match provider.mode() {
    155             crate::signing::Mode::Local => Some(CapabilityId::LOCAL_SIGNING),
    156             crate::signing::Mode::Nip46 => Some(CapabilityId::NIP46_SIGNING),
    157             crate::signing::Mode::Host => None,
    158         };
    159         self.signer = Some(provider.into_signer());
    160         if let Some(capability) = capability {
    161             self.explicitly_configured_capabilities.insert(capability);
    162             self.capability_availability
    163                 .insert(capability, Availability::Available);
    164         }
    165         self
    166     }
    167 
    168     /// Injects an optional inbound event source.
    169     #[must_use]
    170     pub fn source(mut self, source: Arc<dyn EventSource>) -> Self {
    171         self.source = Some(source);
    172         self
    173     }
    174 
    175     /// Injects an optional outbound event sink.
    176     #[must_use]
    177     pub fn sink(mut self, sink: Arc<dyn EventSink>) -> Self {
    178         self.sink = Some(sink);
    179         self
    180     }
    181 
    182     /// Installs one host-reconfigurable Nostr source and sink.
    183     #[cfg(feature = "nostr")]
    184     #[must_use]
    185     pub fn nostr(mut self, slot: crate::transport::NostrSlot) -> Self {
    186         self.source = Some(Arc::new(slot.clone()));
    187         self.sink = Some(Arc::new(slot.clone()));
    188         self.nostr = Some(slot);
    189         self
    190     }
    191 
    192     /// Installs one host-reconfigurable Blossom HTTP adapter slot.
    193     #[cfg(feature = "blossom")]
    194     #[must_use]
    195     pub fn blossom(mut self, slot: crate::transport::BlossomSlot) -> Self {
    196         self.blossom = Some(slot);
    197         self
    198     }
    199 
    200     /// Injects an explicitly composed synchronization engine.
    201     #[cfg(feature = "sync")]
    202     #[must_use]
    203     pub fn sync_engine(mut self, sync: radroots_sync::Engine) -> Self {
    204         self.sync = Some(sync);
    205         self
    206     }
    207 
    208     /// Requests one SDK-composed engine using explicit native host policy.
    209     ///
    210     /// This is available only for SDK-created memory or SQLite storage, whose
    211     /// complete synchronization capability is known without downcasting.
    212     #[cfg(feature = "sync")]
    213     #[must_use]
    214     pub fn host_sync(mut self, policy: crate::sync::HostPolicy) -> Self {
    215         self.host_sync = Some(policy);
    216         self
    217     }
    218 
    219     /// Marks a specialized capability as configured and records its
    220     /// host-observed initial availability without probing resources.
    221     ///
    222     /// Reports ignore this observation for capabilities that are not compiled
    223     /// or configured. Runtime IDs are independent from Cargo feature names.
    224     #[must_use]
    225     pub fn capability_availability(mut self, id: CapabilityId, availability: Availability) -> Self {
    226         self.explicitly_configured_capabilities.insert(id);
    227         self.capability_availability.insert(id, availability);
    228         self
    229     }
    230 
    231     /// Validates the selected capabilities and creates a client handle.
    232     #[allow(unused_mut)]
    233     pub fn build(mut self) -> Result<Client> {
    234         let storage = self.storage.ok_or_else(Error::missing_storage)?;
    235         #[cfg(feature = "sync")]
    236         if let Some(policy) = self.host_sync {
    237             let sync_storage = self
    238                 .sync_storage
    239                 .take()
    240                 .ok_or_else(Error::shared_operation_unavailable)?;
    241             let (clock, ids, deadlines) = policy.composition();
    242             let mut builder = radroots_sync::Engine::builder(sync_storage, clock, ids, deadlines);
    243             if let Some(source) = self.source.as_ref() {
    244                 builder = builder.source(Arc::clone(source));
    245             }
    246             if let Some(sink) = self.sink.as_ref() {
    247                 builder = builder.sink(Arc::clone(sink));
    248             }
    249             if let Some(signer) = self.signer.as_ref() {
    250                 builder = builder.signer(Arc::clone(signer));
    251             }
    252             self.sync = Some(builder.build().map_err(Error::invalid_host_configuration)?);
    253         }
    254         Ok(Client {
    255             inner: Arc::new(ClientInner {
    256                 storage,
    257                 signer: self.signer,
    258                 source: self.source,
    259                 sink: self.sink,
    260                 #[cfg(feature = "sync")]
    261                 sync: self.sync,
    262                 #[cfg(feature = "nostr")]
    263                 nostr: self.nostr,
    264                 #[cfg(feature = "blossom")]
    265                 blossom: self.blossom,
    266                 capability_availability: self.capability_availability,
    267                 explicitly_configured_capabilities: self.explicitly_configured_capabilities,
    268                 lifecycle: AtomicU8::new(OPEN),
    269             }),
    270         })
    271     }
    272 }
    273 
    274 impl Client {
    275     /// Returns a deterministic capability report without probing resources or
    276     /// performing filesystem, network, signing, or storage operations.
    277     #[must_use]
    278     #[allow(unused_mut)]
    279     pub fn capabilities(&self) -> CapabilityReport {
    280         let lifecycle_availability = match self.inner.lifecycle.load(Ordering::Acquire) {
    281             OPEN => Availability::Available,
    282             CLOSING | CLOSE_RETRY_REQUIRED => Availability::Degraded,
    283             _ => Availability::Unavailable,
    284         };
    285         let mut explicitly_configured = self.inner.explicitly_configured_capabilities.clone();
    286         let mut overrides = self.inner.capability_availability.clone();
    287         let mut source_configured = self.inner.source.is_some();
    288         let mut sink_configured = self.inner.sink.is_some();
    289         let mut source_availability = Availability::Unavailable;
    290         let mut sink_availability = Availability::Unavailable;
    291         #[cfg(feature = "nostr")]
    292         if let Some(slot) = &self.inner.nostr {
    293             match slot.relay_status() {
    294                 Some(status) => {
    295                     source_configured = !status.relays().is_empty();
    296                     sink_configured = status
    297                         .relays()
    298                         .iter()
    299                         .any(|relay| relay.endpoint().access().can_write());
    300                     source_availability = map_transport_availability(status.read_availability());
    301                     sink_availability = map_transport_availability(status.write_availability());
    302                     if source_configured {
    303                         explicitly_configured.insert(CapabilityId::NOSTR_FETCH);
    304                         overrides.insert(CapabilityId::NOSTR_FETCH, source_availability);
    305                     }
    306                     if sink_configured {
    307                         explicitly_configured.insert(CapabilityId::NOSTR_DELIVERY);
    308                         overrides.insert(CapabilityId::NOSTR_DELIVERY, sink_availability);
    309                     }
    310                 }
    311                 None => {
    312                     source_configured = false;
    313                     sink_configured = false;
    314                 }
    315             }
    316         }
    317         crate::capability::report(crate::capability::Context {
    318             storage: true,
    319             signer: self.inner.signer.is_some(),
    320             source: source_configured,
    321             sink: sink_configured,
    322             sync: self.sync_is_configured(),
    323             source_availability,
    324             sink_availability,
    325             lifecycle_availability,
    326             explicitly_configured: &explicitly_configured,
    327             overrides: &overrides,
    328         })
    329     }
    330 
    331     /// Returns canonical backend status without exposing a backend handle.
    332     pub async fn storage_status(&self) -> Result<crate::storage::Status> {
    333         let storage = self.storage()?;
    334         radroots_storage::BackupSource::status(storage)
    335             .await
    336             .map_err(Error::storage_inspection_failed)
    337     }
    338 
    339     /// Runs canonical integrity inspection without exposing backend internals.
    340     pub async fn storage_integrity(&self) -> Result<crate::storage::IntegrityStatus> {
    341         let storage = self.storage()?;
    342         radroots_storage::BackupSource::integrity(storage)
    343             .await
    344             .map_err(Error::storage_inspection_failed)
    345     }
    346 
    347     /// Returns the injected canonical storage capability.
    348     pub fn storage(&self) -> Result<&dyn Storage> {
    349         self.require_open()?;
    350         Ok(self.inner.storage.as_ref())
    351     }
    352 
    353     /// Returns backend-neutral backup, restore, status, and integrity operations.
    354     pub fn storage_operations(&self) -> Result<crate::storage::Operations<'_>> {
    355         Ok(crate::storage::Operations::new(self.storage()?))
    356     }
    357 
    358     /// Returns the injected signer, when outbound authoring is enabled.
    359     pub fn signer(&self) -> Result<Option<&dyn Signer>> {
    360         self.require_open()?;
    361         Ok(self.inner.signer.as_deref())
    362     }
    363 
    364     /// Returns focused high-level operations over the configured opaque signer.
    365     pub fn signing(&self) -> Result<Option<crate::signing::Operations<'_>>> {
    366         Ok(self.signer()?.map(crate::signing::Operations::new))
    367     }
    368 
    369     /// Returns the injected inbound source, when pull is enabled.
    370     pub fn source(&self) -> Result<Option<&dyn EventSource>> {
    371         self.require_open()?;
    372         Ok(self.inner.source.as_deref())
    373     }
    374 
    375     /// Returns the injected outbound sink, when delivery is enabled.
    376     pub fn sink(&self) -> Result<Option<&dyn EventSink>> {
    377         self.require_open()?;
    378         Ok(self.inner.sink.as_deref())
    379     }
    380 
    381     /// Returns passive Nostr relay evidence when the concrete adapter is selected.
    382     #[cfg(feature = "nostr")]
    383     pub fn nostr_status(&self) -> Result<Option<crate::transport::RelayStatusReport>> {
    384         self.require_open()?;
    385         Ok(self
    386             .inner
    387             .nostr
    388             .as_ref()
    389             .and_then(crate::transport::NostrSlot::relay_status))
    390     }
    391 
    392     /// Validates a Nostr profile and shuts down the old pool before replacement.
    393     /// This opens no new socket or DNS lookup. Interrupted cleanup can be retried.
    394     #[cfg(feature = "nostr")]
    395     pub async fn configure_nostr(&self, profile: crate::transport::RelayProfile) -> Result<()> {
    396         self.require_open()?;
    397         self.inner
    398             .nostr
    399             .as_ref()
    400             .ok_or_else(Error::shared_operation_unavailable)?
    401             .configure(profile)
    402             .await
    403     }
    404 
    405     /// Returns the explicitly composed Blossom adapter, when configured.
    406     #[cfg(feature = "blossom")]
    407     pub fn blossom(&self) -> Result<Option<&crate::transport::BlossomSlot>> {
    408         self.require_open()?;
    409         Ok(self.inner.blossom.as_ref())
    410     }
    411 
    412     /// Atomically replaces the active Blossom profile without network I/O.
    413     #[cfg(feature = "blossom")]
    414     pub fn configure_blossom(&self, config: crate::transport::BlossomConfig) -> Result<()> {
    415         self.require_open()?;
    416         self.inner
    417             .blossom
    418             .as_ref()
    419             .ok_or_else(Error::shared_operation_unavailable)?
    420             .configure(config)
    421             .map_err(Error::invalid_host_configuration)
    422     }
    423 
    424     /// Returns client-scoped canonical synchronization operations, when configured.
    425     #[cfg(feature = "sync")]
    426     pub fn sync(&self) -> Result<Option<crate::sync::Operations<'_>>> {
    427         self.require_open()?;
    428         Ok(self.inner.sync.as_ref().map(crate::sync::Operations::new))
    429     }
    430 
    431     /// Returns farm commit operations when canonical synchronization is configured.
    432     #[cfg(feature = "sync")]
    433     pub fn farm(&self) -> Result<Option<crate::farm::Operations<'_>>> {
    434         Ok(self.sync()?.map(crate::farm::Operations::new))
    435     }
    436 
    437     /// Returns listing commit operations when canonical synchronization is configured.
    438     #[cfg(feature = "sync")]
    439     pub fn listing(&self) -> Result<Option<crate::listing::Operations<'_>>> {
    440         Ok(self.sync()?.map(crate::listing::Operations::new))
    441     }
    442 
    443     /// Returns trade operations when canonical synchronization is configured.
    444     #[cfg(feature = "sync")]
    445     pub fn trade(&self) -> Result<Option<crate::trade::Operations<'_>>> {
    446         let storage = self.storage()?;
    447         Ok(self
    448             .sync()?
    449             .map(|sync| crate::trade::Operations::new(storage, sync)))
    450     }
    451 
    452     /// Returns whether explicit close completed successfully.
    453     #[must_use]
    454     pub fn is_closed(&self) -> bool {
    455         self.inner.lifecycle.load(Ordering::Acquire) == CLOSED
    456     }
    457 
    458     /// Shuts down the selected Nostr pool before closing storage across every client clone.
    459     ///
    460     /// Dropping this future before its first poll has no effect. Cancellation
    461     /// after close begins leaves the client unavailable and permits an
    462     /// explicit retry; it never reports rollback. Repeated completed close is
    463     /// idempotent. No worker, executor, or blocking `Drop` path is installed.
    464     pub async fn close(&self) -> Result<()> {
    465         loop {
    466             match self.inner.lifecycle.load(Ordering::Acquire) {
    467                 CLOSED => return Ok(()),
    468                 CLOSING => return Err(Error::close_in_progress()),
    469                 state @ (OPEN | CLOSE_RETRY_REQUIRED) => {
    470                     if self
    471                         .inner
    472                         .lifecycle
    473                         .compare_exchange(state, CLOSING, Ordering::AcqRel, Ordering::Acquire)
    474                         .is_ok()
    475                     {
    476                         break;
    477                     }
    478                 }
    479                 _ => return Err(Error::client_closed()),
    480             }
    481         }
    482 
    483         let attempt = CloseAttempt::new(Arc::clone(&self.inner));
    484         #[cfg(feature = "nostr")]
    485         if let Some(slot) = &self.inner.nostr {
    486             slot.shutdown().await;
    487         }
    488         let close_result = radroots_storage::BackupSource::close(self.inner.storage.as_ref()).await;
    489         let result = close_result
    490             .map(|_| ())
    491             .map_err(Error::storage_close_failed);
    492         attempt.finish(result)
    493     }
    494 
    495     fn require_open(&self) -> Result<()> {
    496         match self.inner.lifecycle.load(Ordering::Acquire) {
    497             OPEN => Ok(()),
    498             CLOSING | CLOSE_RETRY_REQUIRED => Err(Error::client_closing()),
    499             _ => Err(Error::client_closed()),
    500         }
    501     }
    502 
    503     #[cfg(feature = "sync")]
    504     fn sync_is_configured(&self) -> bool {
    505         self.inner.sync.is_some()
    506     }
    507 
    508     #[cfg(not(feature = "sync"))]
    509     fn sync_is_configured(&self) -> bool {
    510         false
    511     }
    512 }
    513 
    514 #[cfg(feature = "nostr")]
    515 const fn map_transport_availability(
    516     availability: radroots_transport::capability::Availability,
    517 ) -> Availability {
    518     match availability {
    519         radroots_transport::capability::Availability::Available => Availability::Available,
    520         radroots_transport::capability::Availability::Degraded => Availability::Degraded,
    521         radroots_transport::capability::Availability::Unavailable => Availability::Unavailable,
    522     }
    523 }
    524 
    525 struct CloseAttempt {
    526     inner: Arc<ClientInner>,
    527     completed: bool,
    528 }
    529 
    530 impl CloseAttempt {
    531     fn new(inner: Arc<ClientInner>) -> Self {
    532         Self {
    533             inner,
    534             completed: false,
    535         }
    536     }
    537 
    538     fn finish(mut self, result: Result<()>) -> Result<()> {
    539         if result.is_ok() {
    540             self.inner.lifecycle.store(CLOSED, Ordering::Release);
    541             self.completed = true;
    542         }
    543         result
    544     }
    545 }
    546 
    547 impl Drop for CloseAttempt {
    548     fn drop(&mut self) {
    549         if !self.completed {
    550             self.inner
    551                 .lifecycle
    552                 .store(CLOSE_RETRY_REQUIRED, Ordering::Release);
    553         }
    554     }
    555 }
    556 
    557 impl std::fmt::Debug for Client {
    558     fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    559         let mut debug = formatter.debug_struct("Client");
    560         debug
    561             .field("signer", &self.inner.signer.is_some())
    562             .field("source", &self.inner.source.is_some())
    563             .field("sink", &self.inner.sink.is_some());
    564         #[cfg(feature = "blossom")]
    565         debug.field("blossom", &self.inner.blossom.is_some());
    566         debug
    567             .field("closed", &self.is_closed())
    568             .finish_non_exhaustive()
    569     }
    570 }
    571 
    572 impl std::fmt::Debug for ClientBuilder {
    573     fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    574         let mut debug = formatter.debug_struct("ClientBuilder");
    575         debug
    576             .field("storage", &self.storage.is_some())
    577             .field("signer", &self.signer.is_some())
    578             .field("source", &self.source.is_some())
    579             .field("sink", &self.sink.is_some());
    580         #[cfg(feature = "blossom")]
    581         debug.field("blossom", &self.blossom.is_some());
    582         debug.finish_non_exhaustive()
    583     }
    584 }
    585 
    586 #[cfg(all(test, feature = "memory"))]
    587 mod tests {
    588     use super::*;
    589     use radroots_signing::{
    590         Error as SigningError, SignReceipt, SignRequest, SignerStatus, error::Kind,
    591         signer::BoxFuture as SigningFuture,
    592     };
    593     use radroots_transport::{
    594         DeliveryReceipt, DeliveryRequest, Error as TransportError, FetchPage, FetchRequest,
    595         SinkFailure, SinkStatus, SourceStatus, outcome::Retryability,
    596         source::BoxFuture as TransportFuture,
    597     };
    598     use std::{
    599         future::Future,
    600         sync::Arc,
    601         task::{Context, Poll, Wake, Waker},
    602     };
    603 
    604     struct TestSource;
    605     struct TestSink;
    606     struct TestSigner;
    607 
    608     impl EventSource for TestSource {
    609         fn status(&self) -> TransportFuture<'_, std::result::Result<SourceStatus, TransportError>> {
    610             Box::pin(async { Err(TransportError::UnsupportedOperation) })
    611         }
    612 
    613         fn fetch(
    614             &self,
    615             _request: FetchRequest,
    616         ) -> TransportFuture<'_, std::result::Result<FetchPage, TransportError>> {
    617             Box::pin(async { Err(TransportError::UnsupportedOperation) })
    618         }
    619     }
    620 
    621     impl EventSink for TestSink {
    622         fn status(&self) -> TransportFuture<'_, std::result::Result<SinkStatus, TransportError>> {
    623             Box::pin(async { Err(TransportError::UnsupportedOperation) })
    624         }
    625 
    626         fn deliver(
    627             &self,
    628             request: DeliveryRequest,
    629         ) -> TransportFuture<'_, std::result::Result<DeliveryReceipt, SinkFailure>> {
    630             Box::pin(async move {
    631                 Err(SinkFailure::for_request(
    632                     &request,
    633                     "test_sink_unavailable",
    634                     Retryability::Terminal,
    635                     None,
    636                     None,
    637                     Vec::new(),
    638                 )
    639                 .expect("test sink failure"))
    640             })
    641         }
    642     }
    643 
    644     impl Signer for TestSigner {
    645         fn status(&self) -> SigningFuture<'_, std::result::Result<SignerStatus, SigningError>> {
    646             Box::pin(async { Err(SigningError::new(Kind::InternalError)) })
    647         }
    648 
    649         fn sign(
    650             &self,
    651             _request: SignRequest,
    652         ) -> SigningFuture<'_, std::result::Result<SignReceipt, SigningError>> {
    653             Box::pin(async { Err(SigningError::new(Kind::InternalError)) })
    654         }
    655     }
    656 
    657     fn generation() -> SourceGeneration {
    658         SourceGeneration::new([1; 32]).expect("non-zero generation")
    659     }
    660 
    661     #[test]
    662     fn missing_storage_fails_and_signer_only_composition_is_valid() {
    663         assert!(matches!(
    664             ClientBuilder::new().build(),
    665             Err(error) if error.kind() == crate::error::ErrorKind::MissingStorage
    666         ));
    667         let signer_only = ClientBuilder::memory(generation())
    668             .signer(Arc::new(TestSigner))
    669             .build()
    670             .expect("HTTP-only signing does not require a relay sink");
    671         assert!(signer_only.signer().expect("signer").is_some());
    672         assert!(signer_only.signing().expect("signing operations").is_some());
    673         assert!(signer_only.sink().expect("sink").is_none());
    674     }
    675 
    676     #[test]
    677     fn memory_local_source_only_and_sink_only_compositions_are_explicit() {
    678         let local = ClientBuilder::memory(generation()).build().expect("local");
    679         assert!(local.source().expect("source capability").is_none());
    680         assert!(local.sink().expect("sink capability").is_none());
    681         assert!(local.signer().expect("signer capability").is_none());
    682 
    683         let source = ClientBuilder::memory(generation())
    684             .source(Arc::new(TestSource))
    685             .build()
    686             .expect("source-only");
    687         assert!(source.source().expect("source capability").is_some());
    688         assert!(source.sink().expect("sink capability").is_none());
    689 
    690         let sink = ClientBuilder::memory(generation())
    691             .sink(Arc::new(TestSink))
    692             .build()
    693             .expect("sink-only");
    694         assert!(sink.source().expect("source capability").is_none());
    695         assert!(sink.sink().expect("sink capability").is_some());
    696     }
    697 
    698     #[cfg(feature = "nostr")]
    699     #[test]
    700     fn nostr_capabilities_require_directional_profile_authority_and_evidence() {
    701         let slot = crate::transport::NostrSlot::new();
    702         block_on(
    703             slot.configure(
    704                 crate::transport::RelayProfile::explicit(
    705                     crate::transport::RelayProfileKind::Public,
    706                     [crate::transport::RelayEndpoint::new(
    707                         "wss://radroots.org",
    708                         crate::transport::RelayUrlPolicy::Public,
    709                         crate::transport::RelayAccess::ReadOnly,
    710                     )
    711                     .expect("read-only endpoint")],
    712                 )
    713                 .expect("read-only public profile"),
    714             ),
    715         )
    716         .expect("configure slot");
    717         let client = ClientBuilder::memory(generation())
    718             .nostr(slot)
    719             .build()
    720             .expect("client");
    721 
    722         let capabilities = client.capabilities();
    723         let fetch = capabilities
    724             .get(CapabilityId::NOSTR_FETCH)
    725             .expect("fetch capability");
    726         let delivery = capabilities
    727             .get(CapabilityId::NOSTR_DELIVERY)
    728             .expect("delivery capability");
    729         assert!(fetch.is_configured());
    730         assert_eq!(fetch.availability(), Availability::Unavailable);
    731         assert!(!delivery.is_configured());
    732         assert_eq!(delivery.availability(), Availability::Unavailable);
    733 
    734         block_on(
    735             client.configure_nostr(
    736                 crate::transport::RelayProfile::explicit(
    737                     crate::transport::RelayProfileKind::Public,
    738                     [crate::transport::RelayEndpoint::new(
    739                         "wss://write.example",
    740                         crate::transport::RelayUrlPolicy::Public,
    741                         crate::transport::RelayAccess::ReadWrite,
    742                     )
    743                     .expect("writable endpoint")],
    744                 )
    745                 .expect("writable profile"),
    746             ),
    747         )
    748         .expect("reconfigure");
    749         let capabilities = client.capabilities();
    750         let delivery = capabilities
    751             .get(CapabilityId::NOSTR_DELIVERY)
    752             .expect("delivery capability");
    753         assert!(delivery.is_configured());
    754         assert_eq!(delivery.availability(), Availability::Unavailable);
    755     }
    756 
    757     #[test]
    758     fn signer_with_sink_is_valid_and_diagnostics_are_capability_only() {
    759         let client = ClientBuilder::memory(generation())
    760             .sink(Arc::new(TestSink))
    761             .signer(Arc::new(TestSigner))
    762             .build()
    763             .expect("outbound client");
    764         assert!(client.signer().expect("signer capability").is_some());
    765         let expected = if cfg!(feature = "blossom") {
    766             "Client { signer: true, source: false, sink: true, blossom: false, closed: false, .. }"
    767         } else {
    768             "Client { signer: true, source: false, sink: true, closed: false, .. }"
    769         };
    770         assert_eq!(format!("{client:?}"), expected);
    771     }
    772 
    773     #[cfg(all(feature = "sync", feature = "nip46"))]
    774     #[test]
    775     fn canonical_operation_accessors_and_builder_modes_are_complete() {
    776         let builder = ClientBuilder::memory_default()
    777             .source(Arc::new(TestSource))
    778             .host_sync(crate::sync::HostPolicy::default());
    779         assert!(format!("{builder:?}").contains("storage: true"));
    780         let client = builder.build().expect("sync client");
    781         assert!(client.sync().expect("sync").is_some());
    782         assert!(client.farm().expect("farm").is_some());
    783         assert!(client.listing().expect("listing").is_some());
    784         assert!(client.trade().expect("trade").is_some());
    785         assert!(
    786             format!(
    787                 "{:?}",
    788                 client.storage_operations().expect("storage operations")
    789             )
    790             .contains("borrowed canonical storage")
    791         );
    792         assert!(
    793             format!("{:?}", client.sync().expect("sync").expect("operations"))
    794                 .contains("borrowed canonical engine")
    795         );
    796 
    797         let host = ClientBuilder::memory_default()
    798             .signing(crate::signing::Provider::host(Arc::new(TestSigner)))
    799             .build()
    800             .expect("host signer");
    801         assert!(
    802             !host
    803                 .capabilities()
    804                 .get(CapabilityId::NIP46_SIGNING)
    805                 .expect("nip46")
    806                 .is_configured()
    807         );
    808 
    809         let nip46 = ClientBuilder::memory_default()
    810             .signing(crate::signing::Provider::nip46(Arc::new(TestSigner)))
    811             .build()
    812             .expect("nip46 signer");
    813         assert!(
    814             nip46
    815                 .capabilities()
    816                 .get(CapabilityId::NIP46_SIGNING)
    817                 .expect("nip46")
    818                 .is_configured()
    819         );
    820     }
    821 
    822     #[cfg(feature = "local-signing")]
    823     #[test]
    824     fn module_scoped_signing_provider_configures_the_matching_capability() {
    825         let signer = radroots_nostr::signing::LocalSigner::generate().expect("local signer");
    826         let client = ClientBuilder::memory(generation())
    827             .sink(Arc::new(TestSink))
    828             .signing(crate::signing::Provider::local(signer))
    829             .build()
    830             .expect("client");
    831         let status = client
    832             .capabilities()
    833             .get(CapabilityId::LOCAL_SIGNING)
    834             .expect("local signing");
    835         assert!(status.is_compiled());
    836         assert!(status.is_configured());
    837         assert_eq!(status.availability(), Availability::Available);
    838     }
    839 
    840     #[test]
    841     fn close_is_clone_shared_idempotent_and_rejects_later_capability_access() {
    842         let client = ClientBuilder::memory(generation()).build().expect("client");
    843         let clone = client.clone();
    844         assert!(!client.is_closed());
    845         block_on(client.close()).expect("first close");
    846         assert!(clone.is_closed());
    847         block_on(clone.close()).expect("repeated close");
    848         assert!(matches!(
    849             clone.storage(),
    850             Err(error) if error.kind() == crate::error::ErrorKind::ClientClosed
    851         ));
    852         assert!(matches!(
    853             client.source(),
    854             Err(error) if error.kind() == crate::error::ErrorKind::ClientClosed
    855         ));
    856     }
    857 
    858     #[test]
    859     fn close_cancellation_boundaries_are_explicit_and_retryable() {
    860         let client = ClientBuilder::memory(generation()).build().expect("client");
    861         let unpolled = client.close();
    862         drop(unpolled);
    863         assert!(client.storage().is_ok());
    864 
    865         client.inner.lifecycle.store(CLOSING, Ordering::Release);
    866         let attempt = CloseAttempt::new(Arc::clone(&client.inner));
    867         drop(attempt);
    868         assert!(matches!(
    869             client.storage(),
    870             Err(error) if error.kind() == crate::error::ErrorKind::ClientClosing
    871         ));
    872         block_on(client.close()).expect("retry close");
    873         assert!(client.is_closed());
    874     }
    875 
    876     #[test]
    877     fn storage_close_failure_keeps_admission_closed_and_allows_an_explicit_retry() {
    878         let client = ClientBuilder::memory(generation()).build().expect("client");
    879         let clone = client.clone();
    880         client.inner.lifecycle.store(CLOSING, Ordering::Release);
    881         let attempt = CloseAttempt::new(Arc::clone(&client.inner));
    882         let failure = attempt
    883             .finish(Err(Error::storage_close_failed(
    884                 radroots_storage::Error::BackendUnavailable,
    885             )))
    886             .unwrap_err();
    887         assert_eq!(failure.kind(), crate::error::ErrorKind::StorageCloseFailed);
    888         assert!(!client.is_closed());
    889         assert!(
    890             matches!(clone.storage(), Err(error) if error.kind() == crate::error::ErrorKind::ClientClosing)
    891         );
    892         block_on(clone.close()).expect("retry confirms storage close");
    893         assert!(client.is_closed());
    894     }
    895 
    896     #[cfg(feature = "nostr")]
    897     #[tokio::test]
    898     async fn cancelled_pool_cleanup_retains_resources_until_client_close_is_retried() {
    899         use radroots_storage::status::ShutdownState;
    900         use std::task::Poll;
    901 
    902         let slot = crate::transport::NostrSlot::new();
    903         let profile = crate::transport::RelayProfile::explicit(
    904             crate::transport::RelayProfileKind::Simulator,
    905             [crate::transport::RelayEndpoint::new(
    906                 "ws://127.0.0.1:7447",
    907                 crate::transport::RelayUrlPolicy::Local,
    908                 crate::transport::RelayAccess::ReadWrite,
    909             )
    910             .unwrap()],
    911         )
    912         .unwrap();
    913         slot.configure(profile.clone()).await.unwrap();
    914         let client = ClientBuilder::memory(generation())
    915             .nostr(slot.clone())
    916             .build()
    917             .unwrap();
    918         let clone = client.clone();
    919         let held = slot.hold_transition_for_test().await;
    920         let mut close = Box::pin(client.close());
    921         assert!(matches!(
    922             close.as_mut().poll(&mut Context::from_waker(Waker::noop())),
    923             Poll::Pending
    924         ));
    925         drop(close);
    926         assert!(!client.is_closed());
    927         assert!(
    928             matches!(clone.storage(), Err(error) if error.kind() == crate::error::ErrorKind::ClientClosing)
    929         );
    930         assert_eq!(
    931             radroots_storage::BackupSource::status(client.inner.storage.as_ref())
    932                 .await
    933                 .unwrap()
    934                 .shutdown(),
    935             ShutdownState::Open
    936         );
    937         assert_eq!(
    938             slot.configure(profile).await.unwrap_err().kind(),
    939             crate::error::ErrorKind::ClientClosed
    940         );
    941         drop(held);
    942         clone.close().await.unwrap();
    943         assert!(client.is_closed());
    944         assert_eq!(
    945             radroots_storage::BackupSource::status(client.inner.storage.as_ref())
    946                 .await
    947                 .unwrap()
    948                 .shutdown(),
    949             ShutdownState::Closed
    950         );
    951         assert!(slot.read_targets().is_none());
    952     }
    953 
    954     #[test]
    955     fn concurrent_clones_converge_on_one_closed_state() {
    956         let client = ClientBuilder::memory(generation()).build().expect("client");
    957         let first = client.clone();
    958         let second = client.clone();
    959         let outcomes = std::thread::scope(|scope| {
    960             let first_close = scope.spawn(move || block_on(first.close()));
    961             let second_close = scope.spawn(move || block_on(second.close()));
    962             [
    963                 first_close.join().expect("first thread"),
    964                 second_close.join().expect("second thread"),
    965             ]
    966         });
    967         assert!(outcomes.iter().all(|outcome| {
    968             outcome.is_ok()
    969                 || matches!(
    970                     outcome,
    971                     Err(error)
    972                         if error.kind() == crate::error::ErrorKind::CloseInProgress
    973                 )
    974         }));
    975         if !client.is_closed() {
    976             block_on(client.close()).expect("finish close");
    977         }
    978         assert!(client.is_closed());
    979     }
    980 
    981     #[test]
    982     fn capability_reports_separate_configuration_degradation_and_lifecycle() {
    983         let local = ClientBuilder::memory(generation())
    984             .capability_availability(CapabilityId::CANONICAL_STORAGE, Availability::Degraded)
    985             .build()
    986             .expect("client");
    987         let report = local.capabilities();
    988         let storage = report
    989             .get(CapabilityId::CANONICAL_STORAGE)
    990             .expect("storage");
    991         assert!(storage.is_compiled());
    992         assert!(storage.is_configured());
    993         assert_eq!(storage.availability(), Availability::Degraded);
    994 
    995         let signing = report.get(CapabilityId::LOCAL_SIGNING).expect("signing");
    996         assert!(!signing.is_configured());
    997         assert!(matches!(
    998             signing.availability(),
    999             Availability::Unavailable | Availability::Unsupported
   1000         ));
   1001 
   1002         block_on(local.close()).expect("close");
   1003         assert_eq!(
   1004             local
   1005                 .capabilities()
   1006                 .get(CapabilityId::BACKUP_RESTORE)
   1007                 .expect("backup")
   1008                 .availability(),
   1009             Availability::Unavailable
   1010         );
   1011     }
   1012 
   1013     #[test]
   1014     fn memory_storage_status_integrity_and_lifecycle_use_native_contracts() {
   1015         use radroots_storage::status::{
   1016             IntegrityHealth, ShutdownState, StorageBackend, StorageOpenMode, WriterPolicy,
   1017         };
   1018 
   1019         let client = ClientBuilder::memory(generation()).build().expect("client");
   1020         let status = block_on(client.storage_status()).expect("status");
   1021         assert_eq!(status.backend(), StorageBackend::Memory);
   1022         assert_eq!(status.open_mode(), StorageOpenMode::Create);
   1023         assert_eq!(status.writer_policy(), WriterPolicy::NoWriter);
   1024         assert_eq!(status.shutdown(), ShutdownState::Open);
   1025         assert_eq!(
   1026             block_on(client.storage_integrity())
   1027                 .expect("integrity")
   1028                 .health(),
   1029             IntegrityHealth::Healthy
   1030         );
   1031         block_on(client.close()).expect("close");
   1032         assert_eq!(
   1033             block_on(client.storage_status())
   1034                 .expect_err("closed")
   1035                 .kind(),
   1036             crate::error::ErrorKind::ClientClosed
   1037         );
   1038     }
   1039 
   1040     #[cfg(feature = "sqlite")]
   1041     #[tokio::test]
   1042     async fn sqlite_builder_exposes_native_status_integrity_and_lifecycle() {
   1043         use radroots_storage::status::{
   1044             IntegrityHealth, ShutdownState, StorageBackend, StorageOpenMode, WriterPolicy,
   1045         };
   1046 
   1047         let directory = tempfile::tempdir().expect("temporary directory");
   1048         let paths = crate::storage::SqlitePaths::from_directory(directory.path()).expect("paths");
   1049         let options =
   1050             crate::storage::SqliteOptions::new(paths, crate::storage::SqliteOpenMode::Create)
   1051                 .with_source_generation(generation(), 1)
   1052                 .expect("source generation");
   1053         let client = ClientBuilder::sqlite(options)
   1054             .await
   1055             .expect("open builder")
   1056             .build()
   1057             .expect("client");
   1058         let status = client.storage_status().await.expect("status");
   1059         assert_eq!(status.backend(), StorageBackend::Sqlite);
   1060         assert_eq!(status.open_mode(), StorageOpenMode::Create);
   1061         assert_eq!(status.writer_policy(), WriterPolicy::AdvisoryProcessLock);
   1062         assert_eq!(status.shutdown(), ShutdownState::Open);
   1063         assert!(status.wal_enabled());
   1064         assert_ne!(status.busy_timeout_ms(), 0);
   1065         assert_eq!(
   1066             client
   1067                 .storage_integrity()
   1068                 .await
   1069                 .expect("integrity")
   1070                 .health(),
   1071             IntegrityHealth::Unknown
   1072         );
   1073         client.close().await.expect("close");
   1074         assert!(client.is_closed());
   1075     }
   1076 
   1077     struct ThreadWaker;
   1078 
   1079     impl Wake for ThreadWaker {
   1080         fn wake(self: Arc<Self>) {
   1081             std::thread::current().unpark();
   1082         }
   1083     }
   1084 
   1085     fn block_on<F: Future>(future: F) -> F::Output {
   1086         let waker = Waker::from(Arc::new(ThreadWaker));
   1087         let mut context = Context::from_waker(&waker);
   1088         let mut future = Box::pin(future);
   1089         loop {
   1090             match future.as_mut().poll(&mut context) {
   1091                 Poll::Ready(output) => return output,
   1092                 Poll::Pending => std::thread::park(),
   1093             }
   1094         }
   1095     }
   1096 }