Debian Codegraph @

third_party/rust/uniffi_core/src/ffi/rustfuture/future.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 //! [`RustFuture`] represents a [`Future`] that can be sent to the foreign code over FFI.
6 //!
7 //! This type is not instantiated directly, but via the procedural macros, such as `#[uniffi::export]`.
8 //!
9 //! # The big picture
10 //!
11 //! We implement async foreign functions using a simplified version of the Future API:
12 //!
13 //! 0. At startup, register a [RustFutureContinuationCallback] by calling
14 //! rust_future_continuation_callback_set.
15 //! 1. Call the scaffolding function to get a [Handle]
16 //! 2. In a loop:
17 //! - Call [rust_future_poll]
18 //! - Suspend the function until the [rust_future_poll] continuation function is called
19 //! - If the continuation was function was called with [RustFuturePoll::Ready], then break
20 //! otherwise continue.
21 //! 3. If the async function is cancelled, then call [rust_future_cancel]. This causes the
22 //! continuation function to be called with [RustFuturePoll::Ready] and the [RustFuture] to
23 //! enter a cancelled state.
24 //! 4. Call [rust_future_complete] to get the result of the future.
25 //! 5. Call [rust_future_free] to free the future, ideally in a finally block. This:
26 //! - Releases any resources held by the future
27 //! - Calls any continuation callbacks that have not been called yet
28 //!
29 //! Note: Technically, the foreign code calls the scaffolding versions of the `rust_future_*`
30 //! functions. These are generated by the scaffolding macro, specially prefixed, and extern "C",
31 //! and manually monomorphized in the case of [rust_future_complete]. See
32 //! `uniffi_macros/src/setup_scaffolding.rs` for details.
33 //!
34 //! ## How does `Future` work exactly?
35 //!
36 //! A [`Future`] in Rust does nothing. When calling an async function, it just
37 //! returns a `Future` but nothing has happened yet. To start the computation,
38 //! the future must be polled. It returns [`Poll::Ready(r)`][`Poll::Ready`] if
39 //! the result is ready, [`Poll::Pending`] otherwise. `Poll::Pending` basically
40 //! means:
41 //!
42 //! > Please, try to poll me later, maybe the result will be ready!
43 //!
44 //! This model is very different than what other languages do, but it can actually
45 //! be translated quite easily, fortunately for us!
46 //!
47 //! But… wait a minute… who is responsible to poll the `Future` if a `Future` does
48 //! nothing? Well, it's _the executor_. The executor is responsible _to drive_ the
49 //! `Future`: that's where they are polled.
50 //!
51 //! But… wait another minute… how does the executor know when to poll a [`Future`]?
52 //! Does it poll them randomly in an endless loop? Well, no, actually it depends
53 //! on the executor! A well-designed `Future` and executor work as follows.
54 //! Normally, when [`Future::poll`] is called, a [`Context`] argument is
55 //! passed to it. It contains a [`Waker`]. The [`Waker`] is built on top of a
56 //! [`RawWaker`] which implements whatever is necessary. Usually, a waker will
57 //! signal the executor to poll a particular `Future`. A `Future` will clone
58 //! or pass-by-ref the waker to somewhere, as a callback, a completion, a
59 //! function, or anything, to the system that is responsible to notify when a
60 //! task is completed. So, to recap, the waker is _not_ responsible for waking the
61 //! `Future`, it _is_ responsible for _signaling_ the executor that a particular
62 //! `Future` should be polled again. That's why the documentation of
63 //! [`Poll::Pending`] specifies:
64 //!
65 //! > When a function returns `Pending`, the function must also ensure that the
66 //! > current task is scheduled to be awoken when progress can be made.
67 //!
68 //! “awakening” is done by using the `Waker`.
69 //!
70 //! [`Future`]: https://doc.rust-lang.org/std/future/trait.Future.html
71 //! [`Future::poll`]: https://doc.rust-lang.org/std/future/trait.Future.html#tymethod.poll
72 //! [`Pol::Ready`]: https://doc.rust-lang.org/std/task/enum.Poll.html#variant.Ready
73 //! [`Poll::Pending`]: https://doc.rust-lang.org/std/task/enum.Poll.html#variant.Pending
74 //! [`Context`]: https://doc.rust-lang.org/std/task/struct.Context.html
75 //! [`Waker`]: https://doc.rust-lang.org/std/task/struct.Waker.html
76 //! [`RawWaker`]: https://doc.rust-lang.org/std/task/struct.RawWaker.html
77
78 use std::{
79 future::Future,
80 marker::PhantomData,
81 ops::Deref,
82 panic,
83 pin::Pin,
84 sync::{Arc, Mutex},
85 task::{Context, Poll, Wake},
86 };
87
88 use super::{
89 FutureLowerReturn, RustFutureContinuationCallback, RustFuturePoll, Scheduler,
90 UniffiCompatibleFuture,
91 };
92 use crate::{rust_call_with_out_status, FfiDefault, LiftArgsError, RustCallStatus};
93
94 type BoxedFuture<T> = Pin<Box<dyn UniffiCompatibleFuture<Result<T, LiftArgsError>>>>;
95
96 /// Wraps the actual future we're polling
97 struct WrappedFuture<T, UT>
98 where
99 T: FutureLowerReturn<UT> + 'static,
100 UT: Send + 'static,
101 {
102 // Note: this could be a single enum, but that would make it easy to mess up the future pinning
103 // guarantee. For example you might want to call `std::mem::take()` to try to get the result,
104 // but if the future happened to be stored that would move and break all internal references.
105 future: Option<BoxedFuture<T>>,
106 result: Option<Result<T::ReturnType, RustCallStatus>>,
107 }
108
109 impl<T, UT> WrappedFuture<T, UT>
110 where
111 T: FutureLowerReturn<UT> + 'static,
112 UT: Send + 'static,
113 {
114 fn new(future: BoxedFuture<T>) -> Self {
115 Self {
116 future: Some(future),
117 result: None,
118 }
119 }
120
121 // Poll the future and check if it's ready or not
122 fn poll(&mut self, context: &mut Context<'_>) -> bool {
123 if self.result.is_some() {
124 true
125 } else if let Some(future) = &mut self.future {
126 // SAFETY: We can call Pin::new_unchecked because:
127 // - This is the only time we get a &mut to `self.future`
128 // - We never poll the future after it's moved (for example by using take())
129 // - We never move RustFuture, which contains us.
130 // - RustFuture is private to this module so no other code can move it.
131 let pinned = unsafe { Pin::new_unchecked(future) };
132 // Run the poll and lift the result if it's ready
133 let mut out_status = RustCallStatus::default();
134 let result: Option<Poll<T::ReturnType>> = rust_call_with_out_status(
135 &mut out_status,
136 // This closure uses a `&mut F` value, which means it's not UnwindSafe by
137 // default. If the future panics, it may be in an invalid state.
138 //
139 // However, we can safely use `AssertUnwindSafe` since a panic will lead the `None`
140 // case below and we will never poll the future again.
141 panic::AssertUnwindSafe(|| match pinned.poll(context) {
142 Poll::Pending => Ok(Poll::Pending),
143 Poll::Ready(Ok(v)) => T::lower_return(v).map(Poll::Ready),
144 Poll::Ready(Err(e)) => T::handle_failed_lift(e).map(Poll::Ready),
145 }),
146 );
147 match result {
148 Some(Poll::Pending) => false,
149 Some(Poll::Ready(v)) => {
150 self.future = None;
151 self.result = Some(Ok(v));
152 true
153 }
154 None => {
155 self.future = None;
156 self.result = Some(Err(out_status));
157 true
158 }
159 }
160 } else {
161 trace!("poll with neither future nor result set");
162 true
163 }
164 }
165
166 fn complete(&mut self, out_status: &mut RustCallStatus) -> T::ReturnType {
167 let mut return_value = T::ReturnType::ffi_default();
168 match self.result.take() {
169 Some(Ok(v)) => return_value = v,
170 Some(Err(call_status)) => *out_status = call_status,
171 None => *out_status = RustCallStatus::cancelled(),
172 }
173 self.free();
174 return_value
175 }
176
177 fn free(&mut self) {
178 self.future = None;
179 self.result = None;
180 }
181 }
182
183 // If F and T are Send, then WrappedFuture is too
184 //
185 // Rust will not mark it Send by default when T::ReturnType is a raw pointer. This is promising
186 // that we will treat the raw pointer properly, for example by not returning it twice.
187 unsafe impl<T, UT> Send for WrappedFuture<T, UT>
188 where
189 T: FutureLowerReturn<UT> + 'static,
190 UT: Send + 'static,
191 {
192 }
193
194 /// Future that the foreign code is awaiting
195 pub(super) struct RustFuture<T, UT>
196 where
197 T: FutureLowerReturn<UT> + 'static,
198 UT: Send + 'static,
199 {
200 // This Mutex should never block if our code is working correctly, since there should not be
201 // multiple threads calling [Self::poll] and/or [Self::complete] at the same time.
202 future: Mutex<WrappedFuture<T, UT>>,
203 scheduler: Mutex<Scheduler>,
204 // UT is used as the generic parameter for [LowerReturn].
205 // Let's model this with PhantomData as a function that inputs a UT value.
206 _phantom: PhantomData<fn(UT) -> ()>,
207 }
208
209 impl<T, UT> RustFuture<T, UT>
210 where
211 T: FutureLowerReturn<UT> + 'static,
212 UT: Send + 'static,
213 {
214 pub(super) fn new(future: BoxedFuture<T>, _tag: UT) -> Arc<Self> {
215 Arc::new(Self {
216 future: Mutex::new(WrappedFuture::new(future)),
217 scheduler: Mutex::new(Scheduler::new()),
218 _phantom: PhantomData,
219 })
220 }
221
222 pub(super) fn poll(self: Arc<Self>, callback: RustFutureContinuationCallback, data: u64) {
223 let cancelled = self.is_cancelled();
224 let ready = cancelled || {
225 let mut locked = self.future.lock().unwrap();
226 let waker: std::task::Waker = Arc::clone(&self).into();
227 locked.poll(&mut Context::from_waker(&waker))
228 };
229 if ready {
230 trace!("RustFuture::poll is ready (cancelled: {cancelled})");
231 callback(data, RustFuturePoll::Ready)
232 } else {
233 self.scheduler.lock().unwrap().store(callback, data);
234 }
235 }
236
237 pub(super) fn is_cancelled(&self) -> bool {
238 self.scheduler.lock().unwrap().is_cancelled()
239 }
240
241 pub(super) fn wake(&self) {
242 trace!("RustFuture::wake called");
243 self.scheduler.lock().unwrap().wake();
244 }
245
246 pub(super) fn cancel(&self) {
247 self.scheduler.lock().unwrap().cancel();
248 }
249
250 pub(super) fn complete(&self, call_status: &mut RustCallStatus) -> T::ReturnType {
251 self.future.lock().unwrap().complete(call_status)
252 }
253
254 pub(super) fn free(self: Arc<Self>) {
255 // Call cancel() to send any leftover data to the continuation callback
256 self.scheduler.lock().unwrap().cancel();
257 // Ensure we drop our inner future, releasing all held references
258 self.future.lock().unwrap().free();
259 }
260 }
261
262 impl<T, UT> Wake for RustFuture<T, UT>
263 where
264 T: FutureLowerReturn<UT> + 'static,
265 UT: Send + 'static,
266 {
267 fn wake(self: Arc<Self>) {
268 self.deref().wake()
269 }
270
271 fn wake_by_ref(self: &Arc<Self>) {
272 self.deref().wake()
273 }
274 }
275
276 /// RustFuture FFI trait. This allows `Arc<RustFuture<F, T, UT>>` to be cast to
277 /// `Arc<dyn RustFutureFfi<T::ReturnType>>`, which is needed to implement the public FFI API. In particular, this
278 /// allows you to use RustFuture functionality without knowing the concrete Future type, which is
279 /// unnamable.
280 ///
281 /// This is parametrized on the ReturnType rather than the `T` directly, to reduce the number of
282 /// scaffolding functions we need to generate. If it was parametrized on `T`, then we would need
283 /// to create a poll, cancel, complete, and free scaffolding function for each exported async
284 /// function. That would add ~1kb binary size per exported function based on a quick estimate on a
285 /// x86-64 machine . By parametrizing on `T::ReturnType` we can instead monomorphize by hand and
286 /// only create those functions for each of the 13 possible FFI return types.
287 #[doc(hidden)]
288 pub trait RustFutureFfi<ReturnType>: Send + Sync {
289 fn ffi_poll(self: Arc<Self>, callback: RustFutureContinuationCallback, data: u64);
290 fn ffi_cancel(&self);
291 fn ffi_complete(&self, call_status: &mut RustCallStatus) -> ReturnType;
292 fn ffi_free(self: Arc<Self>);
293 }
294
295 impl<T, UT> RustFutureFfi<T::ReturnType> for RustFuture<T, UT>
296 where
297 T: FutureLowerReturn<UT> + 'static,
298 UT: Send + 'static,
299 {
300 fn ffi_poll(self: Arc<Self>, callback: RustFutureContinuationCallback, data: u64) {
301 self.poll(callback, data)
302 }
303
304 fn ffi_cancel(&self) {
305 self.cancel()
306 }
307
308 fn ffi_complete(&self, call_status: &mut RustCallStatus) -> T::ReturnType {
309 self.complete(call_status)
310 }
311
312 fn ffi_free(self: Arc<Self>) {
313 self.free();
314 }
315 }