1use std::any::Any;
25use std::ffi::{CStr, c_char, c_void};
26use std::panic::{AssertUnwindSafe, catch_unwind};
27use std::rc::Rc;
28use std::sync::mpsc::Sender;
29use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
30use std::time::Duration;
31
32use qaros_sys::{self as sys, QarApi};
33
34use crate::callbacks::Progress;
35use crate::cancel::{CancelHandle, CancelTokenInner};
36use crate::error::{Error, Result, check};
37use crate::library::LibraryInner;
38use crate::runtime::Onboarded;
39use crate::types::ActionSeverity;
40
41pub(crate) type Destroy = fn(&QarApi, usize);
43
44#[derive(Clone, Copy, Debug)]
48pub(crate) struct RawOutcome {
49 pub(crate) result: sys::QarResult,
50 pub(crate) handle: usize,
51 pub(crate) id: [u8; 16],
52}
53
54#[derive(Debug)]
55enum CallState {
56 Pending,
57 Delivered(RawOutcome),
58 Taken,
60}
61
62pub(crate) struct CallShared {
65 state: Mutex<CallState>,
66 called_back: Condvar,
68 progress: Option<Sender<Progress>>,
69 wake: Box<dyn Fn() + Send + Sync>,
70 _keep: Option<Box<dyn Any + Send + Sync>>,
72}
73
74impl CallShared {
75 fn lock(&self) -> MutexGuard<'_, CallState> {
76 self.state.lock().unwrap_or_else(PoisonError::into_inner)
77 }
78
79 fn take_delivered(&self) -> Option<RawOutcome> {
81 let mut state = self.lock();
82 let CallState::Delivered(outcome) = *state else {
83 return None;
84 };
85 *state = CallState::Taken;
86 Some(outcome)
87 }
88
89 fn wait(&self) {
91 let _state = self
92 .called_back
93 .wait_while(self.lock(), |state| matches!(*state, CallState::Pending))
94 .unwrap_or_else(PoisonError::into_inner);
95 }
96}
97
98unsafe fn deliver(user_state: *mut c_void, outcome: RawOutcome) {
105 if user_state.is_null() {
106 return;
107 }
108 let shared = unsafe { Arc::from_raw(user_state.cast_const().cast::<CallShared>()) };
110 *shared.lock() = CallState::Delivered(outcome);
111 shared.called_back.notify_all();
112 if catch_unwind(AssertUnwindSafe(|| (shared.wake)())).is_err() {
113 log::error!("the wake callback of an async call panicked");
114 }
115}
116
117pub(crate) unsafe extern "C" fn onboard_result_trampoline(
118 status: sys::QarResult,
119 onboarding_id: *const sys::QarOnboardingId,
120 session: *mut sys::QarSession,
121 user_state: *mut c_void,
122) {
123 let id = unsafe { onboarding_id.as_ref() }.map_or([0; 16], |id| id.data);
125 unsafe {
127 deliver(
128 user_state,
129 RawOutcome {
130 result: status,
131 handle: session as usize,
132 id,
133 },
134 );
135 }
136}
137
138pub(crate) unsafe extern "C" fn handle_result_trampoline<Handle>(
139 status: sys::QarResult,
140 handle: *mut Handle,
141 user_state: *mut c_void,
142) {
143 unsafe {
145 deliver(
146 user_state,
147 RawOutcome {
148 result: status,
149 handle: handle as usize,
150 id: [0; 16],
151 },
152 );
153 }
154}
155
156pub(crate) unsafe extern "C" fn peer_result_trampoline(
157 status: sys::QarResult,
158 peer_id: *const sys::QarPeerId,
159 user_state: *mut c_void,
160) {
161 let id = unsafe { peer_id.as_ref() }.map_or([0; 16], |id| id.data);
163 unsafe {
165 deliver(
166 user_state,
167 RawOutcome {
168 result: status,
169 handle: 0,
170 id,
171 },
172 );
173 }
174}
175
176unsafe extern "C" fn progress_trampoline(
177 severity: sys::QarActionSeverity,
178 percent: f32,
179 message: *const c_char,
180 user_state: *mut c_void,
181) {
182 if user_state.is_null() {
183 return;
184 }
185 let shared = unsafe { &*user_state.cast_const().cast::<CallShared>() };
188 let Some(sender) = &shared.progress else {
189 return;
190 };
191 let message = if message.is_null() {
192 String::new()
193 } else {
194 unsafe { CStr::from_ptr(message) }
196 .to_string_lossy()
197 .into_owned()
198 };
199 let _ = sender.send(Progress {
201 severity: ActionSeverity::from_raw(severity),
202 percent,
203 message,
204 });
205}
206
207pub(crate) struct AbandonedCall {
209 shared: Arc<CallShared>,
210 _token: Rc<CancelTokenInner>,
213 destroy: Option<Destroy>,
214 function: &'static str,
215 owner_keep: Option<Box<dyn Any>>,
217}
218
219impl std::fmt::Debug for AbandonedCall {
220 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 formatter
222 .debug_struct("AbandonedCall")
223 .field("function", &self.function)
224 .field("state", &*self.shared.lock())
225 .finish_non_exhaustive()
226 }
227}
228
229impl AbandonedCall {
230 pub(crate) fn release_if_delivered(&self, api: &QarApi) -> bool {
232 let Some(outcome) = self.shared.take_delivered() else {
233 return false;
234 };
235 if let Some(destroy) = self.destroy
236 && outcome.handle != 0
237 {
238 destroy(api, outcome.handle);
239 }
240 true
241 }
242
243 pub(crate) fn keep_until_released(&mut self, value: Box<dyn Any>) {
245 self.owner_keep = Some(value);
246 }
247
248 pub(crate) fn settle(&self, api: &QarApi) {
251 self.shared.wait();
252 self.release_if_delivered(api);
253 }
254
255 pub(crate) fn leak_late_delivery(self) {
258 if let Some(outcome) = self.shared.take_delivered()
259 && outcome.handle != 0
260 {
261 log::warn!(
262 "{} delivered a handle while its owner was destroyed; the handle is not released",
263 self.function
264 );
265 }
266 }
267}
268
269type Finish<T> = Box<dyn FnOnce(RawOutcome) -> Result<T>>;
270type Abandon = Box<dyn FnOnce(AbandonedCall)>;
271
272struct Call<T> {
273 shared: Arc<CallShared>,
274 token: Rc<CancelTokenInner>,
275 finish: Finish<T>,
277 abandon: Abandon,
279 before_poll: Box<dyn Fn()>,
281 destroy: Option<Destroy>,
282 function: &'static str,
283}
284
285pub struct PendingCall<T> {
301 call: Option<Call<T>>,
302}
303
304pub type PendingOnboard = PendingCall<Onboarded>;
306
307impl<T> std::fmt::Debug for PendingCall<T> {
308 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309 let call = self
310 .call
311 .as_ref()
312 .map(|call| (call.function, format!("{:?}", *call.shared.lock())));
313 formatter
314 .debug_struct("PendingCall")
315 .field("call", &call)
316 .finish()
317 }
318}
319
320pub(crate) struct CallSpec<T> {
322 pub(crate) function: &'static str,
323 pub(crate) progress: Option<Sender<Progress>>,
324 pub(crate) timeout: Option<Duration>,
325 pub(crate) wake: Box<dyn Fn() + Send + Sync>,
326 pub(crate) keep: Option<Box<dyn Any + Send + Sync>>,
327 pub(crate) finish: Finish<T>,
328 pub(crate) abandon: Abandon,
329 pub(crate) before_poll: Box<dyn Fn()>,
330 pub(crate) destroy: Option<Destroy>,
331}
332
333pub(crate) fn start<T>(
336 library: &Rc<LibraryInner>,
337 spec: CallSpec<T>,
338 start_call: impl FnOnce(
339 *mut c_void,
340 sys::qar_progress_callback_t,
341 *mut sys::QarCancelToken,
342 ) -> sys::QarResult,
343) -> Result<PendingCall<T>> {
344 let token = Rc::new(CancelTokenInner::create(library, spec.timeout)?);
345 let progress_callback: sys::qar_progress_callback_t = spec
346 .progress
347 .as_ref()
348 .map(|_| progress_trampoline as unsafe extern "C" fn(_, _, _, _));
349 let shared = Arc::new(CallShared {
350 state: Mutex::new(CallState::Pending),
351 called_back: Condvar::new(),
352 progress: spec.progress,
353 wake: spec.wake,
354 _keep: spec.keep,
355 });
356 let user_state = Arc::into_raw(Arc::clone(&shared))
357 .cast_mut()
358 .cast::<c_void>();
359 let result = start_call(user_state, progress_callback, token.handle.as_ptr());
360 if let Err(error) = check(&library.api, spec.function, result) {
361 drop(unsafe { Arc::from_raw(user_state.cast_const().cast::<CallShared>()) });
365 return Err(error);
366 }
367 Ok(PendingCall {
368 call: Some(Call {
369 shared,
370 token,
371 finish: spec.finish,
372 abandon: spec.abandon,
373 before_poll: spec.before_poll,
374 destroy: spec.destroy,
375 function: spec.function,
376 }),
377 })
378}
379
380impl<T> PendingCall<T> {
381 pub fn poll(&mut self) -> Option<Result<T>> {
385 let Some(call) = &self.call else {
386 return Some(Err(already_taken()));
387 };
388 (call.before_poll)();
389 let outcome = call.shared.take_delivered()?;
390 let call = self.call.take()?;
391 Some((call.finish)(outcome))
392 }
393
394 pub fn wait(mut self) -> Result<T> {
397 let Some(call) = &self.call else {
398 return Err(already_taken());
399 };
400 call.shared.wait();
401 self.poll().unwrap_or_else(|| Err(already_taken()))
402 }
403
404 pub fn cancel_handle(&self) -> Option<CancelHandle> {
408 self.call
409 .as_ref()
410 .map(|call| CancelHandle::for_token(&call.token))
411 }
412}
413
414fn already_taken() -> Error {
415 Error::InvalidArgument("the outcome of this pending call was already taken".to_string())
416}
417
418impl<T> Drop for PendingCall<T> {
419 fn drop(&mut self) {
420 let Some(call) = self.call.take() else {
421 return;
422 };
423 if let Some(outcome) = call.shared.take_delivered() {
424 drop((call.finish)(outcome));
426 return;
427 }
428 if let Err(error) = call.token.cancel() {
429 log::warn!("cancelling {}: {error}", call.function);
430 }
431 (call.abandon)(AbandonedCall {
432 shared: call.shared,
433 _token: call.token,
434 destroy: call.destroy,
435 function: call.function,
436 owner_keep: None,
437 });
438 }
439}
440
441pub(crate) struct Keep<Data>(pub(crate) Data);
445
446unsafe impl<Data> Send for Keep<Data> {}
448unsafe impl<Data> Sync for Keep<Data> {}