Debian Codegraph @

third_party/rust/wit-bindgen-rt/src/async_support.rs

raw
1 #![deny(missing_docs)]
2 #![allow(static_mut_refs)]
3
4 extern crate std;
5 use std::alloc::{self, Layout};
6 use std::any::Any;
7 use std::boxed::Box;
8 use std::collections::{hash_map, HashMap};
9 use std::fmt::{self, Debug, Display};
10 use std::future::Future;
11 use std::pin::Pin;
12 use std::ptr;
13 use std::string::String;
14 use std::sync::Arc;
15 use std::task::{Context, Poll, Wake, Waker};
16 use std::vec::Vec;
17
18 use futures::channel::oneshot;
19 use futures::future::FutureExt;
20 use futures::stream::{FuturesUnordered, StreamExt};
21 use once_cell::sync::Lazy;
22
23 mod future_support;
24 mod stream_support;
25
26 pub use {
27 future_support::{FutureReader, FutureVtable, FutureWriter},
28 stream_support::{StreamReader, StreamVtable, StreamWriter},
29 };
30
31 pub use futures;
32
33 type BoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
34
35 /// Represents a task created by either a call to an async-lifted export or a
36 /// future run using `block_on` or `poll_future`.
37 struct FutureState {
38 /// Number of in-progress async-lowered import calls and/or stream/future reads/writes.
39 todo: usize,
40 /// Remaining work to do (if any) before this task can be considered "done".
41 ///
42 /// Note that we won't tell the host the task is done until this is drained
43 /// and `todo` is zero.
44 tasks: Option<FuturesUnordered<BoxFuture>>,
45 }
46
47 /// Represents the state of a stream or future.
48 #[doc(hidden)]
49 pub enum Handle {
50 LocalOpen,
51 LocalReady(Box<dyn Any>, Waker),
52 LocalWaiting(oneshot::Sender<Box<dyn Any>>),
53 LocalClosed,
54 Read,
55 Write,
56 }
57
58 /// The current task being polled (or null if none).
59 static mut CURRENT: *mut FutureState = ptr::null_mut();
60
61 /// Map of any in-progress calls to async-lowered imports, keyed by the
62 /// identifiers issued by the host.
63 static mut CALLS: Lazy<HashMap<i32, oneshot::Sender<u32>>> = Lazy::new(HashMap::new);
64
65 /// Any newly-deferred work queued by calls to the `spawn` function while
66 /// polling the current task.
67 static mut SPAWNED: Vec<BoxFuture> = Vec::new();
68
69 /// The states of all currently-open streams and futures.
70 static mut HANDLES: Lazy<HashMap<u32, Handle>> = Lazy::new(HashMap::new);
71
72 #[doc(hidden)]
73 pub fn with_entry<T>(handle: u32, fun: impl FnOnce(hash_map::Entry<'_, u32, Handle>) -> T) -> T {
74 fun(unsafe { HANDLES.entry(handle) })
75 }
76
77 fn dummy_waker() -> Waker {
78 struct DummyWaker;
79
80 impl Wake for DummyWaker {
81 fn wake(self: Arc<Self>) {}
82 }
83
84 static WAKER: Lazy<Arc<DummyWaker>> = Lazy::new(|| Arc::new(DummyWaker));
85
86 WAKER.clone().into()
87 }
88
89 /// Poll the specified task until it either completes or can't make immediate
90 /// progress.
91 unsafe fn poll(state: *mut FutureState) -> Poll<()> {
92 loop {
93 if let Some(futures) = (*state).tasks.as_mut() {
94 CURRENT = state;
95 let poll = futures.poll_next_unpin(&mut Context::from_waker(&dummy_waker()));
96 CURRENT = ptr::null_mut();
97
98 if SPAWNED.is_empty() {
99 match poll {
100 Poll::Ready(Some(())) => (),
101 Poll::Ready(None) => {
102 (*state).tasks = None;
103 break Poll::Ready(());
104 }
105 Poll::Pending => break Poll::Pending,
106 }
107 } else {
108 futures.extend(SPAWNED.drain(..));
109 }
110 } else {
111 break Poll::Ready(());
112 }
113 }
114 }
115
116 /// Poll the future generated by a call to an async-lifted export once, calling
117 /// the specified closure (presumably backed by a call to `task.return`) when it
118 /// generates a value.
119 ///
120 /// This will return a non-null pointer representing the task if it hasn't
121 /// completed immediately; otherwise it returns null.
122 #[doc(hidden)]
123 pub fn first_poll<T: 'static>(
124 future: impl Future<Output = T> + 'static,
125 fun: impl FnOnce(&T) + 'static,
126 ) -> *mut u8 {
127 let state = Box::into_raw(Box::new(FutureState {
128 todo: 0,
129 tasks: Some(
130 [Box::pin(future.map(|v| fun(&v))) as BoxFuture]
131 .into_iter()
132 .collect(),
133 ),
134 }));
135 match unsafe { poll(state) } {
136 Poll::Ready(()) => ptr::null_mut(),
137 Poll::Pending => state as _,
138 }
139 }
140
141 /// Await the completion of a call to an async-lowered import.
142 #[doc(hidden)]
143 pub async unsafe fn await_result(
144 import: unsafe extern "C" fn(*mut u8, *mut u8) -> i32,
145 params_layout: Layout,
146 params: *mut u8,
147 results: *mut u8,
148 ) {
149 const STATUS_STARTING: u32 = 0;
150 const STATUS_STARTED: u32 = 1;
151 const STATUS_RETURNED: u32 = 2;
152 const STATUS_DONE: u32 = 3;
153
154 let result = import(params, results) as u32;
155 let status = result >> 30;
156 let call = (result & !(0b11 << 30)) as i32;
157
158 if status != STATUS_DONE {
159 assert!(!CURRENT.is_null());
160 (*CURRENT).todo += 1;
161 }
162
163 match status {
164 STATUS_STARTING => {
165 let (tx, rx) = oneshot::channel();
166 CALLS.insert(call, tx);
167 rx.await.unwrap();
168 alloc::dealloc(params, params_layout);
169 }
170 STATUS_STARTED => {
171 alloc::dealloc(params, params_layout);
172 let (tx, rx) = oneshot::channel();
173 CALLS.insert(call, tx);
174 rx.await.unwrap();
175 }
176 STATUS_RETURNED | STATUS_DONE => {
177 alloc::dealloc(params, params_layout);
178 }
179 _ => unreachable!(),
180 }
181 }
182
183 /// stream/future read/write results defined by the Component Model ABI.
184 mod results {
185 pub const BLOCKED: u32 = 0xffff_ffff;
186 pub const CLOSED: u32 = 0x8000_0000;
187 pub const CANCELED: u32 = 0;
188 }
189
190 /// Await the completion of a future read or write.
191 #[doc(hidden)]
192 pub async unsafe fn await_future_result(
193 import: unsafe extern "C" fn(u32, *mut u8) -> u32,
194 future: u32,
195 address: *mut u8,
196 ) -> bool {
197 let result = import(future, address);
198 match result {
199 results::BLOCKED => {
200 assert!(!CURRENT.is_null());
201 (*CURRENT).todo += 1;
202 let (tx, rx) = oneshot::channel();
203 CALLS.insert(future as _, tx);
204 let v = rx.await.unwrap();
205 v == 1
206 }
207 results::CLOSED | results::CANCELED => false,
208 1 => true,
209 _ => unreachable!(),
210 }
211 }
212
213 /// Await the completion of a stream read or write.
214 #[doc(hidden)]
215 pub async unsafe fn await_stream_result(
216 import: unsafe extern "C" fn(u32, *mut u8, u32) -> u32,
217 stream: u32,
218 address: *mut u8,
219 count: u32,
220 ) -> Option<usize> {
221 let result = import(stream, address, count);
222 match result {
223 results::BLOCKED => {
224 assert!(!CURRENT.is_null());
225 (*CURRENT).todo += 1;
226 let (tx, rx) = oneshot::channel();
227 CALLS.insert(stream as _, tx);
228 let v = rx.await.unwrap();
229 if let results::CLOSED | results::CANCELED = v {
230 None
231 } else {
232 Some(usize::try_from(v).unwrap())
233 }
234 }
235 results::CLOSED | results::CANCELED => None,
236 v => Some(usize::try_from(v).unwrap()),
237 }
238 }
239
240 /// Call the `subtask.drop` canonical built-in function.
241 fn subtask_drop(subtask: u32) {
242 #[cfg(not(target_arch = "wasm32"))]
243 {
244 _ = subtask;
245 unreachable!();
246 }
247
248 #[cfg(target_arch = "wasm32")]
249 {
250 #[link(wasm_import_module = "$root")]
251 extern "C" {
252 #[link_name = "[subtask-drop]"]
253 fn subtask_drop(_: u32);
254 }
255 unsafe {
256 subtask_drop(subtask);
257 }
258 }
259 }
260
261 /// Handle a progress notification from the host regarding either a call to an
262 /// async-lowered import or a stream/future read/write operation.
263 #[doc(hidden)]
264 pub unsafe fn callback(ctx: *mut u8, event0: i32, event1: i32, event2: i32) -> i32 {
265 const _EVENT_CALL_STARTING: i32 = 0;
266 const EVENT_CALL_STARTED: i32 = 1;
267 const EVENT_CALL_RETURNED: i32 = 2;
268 const EVENT_CALL_DONE: i32 = 3;
269 const _EVENT_YIELDED: i32 = 4;
270 const EVENT_STREAM_READ: i32 = 5;
271 const EVENT_STREAM_WRITE: i32 = 6;
272 const EVENT_FUTURE_READ: i32 = 7;
273 const EVENT_FUTURE_WRITE: i32 = 8;
274
275 match event0 {
276 EVENT_CALL_STARTED => 0,
277 EVENT_CALL_RETURNED | EVENT_CALL_DONE | EVENT_STREAM_READ | EVENT_STREAM_WRITE
278 | EVENT_FUTURE_READ | EVENT_FUTURE_WRITE => {
279 if let Some(call) = CALLS.remove(&event1) {
280 _ = call.send(event2 as _);
281 }
282
283 let state = ctx as *mut FutureState;
284 let done = poll(state).is_ready();
285
286 if event0 == EVENT_CALL_DONE {
287 subtask_drop(event1 as u32);
288 }
289
290 if matches!(
291 event0,
292 EVENT_CALL_DONE
293 | EVENT_STREAM_READ
294 | EVENT_STREAM_WRITE
295 | EVENT_FUTURE_READ
296 | EVENT_FUTURE_WRITE
297 ) {
298 (*state).todo -= 1;
299 }
300
301 if done && (*state).todo == 0 {
302 drop(Box::from_raw(state));
303 1
304 } else {
305 0
306 }
307 }
308 _ => unreachable!(),
309 }
310 }
311
312 /// Represents the Component Model `error-context` type.
313 pub struct ErrorContext {
314 handle: u32,
315 }
316
317 impl ErrorContext {
318 #[doc(hidden)]
319 pub fn from_handle(handle: u32) -> Self {
320 Self { handle }
321 }
322
323 #[doc(hidden)]
324 pub fn handle(&self) -> u32 {
325 self.handle
326 }
327
328 /// Extract the debug message from a given [`ErrorContext`]
329 pub fn debug_message(&self) -> String {
330 #[cfg(not(target_arch = "wasm32"))]
331 {
332 _ = self;
333 unreachable!();
334 }
335
336 #[cfg(target_arch = "wasm32")]
337 {
338 #[link(wasm_import_module = "$root")]
339 extern "C" {
340 #[link_name = "[error-context-debug-message;encoding=utf8;realloc=cabi_realloc]"]
341 fn error_context_debug_message(_: u32, _: *mut u8);
342 }
343
344 unsafe {
345 let mut ret = [0u32; 2];
346 error_context_debug_message(self.handle, ret.as_mut_ptr() as *mut _);
347 let len = usize::try_from(ret[1]).unwrap();
348 String::from_raw_parts(usize::try_from(ret[0]).unwrap() as *mut _, len, len)
349 }
350 }
351 }
352 }
353
354 impl Debug for ErrorContext {
355 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
356 f.debug_struct("ErrorContext").finish()
357 }
358 }
359
360 impl Display for ErrorContext {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 write!(f, "Error")
363 }
364 }
365
366 impl std::error::Error for ErrorContext {}
367
368 impl Drop for ErrorContext {
369 fn drop(&mut self) {
370 #[cfg(not(target_arch = "wasm32"))]
371 {
372 unreachable!();
373 }
374
375 #[cfg(target_arch = "wasm32")]
376 {
377 #[link(wasm_import_module = "$root")]
378 extern "C" {
379 #[link_name = "[error-context-drop]"]
380 fn error_drop(_: u32);
381 }
382 if self.handle != 0 {
383 unsafe { error_drop(self.handle) }
384 }
385 }
386 }
387 }
388
389 /// Defer the specified future to be run after the current async-lifted export
390 /// task has returned a value.
391 ///
392 /// The task will remain in a running state until all spawned futures have
393 /// completed.
394 pub fn spawn(future: impl Future<Output = ()> + 'static) {
395 unsafe { SPAWNED.push(Box::pin(future)) }
396 }
397
398 fn task_wait(state: &mut FutureState) {
399 #[cfg(not(target_arch = "wasm32"))]
400 {
401 _ = state;
402 unreachable!();
403 }
404
405 #[cfg(target_arch = "wasm32")]
406 {
407 #[link(wasm_import_module = "$root")]
408 extern "C" {
409 #[link_name = "[task-wait]"]
410 fn wait(_: *mut i32) -> i32;
411 }
412 let mut payload = [0i32; 2];
413 unsafe {
414 let event0 = wait(payload.as_mut_ptr());
415 callback(state as *mut _ as _, event0, payload[0], payload[1]);
416 }
417 }
418 }
419
420 /// Run the specified future to completion, returning the result.
421 ///
422 /// This uses `task.wait` to poll for progress on any in-progress calls to
423 /// async-lowered imports as necessary.
424 // TODO: refactor so `'static` bounds aren't necessary
425 pub fn block_on<T: 'static>(future: impl Future<Output = T> + 'static) -> T {
426 let (tx, mut rx) = oneshot::channel();
427 let state = &mut FutureState {
428 todo: 0,
429 tasks: Some(
430 [Box::pin(future.map(move |v| drop(tx.send(v)))) as BoxFuture]
431 .into_iter()
432 .collect(),
433 ),
434 };
435 loop {
436 match unsafe { poll(state) } {
437 Poll::Ready(()) => break rx.try_recv().unwrap().unwrap(),
438 Poll::Pending => task_wait(state),
439 }
440 }
441 }
442
443 /// Call the `task.yield` canonical built-in function.
444 ///
445 /// This yields control to the host temporarily, allowing other tasks to make
446 /// progress. It's a good idea to call this inside a busy loop which does not
447 /// otherwise ever yield control the the host.
448 pub fn task_yield() {
449 #[cfg(not(target_arch = "wasm32"))]
450 {
451 unreachable!();
452 }
453
454 #[cfg(target_arch = "wasm32")]
455 {
456 #[link(wasm_import_module = "$root")]
457 extern "C" {
458 #[link_name = "[task-yield]"]
459 fn yield_();
460 }
461 unsafe {
462 yield_();
463 }
464 }
465 }
466
467 /// Call the `task.backpressure` canonical built-in function.
468 ///
469 /// When `enabled` is `true`, this tells the host to defer any new calls to this
470 /// component instance until further notice (i.e. until `task.backpressure` is
471 /// called again with `enabled` set to `false`).
472 pub fn task_backpressure(enabled: bool) {
473 #[cfg(not(target_arch = "wasm32"))]
474 {
475 _ = enabled;
476 unreachable!();
477 }
478
479 #[cfg(target_arch = "wasm32")]
480 {
481 #[link(wasm_import_module = "$root")]
482 extern "C" {
483 #[link_name = "[task-backpressure]"]
484 fn backpressure(_: i32);
485 }
486 unsafe {
487 backpressure(if enabled { 1 } else { 0 });
488 }
489 }
490 }
491
492 /// Call the `error-context.new` canonical built-in function.
493 pub fn error_context_new(debug_message: &str) -> ErrorContext {
494 #[cfg(not(target_arch = "wasm32"))]
495 {
496 _ = debug_message;
497 unreachable!();
498 }
499
500 #[cfg(target_arch = "wasm32")]
501 {
502 #[link(wasm_import_module = "$root")]
503 extern "C" {
504 #[link_name = "[error-context-new;encoding=utf8]"]
505 fn context_new(_: *const u8, _: usize) -> i32;
506 }
507
508 unsafe {
509 let handle = context_new(debug_message.as_ptr(), debug_message.len());
510 // SAFETY: Handles (including error context handles are guaranteed to
511 // fit inside u32 by the Component Model ABI
512 ErrorContext::from_handle(u32::try_from(handle).unwrap())
513 }
514 }
515 }