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

qaros/
runtime.rs

1use std::cell::RefCell;
2use std::ffi::CString;
3use std::path::PathBuf;
4use std::ptr::{self, NonNull};
5use std::rc::Rc;
6use std::sync::mpsc::Sender;
7use std::time::Duration;
8
9use qaros_sys::{self as sys, defaults};
10
11use crate::adapter::GraphicsAdapter;
12use crate::callbacks::{BlockingOptions, Progress};
13use crate::device::DeviceIdentity;
14use crate::device::DeviceIdentityStorage;
15use crate::error::{Error, Result, check};
16use crate::invite::OnboardingInvite;
17use crate::library::{LibraryInner, require_handle};
18use crate::member_hub::MemberHubInvitation;
19use crate::pending::{self, AbandonedCall, CallSpec, PendingOnboard, RawOutcome};
20use crate::session::Session;
21use crate::strings;
22use crate::types::{OnboardingId, PeerId};
23
24/// Options for `qar_runtime_create`; `None` keeps the library default.
25#[derive(Clone, Debug, Default)]
26pub struct RuntimeConfig {
27    /// Directory holding the runtime binaries (the package's `bin/`).
28    pub runtime_binaries_directory: Option<PathBuf>,
29    /// Root for device certificates and session state; the library default
30    /// on Windows is `%LOCALAPPDATA%\Quaternar\QarOS`. Give each runtime
31    /// instance in one application its own directory.
32    pub storage_directory: Option<PathBuf>,
33    /// Keep the identity in memory only (`QarRuntimeEphemeralStorageExt`), for a co-process
34    /// that joins with an invite from its parent app: nothing is written under the storage
35    /// directory, and the deprecated [`Runtime::rejoin`] and [`Runtime::forget`] fail with
36    /// [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`]. A runtime
37    /// older than the extension skips it and stores the identity on disk: check
38    /// [`crate::Library::runtime_info`] before relying on it.
39    pub ephemeral_storage: bool,
40}
41
42/// How this peer presents itself to others (`QarPeerPresentation`). `None` keeps the persisted
43/// value (or a generated default on first onboard).
44#[derive(Clone, Debug, Default)]
45pub struct PeerPresentation {
46    /// The human label advertised to peers; it also feeds the sanitized debug label of the
47    /// certificate and the storage slot.
48    pub display_name: Option<String>,
49    pub app_version: Option<String>,
50    /// App-defined peer metadata.
51    pub custom_info: Option<String>,
52    /// The device this application describes itself as (`QarPeerDeviceIdentity`, chained on the
53    /// presentation of the onboard or rejoin init). `None`: a desktop PC with the fixed id of the
54    /// host OS.
55    pub device_identity: Option<DeviceIdentity>,
56}
57
58/// Where the hub runs, for onboarding with a code against a remote hub (`QarOnboardHostExt`).
59#[deprecated(
60    note = "code onboarding is no longer a supported way to join, so it needs no hub address: \
61            join as a local app (`OnboardMethod::LocalApp`), a companion \
62            (`OnboardMethod::Invite`) or through a member hub \
63            (`OnboardExtensions::remote_app_grant`)"
64)]
65#[derive(Clone, Copy, Debug)]
66pub struct HubAddress<'a> {
67    /// Plain host name or IP address, no URL.
68    pub hostname: &'a str,
69    /// The hub's onboarding port. Required: hubs claim it from a port range,
70    /// and `0` fails with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`].
71    pub port: u16,
72}
73
74/// The onboarding path, chained as exactly one mode extension. An app joins in one of three ways:
75/// as a local app ([`OnboardMethod::LocalApp`]), as a companion of a local app
76/// ([`OnboardMethod::Invite`] with the app's [`crate::Session::request_onboarding_invite`]), or
77/// through a member hub ([`OnboardMethod::LocalApp`] with
78/// [`OnboardExtensions::remote_app_grant`]).
79#[allow(deprecated)] // the deprecated `Code` variant names the deprecated `HubAddress`
80#[derive(Clone, Copy, Debug)]
81pub enum OnboardMethod<'a> {
82    /// A short pairing code minted for the hub's operators (the QAROS
83    /// Visualizer shows none: its hub join code is for another hub only).
84    /// Without an address the library finds only this user's
85    /// hub: through the `hub-endpoint.json` the hub writes to the QAROS data
86    /// root, then a discovery beacon whose owner is this user (up to 6 s), else
87    /// [`crate::StatusCode::ONBOARDING_HUB_UNREACHABLE`]. Any other hub needs
88    /// its host and port in `hub`.
89    #[deprecated(note = "code onboarding is no longer a supported way to join: use \
90                `OnboardMethod::LocalApp` (an app on the hub's PC), `OnboardMethod::Invite` with \
91                an invite from `Session::request_onboarding_invite` (a companion process), or \
92                `OnboardMethod::LocalApp` with `OnboardExtensions::remote_app_grant` (an app on \
93                a member hub's PC)")]
94    Code {
95        code: &'a str,
96        hub: Option<HubAddress<'a>>,
97    },
98    /// An invite: a co-process invite from the local app that started this process
99    /// ([`crate::Session::request_onboarding_invite`]), or one the hub's operators minted. The
100    /// invite is borrowed for the call (for [`Runtime::start_onboard`], for the start call,
101    /// during which the library copies it).
102    Invite(&'a OnboardingInvite),
103    /// A source app joining the QAROS hub installed on this PC, with no code
104    /// (`QarOnboardLocalAppExt`, Windows only). The first start of an app
105    /// waits until a person allows it in the hub, at most `approval_timeout`
106    /// (`None`: the hub's default of 120 s). The C API reads a zero timeout as
107    /// that default, so a duration under 1 ms (`Duration::ZERO` included) or
108    /// over `u32::MAX` milliseconds fails with [`crate::Error::InvalidArgument`]
109    /// before the call; pass `None` for the default. A refusal ends in one of the
110    /// `ONBOARDING_APPROVAL_*`, `ONBOARDING_HUB_NOT_AUTHENTIC` or
111    /// `ONBOARDING_APP_IDENTITY_MISMATCH` codes, see
112    /// [`crate::StatusCode::user_action`]. Stateless: nothing to persist, every start onboards
113    /// again.
114    ///
115    /// `app_tag` (`QarOnboardLocalAppTagExt`) names this instance of the app: the hub remembers
116    /// one peer id per approval and tag, so the next start with the same tag gets the same peer
117    /// id back while no other live process holds it. An identity key: printable ASCII, no space
118    /// at either end, at most `QAR_MAX_APP_TAG_LENGTH` bytes, never starting with `member/`, and
119    /// constant across versions of the app; anything else fails with
120    /// [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`]. `None` is the default tag, remembered the
121    /// same way. Give instances that run together different tags.
122    ///
123    /// A member hub's remote-app grant is redeemed with
124    /// [`OnboardExtensions::remote_app_grant`] next to this mode.
125    LocalApp {
126        approval_timeout: Option<Duration>,
127        app_tag: Option<&'a str>,
128    },
129}
130
131/// The optional extensions of [`Runtime::onboard_with`] and [`Runtime::start_onboard`], chained
132/// after the mode extension in this order: the remote-app grant, the adapter or no graphics
133/// device, the planned peer id (deprecated). The re-enrolled onboarding id (deprecated) goes into the init itself.
134#[derive(Clone, Copy, Debug, Default)]
135pub struct OnboardExtensions<'a> {
136    /// Creates the session's GPU devices, and with them every render sender's frame images, on
137    /// this adapter (`QarGraphicsDeviceId`). `None`: the GPU QAROS selected for an app it
138    /// launched (carried in the launch invite), else one the library picks.
139    pub adapter: Option<GraphicsAdapter>,
140    /// Creates the session without a graphics device (`QarGraphicsDeviceDisabledExt`), for an
141    /// application that never streams media, such as a companion that only drives app volumes,
142    /// GUI panels or peers. The session starts faster: no Vulkan or D3D11 device, no adapter
143    /// enumeration, no transfer plugins. Onboarding, peers, app volumes, GUI panels and rooms
144    /// work as usual; creating a render sender, subscribing to render requests, creating a video
145    /// sender and [`crate::Session::graphics_adapter`] fail with
146    /// [`crate::StatusCode::GRAPHICS_DEVICE_NOT_INITIALIZED`]. Together with
147    /// [`OnboardExtensions::adapter`] it is refused with [`Error::InvalidArgument`] before the
148    /// call (the C API refuses it with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`]). A local-app
149    /// session shared by several onboards of one process keeps the choice of the onboard that
150    /// created it.
151    pub without_graphics_device: bool,
152    /// Joins under this peer id (`QarOnboardPeerIdExt`), for a process whose peer id someone
153    /// else planned and announced to the session. With [`OnboardMethod::Code`] or
154    /// [`OnboardMethod::Invite`] only: it must equal any peer id the hub bound to the code or
155    /// invite (a co-process invite always carries one), else onboarding fails. `None` takes that
156    /// bound peer id, else a fresh one. The id is persisted with the slot, so a later rejoin keeps
157    /// it. [`PeerId::ZERO`] and a local app ([`OnboardMethod::LocalApp`], whose peer id the hub
158    /// assigns) are refused with [`Error::InvalidArgument`] before the call; the C API refuses
159    /// both with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`].
160    #[deprecated(
161        note = "joining under a planned peer id is no longer supported: a local app's peer id \
162                comes from the hub, per approval and `app_tag`, and a companion's from its \
163                invite; leave it `None`"
164    )]
165    pub peer_id: Option<PeerId>,
166    /// Re-enrolls this persisted slot (`QarOnboardInit::onboarding_id`) instead of creating a new
167    /// identity: the slot is reused when it survives and recreated under the same id after a
168    /// wipe, so a persisted id never goes stale, and [`Onboarded::onboarding_id`] echoes it.
169    /// [`OnboardingId::ZERO`] and a local app (stateless) are refused with
170    /// [`Error::InvalidArgument`] before the call. A runtime with
171    /// [`RuntimeConfig::ephemeral_storage`] refuses it with
172    /// [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`], and a slot with a live session with
173    /// [`crate::StatusCode::ONBOARDING_SESSION_STILL_ACTIVE`].
174    #[deprecated(
175        note = "re-enrolling a persisted slot is no longer supported: join as a local app \
176                (`OnboardMethod::LocalApp`), which is stateless; leave it `None`"
177    )]
178    pub onboarding_id: Option<OnboardingId>,
179    /// Redeems a member hub's remote-app grant (`QarOnboardRemoteAppGrantExt`): the invitation
180    /// the primary's app created with [`crate::MemberHubInvitationConfig::app_grant_tag`]. With
181    /// [`OnboardMethod::LocalApp`] only, else [`Error::InvalidArgument`] before the call (the C
182    /// API refuses it with [`crate::StatusCode::ARGUMENT_NOT_SUPPORTED`]). Only a member hub
183    /// redeems a grant: join the hub on this PC to the invitation's primary first
184    /// (`Runtime::join_hub_as_member`). A hub that is not a member ignores the grant, with no
185    /// error of its own, and asks its operator as for any local app: the approval prompt, then
186    /// [`crate::StatusCode::ONBOARDING_APPROVAL_DENIED`] or
187    /// [`crate::StatusCode::ONBOARDING_APPROVAL_TIMEOUT`] when nobody allows it. On a member hub,
188    /// when no approval admits this executable yet, the primary records it as the app the grant
189    /// admits, without a prompt; once another executable redeemed the grant, or when the primary
190    /// refuses it, onboarding fails with [`crate::StatusCode::ONBOARDING_APPROVAL_DENIED`]. When an approval already admits
191    /// it, the invitation is not used. The grant's app tag applies; the method's `app_tag` is not
192    /// needed. The invitation is borrowed for the call (for [`Runtime::start_onboard`], for the
193    /// start call, during which the library copies it). Always `None` where the bindings lack
194    /// member hubs, since no [`MemberHubInvitation`] exists there.
195    pub remote_app_grant: Option<&'a MemberHubInvitation>,
196}
197
198/// The result of a successful onboarding or rejoin.
199#[derive(Debug)]
200pub struct Onboarded {
201    /// The persisted slot's key, the ticket for the deprecated [`Runtime::rejoin`] and
202    /// [`Runtime::forget`]. Zero for a local app ([`OnboardMethod::LocalApp`]) and on a runtime
203    /// with [`RuntimeConfig::ephemeral_storage`]: nothing to persist. A rejoin echoes its id.
204    #[deprecated(
205        note = "onboarding ids only serve rejoin and forget, which are deprecated: a local app, \
206                a companion and a member hub's app store nothing and onboard on every start"
207    )]
208    pub onboarding_id: OnboardingId,
209    pub session: Session,
210}
211
212/// A `QarRuntime`. Sessions keep it alive; it is released after the last of them
213/// (`qar_runtime_handle_destroy`), which ends its pending async onboards and rejoins and waits for
214/// their callbacks.
215#[derive(Debug)]
216pub struct Runtime {
217    pub(crate) inner: Rc<RuntimeInner>,
218}
219
220#[derive(Debug)]
221pub(crate) struct RuntimeInner {
222    handle: NonNull<sys::QarRuntime>,
223    /// Async onboards and rejoins whose [`PendingOnboard`] was dropped before the callback.
224    abandoned_onboards: RefCell<Vec<AbandonedCall>>,
225    pub(crate) library: Rc<LibraryInner>,
226}
227
228/// A [`PeerPresentation`] as C strings and the device identity structure, which the
229/// presentation's `header.next` points at. Lives inside a boxed init storage, so its address is
230/// stable while the library may read it.
231#[derive(Debug)]
232struct PresentationStorage {
233    display_name: Option<CString>,
234    app_version: Option<CString>,
235    custom_info: Option<CString>,
236    device_identity: Option<DeviceIdentityStorage>,
237}
238
239impl PresentationStorage {
240    fn new(presentation: &PeerPresentation) -> Result<Self> {
241        Ok(Self {
242            display_name: strings::optional_c_string(
243                presentation.display_name.as_deref(),
244                "display name",
245            )?,
246            app_version: strings::optional_c_string(
247                presentation.app_version.as_deref(),
248                "app version",
249            )?,
250            custom_info: strings::optional_c_string(
251                presentation.custom_info.as_deref(),
252                "custom peer info",
253            )?,
254            device_identity: presentation
255                .device_identity
256                .as_ref()
257                .map(DeviceIdentityStorage::new)
258                .transpose()?,
259        })
260    }
261
262    /// Fills `raw` with pointers into this storage, which must not move while they are used.
263    fn wire(&mut self, raw: &mut sys::QarPeerPresentation) {
264        raw.display_name = strings::pointer_or_null(self.display_name.as_ref());
265        raw.app_version = strings::pointer_or_null(self.app_version.as_ref());
266        raw.app_custom_peer_info = strings::pointer_or_null(self.custom_info.as_ref());
267        if let Some(identity) = self.device_identity.as_mut() {
268            raw.header.next = (&raw mut identity.raw).cast();
269        }
270    }
271}
272
273/// Points `first` at the first header of `chain` and each header at the next.
274///
275/// # Safety
276///
277/// Every pointer is a valid, stamped structure header that outlives the chain's use.
278unsafe fn link_chain(first: &mut *mut std::ffi::c_void, chain: &[*mut sys::QarStructureHeader]) {
279    let mut next: *mut std::ffi::c_void = ptr::null_mut();
280    for &header in chain.iter().rev() {
281        // SAFETY: forwarded to the caller.
282        unsafe { (*header).next = next };
283        next = header.cast();
284    }
285    *first = next;
286}
287
288/// A `QarOnboardInit`, its extensions and the strings they point to, in one heap allocation the
289/// library may read while the call runs (for the async call, until it calls back).
290#[derive(Debug)]
291pub(crate) struct OnboardInitStorage {
292    init: sys::QarOnboardInit,
293    code: sys::QarOnboardCodeExt,
294    host: sys::QarOnboardHostExt,
295    invite: sys::QarOnboardInviteExt,
296    local_app: sys::QarOnboardLocalAppExt,
297    app_tag: sys::QarOnboardLocalAppTagExt,
298    remote_app_grant: sys::QarOnboardRemoteAppGrantExt,
299    adapter: sys::QarGraphicsDeviceId,
300    graphics_device_disabled: sys::QarGraphicsDeviceDisabledExt,
301    peer_id: sys::QarOnboardPeerIdExt,
302    presentation: PresentationStorage,
303    code_text: Option<CString>,
304    hostname_text: Option<CString>,
305    app_tag_text: Option<CString>,
306}
307
308// SAFETY: the storage is plain data and pointers into itself (or to an invite or invitation
309// handle the library copies during the start call); Rust never reads through them after building
310// it and only frees it, which is sound from any thread.
311unsafe impl Send for OnboardInitStorage {}
312// SAFETY: as above; no `&self` method reads through the pointers.
313unsafe impl Sync for OnboardInitStorage {}
314
315impl OnboardInitStorage {
316    // The deprecated code mode, planned peer id and re-enrolled slot still work.
317    #[allow(deprecated)]
318    pub(crate) fn new(
319        method: &OnboardMethod<'_>,
320        presentation: &PeerPresentation,
321        extensions: &OnboardExtensions<'_>,
322    ) -> Result<Box<Self>> {
323        validate_extensions(method, extensions)?;
324        let mut storage = Box::new(Self {
325            init: defaults::qar_onboard_init_default(),
326            code: defaults::qar_onboard_code_ext_default(),
327            host: defaults::qar_onboard_host_ext_default(),
328            invite: defaults::qar_onboard_invite_ext_default(),
329            local_app: defaults::qar_onboard_local_app_ext_default(),
330            app_tag: defaults::qar_onboard_local_app_tag_ext_default(),
331            remote_app_grant: defaults::qar_onboard_remote_app_grant_ext_default(),
332            adapter: defaults::qar_graphics_device_id_default(),
333            graphics_device_disabled: defaults::qar_graphics_device_disabled_ext_default(),
334            peer_id: defaults::qar_onboard_peer_id_ext_default(),
335            presentation: PresentationStorage::new(presentation)?,
336            code_text: None,
337            hostname_text: None,
338            app_tag_text: None,
339        });
340        // Everything below points into the box, whose contents never move.
341        let this = &mut *storage;
342        if let Some(onboarding_id) = extensions.onboarding_id {
343            this.init.onboarding_id = onboarding_id.to_raw();
344        }
345        this.presentation.wire(&mut this.init.presentation);
346        let mut chain: Vec<*mut sys::QarStructureHeader> = Vec::new();
347        match method {
348            OnboardMethod::Code { code, hub } => {
349                let code = this
350                    .code_text
351                    .insert(strings::to_c_string(code, "pairing code")?);
352                this.code.code = code.as_ptr();
353                chain.push(&raw mut this.code.header);
354                if let Some(address) = hub {
355                    let hostname = this
356                        .hostname_text
357                        .insert(strings::to_c_string(address.hostname, "hub hostname")?);
358                    this.host.hostname = hostname.as_ptr();
359                    this.host.port = address.port;
360                    chain.push(&raw mut this.host.header);
361                }
362            }
363            OnboardMethod::Invite(invite) => {
364                this.invite.invite = invite.as_ptr();
365                chain.push(&raw mut this.invite.header);
366            }
367            OnboardMethod::LocalApp {
368                approval_timeout,
369                app_tag,
370            } => {
371                this.local_app.approval_timeout_ms =
372                    optional_milliseconds(*approval_timeout, "approval timeout")?;
373                chain.push(&raw mut this.local_app.header);
374                if let Some(tag) = app_tag {
375                    let tag = this
376                        .app_tag_text
377                        .insert(strings::to_c_string(tag, "app tag")?);
378                    this.app_tag.app_tag = tag.as_ptr();
379                    chain.push(&raw mut this.app_tag.header);
380                }
381            }
382        }
383        if let Some(invitation) = extensions.remote_app_grant {
384            this.remote_app_grant.invitation = invitation.as_ptr();
385            chain.push(&raw mut this.remote_app_grant.header);
386        }
387        if let Some(adapter) = extensions.adapter {
388            this.adapter = adapter.to_raw();
389            chain.push(&raw mut this.adapter.header);
390        }
391        if extensions.without_graphics_device {
392            chain.push(&raw mut this.graphics_device_disabled.header);
393        }
394        if let Some(peer_id) = extensions.peer_id {
395            this.peer_id.peer_id = peer_id.to_raw();
396            chain.push(&raw mut this.peer_id.header);
397        }
398        // SAFETY: every header is a stamped structure inside the box.
399        unsafe { link_chain(&mut this.init.header.next, &chain) };
400        Ok(storage)
401    }
402
403    pub(crate) fn init(&self) -> *const sys::QarOnboardInit {
404        &raw const self.init
405    }
406}
407
408/// What the C API refuses with `QAR_STATUS_ARGUMENT_NOT_SUPPORTED`, refused before the call.
409#[allow(deprecated)] // checks the deprecated planned peer id and re-enrolled slot too
410fn validate_extensions(
411    method: &OnboardMethod<'_>,
412    extensions: &OnboardExtensions<'_>,
413) -> Result<()> {
414    let local_app = matches!(method, OnboardMethod::LocalApp { .. });
415    let refuse = |message: &str| Err(Error::InvalidArgument(message.to_string()));
416    match extensions.peer_id {
417        Some(peer_id) if peer_id.is_zero() => return refuse("the zero peer id cannot be planned"),
418        Some(_) if local_app => {
419            return refuse("a local app gets its peer id from the hub; no planned peer id");
420        }
421        _ => {}
422    }
423    match extensions.onboarding_id {
424        Some(id) if id.is_zero() => return refuse("the zero onboarding id names no slot"),
425        Some(_) if local_app => return refuse("a local app is stateless; no slot to re-enroll"),
426        _ => {}
427    }
428    if extensions.adapter.is_some() && extensions.without_graphics_device {
429        return refuse("a session without a graphics device takes no adapter");
430    }
431    if extensions.remote_app_grant.is_some() && !local_app {
432        return refuse("a remote-app grant is redeemed only by a local app");
433    }
434    Ok(())
435}
436
437/// A `QarRejoinInit`, its adapter extension and the presentation strings, in one heap allocation.
438#[derive(Debug)]
439pub(crate) struct RejoinInitStorage {
440    init: sys::QarRejoinInit,
441    adapter: sys::QarGraphicsDeviceId,
442    presentation: PresentationStorage,
443}
444
445// SAFETY: as for OnboardInitStorage.
446unsafe impl Send for RejoinInitStorage {}
447// SAFETY: as for OnboardInitStorage.
448unsafe impl Sync for RejoinInitStorage {}
449
450impl RejoinInitStorage {
451    pub(crate) fn new(
452        onboarding_id: OnboardingId,
453        presentation: &PeerPresentation,
454        adapter: Option<GraphicsAdapter>,
455    ) -> Result<Box<Self>> {
456        if onboarding_id.is_zero() {
457            return Err(Error::InvalidArgument(
458                "the zero onboarding id cannot be rejoined".to_string(),
459            ));
460        }
461        let mut storage = Box::new(Self {
462            init: defaults::qar_rejoin_init_default(),
463            adapter: defaults::qar_graphics_device_id_default(),
464            presentation: PresentationStorage::new(presentation)?,
465        });
466        let this = &mut *storage;
467        this.init.onboarding_id = onboarding_id.to_raw();
468        this.presentation.wire(&mut this.init.presentation);
469        if let Some(adapter) = adapter {
470            this.adapter = adapter.to_raw();
471            this.init.header.next = (&raw mut this.adapter.header).cast();
472        }
473        Ok(storage)
474    }
475
476    pub(crate) fn init(&self) -> *const sys::QarRejoinInit {
477        &raw const self.init
478    }
479}
480
481impl Runtime {
482    pub(crate) fn create(library: &Rc<LibraryInner>, config: &RuntimeConfig) -> Result<Self> {
483        let binaries_directory = config
484            .runtime_binaries_directory
485            .as_deref()
486            .map(|directory| strings::path_to_c_string(directory, "runtime binaries directory"))
487            .transpose()?;
488        let storage_directory = config
489            .storage_directory
490            .as_deref()
491            .map(|directory| strings::path_to_c_string(directory, "storage directory"))
492            .transpose()?;
493
494        let mut init = defaults::qar_runtime_init_default();
495        init.runtime_binaries_folder_path = strings::pointer_or_null(binaries_directory.as_ref());
496        init.storage_folder_path = strings::pointer_or_null(storage_directory.as_ref());
497        let mut ephemeral_extension = defaults::qar_runtime_ephemeral_storage_ext_default();
498        if config.ephemeral_storage {
499            init.header.next = (&raw mut ephemeral_extension).cast();
500        }
501
502        let api = &library.api;
503        let mut handle: *mut sys::QarRuntime = ptr::null_mut();
504        // SAFETY: init and its chained extension are stamped and, with their strings, outlive
505        // the call; handle is a valid out-pointer.
506        let result = unsafe { (api.qar_impl_runtime_create)(&raw const init, &raw mut handle) };
507        check(api, "qar_runtime_create", result)?;
508        let handle = require_handle(handle, "qar_runtime_create")?;
509        Ok(Self {
510            inner: Rc::new(RuntimeInner {
511                handle,
512                abandoned_onboards: RefCell::new(Vec::new()),
513                library: Rc::clone(library),
514            }),
515        })
516    }
517
518    /// The `QarRuntime` handle, for the functions only the raw table of
519    /// [`crate::Library::raw_api`] reaches.
520    ///
521    /// Taking the pointer is safe; using it is `unsafe`, under the rules of
522    /// [`crate::Session::as_raw`] for a runtime: valid while this `Runtime` lives, never
523    /// destroyed by the caller (the last of the `Runtime` and its sessions releases it), used on
524    /// the thread that uses this `Runtime`. A session a raw onboard or rejoin hands out is not a
525    /// [`crate::Session`]: the caller destroys it with `qar_session_handle_destroy` before this
526    /// `Runtime` drops.
527    pub fn as_raw(&self) -> *mut sys::QarRuntime {
528        self.inner.handle.as_ptr()
529    }
530
531    /// Restores the persisted session for `onboarding_id` without UI
532    /// (`qar_runtime_rejoin`). [`crate::StatusCode::ONBOARDING_SESSION_NOT_FOUND`]
533    /// means: onboard instead. The zero id (a local app's) is refused with
534    /// [`Error::InvalidArgument`]. The peer id is the one persisted by the onboard.
535    #[deprecated(
536        note = "rejoining a persisted slot is no longer a supported way to join: onboard on \
537                every start, as a local app (`OnboardMethod::LocalApp`), a companion \
538                (`OnboardMethod::Invite`) or through a member hub \
539                (`OnboardExtensions::remote_app_grant`)"
540    )]
541    pub fn rejoin(
542        &self,
543        onboarding_id: OnboardingId,
544        presentation: &PeerPresentation,
545        options: &BlockingOptions<'_>,
546    ) -> Result<Session> {
547        #[allow(deprecated)]
548        self.rejoin_on_adapter(onboarding_id, presentation, None, options)
549    }
550
551    /// [`Runtime::rejoin`] that creates the session's GPU devices, and with
552    /// them every render sender's frame images, on `adapter`
553    /// (`QarGraphicsDeviceId` chained into `QarRejoinInit`). `None` lets the
554    /// library pick.
555    #[deprecated(
556        note = "rejoining a persisted slot is no longer a supported way to join: onboard on \
557                every start with `Runtime::onboard_on_adapter`, as a local app (`OnboardMethod::LocalApp`), a companion \
558                (`OnboardMethod::Invite`) or through a member hub \
559                (`OnboardExtensions::remote_app_grant`)"
560    )]
561    pub fn rejoin_on_adapter(
562        &self,
563        onboarding_id: OnboardingId,
564        presentation: &PeerPresentation,
565        adapter: Option<GraphicsAdapter>,
566        options: &BlockingOptions<'_>,
567    ) -> Result<Session> {
568        self.inner.release_delivered_abandoned_onboards();
569        let storage = RejoinInitStorage::new(onboarding_id, presentation, adapter)?;
570        let api = &self.inner.library.api;
571        let mut session: *mut sys::QarSession = ptr::null_mut();
572        // SAFETY: the init storage outlives the call; the progress state and cancel token are
573        // borrowed from options for the call; valid out-pointer.
574        let result = unsafe {
575            (api.qar_impl_runtime_rejoin)(
576                self.inner.handle.as_ptr(),
577                storage.init(),
578                options.progress_callback(),
579                options.progress_state(),
580                options.cancel_pointer(),
581                &raw mut session,
582            )
583        };
584        check(api, "qar_runtime_rejoin", result)?;
585        let session = require_handle(session, "qar_runtime_rejoin")?;
586        Ok(Session::from_handle(session, Rc::clone(&self.inner)))
587    }
588
589    /// Full onboarding (`qar_runtime_onboard`), chaining the mode extension of `method`. The
590    /// progress callback of `options` reports the steps (for a local app, "Waiting for approval
591    /// in QAROS hub" while the prompt is open) and ends before the call returns.
592    pub fn onboard(
593        &self,
594        method: &OnboardMethod<'_>,
595        presentation: &PeerPresentation,
596        options: &BlockingOptions<'_>,
597    ) -> Result<Onboarded> {
598        self.onboard_with(method, presentation, &OnboardExtensions::default(), options)
599    }
600
601    /// [`Runtime::onboard`] that creates the session's GPU devices, and with
602    /// them every render sender's frame images, on `adapter`
603    /// (`QarGraphicsDeviceId`, chained after the mode extension as in the
604    /// Developer Guide's "Choosing the GPU"). `None` lets the library pick.
605    pub fn onboard_on_adapter(
606        &self,
607        method: &OnboardMethod<'_>,
608        presentation: &PeerPresentation,
609        adapter: Option<GraphicsAdapter>,
610        options: &BlockingOptions<'_>,
611    ) -> Result<Onboarded> {
612        let extensions = OnboardExtensions {
613            adapter,
614            ..OnboardExtensions::default()
615        };
616        self.onboard_with(method, presentation, &extensions, options)
617    }
618
619    /// [`Runtime::onboard`] with the optional extensions of `extensions`.
620    pub fn onboard_with(
621        &self,
622        method: &OnboardMethod<'_>,
623        presentation: &PeerPresentation,
624        extensions: &OnboardExtensions<'_>,
625        options: &BlockingOptions<'_>,
626    ) -> Result<Onboarded> {
627        self.inner.release_delivered_abandoned_onboards();
628        let storage = OnboardInitStorage::new(method, presentation, extensions)?;
629        let api = &self.inner.library.api;
630        let mut onboarding_id = defaults::qar_onboarding_id_default();
631        let mut session: *mut sys::QarSession = ptr::null_mut();
632        // SAFETY: the init storage outlives the call; the progress state and cancel token are
633        // borrowed from options for the call; out-pointers are valid.
634        let result = unsafe {
635            (api.qar_impl_runtime_onboard)(
636                self.inner.handle.as_ptr(),
637                storage.init(),
638                options.progress_callback(),
639                options.progress_state(),
640                options.cancel_pointer(),
641                &raw mut onboarding_id,
642                &raw mut session,
643            )
644        };
645        check(api, "qar_runtime_onboard", result)?;
646        let session = require_handle(session, "qar_runtime_onboard")?;
647        #[allow(deprecated)] // the deprecated field is still filled
648        Ok(Onboarded {
649            onboarding_id: OnboardingId::from_raw(onboarding_id),
650            session: Session::from_handle(session, Rc::clone(&self.inner)),
651        })
652    }
653
654    /// Starts [`Runtime::onboard_with`] without blocking (`qar_runtime_onboard_async`) and
655    /// returns at once; [`PendingOnboard::poll`] or [`PendingOnboard::wait`] picks up the
656    /// [`Onboarded`]. `progress` receives the progress reports, sent from a library thread until
657    /// the result arrives. `timeout` cancels the call through its cancel token, after which the
658    /// library calls back with [`crate::StatusCode::TIMEOUT`]. `wake` runs on a library thread
659    /// right after the result arrived, for example to request a repaint that then polls. See
660    /// [`PendingOnboard`] for dropping it before the result.
661    pub fn start_onboard(
662        &self,
663        method: &OnboardMethod<'_>,
664        presentation: &PeerPresentation,
665        extensions: &OnboardExtensions<'_>,
666        progress: Option<Sender<Progress>>,
667        timeout: Option<Duration>,
668        wake: impl Fn() + Send + Sync + 'static,
669    ) -> Result<PendingOnboard> {
670        self.inner.release_delivered_abandoned_onboards();
671        let storage = OnboardInitStorage::new(method, presentation, extensions)?;
672        let init = storage.init();
673        let runtime = self.inner.handle();
674        let api = &self.inner.library.api;
675        self.start_session_call(
676            "qar_runtime_onboard_async",
677            Box::new(storage),
678            progress,
679            timeout,
680            Box::new(wake),
681            |user_state, progress_callback, token| {
682                // SAFETY: live runtime; init lives in the call's state until the callback; the
683                // token outlives the call (the pending call or its owner keeps it).
684                unsafe {
685                    (api.qar_impl_runtime_onboard_async)(
686                        runtime,
687                        init,
688                        Some(pending::onboard_result_trampoline),
689                        progress_callback,
690                        user_state,
691                        token,
692                    )
693                }
694            },
695        )
696    }
697
698    /// Starts [`Runtime::rejoin_on_adapter`] without blocking (`qar_runtime_rejoin_async`), as
699    /// [`Runtime::start_onboard`] does; the [`Onboarded`] it delivers echoes `onboarding_id`. The
700    /// zero id is refused with [`Error::InvalidArgument`] before the call.
701    #[deprecated(
702        note = "rejoining a persisted slot is no longer a supported way to join: onboard on \
703                every start with `Runtime::start_onboard`, as a local app (`OnboardMethod::LocalApp`), a companion \
704                (`OnboardMethod::Invite`) or through a member hub \
705                (`OnboardExtensions::remote_app_grant`)"
706    )]
707    pub fn start_rejoin(
708        &self,
709        onboarding_id: OnboardingId,
710        presentation: &PeerPresentation,
711        adapter: Option<GraphicsAdapter>,
712        progress: Option<Sender<Progress>>,
713        timeout: Option<Duration>,
714        wake: impl Fn() + Send + Sync + 'static,
715    ) -> Result<PendingOnboard> {
716        self.inner.release_delivered_abandoned_onboards();
717        let storage = RejoinInitStorage::new(onboarding_id, presentation, adapter)?;
718        let init = storage.init();
719        let runtime = self.inner.handle();
720        let api = &self.inner.library.api;
721        self.start_session_call(
722            "qar_runtime_rejoin_async",
723            Box::new(storage),
724            progress,
725            timeout,
726            Box::new(wake),
727            |user_state, progress_callback, token| {
728                // SAFETY: as in start_onboard.
729                unsafe {
730                    (api.qar_impl_runtime_rejoin_async)(
731                        runtime,
732                        init,
733                        Some(pending::onboard_result_trampoline),
734                        progress_callback,
735                        user_state,
736                        token,
737                    )
738                }
739            },
740        )
741    }
742
743    /// Starts an async onboard or rejoin whose callback hands over a session.
744    fn start_session_call(
745        &self,
746        function: &'static str,
747        keep: Box<dyn std::any::Any + Send + Sync>,
748        progress: Option<Sender<Progress>>,
749        timeout: Option<Duration>,
750        wake: Box<dyn Fn() + Send + Sync>,
751        start_call: impl FnOnce(
752            *mut std::ffi::c_void,
753            sys::qar_progress_callback_t,
754            *mut sys::QarCancelToken,
755        ) -> sys::QarResult,
756    ) -> Result<PendingOnboard> {
757        let finish_runtime = Rc::clone(&self.inner);
758        let abandon_runtime = Rc::clone(&self.inner);
759        let poll_runtime = Rc::clone(&self.inner);
760        let spec = CallSpec {
761            function,
762            progress,
763            timeout,
764            wake,
765            keep: Some(keep),
766            finish: Box::new(move |outcome: RawOutcome| {
767                let api = &finish_runtime.library.api;
768                if let Err(error) = check(api, function, outcome.result) {
769                    release_session(api, outcome.handle);
770                    return Err(error);
771                }
772                let session = require_handle(outcome.handle as *mut sys::QarSession, function)?;
773                #[allow(deprecated)] // the deprecated field is still filled
774                Ok(Onboarded {
775                    onboarding_id: OnboardingId(outcome.id),
776                    session: Session::from_handle(session, finish_runtime),
777                })
778            }),
779            abandon: Box::new(move |call| abandon_runtime.abandon_onboard(call)),
780            before_poll: Box::new(move || poll_runtime.release_delivered_abandoned_onboards()),
781            destroy: Some(release_session),
782        };
783        pending::start(&self.inner.library, spec, start_call)
784    }
785
786    /// Erases a persisted identity slot (`qar_runtime_forget`): its certificate, persisted
787    /// instance id and session state. Works with no active session. Fails with
788    /// [`crate::StatusCode::ONBOARDING_SESSION_STILL_ACTIVE`] while a session of that slot is
789    /// alive, and [`crate::StatusCode::ONBOARDING_SESSION_NOT_FOUND`] without a slot.
790    #[deprecated(
791        note = "persisted slots are no longer a supported way to join, so there is nothing to \
792                forget: a local app, a companion and a member hub's app store nothing; dropping \
793                the `Session` ends it, and revoking the app's approval in QAROS removes it"
794    )]
795    pub fn forget(&self, onboarding_id: OnboardingId) -> Result<()> {
796        if onboarding_id.is_zero() {
797            return Err(Error::InvalidArgument(
798                "the zero onboarding id cannot be forgotten".to_string(),
799            ));
800        }
801        let mut init = defaults::qar_forget_init_default();
802        init.onboarding_id = onboarding_id.to_raw();
803        let api = &self.inner.library.api;
804        // SAFETY: init is stamped and lives for the call.
805        let result =
806            unsafe { (api.qar_impl_runtime_forget)(self.inner.handle.as_ptr(), &raw const init) };
807        check(api, "qar_runtime_forget", result)
808    }
809}
810
811impl RuntimeInner {
812    pub(crate) fn handle(&self) -> *mut sys::QarRuntime {
813        self.handle.as_ptr()
814    }
815
816    pub(crate) fn abandon_onboard(&self, onboard: AbandonedCall) {
817        self.abandoned_onboards.borrow_mut().push(onboard);
818    }
819
820    /// Destroys the sessions that abandoned onboards delivered since the last call.
821    pub(crate) fn release_delivered_abandoned_onboards(&self) {
822        let api = &self.library.api;
823        self.abandoned_onboards
824            .borrow_mut()
825            .retain(|onboard| !onboard.release_if_delivered(api));
826    }
827}
828
829impl Drop for RuntimeInner {
830    fn drop(&mut self) {
831        let api = &self.library.api;
832        // A session an abandoned onboard delivered is destroyed while the runtime lives.
833        self.abandoned_onboards
834            .get_mut()
835            .retain(|onboard| !onboard.release_if_delivered(api));
836        // SAFETY: every session holds an Rc to this value, so all session handles are already
837        // destroyed; the handle is not used again. Per the header, the destroy returns only after
838        // the callbacks of the onboards still running have returned (with QAR_STATUS_TIMEOUT).
839        unsafe { (api.qar_impl_runtime_handle_destroy)(self.handle.as_ptr()) };
840        for onboard in std::mem::take(self.abandoned_onboards.get_mut()) {
841            onboard.leak_late_delivery();
842        }
843    }
844}
845
846/// Destroys a session an async onboard or rejoin delivered that nobody takes.
847fn release_session(api: &sys::QarApi, session: usize) {
848    if session != 0 {
849        // SAFETY: delivered to us, used by nobody, and its runtime is alive.
850        unsafe { (api.qar_impl_session_handle_destroy)(session as *mut sys::QarSession) };
851    }
852}
853
854/// `None` is the C API's default, which it spells as `0`; a zero (or sub-millisecond) duration
855/// would mean the same, so it is refused instead of silently becoming the default.
856pub(crate) fn optional_milliseconds(value: Option<Duration>, what: &str) -> Result<u32> {
857    let Some(duration) = value else {
858        return Ok(0);
859    };
860    match u32::try_from(duration.as_millis()) {
861        Ok(0) => Err(Error::InvalidArgument(format!(
862            "a zero {what}; pass None for the default"
863        ))),
864        Ok(milliseconds) => Ok(milliseconds),
865        Err(_) => Err(Error::InvalidArgument(format!(
866            "{what} {duration:?} exceeds u32 milliseconds"
867        ))),
868    }
869}