rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! Fallible, single-threaded `SystemMonitor` ownership and lifecycle.

use std::path::PathBuf;
use std::rc::Rc;

use rustduck_sys::bridge::ffi;

use crate::buffer::encode_utf16;
use crate::error::native_exception;
use crate::host::{invalid_state, require_state};
use crate::{Error, HostState, Report, Result};

/// Optional system-monitor configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SystemMonitorConfig {
    /// Explicit configuration file. `None` uses TSDuck's default configuration.
    pub configuration_file: Option<PathBuf>,
}

/// A `!Send + !Sync` native system-monitor owner.
///
/// Its typed native owner is declared before the retained `Report`, ensuring
/// native destruction precedes release of the report it may still use. A live
/// monitor is stopped and waited before native deletion.
pub struct SystemMonitor {
    native: cxx::UniquePtr<ffi::RustDuckSystemMonitor>,
    report: Rc<Report>,
    native_shutdown_required: bool,
    state: HostState,
}

impl SystemMonitor {
    /// Creates a monitor without starting its native worker.
    pub fn new(report: Rc<Report>, config: Option<&SystemMonitorConfig>) -> Result<Self> {
        let config = config
            .and_then(|config| config.configuration_file.as_ref())
            .map(|path| {
                path.to_str().ok_or(Error::InvalidArgument {
                    field: "configuration_file",
                    message: "must be valid UTF-8 for the TSDuck UTF-16 boundary".to_owned(),
                })
            })
            .transpose()?
            .map(encode_utf16)
            .unwrap_or_default();
        let native = ffi::rustduck_system_monitor_new(report.native(), &config)
            .map_err(|error| native_exception("SystemMonitor::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "SystemMonitor::new",
            });
        }
        Ok(Self {
            native,
            report,
            native_shutdown_required: false,
            state: HostState::Created,
        })
    }

    /// Returns the report retained for the monitor's native lifetime.
    pub fn report(&self) -> &Rc<Report> {
        &self.report
    }

    /// Returns the monitor lifecycle state.
    pub const fn state(&self) -> HostState {
        self.state
    }

    /// Starts the native monitor worker.
    pub fn start(&mut self) -> Result<()> {
        require_state("SystemMonitor", "start", self.state, HostState::Created)?;
        self.native_shutdown_required = true;
        ffi::rustduck_system_monitor_start(self.native.pin_mut())
            .map_err(|error| self.fail_after_native_exception("SystemMonitor::start", error))?;
        self.state = HostState::Running;
        Ok(())
    }

    /// Requests monitor shutdown. Call [`Self::wait_for_termination`] before
    /// relying on the final `Stopped` state.
    pub fn stop(&mut self) -> Result<()> {
        require_state("SystemMonitor", "stop", self.state, HostState::Running)?;
        self.state = HostState::Stopping;
        ffi::rustduck_system_monitor_stop(self.native.pin_mut())
            .map_err(|error| self.fail_after_native_exception("SystemMonitor::stop", error))
    }

    /// Waits until the native worker has stopped.
    pub fn wait_for_termination(&mut self) -> Result<()> {
        if !self.state.is_active() {
            return Err(invalid_state(
                "SystemMonitor",
                "wait_for_termination",
                self.state,
            ));
        }
        ffi::rustduck_system_monitor_wait(self.native.pin_mut()).map_err(|error| {
            self.fail_after_native_exception("SystemMonitor::wait_for_termination", error)
        })?;
        self.native_shutdown_required = false;
        self.state = HostState::Stopped;
        Ok(())
    }

    fn fail_after_native_exception(
        &mut self,
        operation: &'static str,
        error: cxx::Exception,
    ) -> Error {
        self.state = HostState::Failed;
        native_exception(operation, error)
    }
}

impl Drop for SystemMonitor {
    fn drop(&mut self) {
        if self.native_shutdown_required {
            let _ = ffi::rustduck_system_monitor_stop(self.native.pin_mut());
            let _ = ffi::rustduck_system_monitor_wait(self.native.pin_mut());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lifecycle_rejects_repeated_start_before_native_work() {
        let _lock = crate::host::native_test_lock();
        let report = Report::null().expect("report");
        let mut monitor = SystemMonitor::new(report, None).expect("monitor");
        assert!(matches!(
            monitor.stop(),
            Err(Error::InvalidState {
                operation: "stop",
                ..
            })
        ));
    }
}