Skip to main content

rustduck_core/
system_monitor.rs

1//! Fallible, single-threaded `SystemMonitor` ownership and lifecycle.
2
3use std::path::PathBuf;
4use std::rc::Rc;
5
6use rustduck_sys::bridge::ffi;
7
8use crate::buffer::encode_utf16;
9use crate::error::native_exception;
10use crate::host::{invalid_state, require_state};
11use crate::{Error, HostState, Report, Result};
12
13/// Optional system-monitor configuration.
14#[derive(Debug, Clone, Default, PartialEq, Eq)]
15pub struct SystemMonitorConfig {
16    /// Explicit configuration file. `None` uses TSDuck's default configuration.
17    pub configuration_file: Option<PathBuf>,
18}
19
20/// A `!Send + !Sync` native system-monitor owner.
21///
22/// Its typed native owner is declared before the retained `Report`, ensuring
23/// native destruction precedes release of the report it may still use. A live
24/// monitor is stopped and waited before native deletion.
25pub struct SystemMonitor {
26    native: cxx::UniquePtr<ffi::RustDuckSystemMonitor>,
27    report: Rc<Report>,
28    native_shutdown_required: bool,
29    state: HostState,
30}
31
32impl SystemMonitor {
33    /// Creates a monitor without starting its native worker.
34    pub fn new(report: Rc<Report>, config: Option<&SystemMonitorConfig>) -> Result<Self> {
35        let config = config
36            .and_then(|config| config.configuration_file.as_ref())
37            .map(|path| {
38                path.to_str().ok_or(Error::InvalidArgument {
39                    field: "configuration_file",
40                    message: "must be valid UTF-8 for the TSDuck UTF-16 boundary".to_owned(),
41                })
42            })
43            .transpose()?
44            .map(encode_utf16)
45            .unwrap_or_default();
46        let native = ffi::rustduck_system_monitor_new(report.native(), &config)
47            .map_err(|error| native_exception("SystemMonitor::new", error))?;
48        if native.is_null() {
49            return Err(Error::NativeFailure {
50                operation: "SystemMonitor::new",
51            });
52        }
53        Ok(Self {
54            native,
55            report,
56            native_shutdown_required: false,
57            state: HostState::Created,
58        })
59    }
60
61    /// Returns the report retained for the monitor's native lifetime.
62    pub fn report(&self) -> &Rc<Report> {
63        &self.report
64    }
65
66    /// Returns the monitor lifecycle state.
67    pub const fn state(&self) -> HostState {
68        self.state
69    }
70
71    /// Starts the native monitor worker.
72    pub fn start(&mut self) -> Result<()> {
73        require_state("SystemMonitor", "start", self.state, HostState::Created)?;
74        self.native_shutdown_required = true;
75        ffi::rustduck_system_monitor_start(self.native.pin_mut())
76            .map_err(|error| self.fail_after_native_exception("SystemMonitor::start", error))?;
77        self.state = HostState::Running;
78        Ok(())
79    }
80
81    /// Requests monitor shutdown. Call [`Self::wait_for_termination`] before
82    /// relying on the final `Stopped` state.
83    pub fn stop(&mut self) -> Result<()> {
84        require_state("SystemMonitor", "stop", self.state, HostState::Running)?;
85        self.state = HostState::Stopping;
86        ffi::rustduck_system_monitor_stop(self.native.pin_mut())
87            .map_err(|error| self.fail_after_native_exception("SystemMonitor::stop", error))
88    }
89
90    /// Waits until the native worker has stopped.
91    pub fn wait_for_termination(&mut self) -> Result<()> {
92        if !self.state.is_active() {
93            return Err(invalid_state(
94                "SystemMonitor",
95                "wait_for_termination",
96                self.state,
97            ));
98        }
99        ffi::rustduck_system_monitor_wait(self.native.pin_mut()).map_err(|error| {
100            self.fail_after_native_exception("SystemMonitor::wait_for_termination", error)
101        })?;
102        self.native_shutdown_required = false;
103        self.state = HostState::Stopped;
104        Ok(())
105    }
106
107    fn fail_after_native_exception(
108        &mut self,
109        operation: &'static str,
110        error: cxx::Exception,
111    ) -> Error {
112        self.state = HostState::Failed;
113        native_exception(operation, error)
114    }
115}
116
117impl Drop for SystemMonitor {
118    fn drop(&mut self) {
119        if self.native_shutdown_required {
120            let _ = ffi::rustduck_system_monitor_stop(self.native.pin_mut());
121            let _ = ffi::rustduck_system_monitor_wait(self.native.pin_mut());
122        }
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    #[test]
131    fn lifecycle_rejects_repeated_start_before_native_work() {
132        let _lock = crate::host::native_test_lock();
133        let report = Report::null().expect("report");
134        let mut monitor = SystemMonitor::new(report, None).expect("monitor");
135        assert!(matches!(
136            monitor.stop(),
137            Err(Error::InvalidState {
138                operation: "stop",
139                ..
140            })
141        ));
142    }
143}