Skip to main content
QAROS Rust API Dev (main) · versions: Dev (main) · Developer Guide

qaros/
callbacks.rs

1//! Callback plumbing: the C API calls these trampolines on library threads.
2
3use std::ffi::{CStr, c_char, c_void};
4use std::panic::{AssertUnwindSafe, catch_unwind};
5use std::sync::mpsc::{self, Receiver, Sender};
6
7use qaros_sys::QarActionSeverity;
8
9use crate::cancel::CancelToken;
10use crate::types::ActionSeverity;
11
12/// A progress report from a blocking onboarding call.
13#[derive(Clone, Debug, PartialEq)]
14pub struct Progress {
15    pub severity: ActionSeverity,
16    pub percent: f32,
17    pub message: String,
18}
19
20/// Optional progress channel and cancellation for the blocking calls.
21#[derive(Clone, Debug, Default)]
22pub struct BlockingOptions<'token> {
23    /// Receives progress reports, sent from a library thread while the call
24    /// blocks.
25    pub progress: Option<Sender<Progress>>,
26    /// Must stay alive until the call returns, which the borrow ensures.
27    pub cancel: Option<&'token CancelToken>,
28}
29
30impl BlockingOptions<'_> {
31    pub(crate) fn cancel_pointer(&self) -> *mut qaros_sys::QarCancelToken {
32        self.cancel
33            .map_or(std::ptr::null_mut(), CancelToken::as_ptr)
34    }
35
36    pub(crate) fn progress_state(&self) -> *mut c_void {
37        self.progress
38            .as_ref()
39            .map_or(std::ptr::null_mut(), |sender| {
40                std::ptr::from_ref(sender).cast_mut().cast()
41            })
42    }
43
44    pub(crate) fn progress_callback(&self) -> qaros_sys::qar_progress_callback_t {
45        self.progress
46            .as_ref()
47            .map(|_| progress_trampoline as unsafe extern "C" fn(_, _, _, _))
48    }
49}
50
51unsafe extern "C" fn progress_trampoline(
52    severity: QarActionSeverity,
53    percent: f32,
54    message: *const c_char,
55    user_state: *mut c_void,
56) {
57    if user_state.is_null() {
58        return;
59    }
60    // SAFETY: user_state is the &Sender<Progress> from BlockingOptions, which
61    // outlives the blocking call; the docs guarantee no progress callback
62    // after the call returns.
63    let sender = unsafe { &*user_state.cast::<Sender<Progress>>() };
64    let message = if message.is_null() {
65        String::new()
66    } else {
67        // SAFETY: the docs guarantee message is a valid C string for the
68        // duration of the callback.
69        unsafe { CStr::from_ptr(message) }
70            .to_string_lossy()
71            .into_owned()
72    };
73    // A disconnected receiver only means nobody listens any more.
74    let _ = sender.send(Progress {
75        severity: ActionSeverity::from_raw(severity),
76        percent,
77        message,
78    });
79}
80
81/// A callback for subscription events. Called on library threads, possibly
82/// concurrently; it must not call blocking QAROS functions.
83pub type EventCallback<Event> = Box<dyn Fn(Event) + Send + Sync + 'static>;
84
85/// A callback that forwards events into a channel, and the receiving end.
86///
87/// ```no_run
88/// # fn demo(session: &qaros::Session) -> qaros::Result<()> {
89/// let (forward, requests) = qaros::channel();
90/// let _subscription = session.subscribe_render_requests(forward)?;
91/// let first_request = requests.recv();
92/// # Ok(()) }
93/// ```
94pub fn channel<Event: Send + 'static>() -> (impl Fn(Event) + Send + Sync + 'static, Receiver<Event>)
95{
96    let (sender, receiver) = mpsc::channel();
97    let forward = move |event: Event| {
98        // A dropped receiver means the application stopped listening.
99        let _ = sender.send(event);
100    };
101    (forward, receiver)
102}
103
104/// Runs a user callback, stopping a panic at the FFI boundary.
105pub(crate) fn deliver<Event>(callback: &EventCallback<Event>, event: Event, source: &str) {
106    if catch_unwind(AssertUnwindSafe(|| callback(event))).is_err() {
107        log::error!("a {source} callback panicked; the event was dropped");
108    }
109}