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

qaros/
pending.rs

1//! The C API's async calls (`qar_*_async`) as [`PendingCall`]: onboard and rejoin, the
2//! co-process invite, the target-app invite and kill, and the render sender's begin-frame.
3//!
4//! The header's rules for them, and what this module builds on them:
5//!
6//! - **Exactly once.** A start call that succeeds fires its result callback exactly once, on a
7//!   library thread: with the outcome, or with `QAR_STATUS_TIMEOUT` when its cancel token is
8//!   cancelled, times out or is destroyed first, or when its owner (the runtime, session or
9//!   render sender) is destroyed first, whose destroy then returns only after the callback has
10//!   returned. A start call that fails never calls back. A cancel arriving just as the call
11//!   finishes may still deliver the outcome. The callback records the outcome under a mutex and
12//!   runs the caller's `wake`; the Rust value (not `Send`) is built on the thread that polls.
13//! - **`user_state`.** The library holds one `Arc` reference to the call's state from the start
14//!   call until the result callback reclaims it. Progress callbacks borrow that reference: none
15//!   fires after the result callback.
16//! - **What the start reads.** Whatever the init points to stays in the call's state until the
17//!   callback (`keep`), wherever the header does not say it is copied during the start.
18//! - **Abandoned calls.** Dropping a [`PendingCall`] before its outcome is taken cancels the call
19//!   and hands it to its owner. A handle the callback still delivers (a session, an invite, a
20//!   render sender, a frame info) is destroyed by the owner while it lives; the owner's destroy
21//!   waits for the callback, so nothing is left after it. What the library may still use until
22//!   the callback (a D3D11 device's references) stays with the abandoned call.
23
24use std::any::Any;
25use std::ffi::{CStr, c_char, c_void};
26use std::panic::{AssertUnwindSafe, catch_unwind};
27use std::rc::Rc;
28use std::sync::mpsc::Sender;
29use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
30use std::time::Duration;
31
32use qaros_sys::{self as sys, QarApi};
33
34use crate::callbacks::Progress;
35use crate::cancel::{CancelHandle, CancelTokenInner};
36use crate::error::{Error, Result, check};
37use crate::library::LibraryInner;
38use crate::runtime::Onboarded;
39use crate::types::ActionSeverity;
40
41/// Destroys a handle a callback delivered that nobody takes, while its owner lives.
42pub(crate) type Destroy = fn(&QarApi, usize);
43
44/// What a result callback delivered: the status, the handle it hands over (0 for none) and the id
45/// it reports (the onboarding id, or a target app's peer id). Addresses are kept as integers so
46/// the state is `Send`.
47#[derive(Clone, Copy, Debug)]
48pub(crate) struct RawOutcome {
49    pub(crate) result: sys::QarResult,
50    pub(crate) handle: usize,
51    pub(crate) id: [u8; 16],
52}
53
54#[derive(Debug)]
55enum CallState {
56    Pending,
57    Delivered(RawOutcome),
58    /// The outcome went to its owner (a polled value, or a release).
59    Taken,
60}
61
62/// The call's state. One `Arc` reference belongs to the library from the start call until the
63/// result callback reclaims it.
64pub(crate) struct CallShared {
65    state: Mutex<CallState>,
66    /// Notified once the result callback has recorded its outcome.
67    called_back: Condvar,
68    progress: Option<Sender<Progress>>,
69    wake: Box<dyn Fn() + Send + Sync>,
70    /// What the init points to, never read by Rust after the start.
71    _keep: Option<Box<dyn Any + Send + Sync>>,
72}
73
74impl CallShared {
75    fn lock(&self) -> MutexGuard<'_, CallState> {
76        self.state.lock().unwrap_or_else(PoisonError::into_inner)
77    }
78
79    /// The delivered outcome, marking it taken; `None` while pending or once taken.
80    fn take_delivered(&self) -> Option<RawOutcome> {
81        let mut state = self.lock();
82        let CallState::Delivered(outcome) = *state else {
83            return None;
84        };
85        *state = CallState::Taken;
86        Some(outcome)
87    }
88
89    /// Blocks until the result callback has recorded its outcome.
90    fn wait(&self) {
91        let _state = self
92            .called_back
93            .wait_while(self.lock(), |state| matches!(*state, CallState::Pending))
94            .unwrap_or_else(PoisonError::into_inner);
95    }
96}
97
98/// Records a result callback's outcome. Called once per call, by its result trampoline.
99///
100/// # Safety
101///
102/// `user_state` is null or the `Arc::into_raw` reference [`start`] handed to the library, which
103/// the header lets the library return exactly once.
104unsafe fn deliver(user_state: *mut c_void, outcome: RawOutcome) {
105    if user_state.is_null() {
106        return;
107    }
108    // SAFETY: forwarded to the caller: the library's reference, reclaimed here once.
109    let shared = unsafe { Arc::from_raw(user_state.cast_const().cast::<CallShared>()) };
110    *shared.lock() = CallState::Delivered(outcome);
111    shared.called_back.notify_all();
112    if catch_unwind(AssertUnwindSafe(|| (shared.wake)())).is_err() {
113        log::error!("the wake callback of an async call panicked");
114    }
115}
116
117pub(crate) unsafe extern "C" fn onboard_result_trampoline(
118    status: sys::QarResult,
119    onboarding_id: *const sys::QarOnboardingId,
120    session: *mut sys::QarSession,
121    user_state: *mut c_void,
122) {
123    // SAFETY: valid for the duration of the callback when non-null.
124    let id = unsafe { onboarding_id.as_ref() }.map_or([0; 16], |id| id.data);
125    // SAFETY: the result callback of a call started by `start`, called once.
126    unsafe {
127        deliver(
128            user_state,
129            RawOutcome {
130                result: status,
131                handle: session as usize,
132                id,
133            },
134        );
135    }
136}
137
138pub(crate) unsafe extern "C" fn handle_result_trampoline<Handle>(
139    status: sys::QarResult,
140    handle: *mut Handle,
141    user_state: *mut c_void,
142) {
143    // SAFETY: the result callback of a call started by `start`, called once.
144    unsafe {
145        deliver(
146            user_state,
147            RawOutcome {
148                result: status,
149                handle: handle as usize,
150                id: [0; 16],
151            },
152        );
153    }
154}
155
156pub(crate) unsafe extern "C" fn peer_result_trampoline(
157    status: sys::QarResult,
158    peer_id: *const sys::QarPeerId,
159    user_state: *mut c_void,
160) {
161    // SAFETY: valid for the duration of the callback when non-null.
162    let id = unsafe { peer_id.as_ref() }.map_or([0; 16], |id| id.data);
163    // SAFETY: the result callback of a call started by `start`, called once.
164    unsafe {
165        deliver(
166            user_state,
167            RawOutcome {
168                result: status,
169                handle: 0,
170                id,
171            },
172        );
173    }
174}
175
176unsafe extern "C" fn progress_trampoline(
177    severity: sys::QarActionSeverity,
178    percent: f32,
179    message: *const c_char,
180    user_state: *mut c_void,
181) {
182    if user_state.is_null() {
183        return;
184    }
185    // SAFETY: the library's Arc reference keeps the state alive until the result callback, and
186    // no progress callback fires after it.
187    let shared = unsafe { &*user_state.cast_const().cast::<CallShared>() };
188    let Some(sender) = &shared.progress else {
189        return;
190    };
191    let message = if message.is_null() {
192        String::new()
193    } else {
194        // SAFETY: a valid C string for the duration of the callback.
195        unsafe { CStr::from_ptr(message) }
196            .to_string_lossy()
197            .into_owned()
198    };
199    // A disconnected receiver only means nobody listens any more.
200    let _ = sender.send(Progress {
201        severity: ActionSeverity::from_raw(severity),
202        percent,
203        message,
204    });
205}
206
207/// A call whose [`PendingCall`] was dropped before its outcome was taken; its owner keeps it.
208pub(crate) struct AbandonedCall {
209    shared: Arc<CallShared>,
210    /// Kept until the callback; the header would also accept its destruction (the call then
211    /// ends with `QAR_STATUS_TIMEOUT`).
212    _token: Rc<CancelTokenInner>,
213    destroy: Option<Destroy>,
214    function: &'static str,
215    /// What must outlive the callback on the owner's thread, released with this value.
216    owner_keep: Option<Box<dyn Any>>,
217}
218
219impl std::fmt::Debug for AbandonedCall {
220    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221        formatter
222            .debug_struct("AbandonedCall")
223            .field("function", &self.function)
224            .field("state", &*self.shared.lock())
225            .finish_non_exhaustive()
226    }
227}
228
229impl AbandonedCall {
230    /// Destroys a delivered handle; `false` while the callback is pending.
231    pub(crate) fn release_if_delivered(&self, api: &QarApi) -> bool {
232        let Some(outcome) = self.shared.take_delivered() else {
233            return false;
234        };
235        if let Some(destroy) = self.destroy
236            && outcome.handle != 0
237        {
238            destroy(api, outcome.handle);
239        }
240        true
241    }
242
243    /// Keeps `value` until this abandoned call is released, after its callback.
244    pub(crate) fn keep_until_released(&mut self, value: Box<dyn Any>) {
245        self.owner_keep = Some(value);
246    }
247
248    /// Waits for the callback, which the header guarantees and the cancel brings promptly, then
249    /// releases what it delivered.
250    pub(crate) fn settle(&self, api: &QarApi) {
251        self.shared.wait();
252        self.release_if_delivered(api);
253    }
254
255    /// After the owner's destroy, which waited for the callback: a handle delivered then has no
256    /// owner left to be destroyed under, and is leaked.
257    pub(crate) fn leak_late_delivery(self) {
258        if let Some(outcome) = self.shared.take_delivered()
259            && outcome.handle != 0
260        {
261            log::warn!(
262                "{} delivered a handle while its owner was destroyed; the handle is not released",
263                self.function
264            );
265        }
266    }
267}
268
269type Finish<T> = Box<dyn FnOnce(RawOutcome) -> Result<T>>;
270type Abandon = Box<dyn FnOnce(AbandonedCall)>;
271
272struct Call<T> {
273    shared: Arc<CallShared>,
274    token: Rc<CancelTokenInner>,
275    /// Builds the value on the owner's thread; releases a delivered handle on failure.
276    finish: Finish<T>,
277    /// Hands the call to its owner when this value drops before the outcome.
278    abandon: Abandon,
279    /// Runs before every poll: the owner releases what its abandoned calls delivered.
280    before_poll: Box<dyn Fn()>,
281    destroy: Option<Destroy>,
282    function: &'static str,
283}
284
285/// An async call in flight: a render sender creation ([`crate::Session::start_render_sender`]),
286/// an onboard or rejoin ([`crate::Runtime::start_onboard`],
287/// [`crate::Runtime::start_rejoin`]), a co-process invite
288/// ([`crate::Session::start_onboarding_invite`]), a target-app invite or kill
289/// ([`crate::Session::start_invite_target_app`], [`crate::Session::start_kill_target_app`]), or a
290/// begin-frame ([`crate::RenderSender::start_owned_frame`]). It keeps its owner alive.
291///
292/// The library calls back exactly once: with the outcome, or with
293/// [`crate::StatusCode::TIMEOUT`] once the call's cancel token is cancelled
294/// ([`PendingCall::cancel_handle`], the start's `timeout`, or dropping this value). A cancel
295/// arriving just as the call finishes may still deliver the outcome.
296///
297/// Dropping it before the outcome is taken cancels the call and returns at once. The owner keeps
298/// the call until its callback: a handle it still delivers is destroyed by the owner's next call
299/// or by the owner's teardown, whose destroy waits for the callback.
300pub struct PendingCall<T> {
301    call: Option<Call<T>>,
302}
303
304/// An async onboard or rejoin, delivering an [`Onboarded`].
305pub type PendingOnboard = PendingCall<Onboarded>;
306
307impl<T> std::fmt::Debug for PendingCall<T> {
308    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309        let call = self
310            .call
311            .as_ref()
312            .map(|call| (call.function, format!("{:?}", *call.shared.lock())));
313        formatter
314            .debug_struct("PendingCall")
315            .field("call", &call)
316            .finish()
317    }
318}
319
320/// How to start one async call and what to do with its outcome.
321pub(crate) struct CallSpec<T> {
322    pub(crate) function: &'static str,
323    pub(crate) progress: Option<Sender<Progress>>,
324    pub(crate) timeout: Option<Duration>,
325    pub(crate) wake: Box<dyn Fn() + Send + Sync>,
326    pub(crate) keep: Option<Box<dyn Any + Send + Sync>>,
327    pub(crate) finish: Finish<T>,
328    pub(crate) abandon: Abandon,
329    pub(crate) before_poll: Box<dyn Fn()>,
330    pub(crate) destroy: Option<Destroy>,
331}
332
333/// Starts the call: `start_call` passes the user state, the progress trampoline (or none) and
334/// the token's handle to the C start function and returns its result.
335pub(crate) fn start<T>(
336    library: &Rc<LibraryInner>,
337    spec: CallSpec<T>,
338    start_call: impl FnOnce(
339        *mut c_void,
340        sys::qar_progress_callback_t,
341        *mut sys::QarCancelToken,
342    ) -> sys::QarResult,
343) -> Result<PendingCall<T>> {
344    let token = Rc::new(CancelTokenInner::create(library, spec.timeout)?);
345    let progress_callback: sys::qar_progress_callback_t = spec
346        .progress
347        .as_ref()
348        .map(|_| progress_trampoline as unsafe extern "C" fn(_, _, _, _));
349    let shared = Arc::new(CallShared {
350        state: Mutex::new(CallState::Pending),
351        called_back: Condvar::new(),
352        progress: spec.progress,
353        wake: spec.wake,
354        _keep: spec.keep,
355    });
356    let user_state = Arc::into_raw(Arc::clone(&shared))
357        .cast_mut()
358        .cast::<c_void>();
359    let result = start_call(user_state, progress_callback, token.handle.as_ptr());
360    if let Err(error) = check(&library.api, spec.function, result) {
361        // The header: when the call itself returns an error, the callback never fires, so the
362        // library's reference is reclaimed here.
363        // SAFETY: the Arc::into_raw reference above, which the library did not take.
364        drop(unsafe { Arc::from_raw(user_state.cast_const().cast::<CallShared>()) });
365        return Err(error);
366    }
367    Ok(PendingCall {
368        call: Some(Call {
369            shared,
370            token,
371            finish: spec.finish,
372            abandon: spec.abandon,
373            before_poll: spec.before_poll,
374            destroy: spec.destroy,
375            function: spec.function,
376        }),
377    })
378}
379
380impl<T> PendingCall<T> {
381    /// Never blocks. `None` while the call runs; once it called back, the value or the error it
382    /// delivered ([`crate::StatusCode::TIMEOUT`] for a cancelled or timed-out call). Polling
383    /// again after that returns [`Error::InvalidArgument`].
384    pub fn poll(&mut self) -> Option<Result<T>> {
385        let Some(call) = &self.call else {
386            return Some(Err(already_taken()));
387        };
388        (call.before_poll)();
389        let outcome = call.shared.take_delivered()?;
390        let call = self.call.take()?;
391        Some((call.finish)(outcome))
392    }
393
394    /// Blocks until the library called back, which the header guarantees, and returns what
395    /// [`PendingCall::poll`] would.
396    pub fn wait(mut self) -> Result<T> {
397        let Some(call) = &self.call else {
398            return Err(already_taken());
399        };
400        call.shared.wait();
401        self.poll().unwrap_or_else(|| Err(already_taken()))
402    }
403
404    /// Cancels the call from any thread while it runs; the library then calls back with
405    /// [`crate::StatusCode::TIMEOUT`] (or the outcome, when the call was just finishing).
406    /// `None` once the outcome was taken.
407    pub fn cancel_handle(&self) -> Option<CancelHandle> {
408        self.call
409            .as_ref()
410            .map(|call| CancelHandle::for_token(&call.token))
411    }
412}
413
414fn already_taken() -> Error {
415    Error::InvalidArgument("the outcome of this pending call was already taken".to_string())
416}
417
418impl<T> Drop for PendingCall<T> {
419    fn drop(&mut self) {
420        let Some(call) = self.call.take() else {
421            return;
422        };
423        if let Some(outcome) = call.shared.take_delivered() {
424            // An unwanted value is released as it drops.
425            drop((call.finish)(outcome));
426            return;
427        }
428        if let Err(error) = call.token.cancel() {
429            log::warn!("cancelling {}: {error}", call.function);
430        }
431        (call.abandon)(AbandonedCall {
432            shared: call.shared,
433            _token: call.token,
434            destroy: call.destroy,
435            function: call.function,
436            owner_keep: None,
437        });
438    }
439}
440
441/// Keeps what an init points to alive in a call's state. The data is plain C structures and
442/// strings the library reads; Rust never reads it after the start and only frees it, which is
443/// sound from any thread.
444pub(crate) struct Keep<Data>(pub(crate) Data);
445
446// SAFETY: see the type's documentation.
447unsafe impl<Data> Send for Keep<Data> {}
448// SAFETY: see the type's documentation; there is no `&self` access.
449unsafe impl<Data> Sync for Keep<Data> {}