mod.rs (11025B)
1 //! Shared session admission and resumable resource shutdown. 2 //! 3 //! This module creates no runtime or detached task. The executor, rather than a 4 //! caller's observation future, retains each work permit until its safe boundary. 5 //! A permit is resource ownership, never proof of durable command admission. 6 7 pub(crate) mod host; 8 pub mod tasks; 9 10 #[cfg(feature = "workspace_session")] 11 pub mod command; 12 13 #[cfg(feature = "workspace_session")] 14 pub mod commerce; 15 16 #[cfg(feature = "workspace_session")] 17 mod stock_evidence; 18 19 #[cfg(feature = "client_session")] 20 mod client; 21 22 #[cfg(feature = "client_session")] 23 pub use client::ClientSession; 24 25 #[cfg(feature = "signer_session")] 26 mod signer; 27 28 #[cfg(feature = "signer_session")] 29 pub use signer::SignerSession; 30 31 pub use host::{HostBound, HostFuture, SessionHost}; 32 33 use core::{ 34 future::poll_fn, 35 num::NonZeroU16, 36 task::{Poll, Waker}, 37 }; 38 use futures::lock::Mutex as AsyncMutex; 39 use std::sync::{Mutex, MutexGuard}; 40 41 use crate::{Error, Reason, Result}; 42 use host::Shared; 43 44 /// Explicit task admission for a local resource session. No network is selected. 45 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 46 #[non_exhaustive] 47 pub enum StartMode { 48 /// Enables local resource work without opening sockets or replaying writes. 49 LocalOnly, 50 /// Permits explicit commands to use the configured transport. Startup 51 /// itself performs no query, publication or automatic outbox replay. 52 Online, 53 } 54 55 /// Session resource state, independent of durable operation state. 56 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 57 pub enum SessionState { 58 /// Resources are owned but workers have not started. 59 Ready, 60 /// Worker startup is pending or must be resumed. 61 Starting, 62 /// Startup succeeded and new work may be admitted within the fixed limit. 63 Running, 64 /// Admission is permanently closed and shutdown must be awaited or resumed. 65 Closing, 66 /// All resource shutdown hooks completed successfully. 67 Closed, 68 } 69 70 #[derive(Clone, Copy)] 71 enum CloseStage { 72 Quiesce, 73 DrainOwned, 74 Drain, 75 Disconnect, 76 Callbacks, 77 Storage, 78 Complete, 79 } 80 81 struct Gate { 82 state: SessionState, 83 active: u16, 84 drained: Option<Waker>, 85 starting: Option<Waker>, 86 } 87 88 struct Inner<H> { 89 host: H, 90 limit: NonZeroU16, 91 gate: Mutex<Gate>, 92 control: AsyncMutex<CloseStage>, 93 } 94 95 impl<H> Inner<H> { 96 fn gate(&self) -> MutexGuard<'_, Gate> { 97 // Keep bookkeeping short. Waker callbacks and destructors must run 98 // outside the gate, including when a pending observer is replaced. 99 self.gate 100 .lock() 101 .unwrap_or_else(std::sync::PoisonError::into_inner) 102 } 103 } 104 105 /// Cloneable ownership of one coherent session. Native handles are Send/Sync; 106 /// browser handles use Rc and cannot cross their owning thread. 107 pub struct Session<H: SessionHost> { 108 inner: Shared<Inner<H>>, 109 } 110 111 impl<H: SessionHost> Clone for Session<H> { 112 fn clone(&self) -> Self { 113 Self { 114 inner: self.inner.clone(), 115 } 116 } 117 } 118 119 impl<H: SessionHost> Session<H> { 120 /// Takes ownership of already constructed resources without starting work. 121 /// The explicit limit bounds concurrent owned work; it cannot be enlarged. 122 pub fn new(host: H, maximum_in_flight: NonZeroU16) -> Self { 123 Self { 124 inner: Shared::new(Inner { 125 host, 126 limit: maximum_in_flight, 127 gate: Mutex::new(Gate { 128 state: SessionState::Ready, 129 active: 0, 130 drained: None, 131 starting: None, 132 }), 133 control: AsyncMutex::new(CloseStage::Quiesce), 134 }), 135 } 136 } 137 138 /// Returns resource lifecycle state without claiming a durable checkpoint. 139 pub fn state(&self) -> SessionState { 140 self.inner.gate().state 141 } 142 143 /// Starts or resumes startup on the caller's host executor. 144 /// Concurrent calls serialize; completed startup is not repeated. 145 pub async fn start(&self) -> Result<()> { 146 let _control = self.inner.control.lock().await; 147 { 148 let mut gate = self.inner.gate(); 149 match gate.state { 150 SessionState::Running => return Ok(()), 151 SessionState::Closing | SessionState::Closed => return Err(unavailable()), 152 SessionState::Ready | SessionState::Starting => gate.state = SessionState::Starting, 153 } 154 } 155 let mut startup = self.inner.host.start(); 156 let result = poll_fn(|context| { 157 let replacement = context.waker().clone(); 158 let previous = { 159 let mut gate = self.inner.gate(); 160 if gate.state == SessionState::Closing { 161 return Poll::Ready(Err(unavailable())); 162 } 163 if !gate 164 .starting 165 .as_ref() 166 .is_some_and(|w| w.will_wake(context.waker())) 167 { 168 gate.starting.replace(replacement) 169 } else { 170 None 171 } 172 }; 173 drop(previous); 174 startup.as_mut().poll(context) 175 }) 176 .await; 177 let previous = { self.inner.gate().starting.take() }; 178 drop(previous); 179 result?; 180 let mut gate = self.inner.gate(); 181 if gate.state == SessionState::Closing { 182 return Err(unavailable()); 183 } 184 gate.state = SessionState::Running; 185 Ok(()) 186 } 187 188 /// Reserves one unit of live resource ownership for executor work. 189 /// 190 /// The executor must move this permit into the owned operation, independently 191 /// of caller observation, and retain it through result/uncertainty storage. 192 /// This call performs no journal write, authorization or signing. 193 pub fn admit(&self) -> Result<WorkPermit<H>> { 194 self.reserve(false) 195 } 196 197 // Attachment is resource ownership before worker startup, never command 198 // admission. It shares the same fixed bound and permanent close gate. 199 #[cfg(feature = "client_session")] 200 fn retain_resource(&self) -> Result<WorkPermit<H>> { 201 self.reserve(true) 202 } 203 204 fn reserve(&self, before_start: bool) -> Result<WorkPermit<H>> { 205 let mut gate = self.inner.gate(); 206 if matches!(gate.state, SessionState::Closing | SessionState::Closed) 207 || (!before_start && gate.state != SessionState::Running) 208 { 209 return Err(unavailable()); 210 } 211 if gate.active == self.inner.limit.get() { 212 return Err(Error::session_unavailable(Reason::OutOfRange)); 213 } 214 gate.active += 1; 215 Ok(WorkPermit { 216 inner: self.inner.clone(), 217 }) 218 } 219 220 fn stop_admission(&self) -> bool { 221 let starting = { 222 let mut gate = self.inner.gate(); 223 if gate.state == SessionState::Closed { 224 return false; 225 } 226 gate.state = SessionState::Closing; 227 gate.starting.take() 228 }; 229 if let Some(waker) = starting { 230 waker.wake(); 231 } 232 true 233 } 234 235 /// Permanently stops admission and quiesces the host without draining or 236 /// disposing resources. Composing owners must subsequently await close. 237 /// Cancellation resumes the same unfinished hook; completion is shared. 238 pub async fn quiesce(&self) -> Result<()> { 239 if !self.stop_admission() { 240 return Ok(()); 241 } 242 let mut stage = self.inner.control.lock().await; 243 if matches!(*stage, CloseStage::Quiesce) { 244 self.inner.host.quiesce().await?; 245 *stage = CloseStage::DrainOwned; 246 } 247 Ok(()) 248 } 249 250 /// Permanently closes admission on first poll, then shuts down in order. 251 /// 252 /// Cancelling this future retains its last completed stage. Awaiting close 253 /// again resumes the unfinished hook. No Drop implementation claims close. 254 pub async fn close(&self) -> Result<()> { 255 if !self.stop_admission() { 256 return Ok(()); 257 } 258 let mut stage = self.inner.control.lock().await; 259 loop { 260 *stage = match *stage { 261 CloseStage::Quiesce => { 262 self.inner.host.quiesce().await?; 263 CloseStage::DrainOwned 264 } 265 CloseStage::DrainOwned => { 266 self.inner.host.drain().await?; 267 CloseStage::Drain 268 } 269 CloseStage::Drain => { 270 poll_fn(|context| { 271 let replacement = context.waker().clone(); 272 let previous = { 273 let mut gate = self.inner.gate(); 274 if gate.active == 0 { 275 return Poll::Ready(()); 276 } 277 if !gate 278 .drained 279 .as_ref() 280 .is_some_and(|w| w.will_wake(context.waker())) 281 { 282 gate.drained.replace(replacement) 283 } else { 284 None 285 } 286 }; 287 drop(previous); 288 Poll::Pending 289 }) 290 .await; 291 CloseStage::Disconnect 292 } 293 CloseStage::Disconnect => { 294 self.inner.host.disconnect().await?; 295 CloseStage::Callbacks 296 } 297 CloseStage::Callbacks => { 298 self.inner.host.dispose_callbacks().await?; 299 CloseStage::Storage 300 } 301 CloseStage::Storage => { 302 self.inner.host.close_storage().await?; 303 CloseStage::Complete 304 } 305 CloseStage::Complete => { 306 self.inner.gate().state = SessionState::Closed; 307 return Ok(()); 308 } 309 }; 310 } 311 } 312 } 313 314 fn unavailable() -> Error { 315 Error::session_unavailable(Reason::Unavailable) 316 } 317 318 /// Live executor work retaining the session's resources until its safe boundary. 319 /// Dropping a permit releases capacity; it does not cancel or roll back effects. 320 #[must_use = "retain the permit in owned work through its safe journal boundary"] 321 pub struct WorkPermit<H: SessionHost> { 322 inner: Shared<Inner<H>>, 323 } 324 325 impl<H: SessionHost> Drop for WorkPermit<H> { 326 fn drop(&mut self) { 327 let wake = { 328 let mut gate = self.inner.gate(); 329 gate.active -= 1; 330 if gate.active == 0 { 331 gate.drained.take() 332 } else { 333 None 334 } 335 }; 336 if let Some(waker) = wake { 337 waker.wake(); 338 } 339 } 340 }