This repository was archived by the owner on Sep 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathconcurrent.rs
More file actions
3850 lines (3454 loc) · 125 KB
/
concurrent.rs
File metadata and controls
3850 lines (3454 loc) · 125 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use {
crate::{
component::{
func::{self, Func, Options},
Instance, Lift, Lower, Val,
},
store::{StoreId, StoreInner, StoreOpaque},
vm::{
component::{CallContext, ComponentInstance, InstanceFlags, ResourceTables},
mpk::{self, ProtectionMask},
AsyncWasmCallState, PreviousAsyncWasmCallState, SendSyncPtr, VMFuncRef,
VMMemoryDefinition, VMStore, VMStoreRawPtr,
},
AsContext, AsContextMut, Engine, StoreContext, StoreContextMut, ValRaw,
},
anyhow::{anyhow, bail, Context as _, Result},
error_contexts::{GlobalErrorContextRefCount, LocalErrorContextRefCount},
futures::{
channel::oneshot,
future::{self, FutureExt},
stream::{FuturesUnordered, StreamExt},
},
futures_and_streams::{FlatAbi, StreamFutureState, TableIndex, TransmitHandle},
once_cell::sync::Lazy,
ready_chunks::ReadyChunks,
states::StateTable,
std::{
any::Any,
borrow::ToOwned,
boxed::Box,
cell::{RefCell, UnsafeCell},
collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque},
future::Future,
marker::PhantomData,
mem::{self, MaybeUninit},
ops::{Deref, DerefMut, Range},
pin::{pin, Pin},
ptr::{self, NonNull},
sync::{
atomic::{AtomicU32, Ordering::Relaxed},
Arc, Mutex,
},
task::{Context, Poll, Wake, Waker},
vec::Vec,
},
table::{Table, TableError, TableId},
wasmtime_environ::{
component::{
RuntimeComponentInstanceIndex, StringEncoding,
TypeComponentGlobalErrorContextTableIndex, TypeComponentLocalErrorContextTableIndex,
TypeFutureTableIndex, TypeStreamTableIndex, TypeTupleIndex, MAX_FLAT_PARAMS,
MAX_FLAT_RESULTS,
},
fact, PrimaryMap,
},
wasmtime_fiber::{Fiber, Suspend},
};
pub(crate) use futures_and_streams::{
lower_error_context_to_index, lower_future_to_index, lower_stream_to_index,
};
pub use futures_and_streams::{
ErrorContext, FutureReader, FutureWriter, HostFuture, HostStream, Single, StreamReader,
StreamWriter, Watch,
};
mod error_contexts;
mod futures_and_streams;
mod ready_chunks;
mod states;
mod table;
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
#[repr(u32)]
enum Status {
Starting = 1,
Started,
Returned,
}
#[derive(Clone, Copy, Debug)]
enum Event {
None,
_CallStarting,
CallStarted,
CallReturned,
StreamRead {
count: u32,
handle: u32,
ty: TypeStreamTableIndex,
},
StreamWrite {
count: u32,
pending: Option<(TypeStreamTableIndex, u32)>,
},
FutureRead {
count: u32,
handle: u32,
ty: TypeFutureTableIndex,
},
FutureWrite {
count: u32,
pending: Option<(TypeFutureTableIndex, u32)>,
},
}
impl Event {
fn parts(self) -> (u32, u32) {
match self {
Event::None => (0, 0),
Event::_CallStarting => (1, 0),
Event::CallStarted => (2, 0),
Event::CallReturned => (3, 0),
Event::StreamRead { count, .. } => (5, count),
Event::StreamWrite { count, .. } => (6, count),
Event::FutureRead { count, .. } => (7, count),
Event::FutureWrite { count, .. } => (8, count),
}
}
}
mod callback_code {
pub const EXIT: u32 = 0;
pub const YIELD: u32 = 1;
pub const WAIT: u32 = 2;
pub const POLL: u32 = 3;
}
const EXIT_FLAG_ASYNC_CALLEE: u32 = fact::EXIT_FLAG_ASYNC_CALLEE as u32;
/// Represents the result of a concurrent operation.
///
/// This is similar to a [`std::future::Future`] except that it represents an
/// operation which requires exclusive access to a store in order to make
/// progress -- without monopolizing that store for the lifetime of the
/// operation.
pub struct Promise<T> {
inner: Pin<Box<dyn Future<Output = T> + Send + 'static>>,
instance: SendSyncPtr<ComponentInstance>,
id: StoreId,
}
impl<T: Send + Sync + 'static> Promise<T> {
/// Map the result of this `Promise` from one value to another.
pub fn map<U>(self, fun: impl FnOnce(T) -> U + Send + Sync + 'static) -> Promise<U> {
Promise {
inner: Box::pin(self.inner.map(fun)),
instance: self.instance,
id: self.id,
}
}
/// Convert this `Promise` to a future which may be `await`ed for its
/// result.
///
/// The returned future will require exclusive use of the store until it
/// completes. If you need to await more than one `Promise` concurrently,
/// use [`PromisesUnordered`].
pub async fn get<U: Send>(self, mut store: impl AsContextMut<Data = U>) -> Result<T> {
let store = store.as_context_mut();
assert_eq!(store.0.id(), self.id);
unsafe { &mut *self.instance.as_ptr() }
.poll_until(store, self.inner)
.await
}
/// Convert this `Promise` to a future which may be `await`ed for its
/// result.
///
/// Unlike [`Self::get`], this does _not_ take a store parameter, meaning
/// the returned future will not make progress until and unless the event
/// loop for the store it came from is polled. Thus, this method should
/// only be used from within host functions and not from top-level embedder
/// code.
pub fn into_future(self) -> Pin<Box<dyn Future<Output = T> + Send + 'static>> {
self.inner
}
}
impl Instance {
/// Poll the specified future until it yields a result _or_ there are no more
/// tasks to run in the `Store`.
pub async fn get<U: Send, V: Send + Sync + 'static>(
&self,
mut store: impl AsContextMut<Data = U>,
fut: impl Future<Output = V> + Send,
) -> Result<V> {
let store = store.as_context_mut();
let instance = unsafe { &mut *store.0[self.0].as_ref().unwrap().instance_ptr() };
instance.poll_until(store, Box::pin(fut)).await
}
}
/// Represents a collection of zero or more concurrent operations.
///
/// Similar to [`futures::stream::FuturesUnordered`], this type supports
/// `await`ing more than one [`Promise`]s concurrently.
pub struct PromisesUnordered<T> {
inner: FuturesUnordered<Pin<Box<dyn Future<Output = T> + Send + 'static>>>,
instance: Option<(SendSyncPtr<ComponentInstance>, StoreId)>,
}
impl<T: Send + Sync + 'static> PromisesUnordered<T> {
/// Create a new `PromisesUnordered` with no entries.
pub fn new() -> Self {
Self {
inner: FuturesUnordered::new(),
instance: None,
}
}
/// Add the specified [`Promise`] to this collection.
pub fn push(&mut self, promise: Promise<T>) {
if let Some((instance, id)) = self.instance {
assert_eq!(instance, promise.instance);
assert_eq!(id, promise.id);
} else {
self.instance = Some((promise.instance, promise.id));
}
self.inner.push(promise.inner)
}
/// Get the next result from this collection, if any.
pub async fn next<U: Send>(
&mut self,
mut store: impl AsContextMut<Data = U>,
) -> Result<Option<T>> {
if let Some((instance, id)) = self.instance {
let store = store.as_context_mut();
assert_eq!(store.0.id(), id);
unsafe { &mut *instance.as_ptr() }
.poll_until(
store,
Box::pin(self.inner.next())
as Pin<Box<dyn Future<Output = Option<T>> + Send + '_>>,
)
.await
} else {
Ok(None)
}
}
}
/// Provides access to either store data (via the `get` method) or the store
/// itself (via [`AsContext`]/[`AsContextMut`]).
///
/// See [`Accessor::with`] for details.
pub struct Access<'a, T, U>(&'a mut Accessor<T, U>);
impl<'a, T, U> Access<'a, T, U> {
/// Get mutable access to the store data.
pub fn get(&mut self) -> &mut U {
unsafe { &mut *(self.0.get)().0.cast() }
}
/// Spawn a background task.
///
/// See [`Accessor::spawn`] for details.
pub fn spawn(&mut self, task: impl AccessorTask<T, U, Result<()>>) -> SpawnHandle
where
T: 'static,
{
self.0.spawn(task)
}
/// Retrieve the component instance of the caller.
pub fn instance(&self) -> Instance {
self.0.instance()
}
}
impl<'a, T, U> Deref for Access<'a, T, U> {
type Target = U;
fn deref(&self) -> &U {
unsafe { &mut *(self.0.get)().0.cast() }
}
}
impl<'a, T, U> DerefMut for Access<'a, T, U> {
fn deref_mut(&mut self) -> &mut U {
self.get()
}
}
impl<'a, T, U> AsContext for Access<'a, T, U> {
type Data = T;
fn as_context(&self) -> StoreContext<T> {
unsafe { StoreContext(&*(self.0.get)().1.cast()) }
}
}
impl<'a, T, U> AsContextMut for Access<'a, T, U> {
fn as_context_mut(&mut self) -> StoreContextMut<T> {
unsafe { StoreContextMut(&mut *(self.0.get)().1.cast()) }
}
}
/// Provides scoped mutable access to store data in the context of a concurrent
/// host import function.
///
/// This allows multiple host import futures to execute concurrently and access
/// the store data between (but not across) `await` points.
pub struct Accessor<T, U> {
get: Arc<dyn Fn() -> (*mut u8, *mut u8)>,
spawn: fn(Spawned),
instance: Option<Instance>,
_phantom: PhantomData<fn() -> (*mut U, *mut StoreInner<T>)>,
}
unsafe impl<T, U> Send for Accessor<T, U> {}
unsafe impl<T, U> Sync for Accessor<T, U> {}
impl<T, U> Accessor<T, U> {
#[doc(hidden)]
pub unsafe fn new(
get: fn() -> (*mut u8, *mut u8),
spawn: fn(Spawned),
instance: Option<Instance>,
) -> Self {
Self {
get: Arc::new(get),
spawn,
instance,
_phantom: PhantomData,
}
}
/// Run the specified closure, passing it mutable access to the store data.
///
/// Note that the return value of the closure must be `'static`, meaning it
/// cannot borrow from the store data. If you need shared access to
/// something in the store data, it must be cloned (using e.g. `Arc::clone`
/// if appropriate).
pub fn with<R: 'static>(&mut self, fun: impl FnOnce(Access<'_, T, U>) -> R) -> R {
fun(Access(self))
}
/// Run the specified task using a `Accessor` of a different type via the
/// provided mapping function.
///
/// This can be useful for projecting an `Accessor<T, U>` to an `Accessor<T,
/// V>`, where `V` is the type of e.g. a field that can be mutably borrowed
/// from a `&mut U`.
pub async fn forward<R, V>(
&mut self,
fun: impl Fn(&mut U) -> &mut V + Send + Sync + 'static,
task: impl AccessorTask<T, V, R>,
) -> R {
let get = self.get.clone();
let mut accessor = Accessor {
get: Arc::new(move || {
let (host, store) = get();
unsafe { ((fun(&mut *host.cast()) as *mut V).cast(), store) }
}),
spawn: self.spawn,
instance: self.instance,
_phantom: PhantomData,
};
task.run(&mut accessor).await
}
/// Spawn a background task which will receive an `&mut Accessor<T, U>` and
/// run concurrently with any other tasks in progress for the current
/// instance.
///
/// This is particularly useful for host functions which return a `stream`
/// or `future` such that the code to write to the write end of that
/// `stream` or `future` must run after the function returns.
pub fn spawn(&mut self, task: impl AccessorTask<T, U, Result<()>>) -> SpawnHandle
where
T: 'static,
{
let mut accessor = Self {
get: self.get.clone(),
spawn: self.spawn,
instance: self.instance,
_phantom: PhantomData,
};
let future = Arc::new(Mutex::new(SpawnedInner::Unpolled(unsafe {
// This is to avoid a `U: 'static` bound. Rationale: We don't
// actually store a value of type `U` in the `Accessor` we're
// `move`ing into the `async` block, and access to a `U` is brokered
// via `Accessor::with` by way of a thread-local variable in
// `wasmtime-wit-bindgen`-generated code. Furthermore,
// `AccessorTask` implementations are required to be `'static`, so
// no lifetime issues there. We have no way to explain any of that
// to the compiler, though, so we resort to a transmute here.
mem::transmute::<
Pin<Box<dyn Future<Output = Result<()>> + Send>>,
Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>,
>(Box::pin(async move { task.run(&mut accessor).await }))
})));
let handle = SpawnHandle(future.clone());
(self.spawn)(future);
handle
}
/// Retrieve the component instance of the caller.
pub fn instance(&self) -> Instance {
self.instance.unwrap()
}
#[doc(hidden)]
pub fn maybe_instance(&self) -> Option<Instance> {
self.instance
}
}
type SpawnedFuture = Pin<Box<dyn Future<Output = Result<()>> + Send + 'static>>;
#[doc(hidden)]
pub enum SpawnedInner {
Unpolled(SpawnedFuture),
Polled { future: SpawnedFuture, waker: Waker },
Aborted,
}
impl SpawnedInner {
fn abort(&mut self) {
match mem::replace(self, Self::Aborted) {
Self::Unpolled(_) | Self::Aborted => {}
Self::Polled { waker, .. } => waker.wake(),
}
}
}
#[doc(hidden)]
pub type Spawned = Arc<Mutex<SpawnedInner>>;
/// Handle to a spawned task which may be used to abort it.
pub struct SpawnHandle(Spawned);
impl SpawnHandle {
/// Abort the task.
///
/// This will panic if called from within the spawned task itself.
pub fn abort(&self) {
self.0.try_lock().unwrap().abort()
}
/// Return an [`AbortOnDropHandle`] which, when dropped, will abort the
/// task.
///
/// The returned instance will panic if dropped from within the spawned task
/// itself.
pub fn abort_handle(&self) -> AbortOnDropHandle {
AbortOnDropHandle(self.0.clone())
}
}
/// Handle to a spawned task which will abort the task when dropped.
pub struct AbortOnDropHandle(Spawned);
impl Drop for AbortOnDropHandle {
fn drop(&mut self) {
self.0.try_lock().unwrap().abort()
}
}
/// Represents a task which may be provided to `Accessor::spawn` or
/// `Accessor::forward`.
// TODO: Replace this with `std::ops::AsyncFnOnce` when that becomes a viable
// option.
//
// `AsyncFnOnce` is still nightly-only in latest stable Rust version as of this
// writing (1.84.1), and even with 1.85.0-beta it's not possible to specify
// e.g. `Send` and `Sync` bounds on the `Future` type returned by an
// `AsyncFnOnce`. Also, using `F: Future<Output = Result<()>> + Send + Sync,
// FN: FnOnce(&mut Accessor<T>) -> F + Send + Sync + 'static` fails with a type
// mismatch error when we try to pass it an async closure (e.g. `async move |_|
// { ... }`). So this seems to be the best we can do for the time being.
pub trait AccessorTask<T, U, R>: Send + 'static {
/// Run the task.
fn run(self, accessor: &mut Accessor<T, U>) -> impl Future<Output = R> + Send;
}
struct State {
host: *mut u8,
store: *mut u8,
spawned: Vec<Spawned>,
}
thread_local! {
#[cfg(feature = "component-model-async")]
static STATE: RefCell<Option<State>> = RefCell::new(None);
}
struct ResetState(Option<State>);
impl Drop for ResetState {
fn drop(&mut self) {
STATE.with(|v| {
*v.borrow_mut() = self.0.take();
})
}
}
fn get_host_and_store() -> (*mut u8, *mut u8) {
STATE
.with(|v| {
v.borrow()
.as_ref()
.map(|State { host, store, .. }| (*host, *store))
})
.unwrap()
}
fn spawn_task(task: Spawned) {
STATE.with(|v| v.borrow_mut().as_mut().unwrap().spawned.push(task));
}
fn poll_with_state<T, F: Future + ?Sized>(
store: VMStoreRawPtr,
instance: SendSyncPtr<ComponentInstance>,
cx: &mut Context,
future: Pin<&mut F>,
) -> Poll<F::Output> {
let mut store_cx = unsafe { StoreContextMut::new(&mut *store.0.as_ptr().cast()) };
let (result, spawned) = {
let host = store_cx.data_mut();
let old = STATE.with(|v| {
v.replace(Some(State {
host: (host as *mut T).cast(),
store: store.0.as_ptr().cast(),
spawned: Vec::new(),
}))
});
let _reset = ResetState(old);
(future.poll(cx), STATE.with(|v| v.take()).unwrap().spawned)
};
let instance_ref = unsafe { &mut *instance.as_ptr() };
for spawned in spawned {
instance_ref.spawn(future::poll_fn(move |cx| {
let mut spawned = spawned.try_lock().unwrap();
let inner = mem::replace(DerefMut::deref_mut(&mut spawned), SpawnedInner::Aborted);
if let SpawnedInner::Unpolled(mut future) | SpawnedInner::Polled { mut future, .. } =
inner
{
let result = poll_with_state::<T, _>(store, instance, cx, future.as_mut());
*DerefMut::deref_mut(&mut spawned) = SpawnedInner::Polled {
future,
waker: cx.waker().clone(),
};
result
} else {
Poll::Ready(Ok(()))
}
}))
}
result
}
/// Represents the state of a waitable handle.
#[derive(Debug)]
enum WaitableState {
/// Represents a host task handle.
HostTask,
/// Represents a guest task handle.
GuestTask,
/// Represents a stream handle.
Stream(TypeStreamTableIndex, StreamFutureState),
/// Represents a future handle.
Future(TypeFutureTableIndex, StreamFutureState),
/// Represents a waitable-set handle
Set,
}
enum CallerInfo {
Async {
params: u32,
results: u32,
},
Sync {
params: Vec<ValRaw>,
result_count: u32,
},
}
impl ComponentInstance {
pub(crate) fn instance(&self) -> Option<Instance> {
self.instance
}
fn instance_states(&mut self) -> &mut HashMap<RuntimeComponentInstanceIndex, InstanceState> {
&mut self.concurrent_state.instance_states
}
fn unblocked(&mut self) -> &mut HashSet<RuntimeComponentInstanceIndex> {
&mut self.concurrent_state.unblocked
}
fn guest_task(&mut self) -> &mut Option<TableId<GuestTask>> {
&mut self.concurrent_state.guest_task
}
fn push<V: Send + Sync + 'static>(&mut self, value: V) -> Result<TableId<V>, TableError> {
self.concurrent_state.table.push(value)
}
fn get<V: 'static>(&self, id: TableId<V>) -> Result<&V, TableError> {
self.concurrent_state.table.get(id)
}
fn get_mut<V: 'static>(&mut self, id: TableId<V>) -> Result<&mut V, TableError> {
self.concurrent_state.table.get_mut(id)
}
pub fn add_child<T, U>(
&mut self,
child: TableId<T>,
parent: TableId<U>,
) -> Result<(), TableError> {
self.concurrent_state.table.add_child(child, parent)
}
pub fn remove_child<T, U>(
&mut self,
child: TableId<T>,
parent: TableId<U>,
) -> Result<(), TableError> {
self.concurrent_state.table.remove_child(child, parent)
}
fn delete<V: 'static>(&mut self, id: TableId<V>) -> Result<V, TableError> {
self.concurrent_state.table.delete(id)
}
fn push_future(&mut self, future: HostTaskFuture) {
self.concurrent_state
.futures
.get_mut()
.unwrap()
.get_mut()
.push(future);
}
pub(crate) fn spawn(&mut self, task: impl Future<Output = Result<()>> + Send + 'static) {
self.push_future(Box::pin(
async move { HostTaskOutput::Background(task.await) },
))
}
fn yielding(&mut self) -> &mut HashMap<TableId<GuestTask>, Option<TableId<WaitableSet>>> {
&mut self.concurrent_state.yielding
}
fn waitable_tables(
&mut self,
) -> &mut PrimaryMap<RuntimeComponentInstanceIndex, StateTable<WaitableState>> {
&mut self.concurrent_state.waitable_tables
}
fn error_context_tables(
&mut self,
) -> &mut PrimaryMap<
TypeComponentLocalErrorContextTableIndex,
StateTable<LocalErrorContextRefCount>,
> {
&mut self.concurrent_state.error_context_tables
}
fn global_error_context_ref_counts(
&mut self,
) -> &mut BTreeMap<TypeComponentGlobalErrorContextTableIndex, GlobalErrorContextRefCount> {
&mut self.concurrent_state.global_error_context_ref_counts
}
fn maybe_push_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
let task = self.get_mut(guest_task)?;
if task.lift_result.is_some() {
log::trace!("push call context for {}", guest_task.rep());
let call_context = task.call_context.take().unwrap();
unsafe { &mut (*self.store()) }
.store_opaque_mut()
.component_resource_state()
.0
.push(call_context);
}
Ok(())
}
fn maybe_pop_call_context(&mut self, guest_task: TableId<GuestTask>) -> Result<()> {
if self.get_mut(guest_task)?.lift_result.is_some() {
log::trace!("pop call context for {}", guest_task.rep());
let call_context = Some(
unsafe { &mut (*self.store()) }
.component_resource_state()
.0
.pop()
.unwrap(),
);
self.get_mut(guest_task)?.call_context = call_context;
}
Ok(())
}
fn may_enter(
&mut self,
mut guest_task: TableId<GuestTask>,
guest_instance: RuntimeComponentInstanceIndex,
) -> bool {
// Walk the task tree back to the root, looking for potential reentrance.
//
// TODO: This could be optimized by maintaining a per-`GuestTask` bitset
// such that each bit represents and instance which has been entered by that
// task or an ancestor of that task, in which case this would be a constant
// time check.
loop {
match &self.get_mut(guest_task).unwrap().caller {
Caller::Host(_) => break true,
Caller::Guest { task, instance } => {
if *instance == guest_instance {
break false;
} else {
guest_task = *task;
}
}
}
}
}
fn maybe_send_event(
&mut self,
guest_task: TableId<GuestTask>,
event: Event,
waitable: Option<Waitable>,
) -> Result<()> {
assert_ne!(Some(guest_task.rep()), waitable.map(|v| v.rep()));
// We can only send an event to a caller if the callee has suspended at
// least once; otherwise, we will not have had a chance to return a
// `waitable` handle to the caller yet, in which case we can only queue the
// event for later.
let may_send = waitable
.map(|v| v.has_suspended(self))
.unwrap_or(Ok(true))?;
if let (true, Some(callback)) = (may_send, self.get(guest_task)?.callback) {
let handle = if let Some(waitable) = waitable {
let Some((
handle,
WaitableState::HostTask
| WaitableState::GuestTask
| WaitableState::Stream(..)
| WaitableState::Future(..),
)) = self.waitable_tables()[callback.instance].get_mut_by_rep(waitable.rep())
else {
// If there's no handle found for the subtask, that means either the
// subtask was closed by the caller already or the caller called the
// callee via a sync-lowered import. Either way, we can skip this
// event.
if let Event::CallReturned = event {
// Since this is a `CallReturned` event which will never be
// delivered to the caller, we must handle deleting the subtask
// here.
waitable.delete_from(self)?;
}
return Ok(());
};
handle
} else {
0
};
log::trace!(
"use callback to deliver event {event:?} to {} for {:?} (handle {handle}): {:?}",
guest_task.rep(),
waitable.map(|v| v.rep()),
callback.function,
);
if let Some(waitable) = waitable {
waitable.on_delivery(self, event);
}
let old_task = self.guest_task().replace(guest_task);
log::trace!(
"maybe_send_event (callback): replaced {:?} with {} as current task",
old_task.map(|v| v.rep()),
guest_task.rep()
);
self.maybe_push_call_context(guest_task)?;
let code =
(callback.caller)(self, callback.instance, callback.function, event, handle)?;
self.maybe_pop_call_context(guest_task)?;
self.handle_callback_code(callback.instance, guest_task, code, Event::None)?;
*self.guest_task() = old_task;
log::trace!(
"maybe_send_event (callback): restored {:?} as current task",
old_task.map(|v| v.rep())
);
} else if let Some(waitable) = waitable {
waitable.common(self)?.event = Some(event);
waitable.mark_ready(self)?;
let resumed = if let Event::CallReturned = event {
if let Some((fiber, async_)) = self.get_mut(guest_task)?.deferred.take_stackful() {
log::trace!(
"use fiber to deliver event {event:?} to {} for {}",
guest_task.rep(),
waitable.rep()
);
let old_task = self.guest_task().replace(guest_task);
log::trace!(
"maybe_send_event (fiber): replaced {:?} with {} as current task",
old_task.map(|v| v.rep()),
guest_task.rep()
);
self.resume_stackful(guest_task, fiber, async_)?;
*self.guest_task() = old_task;
log::trace!(
"maybe_send_event (fiber): restored {:?} as current task",
old_task.map(|v| v.rep())
);
true
} else {
false
}
} else {
false
};
if !resumed {
log::trace!(
"queue event {event:?} to {} for {}",
guest_task.rep(),
waitable.rep()
);
}
} else {
unreachable!("can't send waitable-less event to non-callback task");
}
Ok(())
}
fn resume_stackful(
&mut self,
guest_task: TableId<GuestTask>,
mut fiber: StoreFiber<'static>,
async_: bool,
) -> Result<()> {
self.maybe_push_call_context(guest_task)?;
let async_cx = AsyncCx::new(unsafe { (*self.store()).store_opaque_mut() });
let mut store = Some(self.store());
loop {
break match resume_fiber(&mut fiber, store.take(), Ok(()))? {
Ok((_, result)) => {
result?;
if async_ {
if self.get(guest_task)?.lift_result.is_some() {
return Err(anyhow!(crate::Trap::NoAsyncResult));
}
}
if let Some(instance) = fiber.instance {
self.maybe_resume_next_task(instance)?;
match &self.get(guest_task)?.caller {
Caller::Host(_) => {
log::trace!(
"resume_stackful will delete task {}",
guest_task.rep()
);
Waitable::Guest(guest_task).delete_from(self)?;
}
Caller::Guest { .. } => {
let waitable = Waitable::Guest(guest_task);
waitable.common(self)?.event = Some(Event::CallReturned);
waitable.send_or_mark_ready(self)?;
}
}
}
Ok(())
}
Err(new_store) => {
if new_store.is_some() {
self.maybe_pop_call_context(guest_task)?;
self.get_mut(guest_task)?.deferred = Deferred::Stackful { fiber, async_ };
Ok(())
} else {
// In this case, the fiber suspended while holding on to its
// `*mut dyn VMStore` instead of returning it to us. That
// means we can't do anything else with the store (or self)
// for now; the only thing we can do is suspend _our_ fiber
// back up to the top level executor, which will resume us
// when we can make more progress, at which point we'll loop
// around and restore the child fiber again.
unsafe { async_cx.suspend(None) }?;
continue;
}
}
};
}
}
fn handle_callback_code(
&mut self,
runtime_instance: RuntimeComponentInstanceIndex,
guest_task: TableId<GuestTask>,
code: u32,
pending_event: Event,
) -> Result<()> {
let (code, set) = unpack_callback_code(code);
log::trace!(
"received callback code from {}: {code} (set: {set})",
guest_task.rep()
);
let task = self.get_mut(guest_task)?;
let event = if task.lift_result.is_some() {
if code == callback_code::EXIT {
return Err(anyhow!(crate::Trap::NoAsyncResult));
}
pending_event
} else {
Event::CallReturned
};
let get_set = |instance: &mut Self, handle| {
if handle == 0 {
bail!("invalid waitable-set handle");
}
let (set, WaitableState::Set) =
instance.waitable_tables()[runtime_instance].get_mut_by_index(handle)?
else {
bail!("invalid waitable-set handle");
};
Ok(TableId::<WaitableSet>::new(set))
};
if !matches!(event, Event::None) {
let waitable = Waitable::Guest(guest_task);
waitable.common(self)?.event = Some(event);
waitable.send_or_mark_ready(self)?;
}
match code {
callback_code::EXIT => match &self.get(guest_task)?.caller {
Caller::Host(_) => {
log::trace!("handle_callback_code will delete task {}", guest_task.rep());
Waitable::Guest(guest_task).delete_from(self)?;
}
Caller::Guest { .. } => {
self.get_mut(guest_task)?.callback = None;
}
},
callback_code::YIELD => {
self.yielding().insert(guest_task, None);
}
callback_code::WAIT => {
let set = get_set(self, set)?;
let set = self.get_mut(set)?;
if let Some(waitable) = set.ready.pop_first() {
let event = waitable.common(self)?.event.take().unwrap();
self.maybe_send_event(guest_task, event, Some(waitable))?;
} else {
set.waiting.insert(guest_task);
}
}
callback_code::POLL => {
let set = get_set(self, set)?;
self.get(set)?; // Just to make sure it exists
self.yielding().insert(guest_task, Some(set));
}
_ => bail!("unsupported callback code: {code}"),
}
Ok(())
}
fn resume_stackless(
&mut self,
guest_task: TableId<GuestTask>,
call: Box<dyn FnOnce(&mut ComponentInstance) -> Result<u32>>,
runtime_instance: RuntimeComponentInstanceIndex,
) -> Result<()> {
self.maybe_push_call_context(guest_task)?;
let code = call(self)?;
self.maybe_pop_call_context(guest_task)?;
self.handle_callback_code(runtime_instance, guest_task, code, Event::CallStarted)?;
self.maybe_resume_next_task(runtime_instance)