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
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::rc::Rc;
use std::sync::{Arc, Mutex, OnceLock};

use rustduck_sys::bridge::{self as sys_bridge, ffi};

use crate::buffer::{decode_utf16, encode_utf16};
use crate::error::native_exception;
use crate::{Error, Result};

/// TSDuck report severity.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Severity {
    /// Fatal error.
    Fatal = -5,
    /// Severe error.
    Severe = -4,
    /// Error.
    Error = -3,
    /// Warning.
    Warning = -2,
    /// Informational message.
    Info = -1,
    /// Verbose message.
    Verbose = 0,
    /// Debug message.
    Debug = 1,
}

impl Severity {
    const fn abi_value(self) -> i32 {
        self as i32
    }

    fn from_i32(value: i32) -> Option<Self> {
        match value {
            -5 => Some(Self::Fatal),
            -4 => Some(Self::Severe),
            -3 => Some(Self::Error),
            -2 => Some(Self::Warning),
            -1 => Some(Self::Info),
            0 => Some(Self::Verbose),
            1 => Some(Self::Debug),
            _ => None,
        }
    }
}

/// Configuration for an asynchronous TSDuck report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AsyncReportConfig {
    /// Maximum accepted severity.
    pub severity: Severity,
    /// Serialize producer calls into the report queue.
    pub synchronous_log: bool,
    /// Prefix messages with time information when supported by TSDuck.
    pub timed_log: bool,
    /// Maximum queued message count.
    pub log_message_count: usize,
}

impl Default for AsyncReportConfig {
    fn default() -> Self {
        Self {
            severity: Severity::Info,
            synchronous_log: false,
            timed_log: false,
            log_message_count: 512,
        }
    }
}

/// An error contained while forwarding a native report callback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ReportForwarderError {
    /// The native callback passed a null message pointer with a non-zero length,
    /// an odd byte length, or invalid UTF-16.
    InvalidMessage,
    /// TSDuck passed a severity value not represented by [`Severity`].
    InvalidSeverity {
        /// The unrecognized native severity value.
        severity: i32,
    },
    /// The user callback panicked. The message was discarded.
    Panic,
}

/// Thread-safe native-report callback forwarding.
///
/// A forwarder can be cloned and inspected from any thread. Its handler can run
/// on a TSDuck worker thread or, when synchronous logging is enabled, on the
/// producer thread; it must perform bounded non-blocking work. A panic is
/// contained, discards that message, and becomes visible through
/// [`Self::take_error`].
///
/// The callback receives a validated [`Severity`] and a decoded message. TSDuck's
/// callback ABI has no userdata, so a process can have only one active
/// forwarding destination. Multiple reports may share it by cloning the same
/// forwarder; [`Report::asynchronous_with_forwarder`] rejects a different
/// forwarder until every report using the active one is terminated or dropped.
#[derive(Clone)]
pub struct ReportForwarder {
    state: Arc<ReportForwarderState>,
}

type ReportForwarderCallback = dyn Fn(Severity, &str) + Send + Sync + 'static;

struct ReportForwarderState {
    callback: Arc<ReportForwarderCallback>,
    error: Mutex<Option<ReportForwarderError>>,
}

struct RegisteredReportForwarder {
    state: Arc<ReportForwarderState>,
    report_count: usize,
}

impl ReportForwarder {
    /// Creates a forwarder for decoded native log messages.
    pub fn new<F>(callback: F) -> Self
    where
        F: Fn(Severity, &str) + Send + Sync + 'static,
    {
        Self {
            state: Arc::new(ReportForwarderState {
                callback: Arc::new(callback),
                error: Mutex::new(None),
            }),
        }
    }

    /// Returns and clears the first callback error observed since the previous
    /// call.
    #[must_use]
    pub fn take_error(&self) -> Option<ReportForwarderError> {
        self.state
            .error
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .take()
    }
}

struct ActiveReportForwarder {
    state: Arc<ReportForwarderState>,
}

impl Drop for ActiveReportForwarder {
    fn drop(&mut self) {
        let mut active = active_report_forwarder()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let Some(registered) = active.as_mut() else {
            return;
        };
        if !Arc::ptr_eq(&registered.state, &self.state) {
            return;
        }
        if registered.report_count == 1 {
            *active = None;
        } else {
            registered.report_count -= 1;
        }
    }
}

fn active_report_forwarder() -> &'static Mutex<Option<RegisteredReportForwarder>> {
    static ACTIVE: OnceLock<Mutex<Option<RegisteredReportForwarder>>> = OnceLock::new();
    ACTIVE.get_or_init(|| Mutex::new(None))
}

