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

qaros/
session.rs

1use std::cell::RefCell;
2use std::ffi::c_void;
3use std::ptr::{self, NonNull};
4use std::rc::Rc;
5use std::sync::mpsc::Sender;
6use std::time::Duration;
7
8use qaros_sys::{self as sys, QarApi, QarCancelToken, QarResult, defaults};
9
10use crate::adapter::GraphicsAdapter;
11use crate::callbacks::{BlockingOptions, EventCallback, Progress, deliver};
12use crate::cancel::CancelTokenInner;
13use crate::error::{Result, check};
14use crate::invite::OnboardingInvite;
15use crate::library::{Library, require_handle};
16use crate::panel_content::PanelContent;
17use crate::panels::GuiPanels;
18use crate::peers::{PeerInfo, read_peer_info};
19use crate::pending::{self, AbandonedCall, CallSpec, Destroy, Keep, PendingCall, RawOutcome};
20use crate::pending_sender::PendingRenderSender;
21use crate::render::{
22    RenderRequest, RenderSender, RenderSenderConfig, SenderGraphics, read_render_request,
23};
24use crate::runtime::RuntimeInner;
25use crate::strings;
26use crate::types::{PeerId, QarosView, SessionId, SessionLifecycle};
27use crate::volumes::AppVolumes;
28
29/// A `QarSession`, obtained by [`crate::Runtime::rejoin`] or
30/// [`crate::Runtime::onboard`].
31///
32/// Dropping the last handle destroys the session (`qar_session_handle_destroy`)
33/// and keeps the persisted identity, so a later rejoin works. Render senders
34/// keep the session alive; the session keeps its runtime alive.
35///
36/// Subscription callback state is owned here and freed only after the
37/// session handle is destroyed. The vendored header ("Ending a
38/// subscription") guarantees that cancelling waits for a running callback,
39/// so freeing at cancel would also be sound; freeing at session end keeps a
40/// channel connected until then, which callers already rely on.
41#[derive(Debug)]
42pub struct Session {
43    pub(crate) inner: Rc<SessionInner>,
44}
45
46pub(crate) struct SessionInner {
47    pub(crate) handle: NonNull<sys::QarSession>,
48    subscriptions: RefCell<Vec<SubscriptionSlot>>,
49    /// Async invites and target-app calls whose [`PendingCall`] was dropped before the callback.
50    abandoned_calls: RefCell<Vec<AbandonedCall>>,
51    pub(crate) runtime: Rc<RuntimeInner>,
52}
53
54/// Callback state is handed to C as a raw pointer from `Box::into_raw` and
55/// never moved again; `release_state` rebuilds and drops the box.
56struct SubscriptionSlot {
57    token: Rc<CancelTokenInner>,
58    callback_state: *mut c_void,
59    release_state: unsafe fn(*mut c_void),
60}
61
62/// # Safety
63///
64/// `callback_state` must come from `Box::into_raw` of a `Box<State>` and must
65/// not be used afterwards.
66unsafe fn release_callback_state<State>(callback_state: *mut c_void) {
67    // SAFETY: forwarded to the caller.
68    drop(unsafe { Box::from_raw(callback_state.cast::<State>()) });
69}
70
71impl Drop for SubscriptionSlot {
72    fn drop(&mut self) {
73        // SAFETY: the slot owns the state; slots are dropped only after the
74        // session handle is destroyed.
75        unsafe { (self.release_state)(self.callback_state) };
76    }
77}
78
79impl std::fmt::Debug for SessionInner {
80    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        formatter
82            .debug_struct("Session")
83            .field("handle", &self.handle)
84            .field("subscriptions", &self.subscriptions.borrow().len())
85            .finish_non_exhaustive()
86    }
87}
88
89/// Guard for one subscription. Dropping it cancels delivery (through the
90/// subscription's cancel token); the callback itself stays allocated until
91/// the session is destroyed. A receiver from [`crate::channel`] therefore
92/// does not disconnect when the guard drops, only when the session does.
93#[derive(Debug)]
94#[must_use = "dropping the subscription cancels it; call detach() to keep it for the session's lifetime"]
95pub struct Subscription {
96    token: Option<Rc<CancelTokenInner>>,
97}
98
99impl Subscription {
100    /// Keeps delivering until the session is destroyed.
101    pub fn detach(mut self) {
102        self.token = None;
103    }
104
105    /// Cancels delivery, as dropping does, and reports a failed cancel.
106    pub fn cancel(mut self) -> Result<()> {
107        match self.token.take() {
108            Some(token) => token.cancel(),
109            None => Ok(()),
110        }
111    }
112}
113
114impl Drop for Subscription {
115    fn drop(&mut self) {
116        if let Some(token) = self.token.take()
117            && let Err(error) = token.cancel()
118        {
119            log::warn!("cancelling a subscription: {error}");
120        }
121    }
122}
123
124/// State behind a subscription's `user_state` pointer. Read from library
125/// threads; it holds only the API table pointer and a `Send + Sync` callback.
126pub(crate) struct CallbackState<Event> {
127    api: NonNull<QarApi>,
128    callback: EventCallback<Event>,
129}
130
131// SAFETY: `api` points into the library's Rc allocation, which outlives the
132// session and therefore every callback; QarApi is a table of function
133// pointers plus the library handle, both safe to share. The callback is
134// Send + Sync by its type.
135unsafe impl<Event> Send for CallbackState<Event> {}
136// SAFETY: as above.
137unsafe impl<Event> Sync for CallbackState<Event> {}
138
139impl<Event> CallbackState<Event> {
140    /// # Safety
141    ///
142    /// `user_state` must be the pointer registered for a live subscription
143    /// of this `Event` type.
144    pub(crate) unsafe fn from_user_state<'state>(user_state: *mut c_void) -> &'state Self {
145        // SAFETY: forwarded to the caller; the state lives until the session
146        // handle is destroyed.
147        unsafe { &*user_state.cast::<Self>() }
148    }
149
150    pub(crate) fn api(&self) -> &QarApi {
151        // SAFETY: see the Send/Sync justification above.
152        unsafe { self.api.as_ref() }
153    }
154
155    pub(crate) fn deliver(&self, event: Event, source: &str) {
156        deliver(&self.callback, event, source);
157    }
158}
159
160impl Session {
161    pub(crate) fn from_handle(handle: NonNull<sys::QarSession>, runtime: Rc<RuntimeInner>) -> Self {
162        Self {
163            inner: Rc::new(SessionInner {
164                handle,
165                subscriptions: RefCell::new(Vec::new()),
166                abandoned_calls: RefCell::new(Vec::new()),
167                runtime,
168            }),
169        }
170    }
171
172    /// The library this session belongs to.
173    pub fn library(&self) -> Library {
174        Library {
175            inner: Rc::clone(&self.inner.runtime.library),
176        }
177    }
178
179    /// The `QarSession` handle, for the functions only the raw table of
180    /// [`Library::raw_api`] reaches (the "Raw only" column of the README's coverage table), as
181    /// in `(library.raw_api().qar_impl_gui_panels_update_visible_to)(session.as_raw(), ...)`.
182    ///
183    /// Taking the pointer is safe; using it is `unsafe`, and the caller keeps these rules:
184    ///
185    /// - It is valid while this `Session` lives; never use it after the `Session` is dropped.
186    /// - Never destroy it (`qar_session_handle_destroy`): the `Session` destroys it on drop.
187    /// - The session's threading rules apply: call with it on the thread that uses this
188    ///   `Session` (no handle type is `Send`). A callback registered through a raw call runs on
189    ///   a library thread, and its state must stay alive until its subscription ends; end the
190    ///   subscription (cancel its token) before the session drops.
191    /// - A handle a raw call hands out (a peer spec, a panel, an invite) is the caller's to
192    ///   destroy with its `_handle_destroy` function.
193    pub fn as_raw(&self) -> *mut sys::QarSession {
194        self.inner.handle.as_ptr()
195    }
196
197    /// The session's id (`qar_session_get_id`).
198    pub fn id(&self) -> Result<SessionId> {
199        let api = self.inner.api();
200        let mut session_id = defaults::qar_session_id_default();
201        // SAFETY: live session handle; valid out-pointer.
202        let result = unsafe {
203            (api.qar_impl_session_get_id)(self.inner.handle.as_ptr(), &raw mut session_id)
204        };
205        check(api, "qar_session_get_id", result)?;
206        Ok(SessionId::from_raw(session_id))
207    }
208
209    /// The GPU adapter the session's graphics devices, and so every render
210    /// sender's frame textures, live on (`qar_session_get_graphics_device_id`):
211    /// the one chained at onboard or rejoin, else the one QAROS or the library
212    /// selected. Create the renderer's device on it. `None` when the session
213    /// knows no adapter. A session created
214    /// [without a graphics device](crate::OnboardExtensions::without_graphics_device) fails
215    /// with [`crate::StatusCode::GRAPHICS_DEVICE_NOT_INITIALIZED`].
216    pub fn graphics_adapter(&self) -> Result<Option<GraphicsAdapter>> {
217        let api = self.inner.api();
218        let mut device_id = defaults::qar_graphics_device_id_default();
219        let mut present = false;
220        // SAFETY: live session handle; valid out-pointers.
221        let result = unsafe {
222            (api.qar_impl_session_get_graphics_device_id)(
223                self.inner.handle.as_ptr(),
224                &raw mut device_id,
225                &raw mut present,
226            )
227        };
228        check(api, "qar_session_get_graphics_device_id", result)?;
229        if present {
230            GraphicsAdapter::from_raw(&device_id).map(Some)
231        } else {
232            Ok(None)
233        }
234    }
235
236    /// This application's own peer.
237    pub fn my_peer(&self) -> Result<PeerInfo> {
238        let api = self.inner.api();
239        let mut spec: *mut sys::QarPeerSpec = ptr::null_mut();
240        // SAFETY: live session handle; valid out-pointer.
241        let result = unsafe {
242            (api.qar_impl_session_get_my_spec)(self.inner.handle.as_ptr(), &raw mut spec)
243        };
244        check(api, "qar_session_get_my_spec", result)?;
245        let spec = OwnedHandle::new(
246            require_handle(spec, "qar_session_get_my_spec")?,
247            api.qar_impl_peer_spec_handle_destroy,
248        );
249        read_peer_info(api, spec.as_ptr())
250    }
251
252    /// Snapshot of every known peer (count-then-fetch).
253    pub fn peers(&self) -> Result<Vec<PeerInfo>> {
254        let api = self.inner.api();
255        let session = self.inner.handle.as_ptr();
256        query_owned_handles(
257            api,
258            // SAFETY: live session handle; valid out-pointer.
259            |count| unsafe { (api.qar_impl_query_peer_specs_count)(session, count) },
260            // SAFETY: the buffer holds `capacity` handle slots.
261            |handles, capacity, written| unsafe {
262                (api.qar_impl_query_peer_specs)(session, handles, capacity, written)
263            },
264            api.qar_impl_peer_spec_handle_destroy,
265            "qar_query_peer_specs",
266            |handle| read_peer_info(api, handle),
267        )
268    }
269
270    /// `qar_peer_update_display_name`.
271    pub fn set_display_name(&self, display_name: &str) -> Result<()> {
272        let api = self.inner.api();
273        let display_name = strings::to_c_string(display_name, "display name")?;
274        // SAFETY: live session handle; NUL-terminated string.
275        let result = unsafe {
276            (api.qar_impl_peer_update_display_name)(
277                self.inner.handle.as_ptr(),
278                display_name.as_ptr(),
279            )
280        };
281        check(api, "qar_peer_update_display_name", result)
282    }
283
284    /// Calls `callback` with a snapshot whenever a peer joins, leaves or
285    /// changes. Runs on library threads.
286    pub fn subscribe_peer_updates(
287        &self,
288        callback: impl Fn(PeerInfo) + Send + Sync + 'static,
289    ) -> Result<Subscription> {
290        let session = self.inner.handle.as_ptr();
291        self.inner.subscribe(
292            Box::new(callback),
293            "qar_peer_subscribe_updates",
294            |api, user_state, token| {
295                // SAFETY: live session; user_state stays valid until the
296                // session handle is destroyed.
297                unsafe {
298                    (api.qar_impl_peer_subscribe_updates)(
299                        session,
300                        Some(peer_update_trampoline),
301                        user_state,
302                        token,
303                    )
304                }
305            },
306        )
307    }
308
309    /// The session's current lifecycle state (`qar_session_get_lifecycle_state`): the session
310    /// id it is in now and, after a move, the one it moved from and why. `reason` is empty here.
311    pub fn lifecycle(&self) -> Result<SessionLifecycle> {
312        let api = self.inner.api();
313        let mut info = defaults::qar_session_lifecycle_info_default();
314        // SAFETY: live session; info is stamped and a valid out-pointer.
315        let result = unsafe {
316            (api.qar_impl_session_get_lifecycle_state)(self.inner.handle.as_ptr(), &raw mut info)
317        };
318        check(api, "qar_session_get_lifecycle_state", result)?;
319        Ok(SessionLifecycle::from_raw(&info))
320    }
321
322    /// Opens a predefined view of the QAROS Visualizer in this session's QAROS
323    /// (`qar_session_open_qaros_view`): the Pair Headset QR code, the Room Origin marker or the
324    /// setup of one device type. The app needs no `qaros://` link, no registered handler, and
325    /// never looks for QAROS itself: an installed QAROS opens it through its own `qaros.exe`, a
326    /// developer setup through the `qaros.exe` of the instance's runtime folder, else the one
327    /// beside the loaded runtime.
328    ///
329    /// Only a session onboarded as a local app can open a view (`ARGUMENT_NOT_SUPPORTED`
330    /// otherwise); `ONBOARDING_HUB_UNREACHABLE` when this session's QAROS has no `qaros.exe`
331    /// where it should be or it could not be started; `NOT_IMPLEMENTED` off Windows. Returns
332    /// once the view was handed over, not when it shows.
333    pub fn open_qaros_view(&self, view: QarosView) -> Result<()> {
334        let api = self.inner.api();
335        let mut info = defaults::qar_open_qaros_view_info_default();
336        (info.view, info.device_kind) = view.to_raw();
337        // SAFETY: live session handle; info is stamped and outlives the call.
338        let result = unsafe {
339            (api.qar_impl_session_open_qaros_view)(self.inner.handle.as_ptr(), &raw const info)
340        };
341        check(api, "qar_session_open_qaros_view", result)
342    }
343
344    /// Calls `callback` with each lifecycle state of the session
345    /// (`qar_session_subscribe_lifecycle`): first the current one, then every change. Runs on
346    /// library threads; hand the snapshot to the app's own thread. On a new session id, get or
347    /// create again what the app keys by it (app volumes, panels, senders); on
348    /// [`crate::SessionLifecycleState::RePairRequired`], drop the session and onboard again.
349    pub fn subscribe_lifecycle(
350        &self,
351        callback: impl Fn(SessionLifecycle) + Send + Sync + 'static,
352    ) -> Result<Subscription> {
353        let session = self.inner.handle.as_ptr();
354        self.inner.subscribe(
355            Box::new(callback),
356            "qar_session_subscribe_lifecycle",
357            |api, user_state, token| {
358                // SAFETY: as in subscribe_peer_updates.
359                unsafe {
360                    (api.qar_impl_session_subscribe_lifecycle)(
361                        session,
362                        Some(session_lifecycle_trampoline),
363                        user_state,
364                        token,
365                    )
366                }
367            },
368        )
369    }
370
371    /// Calls `callback` for each incoming render stream request (for example
372    /// from a visualizer). Runs on library threads; create the sender on the
373    /// session's thread.
374    pub fn subscribe_render_requests(
375        &self,
376        callback: impl Fn(RenderRequest) + Send + Sync + 'static,
377    ) -> Result<Subscription> {
378        let session = self.inner.handle.as_ptr();
379        self.inner.subscribe(
380            Box::new(callback),
381            "qar_render_sender_subscribe_requests",
382            |api, user_state, token| {
383                // SAFETY: as in subscribe_peer_updates.
384                unsafe {
385                    (api.qar_impl_render_sender_subscribe_requests)(
386                        session,
387                        Some(render_request_trampoline),
388                        user_state,
389                        token,
390                    )
391                }
392            },
393        )
394    }
395
396    /// `qar_render_sender_create` with the CPU graphics API.
397    pub fn create_render_sender(
398        &self,
399        config: &RenderSenderConfig,
400        options: &BlockingOptions<'_>,
401    ) -> Result<RenderSender> {
402        RenderSender::create(&self.inner, config, &SenderGraphics::Cpu, options)
403    }
404
405    /// Starts `qar_render_sender_create_async` with the CPU graphics API and
406    /// returns at once; [`PendingRenderSender::poll`] picks the sender up on
407    /// a later frame. `timeout` cancels the creation through its cancel
408    /// token. `wake` runs on a library thread right after the library called
409    /// back, for example to request a repaint that then polls. See
410    /// [`PendingRenderSender`] for dropping a creation before it completes.
411    pub fn start_render_sender(
412        &self,
413        config: &RenderSenderConfig,
414        timeout: Option<Duration>,
415        wake: impl Fn() + Send + Sync + 'static,
416    ) -> Result<PendingRenderSender> {
417        crate::pending_sender::start(
418            &self.inner,
419            config,
420            &SenderGraphics::Cpu,
421            timeout,
422            Box::new(wake),
423        )
424    }
425
426    /// `qar_render_sender_create` with the Vulkan graphics API: QAROS creates
427    /// the frame images on `vulkan.device` and hands them out per frame
428    /// through [`crate::OwnedFrame::vulkan_frame`]. Use
429    /// [`crate::FrameLayout::SeparatedTextures`] for one image per eye and
430    /// kind, as QuaternAR's cube does. See [`crate::vulkan`] for the frame
431    /// protocol.
432    ///
433    /// # Safety
434    ///
435    /// - `vulkan.physical_device` and `vulkan.device` are valid handles, the
436    ///   device was created from that physical device, on the adapter this
437    ///   session was onboarded or rejoined with, and enables
438    ///   [`crate::vulkan::required_device_extensions`].
439    /// - The device outlives the returned sender and every frame and image
440    ///   handle taken from it.
441    #[cfg(feature = "vulkan")]
442    pub unsafe fn create_vulkan_render_sender(
443        &self,
444        config: &RenderSenderConfig,
445        vulkan: crate::vulkan::VulkanStreamParams,
446        options: &BlockingOptions<'_>,
447    ) -> Result<RenderSender> {
448        RenderSender::create(
449            &self.inner,
450            config,
451            &SenderGraphics::Vulkan(vulkan),
452            options,
453        )
454    }
455
456    /// [`Session::start_render_sender`] with the Vulkan graphics API, the
457    /// non-blocking form of [`Session::create_vulkan_render_sender`].
458    ///
459    /// # Safety
460    ///
461    /// As for [`Session::create_vulkan_render_sender`], and the device must
462    /// also stay valid for as long as the library may still create a sender
463    /// on it: until this creation's sender is taken and dropped; if the
464    /// [`PendingRenderSender`] is dropped first, until the session is
465    /// dropped; and if that creation had not called back by then, until the
466    /// library is dropped.
467    #[cfg(feature = "vulkan")]
468    pub unsafe fn start_vulkan_render_sender(
469        &self,
470        config: &RenderSenderConfig,
471        vulkan: crate::vulkan::VulkanStreamParams,
472        timeout: Option<Duration>,
473        wake: impl Fn() + Send + Sync + 'static,
474    ) -> Result<PendingRenderSender> {
475        crate::pending_sender::start(
476            &self.inner,
477            config,
478            &SenderGraphics::Vulkan(vulkan),
479            timeout,
480            Box::new(wake),
481        )
482    }
483
484    /// `qar_render_sender_create` with the D3D11 graphics API: QAROS creates the frame's
485    /// shared textures on the device in `d3d11` and hands them out per frame through
486    /// [`crate::OwnedFrame::d3d11_frame`]. See [`crate::d3d11`] for the frame protocol. The
487    /// sender keeps the references `D3D11StreamParams::new` (Windows) took on the device
488    /// and context until it is destroyed, and its session with it when it held the last
489    /// reference.
490    ///
491    /// # Safety
492    ///
493    /// - The immediate context in `d3d11` is used only on the thread that drives this session
494    ///   and its senders, or the device has multithread protection on: QAROS uses the context
495    ///   at times and on threads the header does not document, and a D3D11 immediate context
496    ///   is not thread-safe.
497    /// - Parameters from [`crate::d3d11::D3D11StreamParams::from_raw`] hold valid pointers as
498    ///   long as that function requires.
499    ///
500    /// The device should be on the adapter this session was onboarded or rejoined with
501    /// ([`Session::graphics_adapter`]); the header creates the session's devices there.
502    #[cfg(qaros_d3d11)]
503    pub unsafe fn create_d3d11_render_sender(
504        &self,
505        config: &RenderSenderConfig,
506        d3d11: crate::d3d11::D3D11StreamParams,
507        options: &BlockingOptions<'_>,
508    ) -> Result<RenderSender> {
509        RenderSender::create(&self.inner, config, &SenderGraphics::D3D11(d3d11), options)
510    }
511
512    /// [`Session::start_render_sender`] with the D3D11 graphics API, the non-blocking form of
513    /// [`Session::create_d3d11_render_sender`]. The device references stay with the creation:
514    /// with the sender once taken; with the session when the [`PendingRenderSender`] is
515    /// dropped first, until its callback comes; and for good when it never comes.
516    ///
517    /// # Safety
518    ///
519    /// As for [`Session::create_d3d11_render_sender`]. Parameters from
520    /// [`crate::d3d11::D3D11StreamParams::from_raw`] must also stay valid for as long as the
521    /// library may still create a sender on them: until this creation's sender is taken and
522    /// its session dropped; if the [`PendingRenderSender`] is dropped first, until the session
523    /// is dropped; and if that creation had not called back by then, until the process ends.
524    #[cfg(qaros_d3d11)]
525    pub unsafe fn start_d3d11_render_sender(
526        &self,
527        config: &RenderSenderConfig,
528        d3d11: crate::d3d11::D3D11StreamParams,
529        timeout: Option<Duration>,
530        wake: impl Fn() + Send + Sync + 'static,
531    ) -> Result<PendingRenderSender> {
532        crate::pending_sender::start(
533            &self.inner,
534            config,
535            &SenderGraphics::D3D11(d3d11),
536            timeout,
537            Box::new(wake),
538        )
539    }
540
541    /// Destroys what async calls dropped before their callback delivered since: a render
542    /// sender, an invite. Every `start_*` and every poll of a [`crate::PendingCall`] of this
543    /// session do it too; call this regularly (once per frame) so such a sender does not stay
544    /// connected to its target while no other call runs.
545    pub fn release_abandoned_creations(&self) {
546        self.inner.release_delivered_abandoned_calls();
547    }
548
549    /// The session's app volume operations.
550    pub fn app_volumes(&self) -> AppVolumes<'_> {
551        AppVolumes::new(&self.inner)
552    }
553
554    /// The session's GUI panel operations.
555    pub fn gui_panels(&self) -> GuiPanels<'_> {
556        GuiPanels::new(&self.inner)
557    }
558
559    /// Web pages this session serves to served GUI panels, and their messages.
560    pub fn panel_content(&self) -> PanelContent<'_> {
561        PanelContent::new(&self.inner)
562    }
563
564    /// Replaces the device this application describes itself as
565    /// (`qar_peer_update_device_identity`), as [`crate::PeerPresentation::device_identity`] sets
566    /// it at onboard or rejoin. A category other than the [`crate::SourceDeviceCategory`] values
567    /// cannot be expressed; an empty device id fails with
568    /// [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`].
569    pub fn update_device_identity(&self, identity: &crate::DeviceIdentity) -> Result<()> {
570        let storage = crate::device::DeviceIdentityStorage::new(identity)?;
571        let api = self.inner.api();
572        // SAFETY: live session; the identity and its strings live for the call.
573        let result = unsafe {
574            (api.qar_impl_peer_update_device_identity)(
575                self.inner.handle.as_ptr(),
576                &raw const storage.raw,
577            )
578        };
579        check(api, "qar_peer_update_device_identity", result)
580    }
581
582    /// Starts [`Session::request_onboarding_invite`] without blocking
583    /// (`qar_session_request_onboarding_invite_async`) and returns at once; the [`PendingCall`]
584    /// delivers the invite. The tag is checked (and copied) before this returns: a refused tag
585    /// is the error of this call, and no callback follows. `progress`, `timeout` and `wake` as
586    /// for [`crate::Runtime::start_onboard`].
587    pub fn start_onboarding_invite(
588        &self,
589        app_tag: &str,
590        progress: Option<Sender<Progress>>,
591        timeout: Option<Duration>,
592        wake: impl Fn() + Send + Sync + 'static,
593    ) -> Result<PendingCall<OnboardingInvite>> {
594        const FUNCTION: &str = "qar_session_request_onboarding_invite_async";
595        let app_tag_text = strings::to_c_string(app_tag, "app tag")?;
596        let mut init = defaults::qar_request_invite_init_default();
597        init.app_tag = app_tag_text.as_ptr();
598        let library = Rc::clone(self.inner.library());
599        let finish = move |outcome: RawOutcome| {
600            let api = &library.api;
601            if let Err(error) = check(api, FUNCTION, outcome.result) {
602                release_invite(api, outcome.handle);
603                return Err(error);
604            }
605            let handle = require_handle(outcome.handle as *mut sys::QarOnboardingInvite, FUNCTION)?;
606            Ok(OnboardingInvite::from_handle(handle, &library))
607        };
608        let session = self.inner.handle.as_ptr();
609        let api = self.inner.api();
610        self.inner.start_call(
611            FUNCTION,
612            progress,
613            timeout,
614            Box::new(wake),
615            None,
616            Box::new(finish),
617            Some(release_invite),
618            |user_state, progress_callback, token| {
619                // SAFETY: live session; init and its tag live for the start call, which copies
620                // the tag; the token outlives the call.
621                unsafe {
622                    (api.qar_impl_session_request_onboarding_invite_async)(
623                        session,
624                        &raw const init,
625                        Some(pending::handle_result_trampoline::<sys::QarOnboardingInvite>),
626                        progress_callback,
627                        user_state,
628                        token,
629                    )
630                }
631            },
632        )
633    }
634
635    /// Asks this machine's hub to start the target app for one AR device
636    /// (`qar_session_invite_target_app`) and returns its peer id once the target app's peer
637    /// has joined the session. `connection` names the device kind and address:
638    /// `"hololens:<host>"`, or a bare host, as `hololens:<host>`;
639    /// [`crate::Library::target_app_connection_string`] builds it. An Android headset
640    /// (`"headset:<host>"`, `"quest:"`, `"android:"`) is never invited: it pairs itself and joins
641    /// the session on its own, and this call fails with
642    /// [`crate::StatusCode::HUB_TARGET_APP_DEVICE_NOT_INVITABLE`] for it; find it with
643    /// [`Session::find_render_target`].
644    ///
645    /// Only this machine's hub answers, and the invite is one-time: the hub remembers the device
646    /// but never re-invites it by itself. A device another hub serves is stopped there first.
647    /// Fails with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`] for a malformed string, one
648    /// without a host or of another kind (a `visualizer:` one, which
649    /// [`Session::find_render_target`] resolves), and with
650    /// [`crate::StatusCode::HUB_TARGET_APP_DEVICE_NOT_INVITABLE`] when the hub has no target app
651    /// for the device family.
652    pub fn invite_target_app(
653        &self,
654        connection: &str,
655        options: &BlockingOptions<'_>,
656    ) -> Result<PeerId> {
657        let connection_text = strings::to_c_string(connection, "connection string")?;
658        let mut init = defaults::qar_session_invite_target_app_init_default();
659        init.connection_string = connection_text.as_ptr();
660        let api = self.inner.api();
661        let mut peer = defaults::qar_peer_id_default();
662        // SAFETY: live session; init and its string live for the call; the progress state and
663        // cancel token are borrowed from options for the call; valid out-pointer.
664        let result = unsafe {
665            (api.qar_impl_session_invite_target_app)(
666                self.inner.handle.as_ptr(),
667                &raw const init,
668                options.progress_callback(),
669                options.progress_state(),
670                options.cancel_pointer(),
671                &raw mut peer,
672            )
673        };
674        check(api, "qar_session_invite_target_app", result)?;
675        Ok(PeerId::from_raw(peer))
676    }
677
678    /// Starts [`Session::invite_target_app`] without blocking
679    /// (`qar_session_invite_target_app_async`); the [`PendingCall`] delivers the target app's
680    /// peer id. `progress`, `timeout` and `wake` as for [`crate::Runtime::start_onboard`].
681    pub fn start_invite_target_app(
682        &self,
683        connection: &str,
684        progress: Option<Sender<Progress>>,
685        timeout: Option<Duration>,
686        wake: impl Fn() + Send + Sync + 'static,
687    ) -> Result<PendingCall<PeerId>> {
688        const FUNCTION: &str = "qar_session_invite_target_app_async";
689        let connection_text = strings::to_c_string(connection, "connection string")?;
690        // The init and its string live in the call's state until the callback: the header does
691        // not say the start copies them.
692        let mut kept = Box::new(Keep((
693            defaults::qar_session_invite_target_app_init_default(),
694            connection_text,
695        )));
696        kept.0.0.connection_string = kept.0.1.as_ptr();
697        let init: *const sys::QarSessionInviteTargetAppInit = &raw const kept.0.0;
698        let library = Rc::clone(self.inner.library());
699        let session = self.inner.handle.as_ptr();
700        let api = self.inner.api();
701        self.inner.start_call(
702            FUNCTION,
703            progress,
704            timeout,
705            Box::new(wake),
706            Some(kept),
707            Box::new(move |outcome: RawOutcome| {
708                check(&library.api, FUNCTION, outcome.result)?;
709                Ok(PeerId(outcome.id))
710            }),
711            None,
712            |user_state, progress_callback, token| {
713                // SAFETY: live session; init lives in the call's state until the callback; the
714                // token outlives the call.
715                unsafe {
716                    (api.qar_impl_session_invite_target_app_async)(
717                        session,
718                        init,
719                        Some(pending::peer_result_trampoline),
720                        progress_callback,
721                        user_state,
722                        token,
723                    )
724                }
725            },
726        )
727    }
728
729    /// Asks this machine's hub to stop a target app it started (`qar_session_kill_target_app`):
730    /// the target app and the whole pipeline feeding it. A target app this machine's hub did not
731    /// start is served by no hub, so the call ends in [`crate::StatusCode::TIMEOUT`], not an
732    /// authorization error.
733    pub fn kill_target_app(&self, target_app: PeerId, options: &BlockingOptions<'_>) -> Result<()> {
734        let peer = target_app.to_raw();
735        let api = self.inner.api();
736        // SAFETY: live session; the peer id lives for the call; the progress state and cancel
737        // token are borrowed from options for the call.
738        let result = unsafe {
739            (api.qar_impl_session_kill_target_app)(
740                self.inner.handle.as_ptr(),
741                &raw const peer,
742                options.progress_callback(),
743                options.progress_state(),
744                options.cancel_pointer(),
745            )
746        };
747        check(api, "qar_session_kill_target_app", result)
748    }
749
750    /// Starts [`Session::kill_target_app`] without blocking
751    /// (`qar_session_kill_target_app_async`). `progress`, `timeout` and `wake` as for
752    /// [`crate::Runtime::start_onboard`].
753    pub fn start_kill_target_app(
754        &self,
755        target_app: PeerId,
756        progress: Option<Sender<Progress>>,
757        timeout: Option<Duration>,
758        wake: impl Fn() + Send + Sync + 'static,
759    ) -> Result<PendingCall<()>> {
760        const FUNCTION: &str = "qar_session_kill_target_app_async";
761        let kept = Box::new(Keep(target_app.to_raw()));
762        let peer: *const sys::QarPeerId = &raw const kept.0;
763        let library = Rc::clone(self.inner.library());
764        let session = self.inner.handle.as_ptr();
765        let api = self.inner.api();
766        self.inner.start_call(
767            FUNCTION,
768            progress,
769            timeout,
770            Box::new(wake),
771            Some(kept),
772            Box::new(move |outcome: RawOutcome| check(&library.api, FUNCTION, outcome.result)),
773            None,
774            |user_state, progress_callback, token| {
775                // SAFETY: live session; the peer id lives in the call's state until the
776                // callback; the token outlives the call.
777                unsafe {
778                    (api.qar_impl_session_kill_target_app_async)(
779                        session,
780                        peer,
781                        Some(pending::peer_result_trampoline),
782                        progress_callback,
783                        user_state,
784                        token,
785                    )
786                }
787            },
788        )
789    }
790
791    /// The peer id of an already-connected render target, from its connection string
792    /// (`qar_session_find_render_target`), for example a `visualizer:` one.
793    pub fn find_render_target(&self, connection: &str) -> Result<PeerId> {
794        let connection_text = strings::to_c_string(connection, "connection string")?;
795        let api = self.inner.api();
796        let mut peer = defaults::qar_peer_id_default();
797        // SAFETY: live session; the string lives for the call; valid out-pointer.
798        let result = unsafe {
799            (api.qar_impl_session_find_render_target)(
800                self.inner.handle.as_ptr(),
801                connection_text.as_ptr(),
802                &raw mut peer,
803            )
804        };
805        check(api, "qar_session_find_render_target", result)?;
806        Ok(PeerId::from_raw(peer))
807    }
808
809    /// Mints a co-process invite (`qar_session_request_onboarding_invite`): a process this app
810    /// starts onboards with it ([`crate::OnboardMethod::Invite`], with
811    /// [`crate::RuntimeConfig::ephemeral_storage`]) and joins under the peer id the hub remembers
812    /// for this app's approval and `app_tag`. `app_tag` is required, an identity key as for
813    /// [`crate::OnboardMethod::LocalApp`]; give the co-process a tag of its own. Only a session
814    /// that joined as a local app, or an app the QAROS launcher started, may request one; any
815    /// other fails with [`crate::StatusCode::ONBOARDING_INVITE_REFUSED`], which is final. A tag
816    /// that breaks the rules fails with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`] before the
817    /// hub is asked; [`crate::StatusCode::ONBOARDING_HUB_UNREACHABLE`] means the session names no
818    /// hub to ask yet: retry. The invite is single use, valid for 60 s and redeemable only on the
819    /// hub's PC.
820    pub fn request_onboarding_invite(
821        &self,
822        app_tag: &str,
823        options: &BlockingOptions<'_>,
824    ) -> Result<OnboardingInvite> {
825        OnboardingInvite::request(&self.inner, app_tag, options)
826    }
827}
828
829impl SessionInner {
830    pub(crate) fn api(&self) -> &QarApi {
831        &self.runtime.library.api
832    }
833
834    pub(crate) fn library(&self) -> &Rc<crate::library::LibraryInner> {
835        &self.runtime.library
836    }
837
838    /// Starts an async call owned by this session (see [`crate::PendingCall`]).
839    #[allow(clippy::too_many_arguments)]
840    fn start_call<T: 'static>(
841        self: &Rc<Self>,
842        function: &'static str,
843        progress: Option<Sender<Progress>>,
844        timeout: Option<Duration>,
845        wake: Box<dyn Fn() + Send + Sync>,
846        keep: Option<Box<dyn std::any::Any + Send + Sync>>,
847        finish: Box<dyn FnOnce(RawOutcome) -> Result<T>>,
848        destroy: Option<Destroy>,
849        start_call: impl FnOnce(
850            *mut c_void,
851            sys::qar_progress_callback_t,
852            *mut QarCancelToken,
853        ) -> QarResult,
854    ) -> Result<PendingCall<T>> {
855        self.release_delivered_abandoned_calls();
856        let abandon_session = Rc::clone(self);
857        let poll_session = Rc::clone(self);
858        // The finish closure keeps the session alive too, so a delivered handle is released
859        // while it lives.
860        let finish_session = Rc::clone(self);
861        let spec = CallSpec {
862            function,
863            progress,
864            timeout,
865            wake,
866            keep,
867            finish: Box::new(move |outcome| {
868                let value = finish(outcome);
869                drop(finish_session);
870                value
871            }),
872            abandon: Box::new(move |call| abandon_session.abandon_call(call)),
873            before_poll: Box::new(move || poll_session.release_delivered_abandoned_calls()),
874            destroy,
875        };
876        pending::start(self.library(), spec, start_call)
877    }
878
879    /// Destroys the handles that abandoned async calls delivered since the last call.
880    pub(crate) fn release_delivered_abandoned_calls(&self) {
881        let api = self.api();
882        self.abandoned_calls
883            .borrow_mut()
884            .retain(|call| !call.release_if_delivered(api));
885    }
886
887    /// Keeps an async call dropped before its callback until the callback has come.
888    pub(crate) fn abandon_call(&self, call: AbandonedCall) {
889        self.abandoned_calls.borrow_mut().push(call);
890    }
891
892    /// Registers callback state and a cancel token, then subscribes. The
893    /// state is owned by the session from here on.
894    pub(crate) fn subscribe<Event: 'static>(
895        &self,
896        callback: EventCallback<Event>,
897        function: &'static str,
898        subscribe: impl FnOnce(&QarApi, *mut c_void, *mut QarCancelToken) -> QarResult,
899    ) -> Result<Subscription> {
900        let token = Rc::new(CancelTokenInner::create(self.library(), None)?);
901        let slot = SubscriptionSlot {
902            token: Rc::clone(&token),
903            callback_state: Box::into_raw(Box::new(CallbackState {
904                api: NonNull::from(self.api()),
905                callback,
906            }))
907            .cast(),
908            release_state: release_callback_state::<CallbackState<Event>>,
909        };
910
911        let result = subscribe(self.api(), slot.callback_state, token.handle.as_ptr());
912        // On failure the library did not register the state; the slot frees it.
913        check(self.api(), function, result)?;
914
915        self.subscriptions.borrow_mut().push(slot);
916        Ok(Subscription { token: Some(token) })
917    }
918}
919
920impl Drop for SessionInner {
921    fn drop(&mut self) {
922        // Render senders and pending calls hold an Rc to this value, so only abandoned calls
923        // can be left. What they delivered is destroyed while the session lives.
924        let abandoned_calls = std::mem::take(self.abandoned_calls.get_mut());
925        for call in &abandoned_calls {
926            call.release_if_delivered(self.api());
927        }
928        let subscriptions = std::mem::take(self.subscriptions.get_mut());
929        for slot in &subscriptions {
930            if let Err(error) = slot.token.cancel() {
931                log::warn!("cancelling a subscription during session teardown: {error}");
932            }
933        }
934        // SAFETY: render senders hold an Rc to this value, so none is alive. Per the header,
935        // the destroy ends the abandoned async calls still running with QAR_STATUS_TIMEOUT and
936        // returns only after their callbacks have returned.
937        unsafe { (self.api().qar_impl_session_handle_destroy)(self.handle.as_ptr()) };
938        // Their tokens, init storage and device references are released only now, after the
939        // callbacks; so are the subscriptions' callback state and tokens.
940        for call in abandoned_calls {
941            call.leak_late_delivery();
942        }
943        drop(subscriptions);
944    }
945}
946
947/// An owned handle from a query or getter, destroyed on drop.
948pub(crate) struct OwnedHandle<Handle> {
949    handle: NonNull<Handle>,
950    destroy: unsafe extern "C" fn(*mut Handle),
951}
952
953impl<Handle> OwnedHandle<Handle> {
954    pub(crate) fn new(handle: NonNull<Handle>, destroy: unsafe extern "C" fn(*mut Handle)) -> Self {
955        Self { handle, destroy }
956    }
957
958    pub(crate) fn as_ptr(&self) -> *mut Handle {
959        self.handle.as_ptr()
960    }
961}
962
963impl<Handle> Drop for OwnedHandle<Handle> {
964    fn drop(&mut self) {
965        // SAFETY: the handle was returned to us as owned and is destroyed once.
966        unsafe { (self.destroy)(self.handle.as_ptr()) };
967    }
968}
969
970/// Count-then-fetch enumeration of owned handles: reads each with
971/// `read_item`, then destroys it.
972pub(crate) fn query_owned_handles<Handle, Item>(
973    api: &QarApi,
974    query_count: impl FnOnce(*mut usize) -> QarResult,
975    query_handles: impl FnOnce(*mut *mut Handle, usize, *mut usize) -> QarResult,
976    destroy: unsafe extern "C" fn(*mut Handle),
977    function: &'static str,
978    mut read_item: impl FnMut(*mut Handle) -> Result<Item>,
979) -> Result<Vec<Item>> {
980    let mut count = 0_usize;
981    check(api, function, query_count(&raw mut count))?;
982    if count == 0 {
983        return Ok(Vec::new());
984    }
985    let mut handles: Vec<*mut Handle> = vec![ptr::null_mut(); count];
986    let mut written = 0_usize;
987    let result = query_handles(handles.as_mut_ptr(), handles.len(), &raw mut written);
988    // Handles written before an error are still ours to destroy.
989    let owned: Vec<OwnedHandle<Handle>> = handles
990        .into_iter()
991        .take(written.min(count))
992        .filter_map(NonNull::new)
993        .map(|handle| OwnedHandle::new(handle, destroy))
994        .collect();
995    check(api, function, result)?;
996    owned
997        .iter()
998        .map(|handle| read_item(handle.as_ptr()))
999        .collect()
1000}
1001
1002unsafe extern "C" fn peer_update_trampoline(
1003    handle: *mut sys::QarPeerSpec,
1004    user_state: *mut c_void,
1005) {
1006    // SAFETY: registered by subscribe_peer_updates with this event type.
1007    let state = unsafe { CallbackState::<PeerInfo>::from_user_state(user_state) };
1008    if handle.is_null() {
1009        return;
1010    }
1011    // The handle is borrowed for the duration of the callback: read, never destroy.
1012    match read_peer_info(state.api(), handle) {
1013        Ok(peer) => state.deliver(peer, "peer update"),
1014        Err(error) => log::warn!("reading a peer update: {error}"),
1015    }
1016}
1017
1018unsafe extern "C" fn render_request_trampoline(
1019    request: *mut sys::QarRenderStreamRequest,
1020    user_state: *mut c_void,
1021) {
1022    // SAFETY: registered by subscribe_render_requests with this event type.
1023    let state = unsafe { CallbackState::<RenderRequest>::from_user_state(user_state) };
1024    if request.is_null() {
1025        return;
1026    }
1027    // Owned by the application: the header (`qar_render_sender_subscribe_requests`,
1028    // "Release each delivered request") and every sample destroy it here, which
1029    // takes precedence over api-conventions' general "borrowed" rule.
1030    let read = read_render_request(state.api(), request);
1031    // SAFETY: the request was delivered to this callback and is released exactly once,
1032    // after its getters ran.
1033    unsafe { (state.api().qar_impl_render_request_handle_destroy)(request) };
1034    match read {
1035        Ok(render_request) => state.deliver(render_request, "render request"),
1036        Err(error) => log::warn!("reading a render request: {error}"),
1037    }
1038}
1039
1040unsafe extern "C" fn session_lifecycle_trampoline(
1041    info: *const sys::QarSessionLifecycleInfo,
1042    user_state: *mut c_void,
1043) {
1044    // SAFETY: registered by subscribe_lifecycle with this event type.
1045    let state = unsafe { CallbackState::<SessionLifecycle>::from_user_state(user_state) };
1046    // SAFETY: the library passes a valid info for the duration of the callback, or null.
1047    let Some(info) = (unsafe { info.as_ref() }) else {
1048        return;
1049    };
1050    state.deliver(SessionLifecycle::from_raw(info), "session lifecycle");
1051}
1052
1053/// Destroys an invite an async invite request delivered that nobody takes.
1054fn release_invite(api: &QarApi, invite: usize) {
1055    if invite != 0 {
1056        // SAFETY: delivered to us and used by nobody.
1057        unsafe {
1058            (api.qar_impl_onboarding_invite_handle_destroy)(
1059                invite as *mut sys::QarOnboardingInvite,
1060            );
1061        };
1062    }
1063}