rustduck-core 1.0.0

Safe typed TSDuck core bindings for rustduck
Documentation
//! Typed, single-threaded `TSProcessor` lifecycle management.

use std::rc::Rc;
use std::sync::Arc;

use rustduck_sys::bridge::ffi;

use crate::error::native_exception;
use crate::host::{invalid_state, require_state};
use crate::memory::{MemoryInputBinding, MemoryOutputBinding, install_dispatcher};
use crate::{CallbackError, Error, HostState, MemoryInput, MemoryOutput, Report, Result};

mod config;
mod native_config;

pub use config::{ProcessorConfig, ProcessorInput, ProcessorOutput};

/// Result of an owner-thread non-blocking termination check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WaitStatus {
    /// Native processing is still active.
    Pending,
    /// Native processing has terminated.
    Stopped,
}

/// A cloneable, thread-safe request-only processor stop token.
///
/// `request` may be called from any thread, including while the owner is in
/// [`TSProcessor::start`]. It neither waits for termination nor exposes a
/// native owner; the thread holding [`TSProcessor`] must still wait before it
/// drops that owner. Requests after native deletion are no-ops.
#[derive(Clone)]
pub struct AbortToken {
    native: cxx::SharedPtr<ffi::RustDuckProcessorAbortToken>,
}

// SAFETY: the token's C++ implementation serializes access to its native
// processor pointer, waits for in-flight requests before deletion, and turns
// requests after deletion into no-ops. It exposes no owner, wait, or delete
// operation to the receiving thread.
unsafe impl Send for AbortToken {}

// SAFETY: `request` is the only operation and the C++ token protects its full
// state with a mutex, so concurrent immutable Rust references are safe.
unsafe impl Sync for AbortToken {}

impl AbortToken {
    /// Requests native processing termination without waiting for it.
    ///
    /// This is idempotent and remains safe while the owner is destroying the
    /// processor; a request made after deletion is ignored.
    pub fn request(&self) {
        if let Some(token) = self.native.as_ref() {
            // The C++ token contains native exceptions and a closed token is a
            // documented no-op. This request-only API intentionally has no
            // caller-actionable failure mode.
            let _ = ffi::rustduck_processor_abort_token_request(token);
        }
    }
}

/// A `!Send + !Sync` TSDuck processor owner.
///
/// `native` is declared before the report, private handler, and endpoint
/// leases. Therefore the native processor is deleted before any object it can
/// borrow. `Drop` aborts and waits for active work before that deletion.
pub struct TSProcessor {
    native: cxx::UniquePtr<ffi::RustDuckTSProcessor>,
    report: Rc<Report>,
    handler: Option<cxx::UniquePtr<ffi::RustDuckMemoryHandler>>,
    input_binding: Option<MemoryInputBinding>,
    output_binding: Option<MemoryOutputBinding>,
    input: Option<Arc<MemoryInput>>,
    output: Option<Arc<MemoryOutput>>,
    native_shutdown_required: bool,
    state: HostState,
}

