lib

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

commit 352d020cd11aa4a1a5d02c9eca7a8ff7b23bd48b
parent b6f927c4d484ed2f8afcf171a83f2c8f967fb4d4
Author: triesap <tyson@radroots.org>
Date:   Sat, 17 Oct 2026 13:34:18 +0000

execution: Own bounded session work and resumable shutdown

- Share one fixed admission limit across cloned session handles.
- Retain resource ownership through executor work and interrupt pending startup on close.
- Resume ordered shutdown after cancellation with storage closed last.
- Verify lifecycle races, native thread bounds and local WASM host compilation.

Diffstat:
MCargo.lock | 1+
Acontracts/execution/session.v1.json | 18++++++++++++++++++
Mcrates/execution/Cargo.toml | 8++++++++
Mcrates/execution/README.md | 28++++++++++++++++++++++++----
Mcrates/execution/src/error.rs | 10++++++++++
Mcrates/execution/src/lib.rs | 6++++++
Acrates/execution/src/session/host.rs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/src/session/mod.rs | 256+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acrates/execution/tests/session.rs | 388+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 765 insertions(+), 4 deletions(-)

diff --git a/Cargo.lock b/Cargo.lock @@ -3154,6 +3154,7 @@ dependencies = [ name = "radroots_execution" version = "0.1.0-alpha" dependencies = [ + "futures", "radroots_domain", ] diff --git a/contracts/execution/session.v1.json b/contracts/execution/session.v1.json @@ -0,0 +1,18 @@ +{ + "schema": "radroots.execution.session.v1", + "package": "radroots_execution", + "feature": "session", + "implementation_scope": "Resource lifecycle coordinator; not durable command admission, authority or qualification of concrete hosts", + "construction_effects": false, + "runtime_owned": false, + "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"], + "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, + "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"] +} diff --git a/crates/execution/Cargo.toml b/crates/execution/Cargo.toml @@ -11,8 +11,16 @@ homepage.workspace = true description = "Typed Radroots command execution and recovery boundaries" readme = "README.md" +[features] +default = [] +session = ["dep:futures"] + [dependencies] radroots_domain = { workspace = true, default-features = false } +futures = { workspace = true, optional = true } + +[dev-dependencies] +futures = { workspace = true } [lints] workspace = true diff --git a/crates/execution/README.md b/crates/execution/README.md @@ -3,7 +3,10 @@ Typed command execution and recovery boundaries. The current implementation contains allocation-free errors with canonical codes, fixed diagnostic enums, four explicit retry classes and a validated operation/admission relationship. -The package supports native Rust and `no_std` targets without a runtime. +The default package supports native Rust and `no_std` targets without a runtime. +The optional `session` feature adds host resource ownership without creating +an async runtime or detached tasks. Native handles and futures are thread safe; +WASM handles use `Rc` and accept thread-local host futures. A proposed operation ID is not durable admission. Unknown signing or commit outcomes keep the original identity and require exact-operation continuation @@ -52,6 +55,23 @@ let _ = Error { }; ``` -The package is unpublished while the shared facade is migrated. It does not -yet implement command admission, durable operations, signing, outbox workers, -inventory authority, public listing/private chat execution or bindings. +With `session`, `Session::new` takes explicit resources and a nonzero in-flight +limit. Construction performs no work. Awaiting `start` starts the host's bounded +workers; only successful startup enables resource admission. Cloned handles +share the same gate. `WorkPermit` retains resources and capacity for owned +executor work, independently of its caller's observation. It is not durable +command admission. Executors must retain it through result/uncertainty storage. + +On its first poll, `close` permanently closes admission and interrupts pending +startup. It then quiesces workers, drains permits, disconnects transports/auth, +disposes callbacks and closes storage last. Successful shutdown stages are +retained across cancellation or known failure. Awaiting close again resumes the +unfinished host hook. Hosts must independently preserve their own partial hook +progress and obtained results. Dropping an unpolled close performs no shutdown; +dropping handles or permits never claims durable completion. + +The package is unpublished while the shared facade is migrated. The session +coordinator is tested with controlled hosts; concrete journal/network/browser +hosts still require qualification. It does not yet implement durable commands, +signing, outbox workers, inventory authority, public listing/private chat +execution, participant attachment or bindings. 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 = "session")] + pub(crate) const fn session_unavailable(reason: crate::Reason) -> Self { + Self { + code: Code::CapabilityUnavailable, + context: OperationContext::proposed(None), + retry: RetryClass::Never, + detail: Some(Detail::new(crate::Field::Operation, reason)), + } + } + /// Validates the relationship between the outcome, durable identity and /// retry policy. Safe same-operation continuation never means blind reissue. pub const fn new( diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs @@ -6,6 +6,12 @@ mod diagnostic; mod error; +#[cfg(feature = "session")] +extern crate std; + +#[cfg(feature = "session")] +pub mod session; + pub use diagnostic::{Detail, Field, Reason}; pub use error::{Admission, Code, Error, InvalidErrorContext, OperationContext, RetryClass}; diff --git a/crates/execution/src/session/host.rs b/crates/execution/src/session/host.rs @@ -0,0 +1,54 @@ +use core::{future::Future, pin::Pin}; +use std::boxed::Box; + +#[cfg(target_arch = "wasm32")] +pub(crate) use std::rc::Rc as Shared; +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use std::sync::Arc as Shared; + +/// An owned host future. Browser futures remain on their originating thread. +#[cfg(not(target_arch = "wasm32"))] +pub type HostFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>; +/// An owned host future. Browser futures remain on their originating thread. +#[cfg(target_arch = "wasm32")] +pub type HostFuture<'a, T> = Pin<Box<dyn Future<Output = T> + 'a>>; + +/// Native hosts are thread safe; browser hosts may retain local callbacks. +#[cfg(not(target_arch = "wasm32"))] +pub trait HostBound: Send + Sync {} +#[cfg(not(target_arch = "wasm32"))] +impl<T: Send + Sync + ?Sized> HostBound for T {} + +/// Native hosts are thread safe; browser hosts may retain local callbacks. +#[cfg(target_arch = "wasm32")] +pub trait HostBound {} +#[cfg(target_arch = "wasm32")] +impl<T: ?Sized> HostBound for T {} + +/// Resources exclusively owned by one session, without a library-owned runtime. +/// +/// Hooks must retain progress across cancellation: repeating an unfinished hook +/// resumes it, including a result already obtained before its waiter was lost. +/// Successful hooks are not repeated. A failed hook must leave its resources +/// available for retry. No hook may report completion while its work is detached. +/// Concrete host qualification must exercise these requirements independently. +pub trait SessionHost: HostBound { + /// Starts the configured bounded workers. Repeat calls resume partial start. + /// No command admission is enabled until this hook succeeds. + fn start(&self) -> HostFuture<'_, crate::Result<()>>; + + /// Stops new background work and quiesces workers. Retain unresolved signing + /// and obtained results in their journal before releasing their work permits. + /// Existing permitted work must remain able to reach its safe boundary. + fn quiesce(&self) -> HostFuture<'_, crate::Result<()>>; + + /// Disconnects every owned transport and its authentication state. + fn disconnect(&self) -> HostFuture<'_, crate::Result<()>>; + + /// Disposes retained callbacks and subscriptions on their owning thread. + fn dispose_callbacks(&self) -> HostFuture<'_, crate::Result<()>>; + + /// Closes storage after workers, admitted work, transports and callbacks. + /// Completion must include any required checkpoint and authority release. + fn close_storage(&self) -> HostFuture<'_, crate::Result<()>>; +} diff --git a/crates/execution/src/session/mod.rs b/crates/execution/src/session/mod.rs @@ -0,0 +1,256 @@ +//! Shared session admission and resumable resource shutdown. +//! +//! This module creates no runtime or detached task. The executor, rather than a +//! caller's observation future, retains each work permit until its safe boundary. +//! A permit is resource ownership, never proof of durable command admission. + +mod host; + +pub use host::{HostBound, HostFuture, SessionHost}; + +use core::{ + future::poll_fn, + num::NonZeroU16, + task::{Poll, Waker}, +}; +use futures::lock::Mutex as AsyncMutex; +use std::sync::{Mutex, MutexGuard}; + +use crate::{Error, Reason, Result}; +use host::Shared; + +/// Session resource state, independent of durable operation state. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SessionState { + /// Resources are owned but workers have not started. + Ready, + /// Worker startup is pending or must be resumed. + Starting, + /// Startup succeeded and new work may be admitted within the fixed limit. + Running, + /// Admission is permanently closed and shutdown must be awaited or resumed. + Closing, + /// All resource shutdown hooks completed successfully. + Closed, +} + +#[derive(Clone, Copy)] +enum CloseStage { + Quiesce, + Drain, + Disconnect, + Callbacks, + Storage, + Complete, +} + +struct Gate { + state: SessionState, + active: u16, + drained: Option<Waker>, + starting: Option<Waker>, +} + +struct Inner<H> { + host: H, + limit: NonZeroU16, + gate: Mutex<Gate>, + control: AsyncMutex<CloseStage>, +} + +impl<H> Inner<H> { + fn gate(&self) -> MutexGuard<'_, Gate> { + // No user code or await runs while holding the gate. Recovery retains + // the closed-admission state if an observer panics during unwinding. + self.gate + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +/// Cloneable ownership of one coherent session. Native handles are Send/Sync; +/// browser handles use Rc and cannot cross their owning thread. +pub struct Session<H: SessionHost> { + inner: Shared<Inner<H>>, +} + +impl<H: SessionHost> Clone for Session<H> { + fn clone(&self) -> Self { + Self { + inner: self.inner.clone(), + } + } +} + +impl<H: SessionHost> Session<H> { + /// Takes ownership of already constructed resources without starting work. + /// The explicit limit bounds concurrent owned work; it cannot be enlarged. + pub fn new(host: H, maximum_in_flight: NonZeroU16) -> Self { + Self { + inner: Shared::new(Inner { + host, + limit: maximum_in_flight, + gate: Mutex::new(Gate { + state: SessionState::Ready, + active: 0, + drained: None, + starting: None, + }), + control: AsyncMutex::new(CloseStage::Quiesce), + }), + } + } + + /// Returns resource lifecycle state without claiming a durable checkpoint. + pub fn state(&self) -> SessionState { + self.inner.gate().state + } + + /// Starts or resumes startup on the caller's host executor. + /// Concurrent calls serialize; completed startup is not repeated. + pub async fn start(&self) -> Result<()> { + let _control = self.inner.control.lock().await; + { + let mut gate = self.inner.gate(); + match gate.state { + SessionState::Running => return Ok(()), + SessionState::Closing | SessionState::Closed => return Err(unavailable()), + SessionState::Ready | SessionState::Starting => gate.state = SessionState::Starting, + } + } + let mut startup = self.inner.host.start(); + let result = poll_fn(|context| { + { + let mut gate = self.inner.gate(); + if gate.state == SessionState::Closing { + return Poll::Ready(Err(unavailable())); + } + if !gate + .starting + .as_ref() + .is_some_and(|w| w.will_wake(context.waker())) + { + gate.starting = Some(context.waker().clone()); + } + } + startup.as_mut().poll(context) + }) + .await; + let mut gate = self.inner.gate(); + gate.starting = None; + result?; + if gate.state == SessionState::Closing { + return Err(unavailable()); + } + gate.state = SessionState::Running; + Ok(()) + } + + /// Reserves one unit of live resource ownership for executor work. + /// + /// The executor must move this permit into the owned operation, independently + /// 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>> { + let mut gate = self.inner.gate(); + if gate.state != SessionState::Running { + return Err(unavailable()); + } + if gate.active == self.inner.limit.get() { + return Err(Error::session_unavailable(Reason::OutOfRange)); + } + gate.active += 1; + Ok(WorkPermit { + inner: self.inner.clone(), + }) + } + + /// 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<()> { + let starting = { + let mut gate = self.inner.gate(); + if gate.state == SessionState::Closed { + return Ok(()); + } + gate.state = SessionState::Closing; + gate.starting.take() + }; + if let Some(waker) = starting { + waker.wake(); + } + let mut stage = self.inner.control.lock().await; + loop { + *stage = match *stage { + CloseStage::Quiesce => { + self.inner.host.quiesce().await?; + CloseStage::Drain + } + CloseStage::Drain => { + poll_fn(|context| { + let mut gate = self.inner.gate(); + if gate.active == 0 { + return Poll::Ready(()); + } + if !gate + .drained + .as_ref() + .is_some_and(|w| w.will_wake(context.waker())) + { + gate.drained = Some(context.waker().clone()); + } + Poll::Pending + }) + .await; + CloseStage::Disconnect + } + CloseStage::Disconnect => { + self.inner.host.disconnect().await?; + CloseStage::Callbacks + } + CloseStage::Callbacks => { + self.inner.host.dispose_callbacks().await?; + CloseStage::Storage + } + CloseStage::Storage => { + self.inner.host.close_storage().await?; + CloseStage::Complete + } + CloseStage::Complete => { + self.inner.gate().state = SessionState::Closed; + return Ok(()); + } + }; + } + } +} + +fn unavailable() -> Error { + Error::session_unavailable(Reason::Unavailable) +} + +/// Live executor work retaining the session's resources until its safe boundary. +/// Dropping a permit releases capacity; it does not cancel or roll back effects. +#[must_use = "retain the permit in owned work through its safe journal boundary"] +pub struct WorkPermit<H: SessionHost> { + inner: Shared<Inner<H>>, +} + +impl<H: SessionHost> Drop for WorkPermit<H> { + fn drop(&mut self) { + let wake = { + let mut gate = self.inner.gate(); + gate.active -= 1; + if gate.active == 0 { + gate.drained.take() + } else { + None + } + }; + if let Some(waker) = wake { + waker.wake(); + } + } +} diff --git a/crates/execution/tests/session.rs b/crates/execution/tests/session.rs @@ -0,0 +1,388 @@ +#![cfg(feature = "session")] + +use std::{ + future::Future, + num::NonZeroU16, + pin::pin, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, +}; + +use futures::{ + executor::block_on, + future::poll_fn, + task::{AtomicWaker, noop_waker}, +}; +use radroots_execution::{ + Code, Error, OperationContext, Result, RetryClass, + session::{HostFuture, Session, SessionHost, SessionState}, +}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(usize)] +enum Hook { + Start, + Quiesce, + Disconnect, + Callbacks, + Storage, +} + +#[derive(Default)] +struct Observations { + calls: Mutex<Vec<Hook>>, + completed: AtomicUsize, + blocked: AtomicUsize, + fail: AtomicUsize, + waker: AtomicWaker, +} + +struct Host(Arc<Observations>); + +impl Host { + fn run(&self, hook: Hook) -> HostFuture<'_, Result<()>> { + Box::pin(async move { + self.0.calls.lock().unwrap().push(hook); + let bit = 1 << hook as usize; + poll_fn(|context| { + self.0.waker.register(context.waker()); + if self.0.blocked.load(Ordering::SeqCst) & bit != 0 { + return Poll::Pending; + } + if self.0.fail.fetch_and(!bit, Ordering::SeqCst) & bit != 0 { + return Poll::Ready(Err(Error::new( + Code::StorageFailure, + OperationContext::proposed(None), + RetryClass::Never, + None, + ) + .unwrap())); + } + self.0.completed.fetch_or(bit, Ordering::SeqCst); + Poll::Ready(Ok(())) + }) + .await + }) + } +} + +impl SessionHost for Host { + fn start(&self) -> HostFuture<'_, Result<()>> { + self.run(Hook::Start) + } + fn quiesce(&self) -> HostFuture<'_, Result<()>> { + self.run(Hook::Quiesce) + } + fn disconnect(&self) -> HostFuture<'_, Result<()>> { + self.run(Hook::Disconnect) + } + fn dispose_callbacks(&self) -> HostFuture<'_, Result<()>> { + self.run(Hook::Callbacks) + } + fn close_storage(&self) -> HostFuture<'_, Result<()>> { + self.run(Hook::Storage) + } +} + +fn fixture(limit: u16) -> (Session<Host>, Arc<Observations>) { + let observations = Arc::new(Observations::default()); + ( + Session::new(Host(observations.clone()), NonZeroU16::new(limit).unwrap()), + observations, + ) +} + +fn poll<F: Future>(future: std::pin::Pin<&mut F>) -> Poll<F::Output> { + future.poll(&mut Context::from_waker(&noop_waker())) +} + +#[test] +fn construction_and_unpolled_futures_have_no_effects() { + let (session, observed) = fixture(2); + assert_eq!(session.state(), SessionState::Ready); + drop(session.start()); + drop(session.close()); + assert_eq!(session.state(), SessionState::Ready); + assert!(observed.calls.lock().unwrap().is_empty()); + assert_eq!( + session.admit().err().unwrap().code(), + Code::CapabilityUnavailable + ); + drop(session); + assert!(observed.calls.lock().unwrap().is_empty()); +} + +#[test] +fn startup_and_close_are_shared_idempotent_and_storage_is_last() { + let (session, observed) = fixture(1); + let clone = session.clone(); + block_on(async { + let (one, two) = futures::join!(session.start(), clone.start()); + one.unwrap(); + two.unwrap(); + assert_eq!(session.state(), SessionState::Running); + let (one, two) = futures::join!(session.close(), clone.close()); + one.unwrap(); + two.unwrap(); + }); + assert_eq!( + observed.calls.lock().unwrap().as_slice(), + &[ + Hook::Start, + Hook::Quiesce, + Hook::Disconnect, + Hook::Callbacks, + Hook::Storage + ] + ); + assert_eq!(clone.state(), SessionState::Closed); + assert!(block_on(clone.start()).is_err()); + assert!(clone.admit().is_err()); + block_on(clone.close()).unwrap(); + assert_eq!(observed.calls.lock().unwrap().len(), 5); +} + +#[test] +fn admission_is_bounded_and_close_waits_for_owned_work() { + let (session, observed) = fixture(2); + block_on(session.start()).unwrap(); + let first = session.admit().unwrap(); + let second = session.clone().admit().unwrap(); + let error = session.admit().err().unwrap(); + assert_eq!(error.code(), Code::CapabilityUnavailable); + assert_eq!(error.context(), OperationContext::proposed(None)); + let mut closing = pin!(session.close()); + assert!(poll(closing.as_mut()).is_pending()); + assert_eq!(session.state(), SessionState::Closing); + assert!(session.admit().is_err()); + assert_eq!( + observed.calls.lock().unwrap().as_slice(), + &[Hook::Start, Hook::Quiesce] + ); + drop(first); + assert!(poll(closing.as_mut()).is_pending()); + drop(second); + assert_eq!(poll(closing.as_mut()), Poll::Ready(Ok(()))); + assert_eq!(observed.calls.lock().unwrap().last(), Some(&Hook::Storage)); +} + +#[test] +fn cancellation_and_known_failure_resume_only_the_unfinished_hook() { + for hook in [ + Hook::Quiesce, + Hook::Disconnect, + Hook::Callbacks, + Hook::Storage, + ] { + for failure in [false, true] { + let (session, observed) = fixture(1); + block_on(session.start()).unwrap(); + let bit = 1 << hook as usize; + if failure { + observed.fail.store(bit, Ordering::SeqCst); + assert_eq!( + block_on(session.close()).unwrap_err().code(), + Code::StorageFailure + ); + } else { + observed.blocked.store(bit, Ordering::SeqCst); + let mut close = Box::pin(session.close()); + assert!(poll(close.as_mut()).is_pending()); + drop(close); + observed.blocked.store(0, Ordering::SeqCst); + } + assert_eq!(session.state(), SessionState::Closing); + assert!(session.admit().is_err()); + assert!(block_on(session.start()).is_err()); + block_on(session.close()).unwrap(); + let calls = observed.calls.lock().unwrap(); + let expected: Vec<_> = [ + Hook::Start, + Hook::Quiesce, + Hook::Disconnect, + Hook::Callbacks, + Hook::Storage, + ] + .into_iter() + .flat_map(|value| { + if value == hook { + vec![value, value] + } else { + vec![value] + } + }) + .collect(); + assert_eq!(*calls, expected); + assert_eq!(session.state(), SessionState::Closed); + } + } +} + +#[test] +fn canceled_drain_resumes_and_concurrent_closers_share_completion() { + let (session, observed) = fixture(1); + block_on(session.start()).unwrap(); + let work = session.admit().unwrap(); + let mut close = Box::pin(session.close()); + assert!(poll(close.as_mut()).is_pending()); + drop(close); + drop(work); + let clone = session.clone(); + block_on(async { + let (a, b) = futures::join!(clone.close(), session.close()); + a.unwrap(); + b.unwrap(); + }); + assert_eq!( + observed.calls.lock().unwrap().as_slice(), + &[ + Hook::Start, + Hook::Quiesce, + Hook::Disconnect, + Hook::Callbacks, + Hook::Storage + ] + ); +} + +#[test] +fn close_interrupts_pending_start_and_never_reopens_admission() { + let (session, observed) = fixture(1); + observed + .blocked + .store(1 << Hook::Start as usize, Ordering::SeqCst); + let mut start = Box::pin(session.start()); + assert!(poll(start.as_mut()).is_pending()); + assert_eq!(session.state(), SessionState::Starting); + assert!(session.admit().is_err()); + let mut close = Box::pin(session.close()); + assert!(poll(close.as_mut()).is_pending()); + assert_eq!(session.state(), SessionState::Closing); + assert!(matches!(poll(start.as_mut()), Poll::Ready(Err(_)))); + assert_eq!(poll(close.as_mut()), Poll::Ready(Ok(()))); + assert_eq!(observed.completed.load(Ordering::SeqCst) & 1, 0); + assert_eq!(observed.calls.lock().unwrap().last(), Some(&Hook::Storage)); +} + +#[test] +fn canceled_and_failed_startup_cannot_admit_and_may_be_resumed_or_closed() { + let (session, observed) = fixture(1); + observed.blocked.store(1, Ordering::SeqCst); + let mut start = Box::pin(session.start()); + assert!(poll(start.as_mut()).is_pending()); + drop(start); + assert!(session.admit().is_err()); + observed.blocked.store(0, Ordering::SeqCst); + observed.fail.store(1, Ordering::SeqCst); + assert!(block_on(session.start()).is_err()); + assert_eq!(session.state(), SessionState::Starting); + assert!(session.admit().is_err()); + block_on(session.start()).unwrap(); + drop(session.admit().unwrap()); + block_on(session.close()).unwrap(); + let (unstarted, _) = fixture(1); + block_on(unstarted.close()).unwrap(); + assert_eq!(unstarted.state(), SessionState::Closed); +} + +#[test] +fn work_permit_retains_resources_after_last_client_handle() { + let (session, observed) = fixture(1); + block_on(session.start()).unwrap(); + let permit = session.admit().unwrap(); + assert_eq!(Arc::strong_count(&observed), 2); + drop(session); + assert_eq!(Arc::strong_count(&observed), 2); + drop(permit); + assert_eq!(Arc::strong_count(&observed), 1); + assert_eq!(observed.calls.lock().unwrap().as_slice(), &[Hook::Start]); +} + +#[test] +fn permit_completion_and_close_wake_their_pending_observers() { + struct WakeCount(AtomicUsize); + impl futures::task::ArcWake for WakeCount { + fn wake_by_ref(arc: &Arc<Self>) { + arc.0.fetch_add(1, Ordering::SeqCst); + } + } + let counter = Arc::new(WakeCount(AtomicUsize::new(0))); + let waker = futures::task::waker(counter.clone()); + let mut context = Context::from_waker(&waker); + let (session, _) = fixture(1); + block_on(session.start()).unwrap(); + let work = session.admit().unwrap(); + let mut close = Box::pin(session.close()); + assert!(close.as_mut().poll(&mut context).is_pending()); + drop(work); + assert_eq!(counter.0.load(Ordering::SeqCst), 1); + assert_eq!(close.as_mut().poll(&mut context), Poll::Ready(Ok(()))); + + let (session, observed) = fixture(1); + observed.blocked.store(1, Ordering::SeqCst); + let mut start = Box::pin(session.start()); + assert!(start.as_mut().poll(&mut context).is_pending()); + let before = counter.0.load(Ordering::SeqCst); + let mut close = Box::pin(session.close()); + assert!(poll(close.as_mut()).is_pending()); + assert!(counter.0.load(Ordering::SeqCst) > before); + assert!(matches!(poll(start.as_mut()), Poll::Ready(Err(_)))); + assert_eq!(poll(close.as_mut()), Poll::Ready(Ok(()))); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_handles_and_futures_are_send_and_concurrent_admission_is_bounded() { + fn send_sync<T: Send + Sync>() {} + fn send<T: Send>(_: T) {} + send_sync::<Session<Host>>(); + let (session, _) = fixture(3); + send(session.start()); + send(session.close()); + block_on(session.start()).unwrap(); + let admitted: Vec<_> = std::thread::scope(|scope| { + let attempts: Vec<_> = (0..32).map(|_| scope.spawn(|| session.admit())).collect(); + attempts + .into_iter() + .filter_map(|attempt| attempt.join().unwrap().ok()) + .collect() + }); + assert_eq!(admitted.len(), 3); + drop(admitted); + block_on(session.close()).unwrap(); +} + +#[cfg(target_arch = "wasm32")] +#[test] +fn browser_host_futures_accept_thread_local_callback_state() { + use std::{cell::Cell, rc::Rc}; + struct Local(Rc<Cell<usize>>); + impl SessionHost for Local { + fn start(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async { + self.0.set(1); + Ok(()) + }) + } + fn quiesce(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async { Ok(()) }) + } + fn disconnect(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async { Ok(()) }) + } + fn dispose_callbacks(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async { Ok(()) }) + } + fn close_storage(&self) -> HostFuture<'_, Result<()>> { + Box::pin(async { Ok(()) }) + } + } + let calls = Rc::new(Cell::new(0)); + let client = Session::new(Local(calls.clone()), NonZeroU16::new(1).unwrap()); + block_on(client.start()).unwrap(); + assert_eq!(calls.get(), 1); + block_on(client.close()).unwrap(); +}