use crate::intrinsics::component::ComponentIntrinsic;
use crate::intrinsics::p3::async_task::AsyncTaskIntrinsic;
use crate::intrinsics::{Intrinsic, RenderIntrinsicsArgs};
use crate::source::Source;
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
#[allow(clippy::enum_variant_names)]
pub enum HostIntrinsic {
PrepareCall,
AsyncStartCall,
SyncStartCall,
StoreEventInComponentMemory,
}
impl HostIntrinsic {
pub fn get_global_names() -> impl IntoIterator<Item = &'static str> {
["syncStartCall", "asyncStartCall", "prepareCall"]
}
pub fn name(&self) -> &'static str {
match self {
Self::PrepareCall => "_prepareCall",
Self::AsyncStartCall => "_asyncStartCall",
Self::SyncStartCall => "_syncStartCall",
Self::StoreEventInComponentMemory => "_storeEventInComponentMemory",
}
}
pub fn render(&self, output: &mut Source, render_args: &RenderIntrinsicsArgs<'_>) {
match self {
Self::PrepareCall => {
let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
let prepare_call_fn = render_args.require_intrinsic(Self::PrepareCall);
let current_task_get_fn = render_args.intrinsic_call_prefix(Intrinsic::AsyncTask(
AsyncTaskIntrinsic::GetCurrentTask,
));
let get_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::GetGlobalCurrentThreadMetaFn);
let create_new_current_task_fn = render_args.intrinsic_call_prefix(
Intrinsic::AsyncTask(AsyncTaskIntrinsic::CreateNewCurrentImplicitThread),
);
let set_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::SetGlobalCurrentThreadMetaFn);
let current_task_may_block =
render_args.require_intrinsic(AsyncTaskIntrinsic::CurrentTaskMayBlock);
let runtime_error_class =
render_args.require_intrinsic(Intrinsic::WebAssemblyRuntimeError);
output.push_str(&format!(
r#"
function {prepare_call_fn}(
memoryIdx,
getMemoryFn,
startFn,
returnFn,
callerComponentIdx,
calleeComponentIdx,
taskReturnTypeIdx,
calleeIsAsyncInt,
stringEncoding,
resultCountOrAsync,
) {{
{debug_log_fn}('[{prepare_call_fn}()]', {{
memoryIdx,
callerComponentIdx,
calleeComponentIdx,
taskReturnTypeIdx,
calleeIsAsyncInt,
stringEncoding,
resultCountOrAsync,
}});
const argArray = [...arguments];
// value passed in *may* be as large as u32::MAX which may be mangled into -2
resultCountOrAsync >>>= 0;
let isAsync = false;
let hasResultPointer = false;
if (resultCountOrAsync === 2**32 - 1) {{
// prepare async with no result (u32::MAX)
isAsync = true;
hasResultPointer = false;
}} else if (resultCountOrAsync === 2**32 - 2) {{
// prepare async with result (u32::MAX - 1)
isAsync = true;
hasResultPointer = true;
}} else if (resultCountOrAsync > 1) {{
// Sync lowering whose flattened results exceed
// MAX_FLAT_RESULTS (1): the results are spilled via a
// return pointer, passed as the caller's trailing core
// argument (the fused [return-call] helper writes
// through it). An unflattenable result count arrives
// as the i32::MAX sentinel and takes this path too.
hasResultPointer = true;
}}
const currentCallerThreadMeta = {get_global_current_thread_meta_fn}callerComponentIdx);
const currentCallerTaskMeta = currentCallerThreadMeta && {current_task_get_fn}callerComponentIdx, currentCallerThreadMeta.taskID);
if (!currentCallerTaskMeta) {{
// Core start functions run without an ambient component task.
// A fused synchronous lower would have to block that implicit
// synchronous task, so report the canonical trap before trying
// to construct its structured-concurrency child.
if (!isAsync && {current_task_may_block}.value === 0) {{
throw new {runtime_error_class}('cannot block a synchronous task before returning');
}}
throw new Error('invalid/missing current task for caller during prepare call');
}}
const currentCallerTask = currentCallerTaskMeta.task;
const callerThreadID = currentCallerThreadMeta.threadID;
if (!currentCallerTask) {{
throw new Error('unexpectedly missing task in meta for caller during prepare call');
}}
if (currentCallerTask.componentIdx() !== callerComponentIdx) {{
throw new Error(`task component idx [${{ currentCallerTask.componentIdx() }}] !== [${{ callerComponentIdx }}] (callee ${{ calleeComponentIdx }})`);
}}
let getCalleeParamsFn;
let resultPtr = null;
let directParamsArr;
if (hasResultPointer) {{
directParamsArr = argArray.slice(10, argArray.length - 1);
getCalleeParamsFn = () => directParamsArr;
resultPtr = argArray[argArray.length - 1] >>> 0;
}} else {{
directParamsArr = argArray.slice(10);
getCalleeParamsFn = () => directParamsArr;
}}
let encoding;
switch (stringEncoding) {{
case 0:
encoding = 'utf8';
break;
case 1:
encoding = 'utf16';
break;
case 2:
encoding = 'compact-utf16';
break;
default:
throw new Error(`unrecognized string encoding enum [${{stringEncoding}}]`);
}}
const subtask = currentCallerTask.createSubtask({{
componentIdx: callerComponentIdx,
parentTask: currentCallerTask,
isAsync,
callMetadata: {{
getMemoryFn,
memoryIdx,
callerThreadID,
resultPtr,
returnFn,
startFn,
stringEncoding: encoding,
}}
}});
const {{ task: newTask, thread: newThread }} = {create_new_current_task_fn}{{
componentIdx: calleeComponentIdx,
isAsync,
getCalleeParamsFn,
entryFnName: [
'task',
subtask.getParentTask().id(),
'subtask',
subtask.id(),
'new-prepared-async-task'
].join('/'),
stringEncoding: encoding,
}});
newTask.setParentSubtask(subtask);
// Whether the callee may block depends on the callee's function type
// (FACT passes `types[lift_ty].async_` here), not on how the caller
// lowered the call or how the callee was lifted.
newTask.setFuncTypeIsAsync(calleeIsAsyncInt !== 0);
newTask.setReturnResultTypeIdx(taskReturnTypeIdx >>> 0);
newTask.setReturnMemoryIdx(memoryIdx);
newTask.setReturnMemory(getMemoryFn());
subtask.setChildTask(newTask);
newTask.subtaskMeta = {{
subtask,
calleeComponentIdx,
callerComponentIdx,
getCalleeParamsFn,
stringEncoding: encoding,
isAsync,
}};
{set_global_current_thread_meta_fn}{{
taskID: newTask.id(),
threadID: newThread.id(),
componentIdx: newTask.componentIdx(),
}});
}}
"#
));
}
Self::AsyncStartCall => {
let report_trap_fn = render_args
.require_intrinsic(Intrinsic::Component(ComponentIntrinsic::ReportTrap));
let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
let async_start_call_fn = render_args.require_intrinsic(Self::AsyncStartCall);
let get_or_create_async_state_fn = render_args.intrinsic_call_prefix(
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
);
let async_event_code_enum =
render_args.require_intrinsic(Intrinsic::AsyncEventCodeEnum);
let async_driver_loop_fn = render_args
.intrinsic_call_prefix(Intrinsic::AsyncTask(AsyncTaskIntrinsic::DriverLoop));
let lookup_memories_for_component_fn =
render_args.intrinsic_call_prefix(Intrinsic::LookupMemoriesForComponent);
let current_component_idx_globals = render_args
.require_intrinsic(AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs);
let blocking_call_depth =
render_args.require_intrinsic(AsyncTaskIntrinsic::AsyncBlockingCallDepth);
let get_current_task_fn = render_args.intrinsic_call_prefix(Intrinsic::AsyncTask(
AsyncTaskIntrinsic::GetCurrentTask,
));
let with_global_current_thread_meta_async_fn = render_args
.intrinsic_call_prefix(Intrinsic::WithGlobalCurrentThreadMetaFnAsync);
let with_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::WithGlobalCurrentThreadMetaFn);
let get_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::GetGlobalCurrentThreadMetaFn);
output.push_str(&format!(r#"
function {async_start_call_fn}(args, callee, paramCount, resultCount, flags) {{
const componentIdx = {current_component_idx_globals}.at(-1);
const globalTaskMeta = {get_global_current_thread_meta_fn}componentIdx);
if (!globalTaskMeta) {{ throw new Error('missing global current task globalTaskMeta'); }}
const taskID = globalTaskMeta.taskID;
const threadID = globalTaskMeta.threadID;
{debug_log_fn}('[{async_start_call_fn}()] args', {{ args, componentIdx }});
const {{ getCallbackFn, callbackIdx, getPostReturnFn, postReturnIdx }} = args;
const preparedTaskMeta = {get_current_task_fn}componentIdx, taskID);
if (!preparedTaskMeta) {{ throw new Error('unexpectedly missing current task'); }}
const preparedTask = preparedTaskMeta.task;
if (!preparedTask) {{ throw new Error('unexpectedly missing current task'); }}
if (!preparedTask.subtaskMeta) {{ throw new Error('missing subtask meta from prepare'); }}
preparedTask.setCalleeIsAsync((flags & 1) !== 0);
const calleeIsAsync = (flags & 1) !== 0;
const {{
subtask,
returnMemoryIdx,
getReturnMemoryFn,
callerComponentIdx,
calleeComponentIdx,
getCalleeParamsFn,
isAsync,
stringEncoding,
}} = preparedTask.subtaskMeta;
if (!subtask) {{ throw new Error("missing subtask from cstate during async start call"); }}
if (calleeComponentIdx !== preparedTask.componentIdx()) {{
throw new Error(`meta callee idx [${{calleeComponentIdx}}] != current task idx [${{preparedTask.componentIdx()}}] during async start call`);
}}
if (calleeComponentIdx !== componentIdx) {{
throw new Error("mismatched componentIdx for async start call (does not match prepare)");
}}
const argArray = [...arguments];
if (resultCount < 0 || resultCount > 1) {{ throw new Error('invalid/unsupported result count'); }}
const callbackFnName = 'callback_' + callbackIdx;
const callbackFn = getCallbackFn();
preparedTask.setCallbackFn(callbackFn, callbackFnName);
preparedTask.setPostReturnFn(getPostReturnFn());
if (resultCount < 0 || resultCount > 1) {{
throw new Error(`unsupported result count [${{ resultCount }}]`);
}}
// NOTE: `params` are the *caller's* lowered core args captured during
// PrepareCall, while `paramCount` describes the *callee's* lifted core
// signature.
//
// The two intentionally differ whenever the caller spilled
// its arguments to memory (async lowers pass a single pointer for
// functions with more than MAX_FLAT_ASYNC_PARAMS flat params).
//
// The fused [async-start] adapter that is provided (`startFn`,
// invoked via `subtask.onStart()` below) performs the conversion.
//
const params = preparedTask.getCalleeParams();
const callerComponentState = {get_or_create_async_state_fn}subtask.componentIdx());
const calleeComponentState = {get_or_create_async_state_fn}preparedTask.componentIdx());
const calleeBackpressure = calleeComponentState.hasBackpressure();
// Set up a handler on subtask completion to lower results from the call into the caller's memory region.
//
// NOTE: during fused guest->guest calls this handler is triggered, but does not actually perform
// lowering manually, as fused modules provider helper functions that can
subtask.registerOnResolveHandler((res) => {{
{debug_log_fn}('[{async_start_call_fn}()] handling subtask result', {{ res, subtaskID: subtask.id() }});
// Cancelled resolutions carry no value; there is nothing to lower
if (!subtask.isReturned()) {{ return; }}
let subtaskCallMeta = subtask.getCallMetadata();
// NOTE: in the case of guest -> guest async calls, there may be no memory/realloc present,
// as the host will intermediate the value storage/movement between calls.
//
// We can simply take the value and lower it as a parameter
if (subtaskCallMeta.memory || subtaskCallMeta.realloc) {{
throw new Error("call metadata unexpectedly contains memory/realloc for guest->guest call");
}}
const callerTask = subtask.getParentTask();
const calleeTask = preparedTask;
const callerMemoryIdx = callerTask.getReturnMemoryIdx();
const callerComponentIdx = callerTask.componentIdx();
// If a helper function was provided we are likely in a fused guest->guest call,
// and the result will be delivered (lift/lowered) via helper function
if (subtaskCallMeta && subtaskCallMeta.returnFn) {{
{debug_log_fn}('[{async_start_call_fn}()] return function present while handling subtask result, returning early (skipping lower)', {{
calleeTaskID: calleeTask.id(),
calleeComponentIdx,
}});
// TODO: centralize calling of returnFn to *one place* (if possible)
if (subtaskCallMeta.returnFnCalled) {{ return; }}
const res = {with_global_current_thread_meta_fn}{{
taskID: callerTask.id(),
threadID: subtaskCallMeta.callerThreadID,
componentIdx: callerTask.componentIdx(),
fn: () => subtaskCallMeta.returnFn.apply(null, [subtaskCallMeta.resultPtr]),
}});
subtaskCallMeta.returnFnCalled = true;
{debug_log_fn}('[{async_start_call_fn}()] finished calling return fn', {{
calleeTaskID: calleeTask.id(),
calleeComponentIdx,
res,
}});
return;
}}
// If there is no where to lower the results, exit early
if (!subtaskCallMeta.resultPtr) {{
{debug_log_fn}('[{async_start_call_fn}()] no result ptr during subtask result handling, returning early (skipping lower)');
return;
}}
let callerMemory;
if (callerMemoryIdx !== null && callerMemoryIdx !== undefined) {{
const memory = {lookup_memories_for_component_fn}{{ componentIdx: callerComponentIdx, memoryIdx: callerMemoryIdx }});
callerMemory = Array.isArray(memory) ? undefined : memory;
}} else {{
const callerMemories = {lookup_memories_for_component_fn}{{ componentIdx: callerComponentIdx }});
if (callerMemories.length !== 1) {{ throw new Error(`unsupported amount of caller memories`); }}
callerMemory = callerMemories[0]?.memory;
}}
if (!callerMemory) {{
{debug_log_fn}('[{async_start_call_fn}()] missing memory', {{ subtaskID: subtask.id(), res }});
throw new Error(`missing memory for to guest->guest call result (subtask [${{subtask.id()}}])`);
}}
const lowerFns = calleeTask.getReturnLowerFns();
if (!lowerFns || lowerFns.length === 0) {{
{debug_log_fn}('[{async_start_call_fn}()] missing result lower metadata for guest->guest call', {{ subtaskID: subtask.id() }});
throw new Error(`missing result lower metadata for guest->guest call (subtask [${{subtask.id()}}])`);
}}
if (lowerFns.length !== 1) {{
{debug_log_fn}('[{async_start_call_fn}()] only single result reportetd for guest->guest call', {{ subtaskID: subtask.id() }});
throw new Error(`only single result supported for guest->guest calls (subtask [${{subtask.id()}}])`);
}}
{debug_log_fn}('[{async_start_call_fn}()] lowering results', {{ subtaskID: subtask.id() }});
lowerFns[0]({{
realloc: undefined,
memory: callerMemory,
vals: [res],
storagePtr: subtaskCallMeta.resultPtr,
componentIdx: callerComponentIdx,
stringEncoding: subtaskCallMeta.stringEncoding,
}});
}});
let startRes;
const startSubtask = () => {{
startRes = subtask.onStart({{ startFnParams: params }});
startRes = startRes === undefined ? [] : Array.isArray(startRes) ? startRes : [startRes];
if (startRes.length !== paramCount) {{
throw new Error(`unexpected callee param count [${{ startRes.length }}] after start fn, {async_start_call_fn} invocation expected [${{ paramCount }}]`);
}}
}};
const registerSubtaskProgress = () => {{
subtask.setOnProgressFn(() => {{
subtask.setPendingEvent(() => {{
if (subtask.isResolved()) {{ subtask.deliverResolve(); }}
const event = {{
code: {async_event_code_enum}.SUBTASK,
payload0: subtask.waitableRep(),
payload1: subtask.getStateNumber(),
}};
return event;
}});
}});
}};
const handleCalleeError = (err) => {{
preparedTask.endFirstSlice();
{debug_log_fn}("[{async_start_call_fn}()] initial subtask callee run failed", err);
{report_trap_fn}(err);
// NOTE: a good place to reject the parent task, if rejection API is enabled
// subtask.reject(err);
// subtask.getParentTask().reject(err);
subtask.getParentTask().setErrored(err);
// Release the enter()-acquired per-slice hold: the driver
// loop that would normally pair it never starts.
if (preparedTask.needsExclusiveLock()) {{
calleeComponentState.exclusiveRelease(preparedTask.id());
}}
}};
const driveCallback = (callbackResult) => {{
// If there was no callback function, we're dealing with a sync function
// that was lifted as async without one, there is only the callee.
if (!callbackFn) {{
{debug_log_fn}("[{async_start_call_fn}()] no callback, resolving w/ callee result", {{
taskID: preparedTask.id(),
componentIdx: preparedTask.componentIdx(),
preparedTask,
stateNumber: preparedTask.taskState(),
isResolved: preparedTask.isResolved(),
callbackFn,
}});
// A sync-lifted callee applies automatic backpressure for
// the complete call. Its entry hold ends when the core
// function returns, not when one of its nested calls parks.
if (preparedTask.needsExclusiveLock()) {{
calleeComponentState.exclusiveRelease(preparedTask.id());
}}
// Cancellation can resolve the task while the
// synchronous callee is still unwinding. Its
// eventual return only ends the slice; it must
// not publish a second resolution.
if (!preparedTask.isResolved()) {{
preparedTask.resolve([callbackResult]);
}}
preparedTask.exit({{ skipExclusiveLockCheck: true }});
return;
}}
let fnName = callbackFn.fnName;
if (!fnName) {{
fnName = [
'<task ',
subtask.parentTaskID(),
'/subtask ',
subtask.id(),
'/task ',
preparedTask.id(),
'>',
].join("");
}}
{debug_log_fn}("[{async_start_call_fn}()] starting driver loop", {{
fnName,
componentIdx: preparedTask.componentIdx(),
subtaskID: subtask.id(),
childTaskID: subtask.childTaskID(),
parentTaskID: subtask.parentTaskID(),
}});
return {async_driver_loop_fn}{{
componentState: calleeComponentState,
task: preparedTask,
fnName,
isAsync: true,
callbackResult,
}});
}};
const driveJspiCallee = async () => {{
try {{ calleeComponentState.throwIfInterrupted(); }} catch (err) {{ handleCalleeError(err); return; }}
let callbackResult;
// A synchronous callee blocks its caller until it fully returns (it may
// suspend mid-way, e.g. on a nested blocking import). Hold the blocking
// marker for the whole execution so any async subtask it starts -- even
// one dispatched after a suspension -- is recognised as originating from
// a blocking function and enters in-slice rather than being deferred.
if (!calleeIsAsync) {{ {blocking_call_depth}.value++; }}
try {{
let jspiCallee;
if (callee._cachedPromising) {{
jspiCallee = callee._cachedPromising;
}} else {{
callee._cachedPromising = WebAssembly.promising(callee);
jspiCallee = callee._cachedPromising;
}}
callbackResult = await {with_global_current_thread_meta_async_fn}{{
taskID: preparedTask.id(),
threadID,
componentIdx: preparedTask.componentIdx(),
fn: () => jspiCallee.apply(null, startRes),
}});
preparedTask.endFirstSlice();
}} catch(err) {{
handleCalleeError(err);
return;
}} finally {{
if (!calleeIsAsync) {{ {blocking_call_depth}.value--; }}
}}
try {{
await driveCallback(callbackResult);
}} catch (err) {{
{debug_log_fn}("[AsyncStartCall] drive loop call failure", {{ err }});
}}
}};
const driveDirectCallee = () => {{
try {{ calleeComponentState.throwIfInterrupted(); }} catch (err) {{ handleCalleeError(err); return; }}
let callbackResult;
if (!calleeIsAsync) {{ {blocking_call_depth}.value++; }}
try {{
callbackResult = {with_global_current_thread_meta_fn}{{
taskID: preparedTask.id(),
threadID,
componentIdx: preparedTask.componentIdx(),
fn: () => callee.apply(null, startRes),
}});
preparedTask.endFirstSlice();
}} catch (err) {{
handleCalleeError(err);
return;
}} finally {{
if (!calleeIsAsync) {{ {blocking_call_depth}.value--; }}
}}
driveCallback(callbackResult)?.catch(err => {{
{debug_log_fn}("[AsyncStartCall] drive loop call failure", {{ err }});
}});
}};
// Enter eagerly when backpressure and the per-component slice lock permit
// it. `tryEnter()` returns null for real contention, preserving an
// observable STARTING state only when the callee genuinely cannot start.
// A successful async entry runs through its first suspension point before
// returning STARTED, matching the canonical ABI scheduling contract.
const enteredSynchronously = preparedTask.tryEnter();
if (enteredSynchronously === true) {{
// Directly returned STARTED is not also delivered as an event, so
// install the progress handler only after the state transition.
startSubtask();
registerSubtaskProgress();
if (callee._jcoMaySuspend === false) {{
driveDirectCallee();
}} else {{
// Calling the async helper runs synchronously through invocation
// of WebAssembly.promising, which executes the guest until its
// first suspending import before returning a Promise.
driveJspiCallee();
}}
}} else if (enteredSynchronously === null) {{
// A delayed transition to STARTED is guest-visible progress.
registerSubtaskProgress();
const enterPromise = preparedTask.enter().then(started => {{
// Entry can finish before the timer below runs. Keep that
// runnable guest work visible to the deadlock detector.
if (started) {{ calleeComponentState.addPendingTaskStart(); }}
return started;
}});
// Entry is blocked by backpressure or an in-flight component slice,
// so resume the call once the task is allowed to enter.
// Nothing catches an exception thrown from a timer callback:
// it would take down the whole process rather than the call.
// Any failure here is reported through the subtask instead.
const failDeferredStart = (err) => {{
handleCalleeError(err);
if (!subtask.isResolved()) {{ subtask.reject(err); }}
}};
setTimeout(async () => {{
try {{
{debug_log_fn}('[{async_start_call_fn}()] continuing started subtask (in JS task)', {{
taskID: preparedTask.id(),
subtaskID: subtask.id(),
callerComponentIdx,
calleeComponentIdx,
}});
// Entry queues FIFO when another slice of the callee
// component is already in flight.
const started = await enterPromise;
if (started) {{ calleeComponentState.removePendingTaskStart(); }}
if (!started) {{
{debug_log_fn}('[{async_start_call_fn}()] task failed early', {{
taskID: preparedTask.id(),
subtaskID: subtask.id(),
}});
// A cancellation-before-start is a valid resolution, not a failure
if (preparedTask.isCancelled()) {{ return; }}
throw preparedTask.isErrored() ?? new Error("task failed to start");
}}
// PrepareCall installs the callee task before the eager
// path runs, but that metadata is gone by the time a
// contended entry resumes in this timer. Fused adapters
// can execute context.get while lowering their inputs,
// so restore the same task context around the delayed
// start that the eager path observes.
{with_global_current_thread_meta_fn}{{
taskID: preparedTask.id(),
threadID,
componentIdx: preparedTask.componentIdx(),
fn: startSubtask,
}});
if (callee._jcoMaySuspend === false) {{
driveDirectCallee();
}} else {{
await driveJspiCallee();
}}
}} catch (err) {{
failDeferredStart(err);
}}
}}, 0);
}}
// A callee that trapped while it ran synchronously (for example
// one that exited without `task.return`) traps its caller as well,
// as in the Canonical ABI: the call does not return a subtask
// state that implies a cancellation nobody requested.
const calleeTrap = preparedTask.isErrored() ?? subtask.getParentTask().isErrored();
if (calleeTrap) {{ throw calleeTrap; }}
const subtaskState = subtask.getStateNumber();
if (subtaskState < 0 || subtaskState > 2**5) {{
throw new Error('invalid subtask state, out of valid range');
}}
{debug_log_fn}('[{async_start_call_fn}()] returning subtask rep & state', {{
subtask: {{
rep: subtask.waitableRep(),
state: subtaskState,
}}
}});
if (subtask.isReturned()) {{
// Eager completion exposes no waitable handle to the caller.
// Consume the parked progress event and retire the internal
// bookkeeping subtask just like an eager host import.
if (subtask.hasPendingEvent()) {{
subtask.getPendingEvent();
}}
if (!subtask.resolveDelivered()) {{
subtask.deliverResolve();
}}
if (subtask.waitableRep() !== null) {{
const removed = callerComponentState.handles.remove(subtask.waitableRep());
if (removed !== subtask) {{
throw new Error('subtask handle cleanup removed unexpected entry');
}}
}}
subtask.drop();
return subtaskState;
}}
return Number(subtask.ensureHandle()) << 4 | subtaskState;
}}
"#));
}
Self::SyncStartCall => {
let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
let sync_start_call_fn = render_args.require_intrinsic(Self::SyncStartCall);
let get_or_create_async_state_fn = render_args.intrinsic_call_prefix(
Intrinsic::Component(ComponentIntrinsic::GetOrCreateAsyncState),
);
let async_driver_loop_fn = render_args
.intrinsic_call_prefix(Intrinsic::AsyncTask(AsyncTaskIntrinsic::DriverLoop));
let current_component_idx_globals = render_args
.require_intrinsic(AsyncTaskIntrinsic::GlobalAsyncCurrentComponentIdxs);
let get_current_task_fn = render_args.intrinsic_call_prefix(Intrinsic::AsyncTask(
AsyncTaskIntrinsic::GetCurrentTask,
));
let with_global_current_thread_meta_async_fn = render_args
.intrinsic_call_prefix(Intrinsic::WithGlobalCurrentThreadMetaFnAsync);
let with_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::WithGlobalCurrentThreadMetaFn);
let get_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::GetGlobalCurrentThreadMetaFn);
let set_global_current_thread_meta_fn =
render_args.intrinsic_call_prefix(Intrinsic::SetGlobalCurrentThreadMetaFn);
let promise_with_resolvers_fn =
render_args.require_intrinsic(Intrinsic::PromiseWithResolversPonyfill);
output.push_str(&format!(
r#"
async function {sync_start_call_fn}(args, callee, paramCount) {{
const componentIdx = {current_component_idx_globals}.at(-1);
const globalTaskMeta = {get_global_current_thread_meta_fn}componentIdx);
if (!globalTaskMeta) {{ throw new Error('missing global current task meta during sync start call'); }}
const taskID = globalTaskMeta.taskID;
const threadID = globalTaskMeta.threadID;
{debug_log_fn}('[{sync_start_call_fn}()] args', {{ args, paramCount, componentIdx }});
const {{ getCallbackFn, callbackIdx }} = args;
const preparedTaskMeta = {get_current_task_fn}componentIdx, taskID);
if (!preparedTaskMeta) {{ throw new Error('unexpectedly missing current (prepared) task'); }}
const preparedTask = preparedTaskMeta.task;
if (!preparedTask) {{ throw new Error('unexpectedly missing current (prepared) task'); }}
if (!preparedTask.subtaskMeta) {{ throw new Error('missing subtask meta from prepare'); }}
// sync-start lowers the caller synchronously but invokes an
// asynchronously lifted callee (callback or stackful).
preparedTask.setCalleeIsAsync(true);
const {{ subtask, calleeComponentIdx, callerComponentIdx }} = preparedTask.subtaskMeta;
if (!subtask) {{ throw new Error('missing subtask from prepare during sync start call'); }}
if (calleeComponentIdx !== preparedTask.componentIdx()) {{
throw new Error(`meta callee idx [${{calleeComponentIdx}}] != current task idx [${{preparedTask.componentIdx()}}] during sync start call`);
}}
// The caller's wasm stack stays suspended across the whole blocking
// call; sibling slices of the caller's component may run meanwhile
// and move its current-task register. Capture the entry at call
// time and restore it before the caller resumes (the same
// discipline as the suspending-import wrapper).
const savedCallerTaskMeta = {get_global_current_thread_meta_fn}callerComponentIdx);
try {{
const callbackFn = getCallbackFn();
preparedTask.setCallbackFn(callbackFn, 'callback_' + callbackIdx);
// NOTE: `params` are the caller's lowered core args captured during
// PrepareCall; the fused [sync-start] helper (`startFn`, invoked via
// `subtask.onStart()` below) converts them into the callee's lifted
// core signature (`paramCount`).
const params = preparedTask.getCalleeParams();
const calleeComponentState = {get_or_create_async_state_fn}preparedTask.componentIdx());
const {{
promise: taskReturnPromise,
resolve: resolveTaskReturn,
reject: rejectTaskReturn,
}} = {promise_with_resolvers_fn}();
preparedTask.registerOnResolveHandler(() => {{
const err = preparedTask.isErrored();
if (err) {{
rejectTaskReturn(err);
}} else {{
resolveTaskReturn();
}}
}});
// For fused guest->guest calls the [return-call] helper performs the
// result copy/lower; it is invoked by the taskReturn intrinsic when
// the callee resolves (this handler is the fallback ordering guard,
// mirroring _asyncStartCall).
subtask.registerOnResolveHandler((res) => {{
{debug_log_fn}('[{sync_start_call_fn}()] handling subtask result', {{ res, subtaskID: subtask.id() }});
if (!subtask.isReturned()) {{ return; }}
const subtaskCallMeta = subtask.getCallMetadata();
if (subtaskCallMeta?.returnFn && !subtaskCallMeta.returnFnCalled) {{
const callerTask = subtask.getParentTask();
subtaskCallMeta.returnFnResult = {with_global_current_thread_meta_fn}{{
taskID: callerTask.id(),
threadID: subtaskCallMeta.callerThreadID,
componentIdx: callerTask.componentIdx(),
fn: () => subtaskCallMeta.returnFn.apply(null, [subtaskCallMeta.resultPtr]),
}});
subtaskCallMeta.returnFnCalled = true;
}}
}});
let startRes = subtask.onStart({{ startFnParams: params }});
startRes = startRes === undefined ? [] : Array.isArray(startRes) ? startRes : [startRes];
if (startRes.length !== paramCount) {{
throw new Error(`unexpected callee param count [${{ startRes.length }}] after start fn, {sync_start_call_fn} invocation expected [${{ paramCount }}]`);
}}
const started = await preparedTask.enter();
if (!started) {{
if (preparedTask.isCancelled()) {{ return undefined; }}
throw new Error('callee task failed to start during sync start call');
}}
// The prepared task was created with the *lowering's* async-ness
// (sync), so enter() took the sync shortcut without acquiring the
// per-slice exclusive lock the callback-driven slices below pair
// with; acquire it here (FIFO-queued when another slice of the callee
// is mid-flight.
if (preparedTask.needsExclusiveLock()) {{
await calleeComponentState.acquireExclusiveLock(preparedTask.id());
}}
let jspiCallee;
if (callee._cachedPromising) {{
jspiCallee = callee._cachedPromising;
}} else {{
callee._cachedPromising = WebAssembly.promising(callee);
jspiCallee = callee._cachedPromising;
}}
const failCalleeLifecycle = (err) => {{
{debug_log_fn}('[{sync_start_call_fn}()] callee lifecycle failed', {{ err }});
// The initial slice owns component entry until it either hands
// control to the callback driver or fails. A failure has no driver
// exit with which to pair this hold.
if (preparedTask.needsExclusiveLock()) {{
calleeComponentState.exclusiveRelease(preparedTask.id());
}}
preparedTask.setErrored(err);
if (!preparedTask.isResolvedState()) {{
preparedTask.reject(err);
}} else {{
// task.return may already have released the synchronous caller.
// Preserve a later trap on the store and reject the still-running
// root task when there is one, rather than losing the detached
// lifecycle failure.
calleeComponentState.markTrapped(err);
const rootTask = preparedTask.getRootTask();
if (!rootTask.isResolvedState()) {{
rootTask.setErrored(err);
rootTask.reject(err);
}}
}}
throw err;
}};
// Invocation begins immediately and runs through its first JSPI
// suspension while the callee owns component entry. Keep driving that
// invocation and its callback/exit protocol in the background after
// task.return releases the synchronous caller.
const calleeLifecyclePromise = (async () => {{
let callbackResult;
try {{
callbackResult = await {with_global_current_thread_meta_async_fn}{{
taskID: preparedTask.id(),
threadID,
componentIdx: preparedTask.componentIdx(),
fn: () => {{
return jspiCallee.apply(null, startRes);
}}
}});
preparedTask.endFirstSlice();
if (!callbackFn) {{
// Async-lifted without a callback (stackful lift): the callee
// ran to completion above; task.return already ran within it.
{debug_log_fn}('[{sync_start_call_fn}()] no callback, resolving w/ callee result', {{
taskID: preparedTask.id(),
componentIdx: preparedTask.componentIdx(),
}});
if (!preparedTask.isResolved()) {{ preparedTask.resolve([callbackResult]); }}
preparedTask.exit({{ skipExclusiveLockCheck: true }});
return;
}}
const fnName = callbackFn.fnName ?? ('<sync-start subtask ' + subtask.id() + '>');
{debug_log_fn}('[{sync_start_call_fn}()] starting driver loop', {{
fnName,
componentIdx: preparedTask.componentIdx(),
subtaskID: subtask.id(),
}});
await {async_driver_loop_fn}{{
componentState: calleeComponentState,
task: preparedTask,
fnName,
isAsync: true,
callbackResult,
}});
const driverError = preparedTask.isErrored();
if (driverError) {{ throw driverError; }}
}} catch (err) {{
failCalleeLifecycle(err);
}}
}})();
// If task.return wins the race below, retain a rejection handler on
// the detached lifecycle while failCalleeLifecycle propagates it to
// the task tree/store.
calleeLifecyclePromise.catch(() => {{}});
// A sync lower blocks only until task.return supplies its result, but
// an earlier initial-invocation failure must still trap the caller.
await Promise.race([
taskReturnPromise,
calleeLifecyclePromise.then(() => taskReturnPromise),
]);
const callMeta = subtask.getCallMetadata();
const flatResult = callMeta?.returnFnResult;
{debug_log_fn}('[{sync_start_call_fn}()] returning flat result', {{
flatResult,
subtaskID: subtask.id(),
taskID: preparedTask.id(),
}});
return flatResult;
}} finally {{
if (savedCallerTaskMeta) {{
{set_global_current_thread_meta_fn}{{
taskID: savedCallerTaskMeta.taskID,
threadID: savedCallerTaskMeta.threadID,
componentIdx: callerComponentIdx,
}});
}}
}}
}}
"#
));
}
Self::StoreEventInComponentMemory => {
let debug_log_fn = render_args.require_intrinsic(Intrinsic::DebugLog);
let store_event_in_component_memory_fn =
render_args.require_intrinsic(Self::StoreEventInComponentMemory);
output.push_str(&format!(
r#"
function {store_event_in_component_memory_fn}(args) {{
{debug_log_fn}('[{store_event_in_component_memory_fn}()] args', args);
const {{ memory, ptr, event }} = args;
if (!memory) {{ throw new Error('unexpectedly missing memory'); }}
if (ptr === undefined || ptr === null) {{ throw new Error('unexpectedly missing pointer'); }}
if (!event) {{ throw new Error('event object missing'); }}
if (event.code === undefined) {{ throw new Error('invalid event object, missing code'); }}
if (event.payload0 === undefined) {{ throw new Error('invalid event object, missing payload0'); }}
if (event.payload1 === undefined) {{ throw new Error('invalid event object, missing payload1'); }}
const dv = new DataView(memory.buffer);
dv.setUint32(ptr >>> 0, event.payload0, true);
dv.setUint32((ptr >>> 0) + 4, event.payload1, true);
return event.code;
}}
"#
));
}
}
}
}