impl TSProcessor {
    /// Creates a processor bound to `report`.
    pub fn new(report: Rc<Report>) -> Result<Self> {
        let native = ffi::rustduck_processor_new(report.native())
            .map_err(|error| native_exception("TSProcessor::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "TSProcessor::new",
            });
        }
        Ok(Self {
            native,
            report,
            handler: None,
            input_binding: None,
            output_binding: None,
            input: None,
            output: None,
            native_shutdown_required: false,
            state: HostState::Created,
        })
    }

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

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

    /// Returns a cloneable token that can request termination from any thread.
    ///
    /// The token is request-only: native waiting and destruction remain on the
    /// thread that owns this processor.
    pub fn abort_token(&self) -> AbortToken {
        AbortToken {
            native: ffi::rustduck_processor_abort_token(
                self.native
                    .as_ref()
                    .expect("TSProcessor construction rejects null owners"),
            ),
        }
    }

    /// Starts native processing with typed plugins and optional memory endpoints.
    pub fn start(&mut self, config: &ProcessorConfig) -> Result<()> {
        require_state("TSProcessor", "start", self.state, HostState::Created)?;
        config::validate(config)?;

        let input = config::memory_input(config);
        let output = config::memory_output(config);
        if input.is_some() || output.is_some() {
            install_dispatcher()?;
        }
        let handler = if input.is_some() || output.is_some() {
            let handler = ffi::rustduck_memory_handler_new()
                .map_err(|error| native_exception("TSProcessor::memory_handler", error))?;
            if handler.is_null() {
                return Err(Error::NativeFailure {
                    operation: "TSProcessor::memory_handler",
                });
            }
            Some(handler)
        } else {
            None
        };

        let input_binding = input.as_ref().map(|endpoint| endpoint.bind()).transpose()?;
        let output_binding = output
            .as_ref()
            .map(|endpoint| endpoint.bind())
            .transpose()?;

        // From here registrations can have modified native state. Store all
        // dependencies before calling native code; any subsequent failure is
        // terminal and releases the leases only after native deletion in Drop.
        self.handler = handler;
        self.input_binding = input_binding;
        self.output_binding = output_binding;
        self.input = input;
        self.output = output;

        self.native_shutdown_required = true;
        if let Err(error) = self.register_memory_handlers() {
            self.fail_memory_endpoints();
            self.state = HostState::Failed;
            return Err(error);
        }

        let native_config = self.native_config(config)?;
        let started = ffi::rustduck_processor_start(self.native.pin_mut(), &native_config)
            .map_err(|error| self.fail_after_native_exception("TSProcessor::start", error))?;
        if !started {
            self.fail_memory_endpoints();
            self.state = HostState::Failed;
            return Err(Error::NativeFailure {
                operation: "TSProcessor::start",
            });
        }
        self.state = HostState::Running;
        Ok(())
    }

    /// Requests processor abort. The host remains owned by this thread.
    pub fn abort(&mut self) -> Result<()> {
        require_state("TSProcessor", "abort", self.state, HostState::Running)?;
        self.fail_memory_endpoints();
        self.state = HostState::Stopping;
        ffi::rustduck_processor_abort(self.native.pin_mut())
            .map_err(|error| self.fail_after_native_exception("TSProcessor::abort", error))
    }

    /// Performs a non-blocking owner-thread termination check.
    ///
    /// This is intentionally a native state probe, not a helper-thread wait.
    /// A returned [`WaitStatus::Stopped`] has the same cleanup effect as
    /// [`Self::wait_for_termination`].
    pub fn try_wait(&mut self) -> Result<WaitStatus> {
        if !self.state.is_active() {
            return Err(invalid_state("TSProcessor", "try_wait", self.state));
        }
        let started = ffi::rustduck_processor_is_started(
            self.native
                .as_ref()
                .expect("TSProcessor construction rejects null owners"),
        )
        .map_err(|error| self.fail_after_native_exception("TSProcessor::try_wait", error))?;
        if started {
            Ok(WaitStatus::Pending)
        } else {
            // `isStarted` reports false only once native processing has ended.
            // Call the native owner-thread wait anyway so this transition has
            // exactly the same join/cleanup semantics as blocking wait.
            ffi::rustduck_processor_wait(self.native.pin_mut()).map_err(|error| {
                self.fail_after_native_exception("TSProcessor::try_wait", error)
            })?;
            self.finish_wait();
            Ok(WaitStatus::Stopped)
        }
    }

    /// Waits for native processing to terminate.
    pub fn wait_for_termination(&mut self) -> Result<()> {
        if !self.state.is_active() {
            return Err(invalid_state(
                "TSProcessor",
                "wait_for_termination",
                self.state,
            ));
        }
        ffi::rustduck_processor_wait(self.native.pin_mut()).map_err(|error| {
            self.fail_after_native_exception("TSProcessor::wait_for_termination", error)
        })?;
        self.finish_wait();
        Ok(())
    }

    /// Takes the latest structured error produced by a bound memory endpoint.
    pub fn take_memory_error(&self) -> Option<CallbackError> {
        self.input
            .as_ref()
            .and_then(|endpoint| endpoint.take_callback_error())
            .or_else(|| {
                self.output
                    .as_ref()
                    .and_then(|endpoint| endpoint.take_callback_error())
            })
    }

    fn finish_wait(&mut self) {
        self.close_memory_outputs();
        self.native_shutdown_required = false;
        self.state = HostState::Stopped;
    }

    fn native_config(&self, config: &ProcessorConfig) -> Result<ffi::RustDuckProcessorConfig> {
        native_config::build(
            config,
            self.input_binding.as_ref(),
            self.output_binding.as_ref(),
        )
    }

    fn register_memory_handlers(&mut self) -> Result<()> {
        let Some(handler) = self.handler.as_ref() else {
            return Ok(());
        };
        if self.input_binding.is_some() {
            ffi::rustduck_processor_register_input(self.native.pin_mut(), handler)
                .map_err(|error| native_exception("TSProcessor::register_input", error))?;
        }
        if self.output_binding.is_some() {
            ffi::rustduck_processor_register_output(self.native.pin_mut(), handler)
                .map_err(|error| native_exception("TSProcessor::register_output", error))?;
        }
        Ok(())
    }

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

    fn fail_memory_endpoints(&self) {
        if let Some(endpoint) = &self.input {
            endpoint.abort();
        }
        if let Some(endpoint) = &self.output {
            endpoint.abort();
        }
    }

    fn close_memory_outputs(&self) {
        if let Some(endpoint) = &self.output {
            endpoint.close();
        }
    }
}

