Skip to content

[Design] WasmJs/WasmWasi exploit SuspendFunctionN <: Function{N + 1} #4694

Description

@alex28sh

What do we have today?

Currently Kotlinx.coroutines for Wasm Backend don't exploit conversion of SuspendFunctionN to Function{N + 1} (cast suspend function to a simple function accepting continuation as the last argument). The reason is that Kotlin compiler Wasm backend didn't provide such feature until 2.4.20-Beta2.

Why does this feel problematic?

For particular situations, like loops implementing interceptor chain pattern in ktor (KTOR-9699 Optimize pipelineStartCoroutineUninterceptedOrReturn for Wasm target), this creates the dispatch/interceptor overhead - it requires wrapping coroutines, dispatching them via startCoroutineUninterceptedOrReturn, etc. Instead suspend functions it could be called directly by providing continuation to them as a last argument:

interceptor: suspend PipelineContext<TSubject, TContext>.(TSubject) -> Unit

previously it was like

val coroutine: suspend () -> Unit = { interceptor.invoke(context, subject) }
coroutine.startCoroutineUninterceptedOrReturn(continuation)

now, it can be

(interceptor as (PipelineContext<TSubject, TContext>, TSubject, Continuation<Unit>) -> Any?)(context, subject, continuation)

Possible alternative (optional)

With implementing KT-78040 K/Wasm: consider making implementations (!) of suspend lambdas a subtype of FunctionX interfaces, K/Wasm backend enabled functions implementing SuspendFunction interface to also implement Function interface - since 2.4.20-Beta2.

Could you review the possible applications of this pattern in kotlinx.coroutines, if it helps to speed up coroutines implementation for Wasm backend?

Trade-offs you see (optional)

No response

Anything else? (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions