Skip to main content

rustduck_core/
processor.rs

1//! Typed, single-threaded `TSProcessor` lifecycle management.
2
3use std::rc::Rc;
4use std::sync::Arc;
5
6use rustduck_sys::bridge::ffi;
7
8use crate::error::native_exception;
9use crate::host::{invalid_state, require_state};
10use crate::memory::{MemoryInputBinding, MemoryOutputBinding, install_dispatcher};
11use crate::{CallbackError, Error, HostState, MemoryInput, MemoryOutput, Report, Result};
12
13mod config;
14mod native_config;
15
16pub use config::{ProcessorConfig, ProcessorInput, ProcessorOutput};
17
18/// Result of an owner-thread non-blocking termination check.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20#[non_exhaustive]
21pub enum WaitStatus {
22    /// Native processing is still active.
23    Pending,
24    /// Native processing has terminated.
25    Stopped,
26}
27
28/// A cloneable, thread-safe request-only processor stop token.
29///
30/// `request` may be called from any thread, including while the owner is in
31/// [`TSProcessor::start`]. It neither waits for termination nor exposes a
32/// native owner; the thread holding [`TSProcessor`] must still wait before it
33/// drops that owner. Requests after native deletion are no-ops.
34#[derive(Clone)]
35pub struct AbortToken {
36    native: cxx::SharedPtr<ffi::RustDuckProcessorAbortToken>,
37}
38
39// SAFETY: the token's C++ implementation serializes access to its native
40// processor pointer, waits for in-flight requests before deletion, and turns
41// requests after deletion into no-ops. It exposes no owner, wait, or delete
42// operation to the receiving thread.
43unsafe impl Send for AbortToken {}
44
45// SAFETY: `request` is the only operation and the C++ token protects its full
46// state with a mutex, so concurrent immutable Rust references are safe.
47unsafe impl Sync for AbortToken {}
48
49impl AbortToken {
50    /// Requests native processing termination without waiting for it.
51    ///
52    /// This is idempotent and remains safe while the owner is destroying the
53    /// processor; a request made after deletion is ignored.
54    pub fn request(&self) {
55        if let Some(token) = self.native.as_ref() {
56            // The C++ token contains native exceptions and a closed token is a
57            // documented no-op. This request-only API intentionally has no
58            // caller-actionable failure mode.
59            let _ = ffi::rustduck_processor_abort_token_request(token);
60        }
61    }
62}
63
64/// A `!Send + !Sync` TSDuck processor owner.
65///
66/// `native` is declared before the report, private handler, and endpoint
67/// leases. Therefore the native processor is deleted before any object it can
68/// borrow. `Drop` aborts and waits for active work before that deletion.
69pub struct TSProcessor {
70    native: cxx::UniquePtr<ffi::RustDuckTSProcessor>,
71    report: Rc<Report>,
72    handler: Option<cxx::UniquePtr<ffi::RustDuckMemoryHandler>>,
73    input_binding: Option<MemoryInputBinding>,
74    output_binding: Option<MemoryOutputBinding>,
75    input: Option<Arc<MemoryInput>>,
76    output: Option<Arc<MemoryOutput>>,
77    native_shutdown_required: bool,
78    state: HostState,
79}
80
81impl TSProcessor {
82    /// Creates a processor bound to `report`.
83    pub fn new(report: Rc<Report>) -> Result<Self> {
84        let native = ffi::rustduck_processor_new(report.native())
85            .map_err(|error| native_exception("TSProcessor::new", error))?;
86        if native.is_null() {
87            return Err(Error::NativeFailure {
88                operation: "TSProcessor::new",
89            });
90        }
91        Ok(Self {
92            native,
93            report,
94            handler: None,
95            input_binding: None,
96            output_binding: None,
97            input: None,
98            output: None,
99            native_shutdown_required: false,
100            state: HostState::Created,
101        })
102    }
103
104    /// Returns the report retained for the processor's native lifetime.
105    pub fn report(&self) -> &Rc<Report> {
106        &self.report
107    }
108
109    /// Returns the observable host lifecycle state.
110    pub const fn state(&self) -> HostState {
111        self.state
112    }
113
114    /// Returns a cloneable token that can request termination from any thread.
115    ///
116    /// The token is request-only: native waiting and destruction remain on the
117    /// thread that owns this processor.
118    pub fn abort_token(&self) -> AbortToken {
119        AbortToken {
120            native: ffi::rustduck_processor_abort_token(
121                self.native
122                    .as_ref()
123                    .expect("TSProcessor construction rejects null owners"),
124            ),
125        }
126    }
127
128    /// Starts native processing with typed plugins and optional memory endpoints.
129    pub fn start(&mut self, config: &ProcessorConfig) -> Result<()> {
130        require_state("TSProcessor", "start", self.state, HostState::Created)?;
131        config::validate(config)?;
132
133        let input = config::memory_input(config);
134        let output = config::memory_output(config);
135        if input.is_some() || output.is_some() {
136            install_dispatcher()?;
137        }
138        let handler = if input.is_some() || output.is_some() {
139            let handler = ffi::rustduck_memory_handler_new()
140                .map_err(|error| native_exception("TSProcessor::memory_handler", error))?;
141            if handler.is_null() {
142                return Err(Error::NativeFailure {
143                    operation: "TSProcessor::memory_handler",
144                });
145            }
146            Some(handler)
147        } else {
148            None
149        };
150
151        let input_binding = input.as_ref().map(|endpoint| endpoint.bind()).transpose()?;
152        let output_binding = output
153            .as_ref()
154            .map(|endpoint| endpoint.bind())
155            .transpose()?;
156
157        // From here registrations can have modified native state. Store all
158        // dependencies before calling native code; any subsequent failure is
159        // terminal and releases the leases only after native deletion in Drop.
160        self.handler = handler;
161        self.input_binding = input_binding;
162        self.output_binding = output_binding;
163        self.input = input;
164        self.output = output;
165
166        self.native_shutdown_required = true;
167        if let Err(error) = self.register_memory_handlers() {
168            self.fail_memory_endpoints();
169            self.state = HostState::Failed;
170            return Err(error);
171        }
172
173        let native_config = self.native_config(config)?;
174        let started = ffi::rustduck_processor_start(self.native.pin_mut(), &native_config)
175            .map_err(|error| self.fail_after_native_exception("TSProcessor::start", error))?;
176        if !started {
177            self.fail_memory_endpoints();
178            self.state = HostState::Failed;
179            return Err(Error::NativeFailure {
180                operation: "TSProcessor::start",
181            });
182        }
183        self.state = HostState::Running;
184        Ok(())
185    }
186
187    /// Requests processor abort. The host remains owned by this thread.
188    pub fn abort(&mut self) -> Result<()> {
189        require_state("TSProcessor", "abort", self.state, HostState::Running)?;
190        self.fail_memory_endpoints();
191        self.state = HostState::Stopping;
192        ffi::rustduck_processor_abort(self.native.pin_mut())
193            .map_err(|error| self.fail_after_native_exception("TSProcessor::abort", error))
194    }
195
196    /// Performs a non-blocking owner-thread termination check.
197    ///
198    /// This is intentionally a native state probe, not a helper-thread wait.
199    /// A returned [`WaitStatus::Stopped`] has the same cleanup effect as
200    /// [`Self::wait_for_termination`].
201    pub fn try_wait(&mut self) -> Result<WaitStatus> {
202        if !self.state.is_active() {
203            return Err(invalid_state("TSProcessor", "try_wait", self.state));
204        }
205        let started = ffi::rustduck_processor_is_started(
206            self.native
207                .as_ref()
208                .expect("TSProcessor construction rejects null owners"),
209        )
210        .map_err(|error| self.fail_after_native_exception("TSProcessor::try_wait", error))?;
211        if started {
212            Ok(WaitStatus::Pending)
213        } else {
214            // `isStarted` reports false only once native processing has ended.
215            // Call the native owner-thread wait anyway so this transition has
216            // exactly the same join/cleanup semantics as blocking wait.
217            ffi::rustduck_processor_wait(self.native.pin_mut()).map_err(|error| {
218                self.fail_after_native_exception("TSProcessor::try_wait", error)
219            })?;
220            self.finish_wait();
221            Ok(WaitStatus::Stopped)
222        }
223    }
224
225    /// Waits for native processing to terminate.
226    pub fn wait_for_termination(&mut self) -> Result<()> {
227        if !self.state.is_active() {
228            return Err(invalid_state(
229                "TSProcessor",
230                "wait_for_termination",
231                self.state,
232            ));
233        }
234        ffi::rustduck_processor_wait(self.native.pin_mut()).map_err(|error| {
235            self.fail_after_native_exception("TSProcessor::wait_for_termination", error)
236        })?;
237        self.finish_wait();
238        Ok(())
239    }
240
241    /// Takes the latest structured error produced by a bound memory endpoint.
242    pub fn take_memory_error(&self) -> Option<CallbackError> {
243        self.input
244            .as_ref()
245            .and_then(|endpoint| endpoint.take_callback_error())
246            .or_else(|| {
247                self.output
248                    .as_ref()
249                    .and_then(|endpoint| endpoint.take_callback_error())
250            })
251    }
252
253    fn finish_wait(&mut self) {
254        self.close_memory_outputs();
255        self.native_shutdown_required = false;
256        self.state = HostState::Stopped;
257    }
258
259    fn native_config(&self, config: &ProcessorConfig) -> Result<ffi::RustDuckProcessorConfig> {
260        native_config::build(
261            config,
262            self.input_binding.as_ref(),
263            self.output_binding.as_ref(),
264        )
265    }
266
267    fn register_memory_handlers(&mut self) -> Result<()> {
268        let Some(handler) = self.handler.as_ref() else {
269            return Ok(());
270        };
271        if self.input_binding.is_some() {
272            ffi::rustduck_processor_register_input(self.native.pin_mut(), handler)
273                .map_err(|error| native_exception("TSProcessor::register_input", error))?;
274        }
275        if self.output_binding.is_some() {
276            ffi::rustduck_processor_register_output(self.native.pin_mut(), handler)
277                .map_err(|error| native_exception("TSProcessor::register_output", error))?;
278        }
279        Ok(())
280    }
281
282    fn fail_after_native_exception(
283        &mut self,
284        operation: &'static str,
285        error: cxx::Exception,
286    ) -> Error {
287        self.fail_memory_endpoints();
288        self.state = HostState::Failed;
289        native_exception(operation, error)
290    }
291
292    fn fail_memory_endpoints(&self) {
293        if let Some(endpoint) = &self.input {
294            endpoint.abort();
295        }
296        if let Some(endpoint) = &self.output {
297            endpoint.abort();
298        }
299    }
300
301    fn close_memory_outputs(&self) {
302        if let Some(endpoint) = &self.output {
303            endpoint.close();
304        }
305    }
306}
307
308impl Drop for TSProcessor {
309    fn drop(&mut self) {
310        if self.native_shutdown_required {
311            self.fail_memory_endpoints();
312            let _ = ffi::rustduck_processor_abort(self.native.pin_mut());
313            let _ = ffi::rustduck_processor_wait(self.native.pin_mut());
314        }
315        // `native` drops first by field order. Its deletion precedes handler
316        // destruction and release of endpoint bindings.
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use std::num::NonZeroUsize;
323    use std::thread;
324
325    use super::*;
326    use crate::{MemoryQueuePolicy, PluginOptions, TS_PACKET_SIZE};
327
328    #[test]
329    fn rejects_untyped_memory_plugin_before_native_state_changes() {
330        let _lock = crate::host::native_test_lock();
331        let report = Report::null().expect("report");
332        let mut processor = TSProcessor::new(report).expect("processor");
333        let config = ProcessorConfig {
334            input: Some(ProcessorInput::Native(PluginOptions::without_arguments(
335                "memory",
336            ))),
337            ..ProcessorConfig::default()
338        };
339        assert!(matches!(
340            processor.start(&config),
341            Err(Error::InvalidArgument { .. })
342        ));
343        assert_eq!(processor.state(), HostState::Created);
344    }
345
346    #[test]
347    fn abort_token_is_send_and_sync_and_becomes_a_no_op_after_owner_drop() {
348        fn assert_send_sync<T: Send + Sync>() {}
349        assert_send_sync::<AbortToken>();
350
351        let token = {
352            let _lock = crate::host::native_test_lock();
353            let report = Report::null().expect("report");
354            let processor = TSProcessor::new(report).expect("processor");
355            processor.abort_token()
356        };
357        thread::spawn(move || token.request())
358            .join()
359            .expect("post-drop request must not access deleted native processor");
360    }
361
362    #[test]
363    fn failed_native_start_keeps_memory_lease_until_owner_drop() {
364        let _lock = crate::host::native_test_lock();
365        let report = Report::null().expect("report");
366        let input = MemoryInput::new(
367            NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
368            MemoryQueuePolicy::Drop,
369        )
370        .expect("input");
371        let mut processor = TSProcessor::new(report).expect("processor");
372        let config = ProcessorConfig {
373            input: Some(ProcessorInput::Memory(Arc::clone(&input))),
374            output: Some(ProcessorOutput::Native(PluginOptions::without_arguments(
375                "rustduck-definitely-not-a-plugin",
376            ))),
377            ..ProcessorConfig::default()
378        };
379        assert!(matches!(
380            processor.start(&config),
381            Err(Error::NativeFailure {
382                operation: "TSProcessor::start"
383            })
384        ));
385        assert_eq!(processor.state(), HostState::Failed);
386        assert!(matches!(input.bind(), Err(Error::InvalidState { .. })));
387        drop(processor);
388        input.bind().expect("lease released after owner deletion");
389    }
390}