impl Drop for TSProcessor {
    fn drop(&mut self) {
        if self.native_shutdown_required {
            self.fail_memory_endpoints();
            let _ = ffi::rustduck_processor_abort(self.native.pin_mut());
            let _ = ffi::rustduck_processor_wait(self.native.pin_mut());
        }
        // `native` drops first by field order. Its deletion precedes handler
        // destruction and release of endpoint bindings.
    }
}

#[cfg(test)]
mod tests {
    use std::num::NonZeroUsize;
    use std::thread;

    use super::*;
    use crate::{MemoryQueuePolicy, PluginOptions, TS_PACKET_SIZE};

    #[test]
    fn rejects_untyped_memory_plugin_before_native_state_changes() {
        let _lock = crate::host::native_test_lock();
        let report = Report::null().expect("report");
        let mut processor = TSProcessor::new(report).expect("processor");
        let config = ProcessorConfig {
            input: Some(ProcessorInput::Native(PluginOptions::without_arguments(
                "memory",
            ))),
            ..ProcessorConfig::default()
        };
        assert!(matches!(
            processor.start(&config),
            Err(Error::InvalidArgument { .. })
        ));
        assert_eq!(processor.state(), HostState::Created);
    }

    #[test]
    fn abort_token_is_send_and_sync_and_becomes_a_no_op_after_owner_drop() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<AbortToken>();

        let token = {
            let _lock = crate::host::native_test_lock();
            let report = Report::null().expect("report");
            let processor = TSProcessor::new(report).expect("processor");
            processor.abort_token()
        };
        thread::spawn(move || token.request())
            .join()
            .expect("post-drop request must not access deleted native processor");
    }

    #[test]
    fn failed_native_start_keeps_memory_lease_until_owner_drop() {
        let _lock = crate::host::native_test_lock();
        let report = Report::null().expect("report");
        let input = MemoryInput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
            MemoryQueuePolicy::Drop,
        )
        .expect("input");
        let mut processor = TSProcessor::new(report).expect("processor");
        let config = ProcessorConfig {
            input: Some(ProcessorInput::Memory(Arc::clone(&input))),
            output: Some(ProcessorOutput::Native(PluginOptions::without_arguments(
                "rustduck-definitely-not-a-plugin",
            ))),
            ..ProcessorConfig::default()
        };
        assert!(matches!(
            processor.start(&config),
            Err(Error::NativeFailure {
                operation: "TSProcessor::start"
            })
        ));
        assert_eq!(processor.state(), HostState::Failed);
        assert!(matches!(input.bind(), Err(Error::InvalidState { .. })));
        drop(processor);
        input.bind().expect("lease released after owner deletion");
    }
}