Debian Codegraph @

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

raw
1 use once_cell::sync::OnceCell;
2 use std::{
3 future::Future,
4 mem::ManuallyDrop,
5 panic,
6 pin::Pin,
7 sync::{Arc, Mutex},
8 task::{Context, Poll, Waker},
9 };
10
11 use super::*;
12 use crate::{test_util::TestError, Lift, RustBuffer, RustCallStatusCode};
13
14 // Sender/Receiver pair that we use for testing
15 struct Channel {
16 result: Option<Result<Result<String, TestError>, LiftArgsError>>,
17 waker: Option<Waker>,
18 }
19
20 struct Sender(Arc<Mutex<Channel>>);
21
22 impl Sender {
23 fn wake(&self) {
24 let inner = self.0.lock().unwrap();
25 if let Some(waker) = &inner.waker {
26 waker.wake_by_ref();
27 }
28 }
29
30 fn send(&self, value: Result<String, TestError>) {
31 let mut inner = self.0.lock().unwrap();
32 if inner.result.replace(Ok(value)).is_some() {
33 panic!("value already sent");
34 }
35 if let Some(waker) = &inner.waker {
36 waker.wake_by_ref();
37 }
38 }
39
40 fn send_lift_args_error(&self, arg_name: &'static str, error: anyhow::Error) {
41 let mut inner = self.0.lock().unwrap();
42 if inner
43 .result
44 .replace(Err(LiftArgsError { arg_name, error }))
45 .is_some()
46 {
47 panic!("value already sent");
48 }
49 if let Some(waker) = &inner.waker {
50 waker.wake_by_ref();
51 }
52 }
53 }
54
55 struct Receiver(Arc<Mutex<Channel>>);
56
57 impl Future for Receiver {
58 type Output = Result<Result<String, TestError>, LiftArgsError>;
59
60 fn poll(
61 self: Pin<&mut Self>,
62 context: &mut Context<'_>,
63 ) -> Poll<Result<Result<String, TestError>, LiftArgsError>> {
64 let mut inner = self.0.lock().unwrap();
65 match inner.result.take() {
66 Some(v) => Poll::Ready(v),
67 None => {
68 inner.waker = Some(context.waker().clone());
69 Poll::Pending
70 }
71 }
72 }
73 }
74
75 // Create a sender and rust future that we can use for testing
76 fn channel() -> (Sender, Arc<dyn RustFutureFfi<RustBuffer>>) {
77 let channel = Arc::new(Mutex::new(Channel {
78 result: None,
79 waker: None,
80 }));
81 let rust_future = RustFuture::new(Box::pin(Receiver(channel.clone())), crate::UniFfiTag);
82 (Sender(channel), rust_future)
83 }
84
85 /// Poll a Rust future and get an OnceCell that's set when the continuation is called
86 fn poll(rust_future: &Arc<dyn RustFutureFfi<RustBuffer>>) -> Arc<OnceCell<RustFuturePoll>> {
87 let cell = Arc::new(OnceCell::new());
88 let handle = Arc::into_raw(cell.clone()) as u64;
89 rust_future.clone().ffi_poll(poll_continuation, handle);
90 cell
91 }
92
93 extern "C" fn poll_continuation(data: u64, code: RustFuturePoll) {
94 let cell = unsafe { Arc::from_raw(data as *const OnceCell<RustFuturePoll>) };
95 cell.set(code).expect("Error setting OnceCell");
96 }
97
98 fn complete(rust_future: Arc<dyn RustFutureFfi<RustBuffer>>) -> (RustBuffer, RustCallStatus) {
99 let mut out_status_code = RustCallStatus::default();
100 let return_value = rust_future.ffi_complete(&mut out_status_code);
101 (return_value, out_status_code)
102 }
103
104 #[test]
105 fn test_success() {
106 let (sender, rust_future) = channel();
107
108 // Test polling the rust future before it's ready
109 let continuation_result = poll(&rust_future);
110 assert_eq!(continuation_result.get(), None);
111 sender.wake();
112 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::MaybeReady));
113
114 // Test polling the rust future when it's ready
115 let continuation_result = poll(&rust_future);
116 assert_eq!(continuation_result.get(), None);
117 sender.send(Ok("All done".into()));
118 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::MaybeReady));
119
120 // Future polls should immediately return ready
121 let continuation_result = poll(&rust_future);
122 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
123
124 // Complete the future
125 let (return_buf, call_status) = complete(rust_future);
126 assert_eq!(call_status.code, RustCallStatusCode::Success);
127 assert_eq!(
128 <String as Lift<crate::UniFfiTag>>::try_lift(return_buf).unwrap(),
129 "All done"
130 );
131 }
132
133 #[test]
134 fn test_error() {
135 let (sender, rust_future) = channel();
136
137 let continuation_result = poll(&rust_future);
138 assert_eq!(continuation_result.get(), None);
139 sender.send(Err("Something went wrong".into()));
140 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::MaybeReady));
141
142 let continuation_result = poll(&rust_future);
143 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
144
145 let (_, call_status) = complete(rust_future);
146 assert_eq!(call_status.code, RustCallStatusCode::Error);
147 assert_eq!(
148 <TestError as Lift<crate::UniFfiTag>>::try_lift_from_rust_buffer(ManuallyDrop::into_inner(
149 call_status.error_buf
150 ))
151 .unwrap(),
152 TestError::from("Something went wrong"),
153 )
154 }
155
156 #[test]
157 fn test_lift_args_error() {
158 let (sender, rust_future) = channel();
159
160 let continuation_result = poll(&rust_future);
161 assert_eq!(continuation_result.get(), None);
162 sender.send_lift_args_error("arg0", anyhow::anyhow!("Invalid handle"));
163 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::MaybeReady));
164
165 let continuation_result = poll(&rust_future);
166 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
167
168 let (_, call_status) = complete(rust_future);
169 assert_eq!(call_status.code, RustCallStatusCode::UnexpectedError);
170 assert_eq!(
171 <String as Lift<crate::UniFfiTag>>::try_lift(ManuallyDrop::into_inner(
172 call_status.error_buf
173 ))
174 .unwrap(),
175 "Failed to convert arg 'arg0': Invalid handle",
176 )
177 }
178
179 // Once `complete` is called, the inner future should be released, even if wakers still hold a
180 // reference to the RustFuture
181 #[test]
182 fn test_cancel() {
183 let (_sender, rust_future) = channel();
184
185 let continuation_result = poll(&rust_future);
186 assert_eq!(continuation_result.get(), None);
187 rust_future.ffi_cancel();
188 // Cancellation should immediately invoke the callback with RustFuturePoll::Ready
189 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
190
191 // Future polls should immediately invoke the callback with RustFuturePoll::Ready
192 let continuation_result = poll(&rust_future);
193 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
194
195 let (_, call_status) = complete(rust_future);
196 assert_eq!(call_status.code, RustCallStatusCode::Cancelled);
197 }
198
199 // Once `free` is called, the inner future should be released, even if wakers still hold a
200 // reference to the RustFuture
201 #[test]
202 fn test_release_future() {
203 let (sender, rust_future) = channel();
204 // Create a weak reference to the channel to use to check if rust_future has dropped its
205 // future.
206 let channel_weak = Arc::downgrade(&sender.0);
207 drop(sender);
208 // Create an extra ref to rust_future, simulating a waker that still holds a reference to
209 // it
210 let rust_future2 = rust_future.clone();
211
212 // Complete the rust future
213 rust_future.ffi_free();
214 // Even though rust_future is still alive, the channel shouldn't be
215 assert!(Arc::strong_count(&rust_future2) > 0);
216 assert_eq!(channel_weak.strong_count(), 0);
217 assert!(channel_weak.upgrade().is_none());
218 }
219
220 // If `free` is called with a continuation still stored, we should call it them then.
221 //
222 // This shouldn't happen in practice, but it seems like good defensive programming
223 #[test]
224 fn test_complete_with_stored_continuation() {
225 let (_sender, rust_future) = channel();
226
227 let continuation_result = poll(&rust_future);
228 rust_future.ffi_free();
229 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
230 }
231
232 // Test what happens if we see a `wake()` call while we're polling the future. This can
233 // happen, for example, with futures that are handled by a tokio thread pool. We should
234 // schedule another poll of the future in this case.
235 #[test]
236 fn test_wake_during_poll() {
237 let mut first_time = true;
238 let future = std::future::poll_fn(move |ctx| {
239 if first_time {
240 first_time = false;
241 // Wake the future while we are in the middle of polling it
242 ctx.waker().wake_by_ref();
243 Poll::Pending
244 } else {
245 // The second time we're polled, we're ready
246 Poll::Ready(Ok("All done".to_owned()))
247 }
248 });
249 let rust_future: Arc<dyn RustFutureFfi<RustBuffer>> =
250 RustFuture::new(Box::pin(future), crate::UniFfiTag);
251 let continuation_result = poll(&rust_future);
252 // The continuation function should called immediately
253 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::MaybeReady));
254 // A second poll should finish the future
255 let continuation_result = poll(&rust_future);
256 assert_eq!(continuation_result.get(), Some(&RustFuturePoll::Ready));
257 let (return_buf, call_status) = complete(rust_future);
258 assert_eq!(call_status.code, RustCallStatusCode::Success);
259 assert_eq!(
260 <String as Lift<crate::UniFfiTag>>::try_lift(return_buf).unwrap(),
261 "All done"
262 );
263 }