fn acquire_report_forwarder(forwarder: &ReportForwarder) -> Result<ActiveReportForwarder> {
    let mut active = active_report_forwarder()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    match active.as_mut() {
        None => {
            *active = Some(RegisteredReportForwarder {
                state: Arc::clone(&forwarder.state),
                report_count: 1,
            });
        }
        Some(registered) if Arc::ptr_eq(&registered.state, &forwarder.state) => {
            registered.report_count += 1;
        }
        Some(_) => {
            return Err(Error::InvalidState {
                object: "ReportForwarder",
                operation: "create a forwarding report",
                state: "a different forwarder is active",
            });
        }
    }
    Ok(ActiveReportForwarder {
        state: Arc::clone(&forwarder.state),
    })
}

fn record_forwarder_error(state: &ReportForwarderState, error: ReportForwarderError) {
    let mut recorded = state
        .error
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if recorded.is_none() {
        *recorded = Some(error);
    }
}

fn dispatch_report_forwarder(severity: i32, message: &[u8], message_valid: bool) {
    let state = {
        let active = active_report_forwarder()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        active
            .as_ref()
            .map(|registered| Arc::clone(&registered.state))
    };
    let Some(state) = state else {
        return;
    };

    if !message_valid {
        record_forwarder_error(&state, ReportForwarderError::InvalidMessage);
        return;
    }
    let Some(severity) = Severity::from_i32(severity) else {
        record_forwarder_error(&state, ReportForwarderError::InvalidSeverity { severity });
        return;
    };
    let Ok(message) = decode_utf16("ReportForwarder", message) else {
        record_forwarder_error(&state, ReportForwarderError::InvalidMessage);
        return;
    };

    if catch_unwind(AssertUnwindSafe(|| (state.callback)(severity, &message))).is_err() {
        record_forwarder_error(&state, ReportForwarderError::Panic);
    }
}

/// A TSDuck report owner.
///
/// `Report` is `!Send + !Sync`. Native objects borrowing a report retain an
/// `Rc<Report>` and release their native owner before releasing that `Rc`.
pub struct Report {
    // `native` must be dropped before `_forwarder`: `RustDuckReport` waits for
    // its async worker, preventing a native callback from observing a released
    // forwarding state.
    native: cxx::UniquePtr<RustDuckReport>,
    _forwarder: Option<ActiveReportForwarder>,
    asynchronous: bool,
    terminated: bool,
}

type RustDuckReport = ffi::RustDuckReport;

impl Report {
    fn from_native(
        native: std::result::Result<cxx::UniquePtr<RustDuckReport>, cxx::Exception>,
        asynchronous: bool,
        forwarder: Option<ActiveReportForwarder>,
    ) -> Result<Rc<Self>> {
        let native = native.map_err(|error| native_exception("Report::new", error))?;
        if native.is_null() {
            return Err(Error::NativeFailure {
                operation: "Report::new",
            });
        }
        Ok(Rc::new(Self {
            native,
            _forwarder: forwarder,
            asynchronous,
            terminated: false,
        }))
    }

    /// Returns TSDuck's process-wide null report.
    pub fn null() -> Result<Rc<Self>> {
        Self::from_native(ffi::rustduck_report_null(), false, None)
    }

    /// Returns TSDuck's process-wide standard-error report.
    pub fn stderr() -> Result<Rc<Self>> {
        Self::from_native(ffi::rustduck_report_stderr(), false, None)
    }

    /// Creates an owned asynchronous report.
    pub fn asynchronous(config: AsyncReportConfig) -> Result<Rc<Self>> {
        Self::from_native(
            ffi::rustduck_report_asynchronous(
                config.severity.abi_value(),
                config.synchronous_log,
                config.timed_log,
                config.log_message_count,
            ),
            true,
            None,
        )
    }

    /// Creates an asynchronous report that forwards native diagnostics.
    ///
    /// The callback receives an owned, decoded view only for the duration of
    /// its invocation. It may run on a TSDuck worker or producer thread and
    /// must not block. `timed_log` is rejected because TSDuck's callback-report
    /// ABI does not expose that option.
    ///
    /// TSDuck's callback-report ABI has no per-report userdata. Multiple
    /// forwarding reports can run only when they clone this same forwarder; a
    /// different destination is rejected until every active report using the
    /// current one is terminated or dropped. Each report retains its forwarding
    /// state until native asynchronous shutdown has completed.
    ///
    /// # Errors
    ///
    /// Returns an error when `timed_log` is enabled, a different forwarding
    /// destination is active, or TSDuck cannot construct the native report.
    pub fn asynchronous_with_forwarder(
        config: AsyncReportConfig,
        forwarder: ReportForwarder,
    ) -> Result<Rc<Self>> {
        if config.timed_log {
            return Err(Error::InvalidArgument {
                field: "AsyncReportConfig::timed_log",
                message: "TSDuck callback reports do not support timed logging".to_owned(),
            });
        }
        if !sys_bridge::install_report_callback_dispatcher(dispatch_report_forwarder) {
            return Err(Error::InvalidState {
                object: "ReportForwarder",
                operation: "install callback dispatcher",
                state: "incompatible dispatcher installed",
            });
        }

        let active = acquire_report_forwarder(&forwarder)?;
        Self::from_native(
            ffi::rustduck_report_asynchronous_with_forwarder(
                config.severity.abi_value(),
                config.synchronous_log,
                config.log_message_count,
            ),
            true,
            Some(active),
        )
    }

