client.rs (19565B)
1 //! Explicit preview/native resource opening and owned session lifecycle. 2 #[cfg(all(test, feature = "native", unix))] 3 #[path = "native_commerce_tests.rs"] 4 mod commerce_tests; 5 #[cfg(any(feature = "client", feature = "native"))] 6 use core::num::NonZeroU16; 7 use radroots_execution::{ 8 Code, Error, OperationContext, RetryClass, 9 session::{ClientSession, HostFuture, SessionHost, SessionState, SignerSession}, 10 }; 11 use radroots_signing::{host::Shared, provider::SignerHandle}; 12 use radroots_storage::{ 13 Storage, 14 status::{ShutdownState, StorageStatus}, 15 }; 16 use std::{boxed::Box, sync::Mutex}; 17 18 const STORAGE_FAILURE: Error = match Error::new( 19 Code::StorageFailure, 20 OperationContext::proposed(None), 21 RetryClass::Never, 22 None, 23 ) { 24 Ok(error) => error, 25 Err(_) => panic!("invalid constant pre-admission storage error"), 26 }; 27 const MISSING_WORKSPACE: Error = match Error::new( 28 Code::MissingAuthority, 29 OperationContext::proposed(None), 30 RetryClass::AfterStateRefresh, 31 None, 32 ) { 33 Ok(error) => error, 34 Err(_) => panic!("invalid constant pre-admission workspace error"), 35 }; 36 37 pub use radroots_execution::session::StartMode; 38 /// A passive resource-start observation, independent of business authority. 39 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 40 pub struct SessionStatus { 41 state: SessionState, 42 } 43 impl SessionStatus { 44 /// Returns the shared resource lifecycle state. 45 pub const fn state(self) -> SessionState { 46 self.state 47 } 48 } 49 /// Confirmed resource closure, without claiming a business operation committed. 50 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 51 pub struct CloseReceipt { 52 storage: StorageStatus, 53 } 54 impl CloseReceipt { 55 fn confirmed(storage: StorageStatus) -> crate::Result<Self> { 56 if storage.shutdown() != ShutdownState::Closed { 57 return Err(STORAGE_FAILURE); 58 } 59 Ok(Self { storage }) 60 } 61 62 /// Returns the actual backend's confirmed closed status. 63 pub const fn storage(self) -> StorageStatus { 64 self.storage 65 } 66 } 67 68 // These are views of one configured owner, never separately selected stores. 69 #[derive(Clone)] 70 struct WorkspaceResource { 71 journal: Shared<dyn radroots_storage::command::OperationJournal>, 72 inventory: Shared<dyn radroots_storage::inventory::InventoryStore>, 73 commerce: Option<Shared<dyn radroots_execution::session::commerce::AcceptanceStore>>, 74 } 75 76 /// Explicit native public-cache opening, without participant/stock authority. 77 /// Participant protected-workspace opening requires the separate authenticated 78 /// workspace/authority contract and is not inferred from cache generations. 79 #[cfg(feature = "native")] 80 pub struct NativeConfig { 81 options: radroots_storage_sqlite::OpenOptions, 82 workspace: Option<WorkspaceResource>, 83 #[cfg(not(target_arch = "wasm32"))] 84 commands: Option<Shared<crate::native_commands::NativeCommands>>, 85 } 86 #[cfg(feature = "native")] 87 impl NativeConfig { 88 /// Uses the host's validated paths/mode and explicit source generation for 89 /// a public cache. Construction opens no file and starts no worker/network. 90 pub fn public_read(options: radroots_storage_sqlite::OpenOptions) -> Self { 91 Self { 92 options, 93 workspace: None, 94 #[cfg(not(target_arch = "wasm32"))] 95 commands: None, 96 } 97 } 98 /// Adds an explicitly opened protected local outbox. A public cache alone 99 /// cannot create this resource or establish a workspace grant. 100 #[cfg(unix)] 101 pub fn with_workspace( 102 mut self, 103 workspace: radroots_storage_sqlite::workspace::NativeWorkspace, 104 ) -> Self { 105 let owner = Shared::new(workspace); 106 self.workspace = Some(WorkspaceResource { 107 journal: owner.clone(), 108 inventory: owner.clone(), 109 commerce: Some(Shared::new(crate::native_commerce::NativeCommerce(owner))), 110 }); 111 self 112 } 113 /// Selects explicit relay destinations and a relay-acceptance criterion. 114 /// Construction opens no socket. Actual command IO requires Online start. 115 #[cfg(not(target_arch = "wasm32"))] 116 pub fn with_nostr( 117 mut self, 118 config: radroots_transport_nostr::Config, 119 policy: radroots_transport::policy::SatisfactionPolicy, 120 ) -> crate::Result<Self> { 121 self.commands = Some(Shared::new( 122 crate::native_commands::NativeCommands::new(config, policy) 123 .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?, 124 )); 125 Ok(self) 126 } 127 } 128 129 #[derive(Clone, Default)] 130 enum TargetRuntime { 131 #[default] 132 Preview, 133 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 134 Native(Shared<crate::native_tasks::NativeTasks>), 135 } 136 impl TargetRuntime { 137 fn task_host(&self) -> Option<Shared<dyn radroots_execution::session::tasks::TaskHost>> { 138 match self { 139 Self::Preview => None, 140 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 141 Self::Native(tasks) => Some(tasks.clone()), 142 } 143 } 144 } 145 pub(crate) struct StoreHost { 146 store: Shared<dyn Storage>, 147 workspace: Option<WorkspaceResource>, 148 closed: Shared<Mutex<Option<CloseReceipt>>>, 149 runtime: TargetRuntime, 150 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 151 commands: Option<Shared<radroots_execution::session::command::CommandRuntime>>, 152 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 153 native_commands: Option<Shared<crate::native_commands::NativeCommands>>, 154 } 155 impl SessionHost for StoreHost { 156 fn start(&self) -> HostFuture<'_, crate::Result<()>> { 157 Box::pin(async move { 158 match &self.runtime { 159 TargetRuntime::Preview => Ok(()), 160 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 161 TargetRuntime::Native(tasks) => tasks.start().await, 162 } 163 }) 164 } 165 fn quiesce(&self) -> HostFuture<'_, crate::Result<()>> { 166 Box::pin(async move { 167 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 168 if let TargetRuntime::Native(tasks) = &self.runtime { 169 tasks.quiesce(); 170 } 171 Ok(()) 172 }) 173 } 174 fn drain(&self) -> HostFuture<'_, crate::Result<()>> { 175 Box::pin(async move { 176 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 177 if let TargetRuntime::Native(tasks) = &self.runtime { 178 let commands = self.commands.clone(); 179 tasks 180 .control( 181 crate::native_tasks::ControlKind::Drain, 182 Box::pin(async move { 183 if let Some(commands) = commands { 184 commands.drain().await?; 185 } 186 Ok(()) 187 }), 188 ) 189 .await?; 190 } 191 Ok(()) 192 }) 193 } 194 fn disconnect(&self) -> HostFuture<'_, crate::Result<()>> { 195 Box::pin(async move { 196 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 197 if let TargetRuntime::Native(tasks) = &self.runtime { 198 let commands = self.native_commands.clone(); 199 tasks 200 .control( 201 crate::native_tasks::ControlKind::Disconnect, 202 Box::pin(async move { 203 if let Some(commands) = commands { 204 commands.disconnect().await; 205 } 206 Ok(()) 207 }), 208 ) 209 .await?; 210 } 211 Ok(()) 212 }) 213 } 214 fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>> { 215 Box::pin(async { Ok(()) }) 216 } 217 fn close_storage(&self) -> HostFuture<'_, crate::Result<()>> { 218 Box::pin(async move { 219 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 220 if let TargetRuntime::Native(tasks) = &self.runtime { 221 tasks.close().await?; 222 } 223 if let Some(workspace) = &self.workspace { 224 workspace 225 .journal 226 .close_workspace() 227 .await 228 .map_err(|_| STORAGE_FAILURE)?; 229 } 230 let status = self.store.close().await.map_err(|_| STORAGE_FAILURE)?; 231 let receipt = CloseReceipt::confirmed(status)?; 232 *self 233 .closed 234 .lock() 235 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(receipt); 236 Ok(()) 237 }) 238 } 239 } 240 241 /// Cloneable handle to one owned local resource session. 242 /// 243 /// Preview/public-cache opening never establishes workspace authorization, 244 /// signing qualification, a retained operation or firm stock capability. 245 #[derive(Clone)] 246 pub struct Client { 247 pub(crate) session: ClientSession<StoreHost>, 248 store: Shared<dyn Storage>, 249 workspace: Option<WorkspaceResource>, 250 closed: Shared<Mutex<Option<CloseReceipt>>>, 251 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 252 native_commands: Option<Shared<crate::native_commands::NativeCommands>>, 253 } 254 impl Client { 255 #[cfg(any(feature = "client", feature = "native"))] 256 fn from_store( 257 store: Shared<dyn Storage>, 258 workspace: Option<WorkspaceResource>, 259 runtime: TargetRuntime, 260 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] native_commands: Option< 261 Shared<crate::native_commands::NativeCommands>, 262 >, 263 ) -> Self { 264 let closed = Shared::new(Mutex::new(None)); 265 let task_host = runtime.task_host(); 266 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 267 let commands = native_commands.as_ref().map(|io| { 268 Shared::new(radroots_execution::session::command::CommandRuntime::new( 269 io.clone(), 270 )) 271 }); 272 #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))] 273 let commands: Option<Shared<radroots_execution::session::command::CommandRuntime>> = None; 274 let host = StoreHost { 275 store: store.clone(), 276 workspace: workspace.clone(), 277 closed: closed.clone(), 278 runtime, 279 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 280 commands: commands.clone(), 281 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 282 native_commands: native_commands.clone(), 283 }; 284 const MAX_RESOURCES: NonZeroU16 = match NonZeroU16::new(32) { 285 Some(limit) => limit, 286 None => panic!("invalid constant resource bound"), 287 }; 288 let session = match task_host { 289 Some(tasks) => ClientSession::new_with_task_host(host, MAX_RESOURCES, tasks), 290 None => ClientSession::new(host, MAX_RESOURCES), 291 }; 292 let session = match commands { 293 Some(commands) => session.with_command_runtime(commands), 294 None => session, 295 }; 296 Self { 297 session, 298 store, 299 workspace, 300 closed, 301 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 302 native_commands, 303 } 304 } 305 /// Creates a deterministic in-memory preview with no filesystem, network, 306 /// entropy, signer or runtime effects. It cannot execute firm stock. 307 #[cfg(feature = "client")] 308 pub fn preview() -> Self { 309 const GENERATION: radroots_storage::event::SourceGeneration = 310 match radroots_storage::event::SourceGeneration::new([1; 32]) { 311 Ok(generation) => generation, 312 Err(_) => panic!("invalid constant preview generation"), 313 }; 314 Self::from_store( 315 Shared::new(radroots_storage::memory::MemoryStorage::new(GENERATION)), 316 None, 317 TargetRuntime::Preview, 318 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 319 None, 320 ) 321 } 322 /// Opens the actual native SQLite cache using explicit host options. This 323 /// reads no participant key and performs no network or automatic replay. 324 #[cfg(feature = "native")] 325 pub async fn open(config: NativeConfig) -> crate::Result<Self> { 326 let store = radroots_storage_sqlite::SqliteStorage::open(config.options) 327 .await 328 .map_err(|_| STORAGE_FAILURE)?; 329 #[cfg(not(target_arch = "wasm32"))] 330 let runtime = TargetRuntime::Native(Shared::new(crate::native_tasks::NativeTasks::new())); 331 #[cfg(target_arch = "wasm32")] 332 let runtime = TargetRuntime::Preview; 333 Ok(Self::from_store( 334 Shared::new(store), 335 config.workspace, 336 runtime, 337 #[cfg(not(target_arch = "wasm32"))] 338 config.commands, 339 )) 340 } 341 /// Observes resource lifecycle without probing signer, store or network. 342 pub fn state(&self) -> SessionState { 343 self.session.state() 344 } 345 pub(crate) fn journal( 346 &self, 347 ) -> crate::Result<Shared<dyn radroots_storage::command::OperationJournal>> { 348 self.workspace 349 .as_ref() 350 .map(|workspace| workspace.journal.clone()) 351 .ok_or(MISSING_WORKSPACE) 352 } 353 pub(crate) fn inventory( 354 &self, 355 ) -> crate::Result<Shared<dyn radroots_storage::inventory::InventoryStore>> { 356 self.workspace 357 .as_ref() 358 .map(|workspace| workspace.inventory.clone()) 359 .ok_or(MISSING_WORKSPACE) 360 } 361 /// Selects owner-private stock operations through this client's explicit 362 /// authenticated attachment. Access alone creates no authority or work. 363 pub fn stock( 364 &self, 365 scope: &radroots_execution::workspace::WorkspaceSession, 366 ) -> crate::stock::Stock<'_> { 367 crate::stock::Stock::new(self, scope.clone()) 368 } 369 370 /// Selects ordinary order workflows through this client's attachment. 371 /// Constructing the view establishes no stock or signing permission. 372 pub fn orders(&self, scope: &crate::WorkspaceSession) -> crate::orders::Orders<'_> { 373 crate::orders::Orders::new(self, scope.clone()) 374 } 375 pub(crate) fn acceptance_store( 376 &self, 377 ) -> crate::Result<Shared<dyn radroots_execution::session::commerce::AcceptanceStore>> { 378 self.workspace 379 .as_ref() 380 .and_then(|v| v.commerce.clone()) 381 .ok_or(MISSING_WORKSPACE) 382 } 383 /// Accesses private inquiry execution. Access alone performs no work. 384 pub const fn inbox(&self) -> crate::inbox::Inbox<'_> { 385 crate::inbox::Inbox::new(self) 386 } 387 /// Accesses initial public listing publication. Access alone has no effects. 388 pub const fn listings(&self) -> crate::listings::Listings<'_> { 389 crate::listings::Listings::new(self) 390 } 391 /// Selects an explicitly authenticated scope for original-operation reads. 392 /// Every query checks that this client owns the attachment and current grant. 393 pub fn operations( 394 &self, 395 scope: &radroots_execution::workspace::WorkspaceSession, 396 ) -> crate::operations::Operations<'_> { 397 crate::operations::Operations::new(self, scope.clone()) 398 } 399 /// Enables the selected local resource host. No background runtime, 400 /// transport, command writer or stock authority is implicitly constructed. 401 pub async fn start(&self, mode: StartMode) -> crate::Result<SessionStatus> { 402 #[cfg(all(feature = "native", not(target_arch = "wasm32")))] 403 if let Some(commands) = &self.native_commands { 404 commands 405 .select(mode == StartMode::Online) 406 .map_err(|error| Error::operation(error, OperationContext::proposed(None)))?; 407 } else if mode == StartMode::Online { 408 return Err(MISSING_WORKSPACE); 409 } 410 #[cfg(not(all(feature = "native", not(target_arch = "wasm32"))))] 411 if mode == StartMode::Online { 412 return Err(MISSING_WORKSPACE); 413 } 414 self.session.start().await?; 415 Ok(SessionStatus { 416 state: self.state(), 417 }) 418 } 419 /// Observes actual passive backend status, without integrity maintenance. 420 pub async fn storage_status(&self) -> crate::Result<StorageStatus> { 421 radroots_storage::BackupSource::status(self.store.as_ref()) 422 .await 423 .map_err(|_| STORAGE_FAILURE) 424 } 425 /// Binds an actual participant observation to an owned revocable callback 426 /// scope. Signer identity grants no command, workspace or stock authority. 427 pub async fn attach_signer(&self, handle: SignerHandle) -> crate::Result<SignerSession> { 428 self.session.attach_signer(handle).await 429 } 430 /// Returns the retained scope even if first attachment failed or lost its 431 /// observer. Explicit close/replacement never erases retained work. 432 pub fn signer_session(&self) -> Option<SignerSession> { 433 self.session.signer_session() 434 } 435 /// Authenticates a protected grant in the explicitly configured workspace. 436 /// Signer observations and arbitrary descriptors cannot supply this grant. 437 pub async fn attach( 438 &self, 439 input: radroots_storage::workspace::AttachmentInput, 440 proof: radroots_storage::workspace::AttachmentProof, 441 ) -> crate::Result<radroots_execution::workspace::WorkspaceSession> { 442 let workspace = self.workspace.clone().ok_or(MISSING_WORKSPACE)?; 443 self.session 444 .attach_workspace(workspace.journal, input, proof) 445 .await 446 } 447 /// Permanently stops admission, drains resources and scoped callbacks, then 448 /// closes the actual store last. Failed/cancelled closure must be resumed. 449 pub async fn close(&self) -> crate::Result<CloseReceipt> { 450 self.session.close().await?; 451 let status = *self 452 .closed 453 .lock() 454 .unwrap_or_else(std::sync::PoisonError::into_inner); 455 status.ok_or(STORAGE_FAILURE) 456 } 457 } 458 459 /// Returns explicit inert local-only policy for advanced retained transports. 460 #[must_use] 461 pub const fn local_only() -> crate::transport::Profile { 462 crate::transport::Profile::local_only() 463 } 464 465 /// Reports compiled geographic capability without host acquisition effects. 466 #[cfg(any(feature = "geonames", feature = "full"))] 467 #[must_use] 468 pub const fn geonames_enabled() -> bool { 469 true 470 } 471 472 /// Reports compiled knowledge capability without event or storage effects. 473 #[cfg(any(feature = "knowledge", feature = "full"))] 474 #[must_use] 475 pub const fn knowledge_enabled() -> bool { 476 true 477 } 478 479 #[cfg(all(test, feature = "client"))] 480 mod tests { 481 use super::{Client, CloseReceipt}; 482 use radroots_execution::Code; 483 use radroots_storage::status::ShutdownState; 484 485 #[test] 486 fn an_actual_open_store_cannot_supply_a_confirmed_close_receipt() { 487 futures::executor::block_on(async { 488 let client = Client::preview(); 489 let open = client.storage_status().await.unwrap(); 490 assert_eq!(open.shutdown(), ShutdownState::Open); 491 assert_eq!( 492 CloseReceipt::confirmed(open).unwrap_err().code(), 493 Code::StorageFailure 494 ); 495 let closed = client.close().await.unwrap(); 496 let observed = client.storage_status().await.unwrap(); 497 assert_eq!(CloseReceipt::confirmed(observed).unwrap(), closed); 498 }); 499 } 500 }