feat: add library lifecycle utility in omrf
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
//! Reference-counted startup/shutdown lifecycle for a DLL-style FFI library, in the spirit of
|
||||
//! COM's `CoInitialize` / `CoUninitialize`.
|
||||
//!
|
||||
//! [`LibraryLifecycle`] holds an internal reference count together with a piece of state `S`:
|
||||
//!
|
||||
//! - on the `0 -> 1` transition ([`startup`](LibraryLifecycle::startup)) the supplied init closure
|
||||
//! runs and its produced `S` is stored;
|
||||
//! - on the `-> 0` transition ([`shutdown`](LibraryLifecycle::shutdown)) the stored `S` is taken
|
||||
//! out and handed to the supplied destroy closure.
|
||||
//!
|
||||
//! Repeated calls are allowed as long as they are paired. The count and the state are guarded by a
|
||||
//! [`RwLock`]; [`with_state`](LibraryLifecycle::with_state) takes a read lock (read access proceeds
|
||||
//! concurrently) while `startup` / `shutdown` take a write lock.
|
||||
//!
|
||||
//! # Typical usage
|
||||
//!
|
||||
//! A single instance is usually stored in a `static LazyLock` and shared across all FFI entry
|
||||
//! points. The state `S` typically aggregates the library's DLL-level resources -- for example a
|
||||
//! number of [`ObjectPool`](crate::object_pool::ObjectPool)s and other globals that must be
|
||||
//! constructed on first startup and torn down on last shutdown.
|
||||
//!
|
||||
//! # Call order
|
||||
//!
|
||||
//! Every `shutdown` must match a preceding successful `startup`. Calling `shutdown` when the count
|
||||
//! is already zero is an error.
|
||||
//!
|
||||
//! # Closures
|
||||
//!
|
||||
//! Init and destroy closures are supplied **per call** (not at construction). Only the closure
|
||||
//! passed to the transition call (`0 -> 1` for init, `-> 0` for destroy) is actually run; on any
|
||||
//! other call the passed closure is dropped without being run, so callers should pass the same
|
||||
//! init/destroy each time.
|
||||
//!
|
||||
//! The init closure may fail; its error is type-erased. The destroy closure must never fail
|
||||
//! (destructor semantics) -- if its cleanup can fail it must be handled inside the closure.
|
||||
//!
|
||||
//! # Re-entrancy
|
||||
//!
|
||||
//! Closures run while the internal lock is held and **must not re-enter** the same
|
||||
//! [`LibraryLifecycle`] (the lock is not re-entrant and would deadlock).
|
||||
|
||||
use std::sync::RwLock;
|
||||
use thiserror::Error as TeError;
|
||||
|
||||
struct Inner<S> {
|
||||
count: usize,
|
||||
state: Option<S>,
|
||||
}
|
||||
|
||||
/// Reference-counted startup/shutdown lifecycle holding a piece of state `S`.
|
||||
///
|
||||
/// See the module-level documentation for the overall contract, call order, and typical usage.
|
||||
pub struct LibraryLifecycle<S> {
|
||||
inner: RwLock<Inner<S>>,
|
||||
}
|
||||
|
||||
/// Error returned by [`LibraryLifecycle`] operations.
|
||||
#[derive(Debug, TeError)]
|
||||
pub enum Error {
|
||||
/// The initialization closure failed; the original error is type-erased.
|
||||
#[error("initialization failed: {0}")]
|
||||
Init(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
|
||||
/// `shutdown` was called when the reference count was already zero (unbalanced call).
|
||||
#[error("shutdown called when reference count is already zero")]
|
||||
Underflow,
|
||||
/// The state was accessed while the lifecycle is not active (before `startup` or after the
|
||||
/// matching `shutdown`).
|
||||
#[error("state accessed while not active")]
|
||||
NotActive,
|
||||
}
|
||||
|
||||
impl<S> LibraryLifecycle<S> {
|
||||
/// Create a new lifecycle with reference count zero and no state.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
inner: RwLock::new(Inner {
|
||||
count: 0,
|
||||
state: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Increment the reference count.
|
||||
///
|
||||
/// On the `0 -> 1` transition the supplied `init` closure runs and its produced `S` is stored.
|
||||
/// If `init` fails, neither the count nor the state is changed and an error is returned.
|
||||
///
|
||||
/// On any other call (count already `> 0`) the supplied `init` is **dropped without being run**
|
||||
/// and the count is simply incremented.
|
||||
///
|
||||
/// The init closure runs under the write lock and must not re-enter this lifecycle. Its error
|
||||
/// type `E` is type-erased.
|
||||
pub fn startup<E>(&self, init: impl FnOnce() -> Result<S, E>) -> Result<(), Error>
|
||||
where
|
||||
E: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
let mut inner = self.inner.write().expect("unexpected poison lock");
|
||||
if inner.count == 0 {
|
||||
let s = init().map_err(|e| Error::Init(Box::new(e)))?;
|
||||
inner.state = Some(s);
|
||||
inner.count = 1;
|
||||
} else {
|
||||
inner.count += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Decrement the reference count.
|
||||
///
|
||||
/// On the `-> 0` transition the stored `S` is taken out and handed to the supplied `destroy`
|
||||
/// closure, which must never fail (destructor semantics). On any other call (count stays `> 0`)
|
||||
/// the supplied `destroy` is **dropped without being run** and the count is simply decremented.
|
||||
///
|
||||
/// Returns an error if the count was already zero.
|
||||
///
|
||||
/// The destroy closure runs under the write lock and must not re-enter this lifecycle.
|
||||
pub fn shutdown(&self, destroy: impl FnOnce(S)) -> Result<(), Error> {
|
||||
let mut inner = self.inner.write().expect("unexpected poison lock");
|
||||
if inner.count == 0 {
|
||||
return Err(Error::Underflow);
|
||||
}
|
||||
inner.count -= 1;
|
||||
if inner.count == 0 {
|
||||
// Invariant: state is Some whenever count > 0.
|
||||
let s = inner.state.take().expect("state present while count > 0");
|
||||
destroy(s);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Access the stored state by shared reference under a read lock.
|
||||
///
|
||||
/// Multiple `with_state` calls can run concurrently. Returns an error if the lifecycle is not
|
||||
/// currently active (count is zero).
|
||||
///
|
||||
/// `S` is immutable from the outside; if mutation is needed, build it into `S` via interior
|
||||
/// mutability (e.g. `Mutex`, atomics). The closure must not re-enter this lifecycle.
|
||||
pub fn with_state<R>(&self, f: impl FnOnce(&S) -> R) -> Result<R, Error> {
|
||||
let inner = self.inner.read().expect("unexpected poison lock");
|
||||
match &inner.state {
|
||||
Some(s) => Ok(f(s)),
|
||||
None => Err(Error::NotActive),
|
||||
}
|
||||
}
|
||||
|
||||
/// Current reference count.
|
||||
pub fn count(&self) -> usize {
|
||||
self.inner.read().expect("unexpected poison lock").count
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user