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

qaros/
cancel.rs

1use std::fmt;
2use std::ptr::{self, NonNull};
3use std::rc::Rc;
4use std::sync::{Arc, Mutex, PoisonError};
5use std::time::Duration;
6
7use qaros_sys::{QarCancelToken, QarResult, QarStatusCode};
8
9use crate::error::{Error, Result, StatusCode, check};
10use crate::library::{LibraryInner, require_handle};
11
12/// A `QarCancelToken`.
13///
14/// Pass it to blocking calls (through [`crate::BlockingOptions`]) and cancel
15/// it from a callback, or create it with a timeout. The token itself is not
16/// `Send` because it shares the library handle; to cancel from another thread
17/// (a Ctrl+C handler, a watcher of stdin), hand that thread a
18/// [`CancelToken::cancel_handle`].
19#[derive(Clone, Debug)]
20pub struct CancelToken {
21    pub(crate) inner: Rc<CancelTokenInner>,
22}
23
24#[derive(Debug)]
25pub(crate) struct CancelTokenInner {
26    pub(crate) handle: NonNull<QarCancelToken>,
27    library: Rc<LibraryInner>,
28    cross_thread: Arc<CrossThreadToken>,
29}
30
31type CancelFunction = unsafe extern "C" fn(*mut QarCancelToken) -> QarResult;
32
33/// The token as other threads see it: the handle while its owner lives, `None` after.
34struct CrossThreadToken {
35    handle: Mutex<Option<TokenPointer>>,
36    cancel: CancelFunction,
37}
38
39struct TokenPointer(NonNull<QarCancelToken>);
40
41// SAFETY: the C API allows `qar_cancel_token_cancel` from any thread; the pointer is only used
42// under the mutex, which the owner takes before it destroys the handle.
43unsafe impl Send for TokenPointer {}
44
45impl fmt::Debug for CrossThreadToken {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        formatter
48            .debug_struct("CrossThreadToken")
49            .finish_non_exhaustive()
50    }
51}
52
53/// Cancels a [`CancelToken`] from any thread (`qar_cancel_token_cancel`). It does not keep the
54/// token alive: once the token's last owner is gone, [`CancelHandle::cancel`] does nothing and
55/// returns `Ok(false)`.
56#[derive(Clone, Debug)]
57pub struct CancelHandle {
58    token: Arc<CrossThreadToken>,
59}
60
61impl CancelHandle {
62    pub(crate) fn for_token(token: &CancelTokenInner) -> Self {
63        Self {
64            token: Arc::clone(&token.cross_thread),
65        }
66    }
67
68    /// Cancels every call that was given the token. `Ok(true)` when the token was cancelled,
69    /// `Ok(false)` when its owner had already dropped it.
70    pub fn cancel(&self) -> Result<bool> {
71        let handle = self
72            .token
73            .handle
74            .lock()
75            .unwrap_or_else(PoisonError::into_inner);
76        let Some(token) = handle.as_ref() else {
77            return Ok(false);
78        };
79        // SAFETY: the owner destroys the handle only after taking this lock and clearing it.
80        let result = unsafe { (self.token.cancel)(token.0.as_ptr()) };
81        if result.code == QarStatusCode::QAR_STATUS_SUCCESS {
82            Ok(true)
83        } else {
84            Err(Error::Api {
85                function: "qar_cancel_token_cancel",
86                code: StatusCode::from_raw(result.code),
87                message: String::new(),
88                causes: Vec::new(),
89            })
90        }
91    }
92}
93
94impl CancelToken {
95    pub(crate) fn create(library: &Rc<LibraryInner>, timeout: Option<Duration>) -> Result<Self> {
96        Ok(Self {
97            inner: Rc::new(CancelTokenInner::create(library, timeout)?),
98        })
99    }
100
101    /// Cancels every call that was given this token (`qar_cancel_token_cancel`).
102    pub fn cancel(&self) -> Result<()> {
103        self.inner.cancel()
104    }
105
106    /// Whether [`Self::cancel`] has been called on this token.
107    pub fn is_cancelled(&self) -> bool {
108        let api = &self.inner.library.api;
109        // SAFETY: the handle is live until CancelTokenInner drops.
110        unsafe { (api.qar_impl_cancel_token_is_cancelled)(self.inner.handle.as_ptr()) }
111    }
112
113    /// Whether the token's timeout has passed.
114    pub fn is_timed_out(&self) -> bool {
115        let api = &self.inner.library.api;
116        // SAFETY: the handle is live until CancelTokenInner drops.
117        unsafe { (api.qar_impl_cancel_token_is_timeout)(self.inner.handle.as_ptr()) }
118    }
119
120    /// A handle that cancels this token from any thread, for as long as the token lives.
121    pub fn cancel_handle(&self) -> CancelHandle {
122        CancelHandle {
123            token: Arc::clone(&self.inner.cross_thread),
124        }
125    }
126
127    /// The `QarCancelToken` handle, for a raw call (through [`crate::Library::raw_api`]) that
128    /// takes a cancel token, or for `qar_cancel_token_cancel_after`.
129    ///
130    /// Taking the pointer is safe; using it is `unsafe`, under the rules of
131    /// [`crate::Session::as_raw`] for a token: valid while this `CancelToken` (or a clone of it)
132    /// lives, never destroyed by the caller, used on the thread that owns the token. To cancel
133    /// from another thread, use [`CancelToken::cancel_handle`].
134    pub fn as_raw(&self) -> *mut QarCancelToken {
135        self.inner.handle.as_ptr()
136    }
137
138    pub(crate) fn as_ptr(&self) -> *mut QarCancelToken {
139        self.inner.handle.as_ptr()
140    }
141}
142
143impl CancelTokenInner {
144    pub(crate) fn create(library: &Rc<LibraryInner>, timeout: Option<Duration>) -> Result<Self> {
145        let api = &library.api;
146        let mut handle: *mut QarCancelToken = ptr::null_mut();
147        let (function, result) = match timeout {
148            None => (
149                "qar_cancel_token_create",
150                // SAFETY: handle is a valid out-pointer.
151                unsafe { (api.qar_impl_cancel_token_create)(&raw mut handle) },
152            ),
153            Some(duration) => {
154                let milliseconds = u32::try_from(duration.as_millis()).map_err(|_| {
155                    Error::InvalidArgument("cancel timeout exceeds u32 milliseconds".to_string())
156                })?;
157                (
158                    "qar_cancel_token_create_with_timeout",
159                    // SAFETY: handle is a valid out-pointer.
160                    unsafe {
161                        (api.qar_impl_cancel_token_create_with_timeout)(
162                            &raw mut handle,
163                            milliseconds,
164                        )
165                    },
166                )
167            }
168        };
169        check(api, function, result)?;
170        let handle = require_handle(handle, function)?;
171        Ok(Self {
172            handle,
173            library: Rc::clone(library),
174            cross_thread: Arc::new(CrossThreadToken {
175                handle: Mutex::new(Some(TokenPointer(handle))),
176                cancel: api.qar_impl_cancel_token_cancel,
177            }),
178        })
179    }
180
181    pub(crate) fn cancel(&self) -> Result<()> {
182        let api = &self.library.api;
183        // SAFETY: the handle is live until this value drops.
184        let result = unsafe { (api.qar_impl_cancel_token_cancel)(self.handle.as_ptr()) };
185        check(api, "qar_cancel_token_cancel", result)
186    }
187}
188
189impl Drop for CancelTokenInner {
190    fn drop(&mut self) {
191        // From here on no other thread reaches the handle.
192        self.cross_thread
193            .handle
194            .lock()
195            .unwrap_or_else(PoisonError::into_inner)
196            .take();
197        // SAFETY: last owner; no call using the token is in progress because
198        // blocking calls borrow the token and subscriptions keep their own
199        // reference until the session handle is destroyed.
200        unsafe { (self.library.api.qar_impl_cancel_token_handle_destroy)(self.handle.as_ptr()) };
201    }
202}