commit 4301e21d780d637b5ce16bb9e270da92e1f5848d
parent 29dc4922ba07ff786b3dd279415a85e59dd1c001
Author: triesap <tyson@radroots.org>
Date: Sat, 17 Oct 2026 17:19:04 +0000
client: own native cache and signer resources through explicit closure
- Compose the ordinary Client over shared execution session ownership.
- Open actual SQLite caches and retain signer attachment before observation.
- Drain callbacks before storage and validate confirmed close receipts.
- Verify real native lifetimes, portable callers, APIs and coverage gates.
Diffstat:
29 files changed, 1325 insertions(+), 282 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -196,7 +196,7 @@ Before editing code:
- Preserve deferred flake expressions as unqualified compatibility inputs;
do not use their evaluation or outputs as evidence until an accepted
contract explicitly reactivates them.
-- `contracts/crates/release.v2.toml` records the nineteen current public Lib
+- `contracts/crates/release.v2.toml` records the twenty-one current public Lib
packages, including `radroots_sdk` and `radroots`. Release V1's earlier
repository split remains history. The approved successor replaces old
SDK/trade/model boundaries directly and retains ancillary capabilities;
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
@@ -10,7 +10,7 @@ reviewable. Before editing, read these files in order:
crate-surface work
5. the affected manifests, implementation, contracts, and tests
-Release V2 records the nineteen current public Lib packages, including
+Release V2 records the twenty-one current public Lib packages, including
`radroots_sdk` and `radroots`. The earlier `radroots.crates.release.v1`
repository split remains immutable history. The approved successor is
`contracts/architecture/decisions/shared_sdk_refactor.v1.json`: Lib owns shared
diff --git a/Cargo.lock b/Cargo.lock
@@ -3040,14 +3040,22 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
name = "radroots"
version = "0.1.0-alpha"
dependencies = [
+ "futures",
"radroots_core",
"radroots_domain",
"radroots_event",
+ "radroots_execution",
"radroots_identity",
+ "radroots_nostr",
"radroots_sdk",
+ "radroots_signing",
+ "radroots_storage",
+ "radroots_storage_sqlite",
"radroots_trade",
"radroots_transport",
"serde_json",
+ "tempfile",
+ "tokio",
"toml 0.8.23",
]
diff --git a/README.md b/README.md
@@ -18,36 +18,26 @@ Build local food networks that help farms and communities organize and communica
- Local couriers carry orders from farms to homes, businesses and pickup points
### How to use
+
+The current ordinary Client supports explicit in-memory preview and native
+public-cache resource ownership. Authenticated workspace commands and the full
+durable commerce workflow remain in implementation.
+
```rust
-use radroots::prelude::*;
-
-let client = Client::builder()
- .signer(signer)
- .transport(Nostr::relays(["wss://radroots.org"])?)
- .build()
- .await?;
-
-let farm = client
- .seller(seller_account)?
- .farm(farm_id)?;
-
-// Farmer creates a listing for freshly picked tomatoes
-let receipt = farm
- .listings()
- .publish("Heirloom tomatoes")
- .id("fresh-tomatoes")
- .description("Locally grown and picked this morning.")
- .price(Price::cad_per_kg(4)?)
- .available(Quantity::kg(20)?)
- .pickup_in(Locality::city("Victoria", "BC", "CA")?)
- .send() // Validates, signs, saves locally, and attempts publication
- .await?;
-
-// Log the published event address
-println!("Published: {}", receipt.address());
-…
+use radroots::{Client, StartMode};
+
+async fn preview() -> radroots::Result<()> {
+ let client = Client::preview();
+ client.start(StartMode::LocalOnly).await?;
+ client.close().await?;
+ Ok(())
+}
```
+See [the ordinary package](crates/radroots/README.md) for current implemented
+boundaries and explicit native opening. Construction does not start networking,
+restore authority or replay business writes.
+
### Getting started
> **Status:** Alpha (`0.1.0-alpha`)
diff --git a/contracts/api_baselines/radroots.txt b/contracts/api_baselines/radroots.txt
@@ -1,17 +1,32 @@
pub mod radroots
-pub use radroots::Client
-pub use radroots::ClientBuilder
pub use radroots::Error
pub use radroots::OperationId
pub use radroots::Result
pub mod radroots::client
+#[non_exhaustive] pub enum radroots::client::StartMode
+pub radroots::client::StartMode::LocalOnly
+pub struct radroots::client::Client
+impl radroots::client::Client
+pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession>
+pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt>
+pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self>
+pub fn radroots::client::Client::preview() -> Self
+pub fn radroots::client::Client::signer_session(&self) -> core::option::Option<radroots_execution::session::signer::SignerSession>
+pub async fn radroots::client::Client::start(&self, radroots::client::StartMode) -> radroots_execution::Result<radroots::client::SessionStatus>
+pub fn radroots::client::Client::state(&self) -> radroots_execution::session::SessionState
+pub async fn radroots::client::Client::storage_status(&self) -> radroots_execution::Result<radroots_storage::status::StorageStatus>
+pub struct radroots::client::CloseReceipt
+impl radroots::client::CloseReceipt
+pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage::status::StorageStatus
+pub struct radroots::client::NativeConfig
+impl radroots::client::NativeConfig
+pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self
+pub struct radroots::client::SessionStatus
+impl radroots::client::SessionStatus
+pub const fn radroots::client::SessionStatus::state(self) -> radroots_execution::session::SessionState
pub const fn radroots::client::geonames_enabled() -> bool
pub const fn radroots::client::knowledge_enabled() -> bool
pub const fn radroots::client::local_only() -> radroots_sdk::transport::Profile
-pub fn radroots::client::memory() -> radroots_sdk::client::ClientBuilder
-pub async fn radroots::client::native(radroots_sdk::storage::SqliteOptions) -> radroots_sdk::error::Result<radroots_sdk::client::ClientBuilder>
-pub fn radroots::client::with_nip46_signer(radroots_sdk::client::ClientBuilder, radroots_sdk::signing::Provider) -> radroots_sdk::client::ClientBuilder
-pub fn radroots::client::with_transport(radroots_sdk::client::ClientBuilder, alloc::sync::Arc<dyn radroots_transport::source::EventSource>, alloc::sync::Arc<dyn radroots_transport::sink::EventSink>) -> radroots_sdk::client::ClientBuilder
pub mod radroots::domain
pub use radroots::domain::AmountError
pub use radroots::domain::Decimal
@@ -90,10 +105,13 @@ pub use radroots::signing::blossom_upload_request
pub mod radroots::storage
pub use radroots::storage::IntegrityStatus
pub use radroots::storage::Operations
+pub use radroots::storage::ShutdownState
+pub use radroots::storage::SourceGeneration
pub use radroots::storage::SqliteOpenMode
pub use radroots::storage::SqliteOptions
pub use radroots::storage::SqlitePaths
pub use radroots::storage::Status
+pub use radroots::storage::StorageBackend
pub mod radroots::sync
pub mod radroots::trade
pub use radroots::trade::Currency
@@ -140,3 +158,24 @@ pub use radroots::transport::Target
pub use radroots::transport::TargetPolicy
pub use radroots::transport::TargetSet
pub use radroots::transport::TransportId
+#[non_exhaustive] pub enum radroots::StartMode
+pub radroots::StartMode::LocalOnly
+pub struct radroots::Client
+impl radroots::client::Client
+pub async fn radroots::client::Client::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::signer::SignerSession>
+pub async fn radroots::client::Client::close(&self) -> radroots_execution::Result<radroots::client::CloseReceipt>
+pub async fn radroots::client::Client::open(radroots::client::NativeConfig) -> radroots_execution::Result<Self>
+pub fn radroots::client::Client::preview() -> Self
+pub fn radroots::client::Client::signer_session(&self) -> core::option::Option<radroots_execution::session::signer::SignerSession>
+pub async fn radroots::client::Client::start(&self, radroots::client::StartMode) -> radroots_execution::Result<radroots::client::SessionStatus>
+pub fn radroots::client::Client::state(&self) -> radroots_execution::session::SessionState
+pub async fn radroots::client::Client::storage_status(&self) -> radroots_execution::Result<radroots_storage::status::StorageStatus>
+pub struct radroots::CloseReceipt
+impl radroots::client::CloseReceipt
+pub const fn radroots::client::CloseReceipt::storage(self) -> radroots_storage::status::StorageStatus
+pub struct radroots::NativeConfig
+impl radroots::client::NativeConfig
+pub fn radroots::client::NativeConfig::public_read(radroots_storage_sqlite::config::OpenOptions) -> Self
+pub struct radroots::SessionStatus
+impl radroots::client::SessionStatus
+pub const fn radroots::client::SessionStatus::state(self) -> radroots_execution::session::SessionState
diff --git a/contracts/api_baselines/radroots_execution.txt b/contracts/api_baselines/radroots_execution.txt
@@ -6,11 +6,22 @@ pub radroots_execution::session::SessionState::Closing
pub radroots_execution::session::SessionState::Ready
pub radroots_execution::session::SessionState::Running
pub radroots_execution::session::SessionState::Starting
+pub struct radroots_execution::session::ClientSession<H: radroots_execution::session::SessionHost>
+impl<H: radroots_execution::session::SessionHost> radroots_execution::session::ClientSession<H>
+pub async fn radroots_execution::session::ClientSession<H>::attach_signer(&self, radroots_signing::provider::SignerHandle) -> radroots_execution::Result<radroots_execution::session::SignerSession>
+pub async fn radroots_execution::session::ClientSession<H>::close(&self) -> radroots_execution::Result<()>
+pub fn radroots_execution::session::ClientSession<H>::new(H, core::num::nonzero::NonZeroU16) -> Self
+pub fn radroots_execution::session::ClientSession<H>::signer_session(&self) -> core::option::Option<radroots_execution::session::SignerSession>
+pub async fn radroots_execution::session::ClientSession<H>::start(&self) -> radroots_execution::Result<()>
+pub fn radroots_execution::session::ClientSession<H>::state(&self) -> radroots_execution::session::SessionState
+impl<H: radroots_execution::session::SessionHost> core::clone::Clone for radroots_execution::session::ClientSession<H>
+pub fn radroots_execution::session::ClientSession<H>::clone(&self) -> Self
pub struct radroots_execution::session::Session<H: radroots_execution::session::SessionHost>
impl<H: radroots_execution::session::SessionHost> radroots_execution::session::Session<H>
pub fn radroots_execution::session::Session<H>::admit(&self) -> radroots_execution::Result<radroots_execution::session::WorkPermit<H>>
pub async fn radroots_execution::session::Session<H>::close(&self) -> radroots_execution::Result<()>
pub fn radroots_execution::session::Session<H>::new(H, core::num::nonzero::NonZeroU16) -> Self
+pub async fn radroots_execution::session::Session<H>::quiesce(&self) -> radroots_execution::Result<()>
pub async fn radroots_execution::session::Session<H>::start(&self) -> radroots_execution::Result<()>
pub fn radroots_execution::session::Session<H>::state(&self) -> radroots_execution::session::SessionState
impl<H: radroots_execution::session::SessionHost> core::clone::Clone for radroots_execution::session::Session<H>
@@ -22,6 +33,7 @@ pub fn radroots_execution::session::SignerSession::identity_changed(&self) -> bo
pub fn radroots_execution::session::SignerSession::new(radroots_signing::provider::SignerHandle) -> Self
pub async fn radroots_execution::session::SignerSession::observe(&self) -> core::result::Result<radroots_signing::provider::ProviderState, radroots_signing::provider::ProviderError>
pub fn radroots_execution::session::SignerSession::observed(&self) -> core::option::Option<radroots_signing::provider::ProviderState>
+pub async fn radroots_execution::session::SignerSession::quiesce(&self) -> radroots_execution::Result<()>
pub fn radroots_execution::session::SignerSession::state(&self) -> radroots_execution::session::SessionState
impl core::clone::Clone for radroots_execution::session::SignerSession
pub fn radroots_execution::session::SignerSession::clone(&self) -> Self
diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml
@@ -2,6 +2,35 @@ schema_version = 1
architecture_id = "radroots.crates.release.v1"
[[deviation]]
+id = "RCRV1-DEV-051"
+date = "2026-10-17"
+status = "closed"
+approval = "The user authorizes the complete approved shared SDK refactor, necessary breaking source changes, verified commits and ordinary source publication."
+affected_steps = ["040", "060", "110", "120", "130"]
+spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#package.radroots", "contracts/crates/release_v1/radroots_crates_release_v1.toml#package.radroots_storage_sqlite"]
+source_evidence = [
+ "The ordinary facade still aliases the prior SDK Client/ClientBuilder. It cannot own the qualified execution session or retain scoped attachment before its first awaited observation.",
+ "Native SQLite already owns real pools and process writer exclusion. Compose those resources with the shared session and the actual participant provider, rather than introducing a parallel lifecycle or claiming a source-generation token establishes stock authority.",
+]
+replacement_action = "Replace the ordinary root Client with shared execution-session composition and explicit native public-cache opening or memory preview. Retain attachment before observation, quiesce it before draining and dispose callbacks before the actual store. Preserve advanced retained capabilities and test purposes at their existing owner while authenticated participant-workspace opening, network workers, complete receipts and durable known-kind commands continue as distinct unfinished obligations."
+verification = [
+ "Validate this prospective record before implementation. Prove actual SQLite opening, shared start/close state, real process-writer retention until callback disposal, concrete LocalSigner attachment before start and cancellation/resumption of actual Client closure.",
+ "Prove pending/failed attachment ownership and the insertion-versus-close race with controlled host callbacks. Construction and unpolled close remain inert; native thread bounds and browser-local composition remain intact.",
+ "Run affected native checks/tests/docs/strict lint, meaningful portable checks, owner-generated public APIs and source boundaries, and unchanged actual coverage gates. Preserve every removed facade test purpose at its actual successor or retained advanced owner before deletion.",
+]
+unresolved_risk = "This bounded native public-cache/preview milestone does not authenticate a participant workspace or stock authority, provide network workers, execute a durable command, qualify browser runtime or complete the remaining facade/receipt/binding and acceptance requirements."
+normative_architecture_change = false
+adr_required = false
+closure_evidence = [
+ "The ordinary root Client now composes shared execution resource ownership with actual native SQLite public-cache opening or explicit memory preview. Start is explicitly local-only; signer observation before start is retained before its first await. No participant workspace or network worker is claimed.",
+ "Actual LocalSigner/SQLite tests verify observed identity, process writer exclusion during callback disposal, close/reopen, cancelled-close resumption and bounded redacted open errors. Controlled composition tests cover lost/failed observation, explicit replacement, pending attachment during close, completed-hook retention and thirty-two overlapping admissions/closures.",
+ "All affected native checks/tests/doctests and strict lint pass. Execution/facade WASM, Rc-local host/provider composition, no_std execution and the actually executed default preview example pass. Two generated public API baselines are fresh. Existing advanced transport and ancillary test purposes remain at their current owner while concrete ordinary integration continues.",
+ "The preserved initial facade coverage failure measured fifty-percent branches. The actual open memory store now exercises rejection by the private confirmed-close receipt constructor, preserving the original closed-state guard. Facade line/function/region/branch coverage is one hundred percent; execution passes the unchanged ninety-percent policy. The obsolete facade no-branches exception is removed, and two active documentation counts match the twenty-one-package allocation.",
+ "Concrete browser/platform callbacks, protected authenticated workspace/context, complete operation receipts, actual durable listing/chat workers, generated consumer bindings and coherent downstream adoption remain required. This checkpoint supplies no stock, network, release or final acceptance authority.",
+]
+
+
+[[deviation]]
id = "RCRV1-DEV-050"
date = "2026-10-17"
status = "closed"
diff --git a/contracts/coverage-profiles.toml b/contracts/coverage-profiles.toml
@@ -5,7 +5,12 @@ test_threads = 1
[profiles.crates."radroots_execution"]
no_default_features = false
-features = ["session", "signer_session"]
+features = ["session", "signer_session", "client_session"]
+test_threads = 1
+
+[profiles.crates."radroots"]
+no_default_features = false
+features = ["native"]
test_threads = 1
[profiles.crates."radroots_log"]
diff --git a/contracts/coverage.toml b/contracts/coverage.toml
@@ -15,11 +15,6 @@ require_branches = false
temporary = true
reason = "branch coverage is not applicable while the crate has no measured branch records"
-[overrides.radroots]
-require_branches = false
-temporary = true
-reason = "branch coverage is not applicable while the facade crate has no measured branch records"
-
[overrides.radroots_core_bindings]
require_branches = false
temporary = true
diff --git a/contracts/execution/session.v1.json b/contracts/execution/session.v1.json
@@ -8,12 +8,34 @@
"detached_tasks_created": false,
"in_flight_limit": "Required nonzero u16, fixed per session; shared by every cloned handle",
"startup": "Repeat/resume a partially completed host start; admission only after success; closing interrupts pending startup and cannot reopen",
- "shutdown_order": ["close_admission", "quiesce", "drain_work_permits", "disconnect", "dispose_callbacks", "close_storage"],
+ "shutdown_order": [
+ "close_admission",
+ "quiesce",
+ "drain_work_permits",
+ "disconnect",
+ "dispose_callbacks",
+ "close_storage"
+ ],
"cancellation": "Retain successful stages; resume only the unfinished hook. Hosts retain hook progress and obtained results across cancellation or failure",
"permit_ownership": "Executor retains permit through its safe journal boundary independently of caller observation; permit retains session resources and is not a durable receipt",
"drop_completion_claim": false,
"waker_callbacks_and_destructors": "Run outside the synchronous admission gate, including replacement, clearing and wake",
- "native": {"shared_handle": "Arc", "host_bounds": "Send + Sync", "future_bound": "Send"},
- "wasm32": {"shared_handle": "Rc", "host_bounds": "local", "future_bound": "local"},
- "remaining_qualification": ["Concrete native and browser resource hosts", "Owned durable command workers and result retention", "Authenticated attachment", "Ordinary facade and generated bindings"]
+ "native": {
+ "shared_handle": "Arc",
+ "host_bounds": "Send + Sync",
+ "future_bound": "Send"
+ },
+ "wasm32": {
+ "shared_handle": "Rc",
+ "host_bounds": "local",
+ "future_bound": "local"
+ },
+ "remaining_qualification": [
+ "Complete native participant and browser resource hosts",
+ "Owned durable command workers and result retention",
+ "Authenticated workspace attachment",
+ "Complete ordinary facade and generated bindings"
+ ],
+ "attachment_retention_before_start": "ClientSession retains one scoped signer before observation using the same fixed resource gate, including before worker startup. This is not command/work admission.",
+ "quiesce": "Permanently stop admission and complete only the host quiesce stage; composing owners then drain work/disconnect transports before final callback disposal and storage closure."
}
diff --git a/contracts/execution/signer_session.v1.json b/contracts/execution/signer_session.v1.json
@@ -3,7 +3,7 @@
"state": "component_qualified_native_and_compile_only_wasm",
"feature": "signer_session",
"construction": "Own provider and its exact host callback scope without invoking either",
- "first_observation": "Owning Client retains the scope before awaiting actual provider identity observation",
+ "first_observation": "ClientSession retains the scope before awaiting actual provider identity observation, including failed or cancelled attachment",
"identity": "First successful key is frozen; identity drift is latched until explicit replacement, even if the original key returns",
"capabilities": "Method observations may change for the same key; cached values grant no command, stock, replay or qualification authority",
"concurrent_observations": 1,
@@ -24,5 +24,6 @@
"Durable commands and obtained-result retention",
"Concrete platform/browser callback host qualification",
"Generated bindings and final acceptance"
- ]
+ ],
+ "composed_quiesce": "Quiesce leaves callback roots owned; ClientSession drains its admitted attachment work and disconnects transports before final signer close/disposal."
}
diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml
@@ -16,6 +16,7 @@ include = ["src/**", "tests/**", "Cargo.toml", "README.md", "LICENSE-APACHE", "L
default = []
session = ["dep:futures"]
signer_session = ["session", "dep:radroots_signing"]
+client_session = ["signer_session"]
[dependencies]
radroots_domain = { workspace = true, default-features = false }
diff --git a/crates/execution/README.md b/crates/execution/README.md
@@ -16,6 +16,13 @@ dispatch, drains observations, awaits host disposal and releases roots. Failed
or cancelled disposal must be resumed. The Client must retain this scope before
awaiting first observation, including when attachment fails or loses its waiter.
+The optional `client_session` feature composes this scope with an actual
+`SessionHost`. Attachment is retained before its first await, including before
+worker startup. Quiesce permanently stops admission and host callback dispatch;
+the owner then drains work, disconnects transports, disposes callbacks and closes
+storage. A failed or cancelled attachment remains reachable for explicit cleanup.
+No lifecycle observation authenticates a workspace or admits a command.
+
A proposed operation ID is not durable admission. Unknown signing or commit
outcomes keep the original identity and require exact-operation continuation
or manual reconciliation. Uncertain initial admission remains explicitly
diff --git a/crates/execution/src/error.rs b/crates/execution/src/error.rs
@@ -191,6 +191,16 @@ pub struct Error {
}
impl Error {
+ #[cfg(feature = "client_session")]
+ pub(crate) const fn identity_changed() -> Self {
+ Self {
+ code: Code::IdentityChanged,
+ context: OperationContext::proposed(None),
+ retry: RetryClass::Never,
+ detail: Some(Detail::new(crate::Field::Signer, crate::Reason::Conflict)),
+ }
+ }
+
#[cfg(feature = "signer_session")]
pub(crate) const fn signer_unavailable() -> Self {
Self {
diff --git a/crates/execution/src/session/client.rs b/crates/execution/src/session/client.rs
@@ -0,0 +1,142 @@
+use super::{HostFuture, Session, SessionHost, SessionState, SignerSession, host::Shared};
+use core::num::NonZeroU16;
+use radroots_signing::provider::{ProviderError, SignerHandle};
+use std::{
+ boxed::Box,
+ sync::{Mutex, MutexGuard},
+};
+
+struct Resources<H> {
+ host: H,
+ signer: Shared<Mutex<Option<SignerSession>>>,
+ host_quiesced: Mutex<bool>,
+}
+fn signer_lock(value: &Mutex<Option<SignerSession>>) -> MutexGuard<'_, Option<SignerSession>> {
+ value
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+}
+impl<H: SessionHost> SessionHost for Resources<H> {
+ fn start(&self) -> HostFuture<'_, crate::Result<()>> {
+ self.host.start()
+ }
+ fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async move {
+ let quiesced = *self
+ .host_quiesced
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ if !quiesced {
+ self.host.quiesce().await?;
+ *self
+ .host_quiesced
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
+ }
+ let signer = signer_lock(&self.signer).clone();
+ if let Some(signer) = signer {
+ signer.quiesce().await?;
+ }
+ Ok(())
+ })
+ }
+ fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> {
+ self.host.disconnect()
+ }
+ fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async move {
+ let signer = signer_lock(&self.signer).clone();
+ if let Some(signer) = signer {
+ signer.close().await?;
+ }
+ self.host.dispose_callbacks().await
+ })
+ }
+ fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> {
+ self.host.close_storage()
+ }
+}
+
+/// Shared client resource ownership and one explicitly attached signer scope.
+///
+/// No observed identity establishes workspace, command or stock authority.
+/// The concrete facade supplies its actual resources through `SessionHost`.
+pub struct ClientSession<H: SessionHost> {
+ session: Session<Resources<H>>,
+ signer: Shared<Mutex<Option<SignerSession>>>,
+}
+impl<H: SessionHost> Clone for ClientSession<H> {
+ fn clone(&self) -> Self {
+ Self {
+ session: self.session.clone(),
+ signer: self.signer.clone(),
+ }
+ }
+}
+impl<H: SessionHost> ClientSession<H> {
+ /// Owns resources without starting workers, observing a signer or networking.
+ pub fn new(host: H, maximum_in_flight: NonZeroU16) -> Self {
+ let signer = Shared::new(Mutex::new(None));
+ Self {
+ session: Session::new(
+ Resources {
+ host,
+ signer: signer.clone(),
+ host_quiesced: Mutex::new(false),
+ },
+ maximum_in_flight,
+ ),
+ signer,
+ }
+ }
+ /// Reports resource lifecycle independently of business authority.
+ pub fn state(&self) -> SessionState {
+ self.session.state()
+ }
+ /// Starts the explicitly configured resource host on the caller's executor.
+ pub async fn start(&self) -> crate::Result<()> {
+ self.session.start().await
+ }
+ /// Retains the provider before awaiting its first actual observation.
+ /// Failed or cancelled attachment remains owned and may be inspected/closed
+ /// through `signer_session`; replacing a live scope is explicitly refused.
+ pub async fn attach_signer(&self, handle: SignerHandle) -> crate::Result<SignerSession> {
+ let _permit = self.session.retain_resource()?;
+ let (scope, retired) = {
+ let mut current = signer_lock(&self.signer);
+ // Insertion and the close hook share this lock. Rechecking resource
+ // admission here prevents an attachment being missed by quiesce.
+ if matches!(self.state(), SessionState::Closing | SessionState::Closed) {
+ return Err(crate::Error::signer_unavailable());
+ }
+ if current
+ .as_ref()
+ .is_some_and(|scope| scope.state() != SessionState::Closed)
+ {
+ return Err(crate::Error::signer_unavailable());
+ }
+ let scope = SignerSession::new(handle);
+ let retired = current.replace(scope.clone());
+ (scope, retired)
+ };
+ drop(retired);
+ scope.observe().await.map_err(|error| {
+ if error == ProviderError::IdentityChanged {
+ crate::Error::identity_changed()
+ } else {
+ crate::Error::signer_unavailable()
+ }
+ })?;
+ Ok(scope)
+ }
+ /// Returns the owned scope, including failed/cancelled first observations.
+ /// It grants no workspace access and cannot reopen closed admission.
+ pub fn signer_session(&self) -> Option<SignerSession> {
+ signer_lock(&self.signer).clone()
+ }
+ /// Stops admission, quiesces callbacks, drains work, disconnects transports,
+ /// disposes callbacks and closes storage last. Cancellation is resumable.
+ pub async fn close(&self) -> crate::Result<()> {
+ self.session.close().await
+ }
+}
diff --git a/crates/execution/src/session/mod.rs b/crates/execution/src/session/mod.rs
@@ -6,6 +6,12 @@
mod host;
+#[cfg(feature = "client_session")]
+mod client;
+
+#[cfg(feature = "client_session")]
+pub use client::ClientSession;
+
#[cfg(feature = "signer_session")]
mod signer;
@@ -163,8 +169,21 @@ impl<H: SessionHost> Session<H> {
/// of caller observation, and retain it through result/uncertainty storage.
/// This call performs no journal write, authorization or signing.
pub fn admit(&self) -> Result<WorkPermit<H>> {
+ self.reserve(false)
+ }
+
+ // Attachment is resource ownership before worker startup, never command
+ // admission. It shares the same fixed bound and permanent close gate.
+ #[cfg(feature = "client_session")]
+ fn retain_resource(&self) -> Result<WorkPermit<H>> {
+ self.reserve(true)
+ }
+
+ fn reserve(&self, before_start: bool) -> Result<WorkPermit<H>> {
let mut gate = self.inner.gate();
- if gate.state != SessionState::Running {
+ if matches!(gate.state, SessionState::Closing | SessionState::Closed)
+ || (!before_start && gate.state != SessionState::Running)
+ {
return Err(unavailable());
}
if gate.active == self.inner.limit.get() {
@@ -176,15 +195,11 @@ impl<H: SessionHost> Session<H> {
})
}
- /// Permanently closes admission on first poll, then shuts down in order.
- ///
- /// Cancelling this future retains its last completed stage. Awaiting close
- /// again resumes the unfinished hook. No Drop implementation claims close.
- pub async fn close(&self) -> Result<()> {
+ fn stop_admission(&self) -> bool {
let starting = {
let mut gate = self.inner.gate();
if gate.state == SessionState::Closed {
- return Ok(());
+ return false;
}
gate.state = SessionState::Closing;
gate.starting.take()
@@ -192,6 +207,32 @@ impl<H: SessionHost> Session<H> {
if let Some(waker) = starting {
waker.wake();
}
+ true
+ }
+
+ /// Permanently stops admission and quiesces the host without draining or
+ /// disposing resources. Composing owners must subsequently await close.
+ /// Cancellation resumes the same unfinished hook; completion is shared.
+ pub async fn quiesce(&self) -> Result<()> {
+ if !self.stop_admission() {
+ return Ok(());
+ }
+ let mut stage = self.inner.control.lock().await;
+ if matches!(*stage, CloseStage::Quiesce) {
+ self.inner.host.quiesce().await?;
+ *stage = CloseStage::Drain;
+ }
+ Ok(())
+ }
+
+ /// Permanently closes admission on first poll, then shuts down in order.
+ ///
+ /// Cancelling this future retains its last completed stage. Awaiting close
+ /// again resumes the unfinished hook. No Drop implementation claims close.
+ pub async fn close(&self) -> Result<()> {
+ if !self.stop_admission() {
+ return Ok(());
+ }
let mut stage = self.inner.control.lock().await;
loop {
*stage = match *stage {
diff --git a/crates/execution/src/session/signer.rs b/crates/execution/src/session/signer.rs
@@ -195,4 +195,11 @@ impl SignerSession {
pub async fn close(&self) -> crate::Result<()> {
self.session.close().await
}
+
+ /// Stops observation admission and host dispatch without releasing roots.
+ /// The composing Client drains its work and transports before awaiting
+ /// close, which disposes these callbacks. Cancellation is resumable.
+ pub async fn quiesce(&self) -> crate::Result<()> {
+ self.session.quiesce().await
+ }
}
diff --git a/crates/execution/tests/client_session.rs b/crates/execution/tests/client_session.rs
@@ -0,0 +1,345 @@
+#![cfg(all(feature = "client_session", not(target_arch = "wasm32")))]
+
+use core::{
+ future::Future,
+ num::NonZeroU16,
+ task::{Context, Poll},
+};
+use futures::{
+ executor::block_on,
+ future::poll_fn,
+ task::{AtomicWaker, noop_waker_ref},
+};
+use radroots_execution::{
+ Code,
+ session::{ClientSession, HostFuture, SessionHost, SessionState},
+};
+use radroots_identity::PublicKey;
+use radroots_signing::{
+ SignReceipt, SignRequest, Signer, SignerStatus,
+ provider::{
+ ParticipantProvider, PrivateCiphertext, PrivateCryptoCapability, PrivateText, ProviderCall,
+ ProviderError, ProviderState, SignerCallbacks, SignerHandle,
+ },
+ recovery::ReplayCapability,
+ signer::BoxFuture,
+};
+use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering},
+};
+
+type Trace = Arc<Mutex<Vec<&'static str>>>;
+struct Host(Trace);
+impl Host {
+ fn run(&self, name: &'static str) -> HostFuture<'_, radroots_execution::Result<()>> {
+ Box::pin(async move {
+ self.0.lock().unwrap().push(name);
+ Ok(())
+ })
+ }
+}
+impl SessionHost for Host {
+ fn start(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run("start")
+ }
+ fn quiesce(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run("quiesce")
+ }
+ fn disconnect(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run("disconnect")
+ }
+ fn dispose_callbacks(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run("host_callbacks")
+ }
+ fn close_storage(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run("storage")
+ }
+}
+struct Provider {
+ trace: Trace,
+ mode: AtomicU8,
+ calls: AtomicUsize,
+ quiesced: AtomicBool,
+ fail_quiesce: AtomicBool,
+ wake: AtomicWaker,
+}
+impl Signer for Provider {
+ fn status(&self) -> BoxFuture<'_, Result<SignerStatus, radroots_signing::Error>> {
+ Box::pin(async { Ok(SignerStatus::unavailable()) })
+ }
+ fn sign(&self, _: SignRequest) -> BoxFuture<'_, Result<SignReceipt, radroots_signing::Error>> {
+ Box::pin(async {
+ Err(radroots_signing::Error::new(
+ radroots_signing::error::Kind::SignerUnavailable,
+ ))
+ })
+ }
+}
+impl ParticipantProvider for Provider {
+ fn provider_state(&self) -> BoxFuture<'_, Result<ProviderState, ProviderError>> {
+ Box::pin(async move {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ poll_fn(|cx| {
+ self.wake.register(cx.waker());
+ if self.quiesced.load(Ordering::SeqCst) {
+ return Poll::Ready(Err(ProviderError::Cancelled));
+ }
+ match self.mode.load(Ordering::SeqCst) {
+ 0 => Poll::Ready(Err(ProviderError::CapabilityUnavailable)),
+ 2 => Poll::Pending,
+ 3 => Poll::Ready(Err(ProviderError::IdentityChanged)),
+ _ => Poll::Ready(Ok(ProviderState::new(
+ PublicKey::from_hex(
+ "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
+ )
+ .unwrap(),
+ PrivateCryptoCapability::Unavailable,
+ PrivateCryptoCapability::Unavailable,
+ ReplayCapability::NonReplayable,
+ ))),
+ }
+ })
+ .await
+ })
+ }
+ fn encrypt_private(
+ &self,
+ _: ProviderCall,
+ _: PublicKey,
+ _: PrivateText,
+ ) -> BoxFuture<'_, Result<PrivateCiphertext, ProviderError>> {
+ Box::pin(async { Err(ProviderError::CapabilityUnavailable) })
+ }
+ fn decrypt_private(
+ &self,
+ _: ProviderCall,
+ _: PublicKey,
+ _: PrivateCiphertext,
+ ) -> BoxFuture<'_, Result<PrivateText, ProviderError>> {
+ Box::pin(async { Err(ProviderError::CapabilityUnavailable) })
+ }
+}
+impl SignerCallbacks for Provider {
+ fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> {
+ Box::pin(async move {
+ self.trace.lock().unwrap().push("signer_quiesce");
+ if self.fail_quiesce.swap(false, Ordering::SeqCst) {
+ return Err(ProviderError::ProviderFailure);
+ }
+ self.quiesced.store(true, Ordering::SeqCst);
+ self.wake.wake();
+ Ok(())
+ })
+ }
+ fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> {
+ Box::pin(async move {
+ self.trace.lock().unwrap().push("signer_callbacks");
+ Ok(())
+ })
+ }
+}
+fn provider(trace: &Trace, mode: u8) -> Arc<Provider> {
+ Arc::new(Provider {
+ trace: trace.clone(),
+ mode: AtomicU8::new(mode),
+ calls: AtomicUsize::new(0),
+ quiesced: AtomicBool::new(false),
+ fail_quiesce: AtomicBool::new(false),
+ wake: AtomicWaker::new(),
+ })
+}
+fn handle(provider: &Arc<Provider>) -> SignerHandle {
+ SignerHandle::new(provider.clone(), provider.clone())
+}
+fn client(trace: &Trace) -> ClientSession<Host> {
+ ClientSession::new(Host(trace.clone()), NonZeroU16::MIN)
+}
+
+#[test]
+fn attachment_before_start_is_owned_and_closed_in_the_actual_composition_order() {
+ let trace = Trace::default();
+ let client = client(&trace);
+ let provider = provider(&trace, 1);
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 0);
+ let scope = block_on(client.attach_signer(handle(&provider))).unwrap();
+ assert!(trace.lock().unwrap().is_empty());
+ assert_eq!(client.state(), SessionState::Ready);
+ assert!(client.signer_session().unwrap().observed().is_some());
+ assert!(block_on(client.attach_signer(handle(&provider))).is_err());
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
+ block_on(client.start()).unwrap();
+ block_on(client.clone().close()).unwrap();
+ block_on(client.close()).unwrap();
+ assert_eq!(scope.state(), SessionState::Closed);
+ assert_eq!(
+ *trace.lock().unwrap(),
+ [
+ "start",
+ "quiesce",
+ "signer_quiesce",
+ "disconnect",
+ "signer_callbacks",
+ "host_callbacks",
+ "storage"
+ ]
+ );
+ assert!(block_on(client.attach_signer(handle(&provider))).is_err());
+ assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
+}
+
+#[test]
+fn close_quiesces_a_pending_attachment_before_waiting_for_its_resource_permit() {
+ let trace = Trace::default();
+ let client = client(&trace);
+ let provider = provider(&trace, 2);
+ let mut attach = Box::pin(client.attach_signer(handle(&provider)));
+ let mut cx = Context::from_waker(noop_waker_ref());
+ assert!(attach.as_mut().poll(&mut cx).is_pending());
+ assert!(client.signer_session().is_some());
+ let mut close = Box::pin(client.close());
+ assert!(close.as_mut().poll(&mut cx).is_pending());
+ assert_eq!(client.state(), SessionState::Closing);
+ assert!(matches!(attach.as_mut().poll(&mut cx), Poll::Ready(Err(_))));
+ assert!(matches!(close.as_mut().poll(&mut cx), Poll::Ready(Ok(()))));
+ assert_eq!(
+ *trace.lock().unwrap(),
+ [
+ "quiesce",
+ "signer_quiesce",
+ "disconnect",
+ "signer_callbacks",
+ "host_callbacks",
+ "storage"
+ ]
+ );
+}
+
+#[test]
+fn failed_and_cancelled_attachment_remain_reachable_and_explicitly_replaceable() {
+ for mode in [0, 2, 3] {
+ let trace = Trace::default();
+ let client = client(&trace);
+ let original = provider(&trace, mode);
+ if mode == 2 {
+ let mut attach = Box::pin(client.attach_signer(handle(&original)));
+ assert!(
+ attach
+ .as_mut()
+ .poll(&mut Context::from_waker(noop_waker_ref()))
+ .is_pending()
+ );
+ drop(attach);
+ } else {
+ let error = match block_on(client.attach_signer(handle(&original))) {
+ Err(error) => error,
+ Ok(_) => panic!("failed observation accepted"),
+ };
+ assert_eq!(
+ error.code(),
+ if mode == 3 {
+ Code::IdentityChanged
+ } else {
+ Code::SignerUnavailable
+ }
+ );
+ }
+ let retained = client.signer_session().unwrap();
+ assert!(retained.observed().is_none());
+ block_on(retained.close()).unwrap();
+ let replacement = provider(&trace, 1);
+ assert!(
+ block_on(client.attach_signer(handle(&replacement)))
+ .unwrap()
+ .observed()
+ .is_some()
+ );
+ block_on(client.close()).unwrap();
+ }
+}
+
+#[test]
+fn resuming_signer_quiesce_does_not_repeat_the_completed_host_hook() {
+ let trace = Trace::default();
+ let client = client(&trace);
+ let provider = provider(&trace, 1);
+ block_on(client.attach_signer(handle(&provider))).unwrap();
+ provider.fail_quiesce.store(true, Ordering::SeqCst);
+ assert!(block_on(client.close()).is_err());
+ assert_eq!(*trace.lock().unwrap(), ["quiesce", "signer_quiesce"]);
+ block_on(client.close()).unwrap();
+ assert_eq!(
+ *trace.lock().unwrap(),
+ [
+ "quiesce",
+ "signer_quiesce",
+ "signer_quiesce",
+ "disconnect",
+ "signer_callbacks",
+ "host_callbacks",
+ "storage"
+ ]
+ );
+ let no_signer = self::client(&Trace::default());
+ assert!(no_signer.signer_session().is_none());
+ block_on(no_signer.close()).unwrap();
+}
+
+#[test]
+fn overlapping_attachment_and_close_never_publish_an_unquiesced_scope() {
+ use std::{
+ sync::{Barrier, mpsc},
+ thread,
+ time::Duration,
+ };
+ for _ in 0..32 {
+ let trace = Trace::default();
+ let client = client(&trace);
+ let provider = provider(&trace, 1);
+ let barrier = Arc::new(Barrier::new(3));
+ let (attached, observation) = mpsc::sync_channel(1);
+ let (closed, completion) = mpsc::sync_channel(1);
+ let joining = {
+ let client = client.clone();
+ let provider = provider.clone();
+ let barrier = barrier.clone();
+ thread::spawn(move || {
+ barrier.wait();
+ attached
+ .send(block_on(client.attach_signer(handle(&provider))))
+ .unwrap();
+ })
+ };
+ let closing = {
+ let client = client.clone();
+ let barrier = barrier.clone();
+ thread::spawn(move || {
+ barrier.wait();
+ closed.send(block_on(client.close())).unwrap();
+ })
+ };
+ barrier.wait();
+ let scope = observation
+ .recv_timeout(Duration::from_secs(10))
+ .expect("attachment completed");
+ completion
+ .recv_timeout(Duration::from_secs(10))
+ .expect("close completed")
+ .unwrap();
+ joining.join().unwrap();
+ closing.join().unwrap();
+ assert_eq!(client.state(), SessionState::Closed);
+ if let Ok(scope) = scope {
+ assert_eq!(scope.state(), SessionState::Closed);
+ }
+ if let Some(scope) = client.signer_session() {
+ assert_eq!(scope.state(), SessionState::Closed);
+ }
+ assert!(provider.calls.load(Ordering::SeqCst) <= 1);
+ let trace = trace.lock().unwrap();
+ assert_eq!(trace.last(), Some(&"storage"));
+ if let Some(callback) = trace.iter().position(|item| *item == "signer_callbacks") {
+ assert!(callback < trace.iter().position(|item| *item == "storage").unwrap());
+ }
+ }
+}
diff --git a/crates/execution/tests/session.rs b/crates/execution/tests/session.rs
@@ -547,3 +547,37 @@ fn browser_host_futures_accept_thread_local_callback_state() {
assert_eq!(calls.get(), 1);
block_on(client.close()).unwrap();
}
+
+#[test]
+fn explicit_quiesce_stops_admission_without_draining_or_disposing_resources() {
+ let (session, observed) = fixture(1);
+ block_on(session.start()).unwrap();
+ let permit = session.admit().unwrap();
+ drop(session.quiesce());
+ assert_eq!(session.state(), SessionState::Running);
+ block_on(session.quiesce()).unwrap();
+ assert_eq!(session.state(), SessionState::Closing);
+ assert!(session.admit().is_err());
+ assert_eq!(
+ *observed.calls.lock().unwrap(),
+ [Hook::Start, Hook::Quiesce]
+ );
+ block_on(session.quiesce()).unwrap();
+ assert_eq!(
+ *observed.calls.lock().unwrap(),
+ [Hook::Start, Hook::Quiesce]
+ );
+ drop(permit);
+ block_on(session.close()).unwrap();
+ block_on(session.quiesce()).unwrap();
+ assert_eq!(
+ *observed.calls.lock().unwrap(),
+ [
+ Hook::Start,
+ Hook::Quiesce,
+ Hook::Disconnect,
+ Hook::Callbacks,
+ Hook::Storage
+ ]
+ );
+}
diff --git a/crates/execution/tests/signer_session.rs b/crates/execution/tests/signer_session.rs
@@ -372,4 +372,49 @@ fn browser_scope_accepts_rc_local_provider_and_callbacks() {
));
assert_eq!(block_on(session.observe()).unwrap().identity(), key(false));
block_on(session.close()).unwrap();
+ assert_eq!(session.state(), SessionState::Closed);
+}
+
+#[cfg(all(target_arch = "wasm32", feature = "client_session"))]
+#[test]
+fn browser_client_composes_local_host_and_retained_callback_scope() {
+ use radroots_execution::session::{ClientSession, HostFuture, SessionHost};
+ struct LocalHost(std::rc::Rc<std::cell::Cell<u8>>);
+ impl LocalHost {
+ fn run(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ Box::pin(async move {
+ self.0.set(self.0.get() + 1);
+ Ok(())
+ })
+ }
+ }
+ impl SessionHost for LocalHost {
+ fn start(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run()
+ }
+ fn quiesce(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run()
+ }
+ fn disconnect(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run()
+ }
+ fn dispose_callbacks(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run()
+ }
+ fn close_storage(&self) -> HostFuture<'_, radroots_execution::Result<()>> {
+ self.run()
+ }
+ }
+ let observations = std::rc::Rc::new(std::cell::Cell::new(0));
+ let client = ClientSession::new(LocalHost(observations.clone()), core::num::NonZeroU16::MIN);
+ let control = control();
+ block_on(client.attach_signer(SignerHandle::new(
+ Shared::new(Provider(control.clone())),
+ Shared::new(Callbacks(control)),
+ )))
+ .unwrap();
+ assert_eq!(observations.get(), 0);
+ block_on(client.start()).unwrap();
+ block_on(client.close()).unwrap();
+ assert_eq!(observations.get(), 5);
}
diff --git a/crates/radroots/Cargo.toml b/crates/radroots/Cargo.toml
@@ -38,26 +38,34 @@ path = "src/lib.rs"
[dependencies]
radroots_core = { workspace = true }
radroots_domain = { workspace = true, features = ["std", "serde"] }
+radroots_execution = { workspace = true, features = ["client_session"] }
radroots_event = { workspace = true }
radroots_identity = { workspace = true, features = ["std"] }
radroots_sdk = { workspace = true }
+radroots_signing = { workspace = true }
+radroots_storage = { workspace = true }
+radroots_storage_sqlite = { workspace = true, optional = true }
radroots_trade = { workspace = true, features = ["json", "std"] }
radroots_transport = { workspace = true }
[features]
default = ["client"]
-client = ["radroots_sdk/default"]
-native = ["client", "radroots_sdk/native"]
+client = ["radroots_sdk/default", "radroots_storage/memory"]
+native = ["client", "radroots_sdk/native", "dep:radroots_storage_sqlite"]
nostr = ["client", "radroots_sdk/nostr"]
blossom = ["client", "radroots_sdk/blossom"]
nip46 = ["nostr", "radroots_sdk/nip46"]
radrootsd = ["client", "radroots_sdk/radrootsd"]
geonames = ["client", "radroots_sdk/geonames"]
knowledge = ["client", "radroots_sdk/knowledge"]
-full = ["radroots_sdk/full"]
+full = ["native", "radroots_sdk/full"]
[dev-dependencies]
+futures = { workspace = true }
+radroots_nostr = { workspace = true, features = ["signing"] }
serde_json = { workspace = true, features = ["std"] }
+tempfile = { workspace = true }
+tokio = { workspace = true, features = ["macros", "rt"] }
toml = { workspace = true }
[[example]]
diff --git a/crates/radroots/README.md b/crates/radroots/README.md
@@ -1,100 +1,78 @@
# radroots
-`radroots` is the canonical ordinary-user Rust package for Radroots. It offers
-safe local construction, deliberate domain paths, and the common client
-boundary without exposing every lower crate or duplicating the advanced SDK
-engine.
+`radroots` is the ordinary Rust entry to shared Radroots values and execution.
+The Client owns one coherent execution session and its actual store. Clones
+share admission and shutdown. Source is in refactor; package release remains
+separately governed.
-The package is enabled for validation-only release qualification. After the
-separately approved publication gate, the onboarding command is:
+## Explicit preview
-```sh
-cargo add radroots
-```
-
-## Start locally
-
-The default `client` feature enables deterministic in-process memory storage.
-Construction creates no file, contacts no network or daemon, reads no keyring,
-installs no runtime or subscriber, and starts no worker. The initial transport
-profile is explicitly local-only.
+The default `client` feature enables an in-memory preview. Construction opens
+no file, network, keyring, runtime or worker. Its deterministic cache generation
+is not an operation ID or stock authority.
```rust
# async fn run() -> radroots::Result<()> {
-let client = radroots::client::memory().build()?;
-let profile = radroots::client::local_only();
-assert!(profile.is_local_only());
-
-// Clone handles share lifecycle state; shutdown is explicit and asynchronous.
+use radroots::{Client, StartMode};
+let client = Client::preview();
+client.start(StartMode::LocalOnly).await?;
client.close().await?;
# Ok(())
# }
```
-The default memory generation is process-local and deterministic. Hosts that
-persist cursors or compose their own storage generation should use
-`radroots_sdk::ClientBuilder` directly.
-
-## Product operations
-
-Farm, listing, and trade writes follow one reliability boundary:
-
-1. `prepare` validates and freezes a side-effect-free plan.
-2. The configured signer authorizes and signs that plan.
-3. Enqueue durably accepts it under an operation ID and idempotency key.
-4. Delivery runs only for an explicitly selected transport profile.
-
-Cancellation before durable acceptance makes no commit claim. Cancellation
-after acceptance cannot roll back the accepted event; resume with the same
-idempotency identity and inspect the canonical receipt. Public event models do
-not contain exact farm coordinates, private trade terms, credentials, or key
-material.
-
-Errors expose stable classifications and recovery metadata while retaining
-their lower source chain for local diagnostics. Display, debug, diagnostics,
-and protocol reports redact bearer credentials and signer material. Canonical
-lower crates own serialization and versioned wire contracts; facade aliases
-are Rust paths, not a second persistence format.
-
-## Features
-
-| Feature | Behavior |
-| --- | --- |
-| `client` | safe memory-backed client; the default |
-| `native` | explicit SQLite, sync, and local-signing SDK capabilities |
-| `blossom` | HTTP-only BUD-11 upload authorization through an opaque host signer |
-| `nostr` | explicit Nostr source/sink composition |
-| `nip46` | host-owned NIP-46 signer composition; implies `nostr` |
-| `radrootsd` | explicitly invoked daemon delivery |
-| `geonames` | concrete GeoNames provider capability |
-| `knowledge` | canonical knowledge event contracts |
-| `full` | the governed complete SDK capability bundle |
-
-Enabling a feature compiles capability; it never performs I/O. Native storage
-opens only through `client::native`, transport is caller-injected, and daemon
-delivery happens only when its `deliver` method is invoked.
-
-## When to use radroots_sdk
-
-`radroots::domain` exposes exact decimal values and separate order, thread,
-workspace, executor and operation identities. `radroots::OperationId` is the
-retained operation identity, not an operation-kind enum. These validated values
-do not authenticate a participant or establish durable command admission.
-
-Use `radroots` for ordinary applications and the primary farm, listing, trade,
-identity, event, and transport paths. Use `radroots_sdk` directly when the host
-must own source-generation identity, inject arbitrary storage/signing/sync
-implementations, coordinate FFI/mobile lifecycle, or inspect advanced
-capability and diagnostics contracts. There is intentionally no
-`radroots::sdk` namespace or wildcard SDK reexport.
-
-The namespace separation is a compiled contract:
+With `native`, `Client::open(NativeConfig::public_read(options)).await` opens
+the actual SQLite cache from explicit validated host paths, mode and source
+generation. It performs no networking or automatic command replay. This public
+cache scope does not open an authenticated participant workspace or create
+seller stock authority. Protected workspace/authority opening, network workers,
+complete command receipts and durable listing/chat operations remain separate
+unfinished implementation requirements.
+
+`attach_signer` observes the concrete provider only after retaining its callback
+scope. The first successful key freezes and later drift invalidates that scope.
+Observation grants no workspace, command or stock authority. Failed/cancelled
+attachment remains reachable through `signer_session` for explicit cleanup.
+
+Close permanently stops admission, quiesces callback dispatch, drains work,
+disconnects owned transports, disposes callbacks and closes storage last. Failed
+or cancelled close retains its unfinished stage; await close again. An unpolled
+future has no shutdown effect, and Drop supplies no completion receipt.
+`CloseReceipt` reports actual resource closure, never business installation.
+Native handles/futures retain thread guarantees; shared browser resource code
+uses local handles/futures. Compilation does not qualify browser runtime hosts.
+
+Errors come from `radroots_execution`: fixed codes, bounded redacted details,
+explicit admission/retry disposition and optional exact operation identity.
+Backend prose, private payloads and paths are not retained in the error.
+
+## Values and retained capabilities
+
+`radroots::domain` provides exact decimals and distinct order, thread, workspace,
+executor and operation identities. `radroots::OperationId` is the 256-bit
+retained identity. These values alone perform no authorization or transaction.
+
+Farm, listing, trade, event, identity, transport, geographic and knowledge
+modules retain their source-owned values/planners and advanced capability
+paths. The advanced `radroots_sdk` still owns its existing explicit transport
+composition while concrete ordinary network integration is unfinished; the
+new Client does not wrap that engine or report its writes as new durable
+commerce. Optional capabilities remain governed by their actual host/target
+qualification and do not become available because a feature compiles.
+
+The former root `ClientBuilder` and builder-returning memory/native helpers
+are replaced by explicit Client preview/open methods. Advanced SDK callers
+remain at their owning package. No wildcard or SDK namespace is exposed:
```compile_fail
use radroots::sdk;
```
-The normative package charter is the [`radroots` release-v1
-specification](../../contracts/crates/release_v1/radroots_crates_release_v1.toml).
-The reviewed pre-release public API is recorded in the
-[`radroots` baseline](../../contracts/api_baselines/radroots.txt).
+```compile_fail
+use radroots::ClientBuilder;
+```
+
+The reviewed Rust API lives in
+[`contracts/api_baselines/radroots.txt`](../../contracts/api_baselines/radroots.txt).
+The approved successor ownership and host contracts live in
+[`shared_sdk_refactor.v1.json`](../../contracts/architecture/decisions/shared_sdk_refactor.v1.json).
diff --git a/crates/radroots/examples/ordinary_memory.rs b/crates/radroots/examples/ordinary_memory.rs
@@ -1,10 +1,14 @@
//! Constructs the ordinary, safe, local-only Radroots front door.
fn main() -> radroots::Result<()> {
- let client = radroots::client::memory().build()?;
- let profile = radroots::client::local_only();
-
- assert!(!client.is_closed());
- assert!(profile.is_local_only());
- Ok(())
+ futures::executor::block_on(async {
+ let client = radroots::Client::preview();
+ assert_eq!(
+ client.state(),
+ radroots_execution::session::SessionState::Ready
+ );
+ client.start(radroots::StartMode::LocalOnly).await?;
+ client.close().await?;
+ Ok(())
+ })
}
diff --git a/crates/radroots/src/client.rs b/crates/radroots/src/client.rs
@@ -1,145 +1,240 @@
-//! Curated client construction and operation entry points.
-
-#[cfg(any(feature = "nostr", feature = "full"))]
-use std::sync::Arc;
-
-#[cfg(any(feature = "nostr", feature = "full"))]
-use radroots_transport::{EventSink, EventSource};
-
-#[cfg(any(
- feature = "client",
- feature = "native",
- feature = "nostr",
- feature = "nip46",
- feature = "full"
-))]
-use crate::ClientBuilder;
-use crate::transport::Profile;
+//! Explicit preview/native resource opening and owned session lifecycle.
+#[cfg(any(feature = "client", feature = "native"))]
+use core::num::NonZeroU16;
+use radroots_execution::{
+ Code, Error, OperationContext, RetryClass,
+ session::{ClientSession, HostFuture, SessionHost, SessionState, SignerSession},
+};
+use radroots_signing::{host::Shared, provider::SignerHandle};
+use radroots_storage::{
+ Storage,
+ status::{ShutdownState, StorageStatus},
+};
+use std::{boxed::Box, sync::Mutex};
+
+const STORAGE_FAILURE: Error = match Error::new(
+ Code::StorageFailure,
+ OperationContext::proposed(None),
+ RetryClass::Never,
+ None,
+) {
+ Ok(error) => error,
+ Err(_) => panic!("invalid constant pre-admission storage error"),
+};
+
+/// Explicit task admission for a local resource session. No network is selected.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
+pub enum StartMode {
+ /// Enables local resource work without opening sockets or replaying writes.
+ LocalOnly,
+}
+/// A passive resource-start observation, independent of business authority.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct SessionStatus {
+ state: SessionState,
+}
+impl SessionStatus {
+ /// Returns the shared resource lifecycle state.
+ pub const fn state(self) -> SessionState {
+ self.state
+ }
+}
+/// Confirmed resource closure, without claiming a business operation committed.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct CloseReceipt {
+ storage: StorageStatus,
+}
+impl CloseReceipt {
+ fn confirmed(storage: StorageStatus) -> crate::Result<Self> {
+ if storage.shutdown() != ShutdownState::Closed {
+ return Err(STORAGE_FAILURE);
+ }
+ Ok(Self { storage })
+ }
-/// Creates the safe ordinary client builder with deterministic in-process
-/// storage and no transport, signer, runtime, worker, or file authority.
-#[cfg(feature = "client")]
-#[must_use]
-pub fn memory() -> ClientBuilder {
- ClientBuilder::memory_default()
+ /// Returns the actual backend's confirmed closed status.
+ pub const fn storage(self) -> StorageStatus {
+ self.storage
+ }
}
-/// Returns the explicit no-transport profile used by ordinary local work.
-#[must_use]
-pub const fn local_only() -> Profile {
- Profile::local_only()
+/// Explicit native public-cache opening, without participant/stock authority.
+/// Participant protected-workspace opening requires the separate authenticated
+/// workspace/authority contract and is not inferred from cache generations.
+#[cfg(feature = "native")]
+pub struct NativeConfig {
+ options: radroots_storage_sqlite::OpenOptions,
+}
+#[cfg(feature = "native")]
+impl NativeConfig {
+ /// Uses the host's validated paths/mode and explicit source generation for
+ /// a public cache. Construction opens no file and starts no worker/network.
+ pub fn public_read(options: radroots_storage_sqlite::OpenOptions) -> Self {
+ Self { options }
+ }
}
-/// Adds caller-owned source and sink capabilities without connecting them or
-/// selecting a fallback transport.
-#[cfg(any(feature = "nostr", feature = "full"))]
-#[must_use]
-pub fn with_transport(
- builder: ClientBuilder,
- source: Arc<dyn EventSource>,
- sink: Arc<dyn EventSink>,
-) -> ClientBuilder {
- builder.source(source).sink(sink)
+struct StoreHost {
+ store: Shared<dyn Storage>,
+ closed: Shared<Mutex<Option<CloseReceipt>>>,
+}
+impl SessionHost for StoreHost {
+ fn start(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async { Ok(()) })
+ }
+ fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async { Ok(()) })
+ }
+ fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async { Ok(()) })
+ }
+ fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async { Ok(()) })
+ }
+ fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> {
+ Box::pin(async move {
+ let status = self.store.close().await.map_err(|_| STORAGE_FAILURE)?;
+ let receipt = CloseReceipt::confirmed(status)?;
+ *self
+ .closed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(receipt);
+ Ok(())
+ })
+ }
}
-/// Adds an explicitly constructed NIP-46 signer provider.
-#[cfg(any(feature = "nip46", feature = "full"))]
-#[must_use]
-#[cfg_attr(coverage_nightly, coverage(off))]
-pub fn with_nip46_signer(
- builder: ClientBuilder,
- provider: crate::signing::Provider,
-) -> ClientBuilder {
- builder.signing(provider)
+/// Cloneable handle to one owned local resource session.
+///
+/// Preview/public-cache opening never establishes workspace authorization,
+/// signing qualification, a retained operation or firm stock capability.
+#[derive(Clone)]
+pub struct Client {
+ session: ClientSession<StoreHost>,
+ store: Shared<dyn Storage>,
+ closed: Shared<Mutex<Option<CloseReceipt>>>,
+}
+impl Client {
+ #[cfg(any(feature = "client", feature = "native"))]
+ fn from_store(store: Shared<dyn Storage>) -> Self {
+ let closed = Shared::new(Mutex::new(None));
+ let session = ClientSession::new(
+ StoreHost {
+ store: store.clone(),
+ closed: closed.clone(),
+ },
+ NonZeroU16::MIN,
+ );
+ Self {
+ session,
+ store,
+ closed,
+ }
+ }
+ /// Creates a deterministic in-memory preview with no filesystem, network,
+ /// entropy, signer or runtime effects. It cannot execute firm stock.
+ #[cfg(feature = "client")]
+ pub fn preview() -> Self {
+ const GENERATION: radroots_storage::event::SourceGeneration =
+ match radroots_storage::event::SourceGeneration::new([1; 32]) {
+ Ok(generation) => generation,
+ Err(_) => panic!("invalid constant preview generation"),
+ };
+ Self::from_store(Shared::new(radroots_storage::memory::MemoryStorage::new(
+ GENERATION,
+ )))
+ }
+ /// Opens the actual native SQLite cache using explicit host options. This
+ /// reads no participant key and performs no network or automatic replay.
+ #[cfg(feature = "native")]
+ pub async fn open(config: NativeConfig) -> crate::Result<Self> {
+ let store = radroots_storage_sqlite::SqliteStorage::open(config.options)
+ .await
+ .map_err(|_| STORAGE_FAILURE)?;
+ Ok(Self::from_store(Shared::new(store)))
+ }
+ /// Observes resource lifecycle without probing signer, store or network.
+ pub fn state(&self) -> SessionState {
+ self.session.state()
+ }
+ /// Enables the selected local resource host. No background runtime,
+ /// transport, command writer or stock authority is implicitly constructed.
+ pub async fn start(&self, mode: StartMode) -> crate::Result<SessionStatus> {
+ match mode {
+ StartMode::LocalOnly => self.session.start().await?,
+ }
+ Ok(SessionStatus {
+ state: self.state(),
+ })
+ }
+ /// Observes actual passive backend status, without integrity maintenance.
+ pub async fn storage_status(&self) -> crate::Result<StorageStatus> {
+ radroots_storage::BackupSource::status(self.store.as_ref())
+ .await
+ .map_err(|_| STORAGE_FAILURE)
+ }
+ /// Binds an actual participant observation to an owned revocable callback
+ /// scope. Signer identity grants no command, workspace or stock authority.
+ pub async fn attach_signer(&self, handle: SignerHandle) -> crate::Result<SignerSession> {
+ self.session.attach_signer(handle).await
+ }
+ /// Returns the retained scope even if first attachment failed or lost its
+ /// observer. Explicit close/replacement never erases retained work.
+ pub fn signer_session(&self) -> Option<SignerSession> {
+ self.session.signer_session()
+ }
+ /// Permanently stops admission, drains resources and scoped callbacks, then
+ /// closes the actual store last. Failed/cancelled closure must be resumed.
+ pub async fn close(&self) -> crate::Result<CloseReceipt> {
+ self.session.close().await?;
+ let status = *self
+ .closed
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ status.ok_or(STORAGE_FAILURE)
+ }
}
-/// Explicitly opens validated native SQLite storage.
-#[cfg(any(feature = "native", feature = "full"))]
-#[cfg_attr(coverage_nightly, coverage(off))]
-pub async fn native(options: crate::storage::SqliteOptions) -> crate::Result<ClientBuilder> {
- ClientBuilder::sqlite(options).await
+/// Returns explicit inert local-only policy for advanced retained transports.
+#[must_use]
+pub const fn local_only() -> crate::transport::Profile {
+ crate::transport::Profile::local_only()
}
-/// Reports whether the concrete GeoNames capability was selected at compile
-/// time. Asset inspection, acquisition, and database opening remain explicit.
+/// Reports compiled geographic capability without host acquisition effects.
#[cfg(any(feature = "geonames", feature = "full"))]
#[must_use]
pub const fn geonames_enabled() -> bool {
true
}
-/// Reports whether canonical knowledge contracts were selected at compile
-/// time. Merely selecting the feature performs no event or storage operation.
+/// Reports compiled knowledge capability without event or storage effects.
#[cfg(any(feature = "knowledge", feature = "full"))]
#[must_use]
pub const fn knowledge_enabled() -> bool {
true
}
-#[cfg(all(test, feature = "full"))]
+#[cfg(all(test, feature = "client"))]
mod tests {
- use super::{
- Arc, EventSink, EventSource, Profile, geonames_enabled, knowledge_enabled, local_only,
- memory, with_transport,
- };
- use radroots_transport::{
- DeliveryReceipt, DeliveryRequest, Error as TransportError, FetchPage, FetchRequest,
- SinkFailure, SinkStatus, SourceStatus, outcome::Retryability,
- source::BoxFuture as TransportFuture,
- };
-
- struct TestSource;
- struct TestSink;
-
- impl EventSource for TestSource {
- fn status(&self) -> TransportFuture<'_, Result<SourceStatus, TransportError>> {
- Box::pin(async { Err(TransportError::UnsupportedOperation) })
- }
-
- fn fetch(
- &self,
- _request: FetchRequest,
- ) -> TransportFuture<'_, Result<FetchPage, TransportError>> {
- Box::pin(async { Err(TransportError::UnsupportedOperation) })
- }
- }
-
- impl EventSink for TestSink {
- fn status(&self) -> TransportFuture<'_, Result<SinkStatus, TransportError>> {
- Box::pin(async { Err(TransportError::UnsupportedOperation) })
- }
-
- fn deliver(
- &self,
- request: DeliveryRequest,
- ) -> TransportFuture<'_, Result<DeliveryReceipt, SinkFailure>> {
- Box::pin(async move {
- Err(SinkFailure::for_request(
- &request,
- "test_sink_unavailable",
- Retryability::Terminal,
- None,
- None,
- Vec::new(),
- )
- .expect("test sink failure"))
- })
- }
- }
+ use super::{Client, CloseReceipt};
+ use radroots_execution::Code;
+ use radroots_storage::status::ShutdownState;
#[test]
- fn curated_builders_cover_every_directly_testable_entry_point() {
- let local = memory().build().expect("memory client");
- assert_eq!(local_only(), Profile::local_only());
- assert!(local.source().expect("source").is_none());
-
- let composed = with_transport(memory(), Arc::new(TestSource), Arc::new(TestSink))
- .build()
- .expect("transport client");
- assert!(composed.source().expect("source").is_some());
- assert!(composed.sink().expect("sink").is_some());
-
- assert!(geonames_enabled());
- assert!(knowledge_enabled());
+ fn an_actual_open_store_cannot_supply_a_confirmed_close_receipt() {
+ futures::executor::block_on(async {
+ let client = Client::preview();
+ let open = client.storage_status().await.unwrap();
+ assert_eq!(open.shutdown(), ShutdownState::Open);
+ assert_eq!(
+ CloseReceipt::confirmed(open).unwrap_err().code(),
+ Code::StorageFailure
+ );
+ let closed = client.close().await.unwrap();
+ let observed = client.storage_status().await.unwrap();
+ assert_eq!(CloseReceipt::confirmed(observed).unwrap(), closed);
+ });
}
}
diff --git a/crates/radroots/src/lib.rs b/crates/radroots/src/lib.rs
@@ -16,5 +16,8 @@ pub mod sync;
pub mod trade;
pub mod transport;
+#[cfg(feature = "native")]
+pub use client::NativeConfig;
+pub use client::{Client, CloseReceipt, SessionStatus, StartMode};
pub use radroots_domain::OperationId;
-pub use radroots_sdk::{Client, ClientBuilder, Error, Result};
+pub use radroots_execution::{Error, Result};
diff --git a/crates/radroots/src/storage.rs b/crates/radroots/src/storage.rs
@@ -1,6 +1,10 @@
//! Curated storage entry points.
pub use radroots_sdk::storage::{IntegrityStatus, Operations, Status};
+pub use radroots_storage::{
+ event::SourceGeneration,
+ status::{ShutdownState, StorageBackend},
+};
#[cfg(any(feature = "native", feature = "full"))]
pub use radroots_sdk::storage::{SqliteOpenMode, SqliteOptions, SqlitePaths};
diff --git a/crates/radroots/tests/native_client.rs b/crates/radroots/tests/native_client.rs
@@ -0,0 +1,185 @@
+#![cfg(feature = "native")]
+
+use futures::{future::poll_fn, task::AtomicWaker};
+use radroots::{Client, NativeConfig, StartMode};
+use radroots_execution::session::SessionState;
+use radroots_nostr::{key::parse_secret_key, signing::LocalSigner};
+use radroots_signing::{
+ provider::{ProviderError, SignerCallbacks, SignerHandle},
+ signer::BoxFuture,
+};
+use radroots_storage::{event::SourceGeneration, status::ShutdownState};
+use radroots_storage_sqlite::{OpenMode, OpenOptions, Paths, SqliteStorage};
+use std::sync::{
+ Arc,
+ atomic::{AtomicBool, AtomicUsize, Ordering},
+};
+
+fn options(root: &std::path::Path) -> OpenOptions {
+ OpenOptions::new(Paths::from_directory(root).unwrap(), OpenMode::Create)
+ .with_source_generation(SourceGeneration::new([17; 32]).unwrap(), 1)
+ .unwrap()
+}
+
+#[tokio::test]
+async fn native_open_start_and_close_own_the_actual_store_without_creating_authority() {
+ let root = tempfile::tempdir().unwrap();
+ let options = options(root.path());
+ let client = Client::open(NativeConfig::public_read(options.clone()))
+ .await
+ .unwrap();
+ let copy = client.clone();
+ assert_eq!(client.state(), SessionState::Ready);
+ let blocked = match Client::open(NativeConfig::public_read(options.clone())).await {
+ Err(error) => error,
+ Ok(_) => panic!("second writer accepted"),
+ };
+ assert_eq!(blocked.code(), radroots_execution::Code::StorageFailure);
+ assert!(!format!("{blocked:?}").contains(root.path().to_str().unwrap()));
+ assert_eq!(
+ client.storage_status().await.unwrap().shutdown(),
+ ShutdownState::Open
+ );
+ assert!(matches!(
+ SqliteStorage::open(options.clone()).await,
+ Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. })
+ ));
+ drop(client.start(StartMode::LocalOnly));
+ assert_eq!(client.state(), SessionState::Ready);
+ client.start(StartMode::LocalOnly).await.unwrap();
+ assert_eq!(copy.state(), SessionState::Running);
+ drop(client.close());
+ assert_eq!(copy.state(), SessionState::Running);
+ let receipt = copy.close().await.unwrap();
+ assert_eq!(receipt.storage().shutdown(), ShutdownState::Closed);
+ assert_eq!(client.state(), SessionState::Closed);
+ assert_eq!(client.close().await.unwrap(), receipt);
+ assert!(client.start(StartMode::LocalOnly).await.is_err());
+ let reopened = SqliteStorage::open(options).await.unwrap();
+ reopened.close().await.unwrap();
+}
+
+struct Callbacks {
+ options: OpenOptions,
+ quiesces: AtomicUsize,
+ closes: AtomicUsize,
+ ready: AtomicBool,
+ wake: AtomicWaker,
+}
+impl SignerCallbacks for Callbacks {
+ fn quiesce(&self) -> BoxFuture<'_, Result<(), ProviderError>> {
+ Box::pin(async move {
+ self.quiesces.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ })
+ }
+ fn close(&self) -> BoxFuture<'_, Result<(), ProviderError>> {
+ Box::pin(async move {
+ self.closes.fetch_add(1, Ordering::SeqCst);
+ // The real database writer remains owned while callbacks drain.
+ assert!(matches!(
+ SqliteStorage::open(self.options.clone()).await,
+ Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. })
+ ));
+ poll_fn(|cx| {
+ self.wake.register(cx.waker());
+ if self.ready.load(Ordering::SeqCst) {
+ std::task::Poll::Ready(())
+ } else {
+ std::task::Poll::Pending
+ }
+ })
+ .await;
+ Ok(())
+ })
+ }
+}
+fn callbacks(options: OpenOptions, ready: bool) -> Arc<Callbacks> {
+ Arc::new(Callbacks {
+ options,
+ quiesces: AtomicUsize::new(0),
+ closes: AtomicUsize::new(0),
+ ready: AtomicBool::new(ready),
+ wake: AtomicWaker::new(),
+ })
+}
+fn local() -> Arc<LocalSigner> {
+ // Published synthetic interoperability identity, never custody material.
+ Arc::new(
+ LocalSigner::new(
+ parse_secret_key("0000000000000000000000000000000000000000000000000000000000000001")
+ .unwrap(),
+ )
+ .unwrap(),
+ )
+}
+
+#[tokio::test]
+async fn actual_native_signer_attaches_before_start_and_callbacks_close_before_the_store() {
+ let root = tempfile::tempdir().unwrap();
+ let options = options(root.path());
+ let client = Client::open(NativeConfig::public_read(options.clone()))
+ .await
+ .unwrap();
+ let provider = local();
+ let weak = Arc::downgrade(&provider);
+ let expected = provider.public_key();
+ let callbacks = callbacks(options.clone(), true);
+ let signer = client
+ .attach_signer(SignerHandle::new(provider, callbacks.clone()))
+ .await
+ .unwrap();
+ assert_eq!(signer.observed().unwrap().identity(), expected);
+ assert_eq!(client.state(), SessionState::Ready);
+ assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 0);
+ client.close().await.unwrap();
+ assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1);
+ assert_eq!(callbacks.closes.load(Ordering::SeqCst), 1);
+ assert!(weak.upgrade().is_none());
+ assert_eq!(signer.state(), SessionState::Closed);
+ signer.quiesce().await.unwrap();
+ assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1);
+ let reopened = SqliteStorage::open(options).await.unwrap();
+ reopened.close().await.unwrap();
+}
+
+#[tokio::test]
+async fn cancelled_client_close_retains_actual_provider_and_writer_until_callback_completion() {
+ use std::{
+ future::Future,
+ task::{Context, Poll},
+ };
+ let root = tempfile::tempdir().unwrap();
+ let options = options(root.path());
+ let client = Client::open(NativeConfig::public_read(options.clone()))
+ .await
+ .unwrap();
+ let provider = local();
+ let weak = Arc::downgrade(&provider);
+ let callbacks = callbacks(options.clone(), false);
+ client
+ .attach_signer(SignerHandle::new(provider, callbacks.clone()))
+ .await
+ .unwrap();
+ let mut close = Box::pin(client.close());
+ assert!(matches!(
+ close
+ .as_mut()
+ .poll(&mut Context::from_waker(futures::task::noop_waker_ref())),
+ Poll::Pending
+ ));
+ drop(close);
+ assert_eq!(client.state(), SessionState::Closing);
+ assert!(weak.upgrade().is_some());
+ assert!(matches!(
+ SqliteStorage::open(options.clone()).await,
+ Err(radroots_storage_sqlite::Error::WriterAlreadyActive { .. })
+ ));
+ callbacks.ready.store(true, Ordering::SeqCst);
+ callbacks.wake.wake();
+ client.close().await.unwrap();
+ assert!(weak.upgrade().is_none());
+ assert_eq!(callbacks.quiesces.load(Ordering::SeqCst), 1);
+ let reopened = SqliteStorage::open(options).await.unwrap();
+ reopened.close().await.unwrap();
+}
diff --git a/crates/radroots/tests/package_boundary.rs b/crates/radroots/tests/package_boundary.rs
@@ -15,8 +15,12 @@ fn package_has_final_identity_and_exact_dependencies() {
"radroots_core",
"radroots_domain",
"radroots_event",
+ "radroots_execution",
"radroots_identity",
"radroots_sdk",
+ "radroots_signing",
+ "radroots_storage",
+ "radroots_storage_sqlite",
"radroots_trade",
"radroots_transport",
])
@@ -30,14 +34,14 @@ fn package_has_final_identity_and_exact_dependencies() {
fn features_forward_the_exact_user_oriented_graph() {
for forwarding in [
"default = [\"client\"]",
- "client = [\"radroots_sdk/default\"]",
- "native = [\"client\", \"radroots_sdk/native\"]",
+ "client = [\"radroots_sdk/default\", \"radroots_storage/memory\"]",
+ "native = [\"client\", \"radroots_sdk/native\", \"dep:radroots_storage_sqlite\"]",
"nostr = [\"client\", \"radroots_sdk/nostr\"]",
"nip46 = [\"nostr\", \"radroots_sdk/nip46\"]",
"radrootsd = [\"client\", \"radroots_sdk/radrootsd\"]",
"geonames = [\"client\", \"radroots_sdk/geonames\"]",
"knowledge = [\"client\", \"radroots_sdk/knowledge\"]",
- "full = [\"radroots_sdk/full\"]",
+ "full = [\"native\", \"radroots_sdk/full\"]",
] {
assert!(MANIFEST.contains(forwarding), "missing `{forwarding}`");
}
@@ -46,11 +50,14 @@ fn features_forward_the_exact_user_oriented_graph() {
#[test]
fn root_has_exact_exports_and_no_sdk_namespace() {
- assert!(ROOT.contains("pub use radroots_sdk::{Client, ClientBuilder, Error, Result};"));
+ assert!(ROOT.contains("pub use client::{Client, CloseReceipt, SessionStatus, StartMode};"));
+ assert!(ROOT.contains("pub use radroots_execution::{Error, Result};"));
+ assert!(!ROOT.contains("ClientBuilder"));
+ assert!(!ROOT.contains("pub use radroots_sdk::{Client"));
assert!(!ROOT.contains("pub mod sdk"));
assert!(!ROOT.contains("pub use radroots_sdk::*"));
assert!(ROOT.contains("pub use radroots_domain::OperationId;"));
- assert_eq!(ROOT.matches("pub use ").count(), 2);
+ assert_eq!(ROOT.matches("pub use ").count(), 4);
assert!(README.contains("```compile_fail\nuse radroots::sdk;\n```"));
}
diff --git a/crates/radroots/tests/public_surface.rs b/crates/radroots/tests/public_surface.rs
@@ -8,12 +8,14 @@ fn approved_module_skeleton_is_public() {
#[test]
fn root_exports_only_the_client_boundary() {
- fn assert_client<T: Clone + Send + Sync>() {}
- fn assert_builder<T: Send + Sync>() {}
+ fn assert_client<T: Clone>() {}
+ #[cfg(not(target_arch = "wasm32"))]
+ fn assert_native_client<T: Send + Sync>() {}
fn assert_error<T: std::error::Error + Send + Sync + 'static>() {}
assert_client::<radroots::Client>();
- assert_builder::<radroots::ClientBuilder>();
+ #[cfg(not(target_arch = "wasm32"))]
+ assert_native_client::<radroots::Client>();
assert_error::<radroots::Error>();
let result: radroots::Result<()> = Ok(());
assert!(result.is_ok());
@@ -37,14 +39,17 @@ fn canonical_domain_paths_compile() {
#[cfg(feature = "client")]
#[test]
fn ordinary_memory_and_local_only_construction_is_inert() {
- let client = radroots::client::memory().build().expect("memory client");
- assert!(!client.is_closed());
+ let client = radroots::Client::preview();
+ assert_eq!(
+ client.state(),
+ radroots_execution::session::SessionState::Ready
+ );
assert!(radroots::client::local_only().is_local_only());
}
#[cfg(any(feature = "nostr", feature = "full"))]
#[test]
-fn explicit_transport_composition_is_inert() {
+fn retained_advanced_transport_composition_is_inert() {
use std::sync::Arc;
use radroots::transport::{EventSink, EventSource};
@@ -89,13 +94,14 @@ fn explicit_transport_composition_is_inert() {
}
}
- let client = radroots::client::with_transport(
- radroots::client::memory(),
- Arc::new(Source),
- Arc::new(Sink),
- )
- .build()
- .expect("explicit transport client");
+ // The retained advanced SDK owns this source/sink composition until its
+ // concrete ordinary network host is qualified. This does not claim the
+ // new preview/native Client implements a network worker.
+ let client = radroots_sdk::ClientBuilder::memory_default()
+ .source(Arc::new(Source))
+ .sink(Arc::new(Sink))
+ .build()
+ .expect("explicit advanced transport client");
assert!(client.source().expect("source").is_some());
assert!(client.sink().expect("sink").is_some());
}
@@ -118,3 +124,23 @@ fn canonical_knowledge_paths_compile() {
#[allow(unused_imports)]
use radroots::knowledge::{KnowledgeClaim, WikiArticle, normalize_wiki_d_tag};
}
+
+#[cfg(feature = "client")]
+#[test]
+fn preview_handles_share_explicit_start_and_actual_memory_close() {
+ use radroots::{Client, StartMode};
+ use radroots_execution::session::SessionState;
+ use radroots_storage::status::{ShutdownState, StorageBackend};
+ let client = Client::preview();
+ let clone = client.clone();
+ let status = futures::executor::block_on(client.storage_status()).unwrap();
+ assert_eq!(status.backend(), StorageBackend::Memory);
+ assert_eq!(status.shutdown(), ShutdownState::Open);
+ assert!(client.signer_session().is_none());
+ let started = futures::executor::block_on(client.start(StartMode::LocalOnly)).unwrap();
+ assert_eq!(started.state(), SessionState::Running);
+ assert_eq!(clone.state(), SessionState::Running);
+ let receipt = futures::executor::block_on(clone.close()).unwrap();
+ assert_eq!(receipt.storage().shutdown(), ShutdownState::Closed);
+ assert_eq!(client.state(), SessionState::Closed);
+}