forked from bytecodealliance/jco
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync_task.rs
More file actions
2621 lines (2224 loc) · 127 KB
/
Copy pathasync_task.rs
File metadata and controls
2621 lines (2224 loc) · 127 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
//! Intrinsics that represent helpers that implement async tasks
use std::fmt::Write;
use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::conversion::ConversionIntrinsic;
use crate::intrinsics::p3::waitable::WaitableIntrinsic;
use crate::intrinsics::{Intrinsic, RenderIntrinsicsArgs};
use crate::source::Source;
use crate::uwriteln;
/// This enum contains intrinsics that implement async tasks
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum AsyncTaskIntrinsic {
/// Set the value of a context local storage for the current task/thread
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// type SlotIndex = 0 | 1;
/// function contextSet(slot: SlotIndex, value: number);
/// ```
///
ContextSet,
/// Gets the value stored in context local storage for the current task/thread
///
/// Guest code uses this to reference internally stored context local storage,
/// whether that is task local or thread local.
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// type SlotIndex = 0 | 1;
/// function contextGet(slot: SlotIndex): i32;
/// ```
///
ContextGet,
/// Return a value to a caller of an lifted export.
///
/// Consider the following scenario:
/// - Some component A is created with a async lifted export
/// - A caller of component A (Host/other component) calls the lifted export
/// - During component A's execution, component A triggers `task.return` with a (possibly partial) result of computation
/// - While processing the `task.return` intrinsic:
/// - The host lifts the return values from the partial computation
/// - The host pauses execution (if necessary) of component A
/// - The host delivers return values to possibly waiting tasks
/// - The host continues executing the appropriate next task
///
/// Note that it *is* possible for the lifted export to be sync.
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type u32 = number;
/// type usize = bigint;
/// type ComponentIdx = number;
/// type TypeIdx = number;
/// type ValueWithTypeIdx = (ComponentIdx, TypeIdx, any);
/// type LiftFn = function(ptr: u32, totalLen: usize): ValueWithTypeIndex[];
///
/// function taskReturn(taskId: number, resultLiftFns: LiftFn[], storagePtr: u32, storageLen: usize);
/// ```
///
TaskReturn,
/// Remove the subtask (waitable) at the given index, for a given component
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// function subtaskDrop(componentIdx: number, taskId: i32);
/// ```
///
SubtaskDrop,
/// Yield a task
///
/// Guest code uses this to yield control flow to the host (and possibly other components)
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// function yield_(isAsync: boolean);
/// ```
Yield,
/// Cancel the current async subtask for a given component instance
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// function subtaskCancel(componentIdx: number, isAsync: boolean);
/// ```
SubtaskCancel,
/// Cancel the current task
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// function taskCancel(componentIdx: i32);
/// ```
TaskCancel,
/// Function that retrieves the current global async current task
GetCurrentTask,
/// Function that creates a new task, and marks it as the current executing task
CreateNewCurrentTask,
/// Function that stops the current task
ClearCurrentTask,
/// Global that stores the current task for a given invocation.
///
/// This global variable is populated *only* when we are performing a call
/// that was triggered by an async lifted export.
///
/// You can consider the type of the global variable to be:
///
/// ```ts
/// type Task = {
/// componentIdx: number,
/// storage: [number]
/// returnCalls: number,
/// requested: boolean,
/// borrowedHandles: Record<number, boolean>,
/// cancelled: boolean,
/// }
///
/// type GlobalAsyncCurrentTaskMap = Map<number, Task>;
/// ```
GlobalAsyncCurrentTaskMap,
/// Global that stores the current task ID
///
/// This global variable is populated when a task is started, and cleared
/// (reset to `null` in JS) when a task ends.
///
/// This global is used only when *necessary* -- for canonical builtins that
/// do not include/cannot access the current task any other way, often because
/// they have no access to the current component instance index (e.g. `context.get`).
///
/// ```ts
/// type GlobalAsyncCurrentTaskIds = number[];
/// ```
GlobalAsyncCurrentTaskIds,
/// Global that stores the current component ID (for the current task)
///
/// This global variable is populated when a task is started, and cleared
/// (reset to `null` in JS) when a task ends.
///
/// ```ts
/// type GlobalAsyncCurrentTaskIds = number[];
/// ```
GlobalAsyncCurrentComponentIdxs,
/// The definition of the `AsyncTask` JS class
AsyncTaskClass,
/// The constant that represents that a async task is blocked
AsyncBlockedConstant,
/// The definition of the `AsyncSubtask` JS class
AsyncSubtaskClass,
/// A utility function used for unpacking results to callbck that mostly contain
/// a callback code and possibly a waitable set index to be watied on or polled
///
/// # Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// type i32 = number;
/// function unpackCallbackResult(callbackResult: i32): [i32, i32];
/// ```
UnpackCallbackResult,
/// JS that contains the loop which drives a given async task to completion.
///
/// This intrinsic is not a canon function but instead a reusable JS snippet
/// that controls
///
/// The Canonical ABI pseudo-code equivalent be `thread_func(thread)` in `canon_lift`
/// though threads are not yet implemented.
///
/// Normally, the async driver loop returns a Promise that resolves to the result
/// of the original async function that was called.
///
/// See `Instruction::CallWasm` for example usage.
///
/// ```ts
/// interface DriverLoopArgs {
/// componentState: ComponentAsyncState,
/// task: AsyncTask,
/// fnName: string,
/// callbackFnName: string,
/// isAsync: boolean, // whether using JSPI *or* lifted async function
/// callbackResult: number, // initial wasm call result that contains callback code and more metadata
/// // Normally, the driver loop is run in a separately executing Promise,
/// // so we ensure that the enclosing promise itself can eventually be resolved
/// resolve: () => void,
/// reject: () => void,
/// }
///
/// function asyncDriverLoop(args: DriverLoopArgs): Promise<any>;
/// ```
DriverLoop,
/// Intrinsic used when components lower imports to be used
/// from other components or the host.
///
/// # Component Intrinsic implementation function
///
/// The function that implements this intrinsic has the following definition:
///
/// ```ts
/// ```
///
LowerImport,
/// Version of lower import written explicitly for backwards compatibility
///
/// TODO(breaking): remove this when specifying async imports/exports is removed.
LowerImportBackwardsCompat,
/// Global variable that represents whether the *current* task my block
/// see `CoreDef::TaskMayBlock`
CurrentTaskMayBlock,
/// Called before entering sync-to-sync guest-to-guest call
EnterSymmetricSyncGuestCall,
/// Called when exiting a sync-to-sync guest-to-guest call
ExitSymmetricSyncGuestCall,
/// Component index that is saved across sync-to-sync guest calls
SymmetricSyncGuestCallStack,
}
impl AsyncTaskIntrinsic {
/// Retrieve dependencies for this intrinsic
pub fn deps() -> &'static [&'static Intrinsic] {
&[]
}
/// Retrieve global names for this intrinsic
pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
[
Self::CurrentTaskMayBlock.name(),
Self::AsyncBlockedConstant.name(),
Self::AsyncSubtaskClass.name(),
Self::AsyncTaskClass.name(),
Self::ContextGet.name(),
Self::ContextSet.name(),
Self::GetCurrentTask.name(),
Self::CreateNewCurrentTask.name(),
Self::ClearCurrentTask.name(),
Self::GlobalAsyncCurrentTaskMap.name(),
Self::GlobalAsyncCurrentTaskIds.name(),
Self::GlobalAsyncCurrentComponentIdxs.name(),
Self::SubtaskCancel.name(),
Self::SubtaskDrop.name(),
Self::TaskCancel.name(),
Self::TaskReturn.name(),
Self::Yield.name(),
Self::UnpackCallbackResult.name(),
Self::DriverLoop.name(),
Self::LowerImport.name(),
Self::LowerImportBackwardsCompat.name(),
Self::EnterSymmetricSyncGuestCall.name(),
Self::ExitSymmetricSyncGuestCall.name(),
Self::SymmetricSyncGuestCallStack.name(),
]
}
/// Get the name for the intrinsic
pub fn name(&self) -> &'static str {
match self {
Self::CurrentTaskMayBlock => "CURRENT_TASK_MAY_BLOCK",
Self::AsyncBlockedConstant => "ASYNC_BLOCKED_CODE",
Self::AsyncSubtaskClass => "AsyncSubtask",
Self::AsyncTaskClass => "AsyncTask",
Self::ContextGet => "contextGet",
Self::ContextSet => "contextSet",
Self::GetCurrentTask => "getCurrentTask",
Self::CreateNewCurrentTask => "createNewCurrentTask",
Self::ClearCurrentTask => "clearCurrentTask",
Self::GlobalAsyncCurrentTaskMap => "ASYNC_TASKS_BY_COMPONENT_IDX",
Self::GlobalAsyncCurrentTaskIds => "ASYNC_CURRENT_TASK_IDS",
Self::GlobalAsyncCurrentComponentIdxs => "ASYNC_CURRENT_COMPONENT_IDXS",
Self::SubtaskCancel => "subtaskCancel",
Self::SubtaskDrop => "subtaskDrop",
Self::TaskCancel => "taskCancel",
Self::TaskReturn => "taskReturn",
Self::Yield => "asyncYield",
Self::UnpackCallbackResult => "unpackCallbackResult",
Self::DriverLoop => "_driverLoop",
Self::LowerImport => "_lowerImport",
Self::LowerImportBackwardsCompat => "_lowerImportBackwardsCompat",
Self::EnterSymmetricSyncGuestCall => "_symmetricSyncGuestCallEnter",
Self::ExitSymmetricSyncGuestCall => "_symmetricSyncGuestCallExit",
Self::SymmetricSyncGuestCallStack => "SYMMETRIC_SYNC_GUEST_CALL_STACK",
}
}
/// Render an intrinsic to a string
pub fn render(&self, output: &mut Source, _render_args: &RenderIntrinsicsArgs<'_>) {
match self {
Self::CurrentTaskMayBlock => {
let var_name = self.name();
uwriteln!(
output,
r#"
const {var_name} = new WebAssembly.Global({{ value: 'i32', mutable: true }}, 0);
"#
);
}
Self::GlobalAsyncCurrentTaskMap => {
let var_name = Self::GlobalAsyncCurrentTaskMap.name();
output.push_str(&format!("const {var_name} = new Map();\n"));
}
Self::GlobalAsyncCurrentTaskIds => {
output.push_str(&format!("const {var_name} = [];\n", var_name = self.name(),));
}
Self::GlobalAsyncCurrentComponentIdxs => {
output.push_str(&format!("const {var_name} = [];\n", var_name = self.name(),));
}
Self::AsyncBlockedConstant => {
let name = Self::AsyncBlockedConstant.name();
output.push_str(&format!("const {name} = 0xFFFF_FFFF;"));
}
Self::ContextSet => {
let debug_log_fn = Intrinsic::DebugLog.name();
let context_set_fn = Self::ContextSet.name();
let current_task_get_fn = Self::GetCurrentTask.name();
let type_check_i32 = Intrinsic::TypeCheckValidI32.name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
uwriteln!(
output,
r#"
function {context_set_fn}(ctx, value) {{
const {{ componentIdx, slot }} = ctx;
if (componentIdx === undefined) {{ throw new TypeError("missing component idx"); }}
if (slot === undefined) {{ throw new TypeError("missing slot"); }}
if (!({type_check_i32}(value))) {{ throw new Error('invalid value for context set (not valid i32)'); }}
const currentTaskMeta = {get_global_current_task_meta_fn}(componentIdx);
if (!currentTaskMeta) {{
throw new Error(`missing/incomplete global current task meta for component idx [${{componentIdx}}] during context set`);
}}
const taskID = currentTaskMeta.taskID;
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('failed to retrieve current task'); }}
let task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing current task in metadata while setting context'); }}
{debug_log_fn}('[{context_set_fn}()] args', {{
slot,
value,
storage: task.storage,
taskID: task.id(),
componentIdx: task.componentIdx(),
}});
if (slot < 0 || slot >= task.storage.length) {{ throw new Error('invalid slot for current task'); }}
task.storage[slot] = value;
}}
"#
);
}
Self::ContextGet => {
let debug_log_fn = Intrinsic::DebugLog.name();
let context_get_fn = Self::ContextGet.name();
let current_task_get_fn = Self::GetCurrentTask.name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
uwriteln!(
output,
r#"
function {context_get_fn}(ctx) {{
const {{ componentIdx, slot }} = ctx;
if (componentIdx === undefined) {{ throw new TypeError("missing component idx"); }}
if (slot === undefined) {{ throw new TypeError("missing slot"); }}
const currentTaskMeta = {get_global_current_task_meta_fn}(componentIdx);
if (!currentTaskMeta) {{
throw new Error(`missing/incomplete global current task meta for component idx [${{componentIdx}}] during context set`);
}}
const taskID = currentTaskMeta.taskID;
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('failed to retrieve current task'); }}
let task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing current task in metadata while getting context'); }}
{debug_log_fn}('[{context_get_fn}()] args', {{
slot,
storage: task.storage,
taskID: task.id(),
componentIdx: task.componentIdx(),
}});
if (slot < 0 || slot >= task.storage.length) {{ throw new Error('invalid slot for current task'); }}
return task.storage[slot];
}}
"#
);
}
// Equivalent of `task.return`
Self::TaskReturn => {
let debug_log_fn = Intrinsic::DebugLog.name();
let task_return_fn = Self::TaskReturn.name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
let current_task_get_fn = Self::GetCurrentTask.name();
output.push_str(&format!(r#"
function {task_return_fn}(ctx) {{
const {{
componentIdx,
getMemoryFn,
memoryIdx,
callbackFnIdx,
liftFns,
lowerFns,
stringEncoding,
}} = ctx;
const params = [...arguments].slice(1);
const memory = getMemoryFn();
let useDirectParams = ctx.useDirectParams;
const {{ taskID }} = {get_global_current_task_meta_fn}(componentIdx);
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('failed to retrieve current task metadata'); }}
const task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing current task in metadata'); }}
{debug_log_fn}('[{task_return_fn}()] args', {{
componentIdx,
taskID: task.id(),
subtaskID: task.getParentSubtask()?.id(),
callbackFnIdx,
memoryIdx,
liftFns,
lowerFns,
params,
}});
// If we are in a subtask, and have a fused helper function provided to use
// via PrepareCall, we can use that function rather than performing lifting manually.
//
// See also documentation on `HostIntrinsic::PrepareCall`
const subtaskCallMetadata = task.getParentSubtask()?.getCallMetadata();
if (subtaskCallMetadata?.returnFn) {{
subtaskCallMetadata.returnFn.apply(null, [...params, subtaskCallMetadata.resultPtr]);
subtaskCallMetadata.returnFnCalled = true;
task.resolve([]);
return;
}}
const expectedMemoryIdx = task.getReturnMemoryIdx();
if (expectedMemoryIdx !== null && memoryIdx !== null && expectedMemoryIdx !== memoryIdx) {{
{debug_log_fn}("[{task_return_fn}()] mismatched memory indices", {{ expectedMemoryIdx, memoryIdx }});
throw new Error('task.return memory [' + memoryIdx + '] does not match task [' + expectedMemoryIdx + ']');
}}
task.callbackFnIdx = callbackFnIdx;
if (!memory && liftFns.length > 4) {{
{debug_log_fn}("[{task_return_fn}()] memory not present for max async flat lifts");
throw new Error('memory must be present if more than max async flat lifts are performed');
}}
let liftCtx = {{ memory, useDirectParams, params, componentIdx, stringEncoding }};
if (!useDirectParams) {{
if (!ctx.memory) {{
{debug_log_fn}('missing memory despite indirect param usage', {{ useDirectParams, liftCtx, ctx }});
throw new Error('missing memory despite indirect param usage');
}}
liftCtx.storagePtr = params[0];
liftCtx.storageLen = params[1];
}}
const liftedResults = [];
{debug_log_fn}('[{task_return_fn}()] lifting results out of memory', {{ liftCtx }});
for (const liftFn of liftFns) {{
if (liftCtx.storageLen !== undefined && liftCtx.storageLen <= 0) {{
{debug_log_fn}(`[{task_return_fn}()] ran out of range while writing storageLen = [${{liftCtx.storageLen}}]`);
throw new Error('ran out of storage while writing');
}}
const [ val, newLiftCtx ] = liftFn(liftCtx);
liftCtx = newLiftCtx;
liftedResults.push(val);
}}
task.resolve(liftedResults);
}}
"#));
}
Self::SubtaskDrop => {
let debug_log_fn = Intrinsic::DebugLog.name();
let subtask_drop_fn = Self::SubtaskDrop.name();
let get_or_create_async_state_fn =
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
output.push_str(&format!("
function {subtask_drop_fn}(componentIdx, subtaskWaitableRep) {{
{debug_log_fn}('[{subtask_drop_fn}()] args', {{ componentIdx, subtaskWaitableRep }});
const cstate = {get_or_create_async_state_fn}(componentIdx);
if (!cstate.mayLeave) {{ throw new Error('component is not marked as may leave, cannot be cancelled'); }}
const subtask = cstate.handles.remove(subtaskWaitableRep);
if (!subtask) {{ throw new Error('missing/invalid subtask specified for drop in component instance'); }}
subtask.drop();
}}
"));
}
Self::Yield => {
let debug_log_fn = Intrinsic::DebugLog.name();
let yield_fn = Self::Yield.name();
let current_task_get_fn = Self::GetCurrentTask.name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
output.push_str(&format!(
"
function {yield_fn}(ctx) {{
{debug_log_fn}('[{yield_fn}()] args', {{ ctx }});
const {{ componentIdx, isCancellable }} = ctx;
const {{ taskID }} = {get_global_current_task_meta_fn}(componentIdx);
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}
const task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing async task'); }}
await task.yield({{ isAsync, isCancellable }});
}}
"
));
}
Self::SubtaskCancel => {
let debug_log_fn = Intrinsic::DebugLog.name();
let task_cancel_fn = Self::SubtaskCancel.name();
let current_task_get_fn = Self::GetCurrentTask.name();
let get_or_create_async_state_fn =
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
output.push_str(&format!("
function {task_cancel_fn}(componentIdx, isAsync) {{
{debug_log_fn}('[{task_cancel_fn}()] args', {{ componentIdx, isAsync }});
const state = {get_or_create_async_state_fn}(componentIdx);
if (!state.mayLeave) {{ throw new Error('component instance is not marked as may leave, cannot be cancelled'); }}
const {{ taskID }} = {get_global_current_task_meta_fn}(componentIdx);
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}
const task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing async task'); }}
if (task.sync && !task.alwaysTaskReturn) {{
throw new Error('cannot cancel sync tasks without always task return set');
}}
if (!task.cancelRequested) {{ throw new Error('task cancellation has not been requested'); }}
if (task.borrowedHandles.length > 0) {{ throw new Error('task still has borrow handles'); }}
if (task.returnCalls > 0) {{ throw new Error('cannot cancel task that has already returned a value'); }}
if (task.cancelled) {{ throw new Error('cannot cancel task that has already been cancelled'); }}
task.cancelled = true;
}}
"));
}
Self::TaskCancel => {
let debug_log_fn = Intrinsic::DebugLog.name();
let task_cancel_fn = Self::TaskCancel.name();
let current_task_get_fn = Self::GetCurrentTask.name();
let get_or_create_async_state_fn =
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
let get_global_current_task_meta_fn = Intrinsic::GetGlobalCurrentTaskMetaFn.name();
output.push_str(&format!("
function {task_cancel_fn}(componentIdx) {{
{debug_log_fn}('[{task_cancel_fn}()] args', {{ componentIdx, isAsync }});
const state = {get_or_create_async_state_fn}(componentIdx);
if (!state.mayLeave) {{ throw new Error('component instance is not marked as may leave, cannot be cancelled'); }}
const {{ taskID }} = {get_global_current_task_meta_fn}(componentIdx);
const taskMeta = {current_task_get_fn}(componentIdx, taskID);
if (!taskMeta) {{ throw new Error('invalid/missing async task meta'); }}
const task = taskMeta.task;
if (!task) {{ throw new Error('invalid/missing async task'); }}
if (task.sync && !task.alwaysTaskReturn) {{
throw new Error('cannot cancel sync tasks without always task return set');
}}
task.cancel();
}}
"));
}
Self::CreateNewCurrentTask => {
let debug_log_fn = Intrinsic::DebugLog.name();
let task_class = Self::AsyncTaskClass.name();
let global_task_map = Self::GlobalAsyncCurrentTaskMap.name();
let task_id_globals = Self::GlobalAsyncCurrentTaskIds.name();
let component_idx_globals = Self::GlobalAsyncCurrentComponentIdxs.name();
output.push_str(&format!(
r#"
function {fn_name}(args) {{
{debug_log_fn}('[{fn_name}()] args', args);
const {{
componentIdx,
isAsync,
isManualAsync,
entryFnName,
parentSubtaskID,
callbackFnName,
getCallbackFn,
getParamsFn,
stringEncoding,
errHandling,
getCalleeParamsFn,
resultPtr,
callingWasmExport,
}} = args;
if (componentIdx === undefined || componentIdx === null) {{
throw new Error('missing/invalid component instance index while starting task');
}}
let taskMetas = {global_task_map}.get(componentIdx);
const callbackFn = getCallbackFn ? getCallbackFn() : null;
const newTask = new {task_class}({{
componentIdx,
isAsync,
isManualAsync,
entryFnName,
callbackFn,
callbackFnName,
stringEncoding,
getCalleeParamsFn,
resultPtr,
errHandling,
}});
const newTaskID = newTask.id();
const newTaskMeta = {{ id: newTaskID, componentIdx, task: newTask }};
// NOTE: do not track host tasks
{task_id_globals}.push(newTaskID);
{component_idx_globals}.push(componentIdx);
if (!taskMetas) {{
taskMetas = [newTaskMeta];
{global_task_map}.set(componentIdx, [newTaskMeta]);
}} else {{
taskMetas.push(newTaskMeta);
}}
return [newTask, newTaskID];
}}
"#,
fn_name = self.name(),
));
}
// Debug log for this is disabled since it is fairly noisy
Self::GetCurrentTask => {
let global_task_map = Self::GlobalAsyncCurrentTaskMap.name();
let current_component_idx_globals =
AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs.name();
output.push_str(&format!(
r#"
function {fn_name}(componentIdx, taskID) {{
let usedGlobal = false;
if (componentIdx === undefined || componentIdx === null) {{
throw new Error('missing component idx'); // TODO(fix)
// componentIdx = {current_component_idx_globals}.at(-1);
// usedGlobal = true;
}}
const taskMetas = {global_task_map}.get(componentIdx);
if (taskMetas === undefined || taskMetas.length === 0) {{ return undefined; }}
if (taskID) {{
return taskMetas.find(meta => meta.task.id() === taskID);
}}
const taskMeta = taskMetas[taskMetas.length - 1];
if (!taskMeta || !taskMeta.task) {{ return undefined; }}
return taskMeta;
}}
"#,
fn_name = self.name(),
));
}
Self::ClearCurrentTask => {
let debug_log_fn = Intrinsic::DebugLog.name();
let fn_name = self.name();
let global_task_map = Self::GlobalAsyncCurrentTaskMap.name();
let task_id_globals = Self::GlobalAsyncCurrentTaskIds.name();
let component_idx_globals = Self::GlobalAsyncCurrentComponentIdxs.name();
output.push_str(&format!(
r#"
function {fn_name}(componentIdx, taskID) {{
{debug_log_fn}('[{fn_name}()] args', {{ componentIdx, taskID }});
if (componentIdx === undefined || componentIdx === null) {{
throw new Error('missing/invalid component instance index while ending current task');
}}
const tasks = {global_task_map}.get(componentIdx);
if (!tasks || !Array.isArray(tasks)) {{
throw new Error('missing/invalid tasks for component instance while ending task');
}}
if (tasks.length == 0) {{
throw new Error(`no current tasks for component instance [${{componentIdx}}] while ending task`);
}}
if (taskID !== undefined) {{
const last = tasks[tasks.length - 1];
if (last.id !== taskID) {{
// throw new Error('current task does not match expected task ID');
return;
}}
}}
{task_id_globals}.pop();
{component_idx_globals}.pop();
const taskMeta = tasks.pop();
return taskMeta.task;
}}
"#,
));
}
// NOTE: since threads are not yet supported, places that would have called out to threads instead run
// `immediate<original function>` -- i.e. `Thread#suspendUntil` becomes `AsyncTask#immediateSuspendUntil`
Self::AsyncTaskClass => {
let debug_log_fn = Intrinsic::DebugLog.name();
let get_or_create_async_state_fn =
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState).name();
let event_code_enum = Intrinsic::AsyncEventCodeEnum.name();
let task_class = Self::AsyncTaskClass.name();
let subtask_class = Self::AsyncSubtaskClass.name();
let global_async_determinism = Intrinsic::GlobalAsyncDeterminism.name();
let coin_flip_fn = Intrinsic::CoinFlip.name();
let waitable_class = Intrinsic::Waitable(WaitableIntrinsic::WaitableClass).name();
let clear_current_task_fn =
Intrinsic::AsyncTask(AsyncTaskIntrinsic::ClearCurrentTask).name();
let with_global_current_task_meta_async_fn =
Intrinsic::WithGlobalCurrentTaskMetaFnAsync.name();
output.push_str(&format!(r#"
class {task_class} {{
static _ID = 0n;
static State = {{
INITIAL: 'initial',
CANCELLED: 'cancelled',
CANCEL_PENDING: 'cancel-pending',
CANCEL_DELIVERED: 'cancel-delivered',
RESOLVED: 'resolved',
}}
static BlockResult = {{
CANCELLED: 'block.cancelled',
NOT_CANCELLED: 'block.not-cancelled',
}}
#id;
#componentIdx;
#state;
#isAsync;
#isManualAsync;
#entryFnName = null;
#onResolveHandlers = [];
#completionPromise = null;
#rejected = false;
#exitPromise = null;
#onExitHandlers = [];
#memoryIdx = null;
#memory = null;
#callbackFn = null;
#callbackFnName = null;
#postReturnFn = null;
#getCalleeParamsFn = null;
#stringEncoding = null;
#parentSubtask = null;
#errHandling;
#backpressurePromise;
#backpressureWaiters = 0n;
#returnLowerFns = null;
#subtasks = [];
#entered = false;
#exited = false;
#errored = null;
cancelled = false;
cancelRequested = false;
alwaysTaskReturn = false;
returnCalls = 0;
storage = [0, 0];
borrowedHandles = {{}};
tmpRetI64HighBits = 0|0;
constructor(opts) {{
this.#id = ++{task_class}._ID;
if (opts?.componentIdx === undefined) {{
throw new TypeError('missing component id during task creation');
}}
this.#componentIdx = opts.componentIdx;
this.#state = {task_class}.State.INITIAL;
this.#isAsync = opts?.isAsync ?? false;
this.#isManualAsync = opts?.isManualAsync ?? false;
this.#entryFnName = opts.entryFnName;
const {{
promise: completionPromise,
resolve: resolveCompletionPromise,
reject: rejectCompletionPromise,
}} = promiseWithResolvers();
this.#completionPromise = completionPromise;
this.#onResolveHandlers.push((results) => {{
if (this.#errored !== null) {{
rejectCompletionPromise(this.#errored);
return;
}} else if (this.#rejected) {{
rejectCompletionPromise(results);
return;
}}
resolveCompletionPromise(results);
}});
const {{
promise: exitPromise,
resolve: resolveExitPromise,
reject: rejectExitPromise,
}} = promiseWithResolvers();
this.#exitPromise = exitPromise;
this.#onExitHandlers.push(() => {{
resolveExitPromise();
}});
if (opts.callbackFn) {{ this.#callbackFn = opts.callbackFn; }}
if (opts.callbackFnName) {{ this.#callbackFnName = opts.callbackFnName; }}
if (opts.getCalleeParamsFn) {{ this.#getCalleeParamsFn = opts.getCalleeParamsFn; }}
if (opts.stringEncoding) {{ this.#stringEncoding = opts.stringEncoding; }}
if (opts.parentSubtask) {{ this.#parentSubtask = opts.parentSubtask; }}
if (opts.errHandling) {{ this.#errHandling = opts.errHandling; }}
}}
taskState() {{ return this.#state; }}
id() {{ return this.#id; }}
componentIdx() {{ return this.#componentIdx; }}
entryFnName() {{ return this.#entryFnName; }}
completionPromise() {{ return this.#completionPromise; }}
exitPromise() {{ return this.#exitPromise; }}
isAsync() {{ return this.#isAsync; }}
isSync() {{ return !this.isAsync(); }}
getErrHandling() {{ return this.#errHandling; }}
hasCallback() {{ return this.#callbackFn !== null; }}
getReturnMemoryIdx() {{ return this.#memoryIdx; }}
setReturnMemoryIdx(idx) {{
if (idx === null) {{ return; }}
this.#memoryIdx = idx;
}}
getReturnMemory() {{ return this.#memory; }}
setReturnMemory(m) {{
if (m === null) {{ return; }}
this.#memory = m;
}}
setReturnLowerFns(fns) {{ this.#returnLowerFns = fns; }}
getReturnLowerFns() {{ return this.#returnLowerFns; }}
setParentSubtask(subtask) {{
if (!subtask || !(subtask instanceof {subtask_class})) {{ return }}
if (this.#parentSubtask) {{ throw new Error('parent subtask can only be set once'); }}
this.#parentSubtask = subtask;
}}
getParentSubtask() {{ return this.#parentSubtask; }}
// TODO(threads): this is very inefficient, we can pass along a root task,
// and ideally do not need this once thread support is in place
getRootTask() {{
let currentSubtask = this.getParentSubtask();
let task = this;
while (currentSubtask) {{
task = currentSubtask.getParentTask();
currentSubtask = task.getParentSubtask();
}}
return task;
}}
setPostReturnFn(f) {{
if (!f) {{ return; }}
if (this.#postReturnFn) {{ throw new Error('postReturn fn can only be set once'); }}
this.#postReturnFn = f;
}}
setCallbackFn(f, name) {{
if (!f) {{ return; }}
if (this.#callbackFn) {{ throw new Error('callback fn can only be set once'); }}
this.#callbackFn = f;
this.#callbackFnName = name;
}}
getCallbackFnName() {{
if (!this.#callbackFnName) {{ return undefined; }}
return this.#callbackFnName;
}}
async runCallbackFn(...args) {{