    /// Changes this report's maximum severity.
    pub fn set_max_severity(&mut self, severity: Severity) -> Result<()> {
        self.ensure_active("set maximum severity")?;
        ffi::rustduck_report_set_max_severity(self.native.pin_mut(), severity.abi_value())
            .map_err(|error| native_exception("Report::set_max_severity", error))
    }

    /// Writes one message to this report.
    pub fn log(&self, severity: Severity, message: &str) -> Result<()> {
        self.ensure_active("log")?;
        let message = encode_utf16(message);
        ffi::rustduck_report_log(self.native(), severity.abi_value(), &message)
            .map_err(|error| native_exception("Report::log", error))
    }

    /// Flushes and terminates an asynchronous report.
    ///
    /// This waits for queued forwarding callbacks to finish. Calling it more
    /// than once is a no-op; static reports cannot be terminated.
    pub fn terminate(&mut self) -> Result<()> {
        if !self.asynchronous {
            return Err(Error::InvalidState {
                object: "Report",
                operation: "terminate",
                state: "static",
            });
        }
        if self.terminated {
            return Ok(());
        }
        ffi::rustduck_report_terminate(self.native.pin_mut())
            .map_err(|error| native_exception("Report::terminate", error))?;
        self.terminated = true;
        // Native termination waits for the async worker, so no callback can
        // observe the forwarding slot after it is released.
        self._forwarder.take();
        Ok(())
    }

    fn ensure_active(&self, operation: &'static str) -> Result<()> {
        if self.terminated {
            return Err(Error::InvalidState {
                object: "Report",
                operation,
                state: "terminated",
            });
        }
        Ok(())
    }

    pub(crate) fn native(&self) -> &RustDuckReport {
        self.native
            .as_ref()
            .expect("Report construction rejects null owners")
    }
}

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

    fn forwarder_test_lock() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
        LOCK.get_or_init(|| Mutex::new(()))
            .lock()
            .expect("forwarder test lock")
    }

    #[test]
    fn severity_uses_stable_abi_values() {
        assert_eq!(Severity::Error.abi_value(), -3);
        assert_eq!(Severity::from_i32(42), None);
    }

    #[test]
    fn rejects_timed_callback_reports_before_reserving_the_forwarder() {
        let forwarder = ReportForwarder::new(|_, _| {});
        assert!(matches!(
            Report::asynchronous_with_forwarder(
                AsyncReportConfig {
                    timed_log: true,
                    ..AsyncReportConfig::default()
                },
                forwarder
            ),
            Err(Error::InvalidArgument {
                field: "AsyncReportConfig::timed_log",
                ..
            })
        ));
    }

    #[test]
    fn contains_forwarder_panics() {
        let _lock = forwarder_test_lock();
        let forwarder = ReportForwarder::new(|_, _| panic!("callback"));
        let active = acquire_report_forwarder(&forwarder).expect("first forwarder");
        dispatch_report_forwarder(Severity::Info.abi_value(), &[0xFF, 0xFE, b'x', 0], true);
        assert_eq!(forwarder.take_error(), Some(ReportForwarderError::Panic));
        drop(active);
    }

    #[test]
    fn retains_the_first_callback_error() {
        let _lock = forwarder_test_lock();
        let forwarder = ReportForwarder::new(|_, _| {});
        let active = acquire_report_forwarder(&forwarder).expect("first forwarder");
        dispatch_report_forwarder(99, &[], true);
        dispatch_report_forwarder(Severity::Info.abi_value(), &[0x01], true);
        assert_eq!(
            forwarder.take_error(),
            Some(ReportForwarderError::InvalidSeverity { severity: 99 })
        );
        drop(active);
    }

    #[test]
    fn permits_reports_sharing_one_forwarder() {
        let _lock = forwarder_test_lock();
        let forwarder = ReportForwarder::new(|_, _| {});
        let first = acquire_report_forwarder(&forwarder).expect("first forwarder");
        let second = acquire_report_forwarder(&forwarder).expect("shared forwarder");
        drop(first);
        let third = acquire_report_forwarder(&forwarder).expect("remaining shared forwarder");
        drop(second);
        drop(third);
    }

    #[test]
    fn rejects_a_different_forwarder_while_one_is_active() {
        let _lock = forwarder_test_lock();
        let first = ReportForwarder::new(|_, _| {});
        let second = ReportForwarder::new(|_, _| {});
        let active = acquire_report_forwarder(&first).expect("first forwarder");
        assert!(acquire_report_forwarder(&second).is_err());
        drop(active);
    }
}