rustduck-core 1.1.0

Safe typed TSDuck core bindings for rustduck
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Typed, single-threaded `TSProcessor` lifecycle management.

use std::rc::Rc;
use std::sync::{Arc, Mutex};

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>,
    endpoints: Arc<Mutex<Option<AbortEndpoints>>>,
}

struct AbortEndpoints {
    input: Option<Arc<MemoryInput>>,
    output: Option<Arc<MemoryOutput>>,
}

// 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. Rust endpoint access is synchronized by
// its own mutex, and both endpoint types are Send + Sync.
unsafe impl Send for AbortToken {}

// SAFETY: `request` is the public operation and the C++ token protects its full
// state with a mutex. The Rust endpoint state also uses 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. Bound memory queues
    /// are aborted before the native request, waking blocked callbacks and callers.
    pub fn request(&self) {
        {
            // Lock order is endpoint attachment, then queue. Owner cleanup
            // detaches under this same lock, draining access to its endpoints.
            // Release this guard before calling native code.
            let endpoints = self
                .endpoints
                .lock()
                .unwrap_or_else(|error| error.into_inner());
            if let Some(endpoints) = endpoints.as_ref() {
                if let Some(input) = &endpoints.input {
                    input.abort();
                }
                if let Some(output) = &endpoints.output {
                    output.abort();
                }
            }
        }
        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);
        }
    }

    fn detach_endpoints(&self) {
        self.endpoints
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .take();
    }
}

/// 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>>,
    abort_token: AbortToken,
    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))?;
        let Some(native_ref) = native.as_ref() else {
            return Err(Error::NativeFailure {
                operation: "TSProcessor::new",
            });
        };
        let abort_token = AbortToken {
            native: ffi::rustduck_processor_abort_token(native_ref),
            endpoints: Arc::new(Mutex::new(None)),
        };
        Ok(Self {
            native,
            report,
            handler: None,
            input_binding: None,
            output_binding: None,
            input: None,
            output: None,
            abort_token,
            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 {
        self.abort_token.clone()
    }

    /// 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
            .abort_token
            .endpoints
            .lock()
            .unwrap_or_else(|error| error.into_inner()) = Some(AbortEndpoints {
            input: self.input.as_ref().map(Arc::clone),
            output: self.output.as_ref().map(Arc::clone),
        });

        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.abort_token.detach_endpoints();
        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) {
        self.abort_token.detach_endpoints();
        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::sync::mpsc;
    use std::thread;
    use std::time::Duration;

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

    fn assert_token_wakes_callback(
        config: ProcessorConfig,
        wait_for_callback: impl FnOnce() -> bool,
        rescue: impl FnOnce(),
    ) {
        let (token_sender, token_receiver) = mpsc::channel();
        let (done_sender, done_receiver) = mpsc::channel();
        let owner = thread::spawn(move || {
            let mut processor =
                TSProcessor::new(Report::stderr().expect("report")).expect("processor");
            token_sender
                .send(processor.abort_token())
                .expect("send token");
            let started = processor.start(&config);
            if started.is_ok() {
                processor
                    .wait_for_termination()
                    .expect("wait after cancellation");
            }
            drop(processor);
            done_sender.send(()).expect("send owner completion");
        });
        let token = token_receiver
            .recv_timeout(Duration::from_secs(5))
            .expect("token");
        let waiting = wait_for_callback();
        let requester = thread::spawn(move || token.request());
        let completed = done_receiver.recv_timeout(Duration::from_secs(2));
        // Rescue a regressed implementation before joining its native owner.
        rescue();
        requester.join().expect("requester join");
        owner.join().expect("owner join");
        assert!(waiting, "native callback must reach the queue wait");
        assert!(
            completed.is_ok(),
            "token must wake the blocked native callback"
        );
    }

    #[test]
    fn abort_token_wakes_input_callbacks_during_start_and_processing() {
        let _lock = crate::host::native_test_lock();
        for initially_queued in [false, true] {
            let input = MemoryInput::new(
                NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
                MemoryQueuePolicy::Backpressure,
            )
            .expect("input");
            if initially_queued {
                input.push(&[0x47; TS_PACKET_SIZE]).expect("initial packet");
            }
            assert_token_wakes_callback(
                ProcessorConfig {
                    initial_input_packets: 1,
                    max_input_packets: 1,
                    input: Some(ProcessorInput::Memory(Arc::clone(&input))),
                    output: Some(ProcessorOutput::Native(PluginOptions::without_arguments(
                        "drop",
                    ))),
                    ..ProcessorConfig::default()
                },
                || input.inner.wait_for_waiter(),
                || input.abort(),
            );
        }
    }

    #[test]
    fn abort_token_wakes_backpressured_output_callback() {
        let _lock = crate::host::native_test_lock();
        let output = MemoryOutput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
            MemoryQueuePolicy::Backpressure,
        )
        .expect("output");
        assert_token_wakes_callback(
            ProcessorConfig {
                max_output_packets: 1,
                input: Some(ProcessorInput::Native(PluginOptions::new("null", ["3"]))),
                output: Some(ProcessorOutput::Memory(Arc::clone(&output))),
                ..ProcessorConfig::default()
            },
            || output.inner.wait_for_waiter(),
            || output.abort(),
        );
    }

    #[test]
    fn abort_token_preserves_draining_output_after_wait_and_owner_drop() {
        let _lock = crate::host::native_test_lock();
        let output = MemoryOutput::new(
            NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
            MemoryQueuePolicy::Backpressure,
        )
        .expect("output");
        let mut processor = TSProcessor::new(Report::null().expect("report")).expect("processor");
        let token = processor.abort_token();
        processor
            .start(&ProcessorConfig {
                input: Some(ProcessorInput::Native(PluginOptions::new("null", ["1"]))),
                output: Some(ProcessorOutput::Memory(Arc::clone(&output))),
                ..ProcessorConfig::default()
            })
            .expect("start");
        processor.wait_for_termination().expect("wait");
        token.request();
        drop(processor);
        token.request();
        assert_eq!(
            output.recv_shared().expect("drain").expect("packet").len(),
            TS_PACKET_SIZE
        );
        assert_eq!(output.recv_shared().expect("EOF"), None);
    }

    #[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");
    }
}