Skip to main content

rustduck_core/
host.rs

1//! Shared lifecycle state and transition validation for native plugin hosts.
2
3use crate::{Error, Result};
4
5/// The lifecycle state of a native host.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum HostState {
9    /// The host exists but has not been started.
10    Created,
11    /// The host has started native work.
12    Running,
13    /// Termination has been requested.
14    Stopping,
15    /// Native work has terminated.
16    Stopped,
17    /// Registration or native startup failed; the host cannot be reused.
18    Failed,
19}
20
21impl HostState {
22    pub(crate) const fn as_str(self) -> &'static str {
23        match self {
24            Self::Created => "created",
25            Self::Running => "running",
26            Self::Stopping => "stopping",
27            Self::Stopped => "stopped",
28            Self::Failed => "failed",
29        }
30    }
31
32    pub(crate) const fn is_active(self) -> bool {
33        matches!(self, Self::Running | Self::Stopping)
34    }
35}
36
37pub(crate) fn require_state(
38    object: &'static str,
39    operation: &'static str,
40    actual: HostState,
41    expected: HostState,
42) -> Result<()> {
43    if actual == expected {
44        Ok(())
45    } else {
46        Err(invalid_state(object, operation, actual))
47    }
48}
49
50pub(crate) fn invalid_state(
51    object: &'static str,
52    operation: &'static str,
53    state: HostState,
54) -> Error {
55    Error::InvalidState {
56        object,
57        operation,
58        state: state.as_str(),
59    }
60}
61
62#[cfg(test)]
63pub(crate) fn native_test_lock() -> std::sync::MutexGuard<'static, ()> {
64    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
65    LOCK.get_or_init(|| std::sync::Mutex::new(()))
66        .lock()
67        .expect("native lifecycle test lock")
68}