Skip to content

KTOR-9595 Fix ktor-network compatibility with jsBrowser and wasmJsBrowser - #5657

Merged
Osip Fatkullin (osipxd) merged 2 commits into
release/3.xfrom
osipxd/ktor-network-wasm-browser-compatibility
May 27, 2026
Merged

Osip Fatkullin (osipxd) merged 2 commits into
release/3.xfrom
osipxd/ktor-network-wasm-browser-compatibility

Conversation

@osipxd

Copy link
Copy Markdown
Member

Subsystem
ktor-network

Motivation
KTOR-9595 CIO: The engine imports node:net statically and breaks wasmJsBrowser webpack build

Solution
Use the approach with await import similar to this commit.

@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Karma headless launcher adds --password-store=basic; Karma config enables console capture and sets Mocha timeout to 0. The static @JsModule("node:net") binding is replaced by an async loadNodeNet() contract with JS and WasmJs lazy, conditional dynamic imports; socket connect/bind functions use explicit coroutine returns.

Changes

Test Infrastructure & Karma Configuration

Layer / File(s) Summary
Karma configuration and Chrome launcher
karma/chrome_bin.js, karma/config.js
Chrome headless launcher adds --password-store=basic; Karma config enables client.captureConsole and sets Mocha timeout to 0.

Node.js Dynamic Module Loading

Layer / File(s) Summary
Node module loading contract
ktor-network/web/src/io/ktor/network/sockets/nodejs/node.net.kt
Removes static @JsModule("node:net") binding and adds internal expect suspend fun loadNodeNet(): NodeNet asynchronous contract.
JS target dynamic Node module loading
ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt
Implements loadNodeNet() to await a lazy Promise that conditionally imports node:net via loadNodeModule() (runtime check) and throws UnsupportedOperationException when unavailable; imports coroutine await and Promise types.
WasmJs target dynamic Node module loading
ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt
Adds a lazy nodeNet initializer backed by JS interop loadNodeNetModule() which conditionally dynamic-imports node:net and throws when Node.js is not present.
Socket engine coroutine refactor
ktor-network/web/src/io/ktor/network/sockets/SocketEngine.web.kt
tcpConnect and tcpBind refactored from expression bodies to explicit block bodies returning suspendCancellableCoroutine, preserving existing connection/server initiation flow.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • ktorio/ktor#5642: Modifies karma/chrome_bin.js custom Chrome Headless launcher configuration and related Chrome binary setup.

Suggested reviewers

  • zibet27
  • bjhham
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.69% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main objective of the changeset: fixing ktor-network compatibility with jsBrowser and wasmJsBrowser builds.
Description check ✅ Passed The description follows the required template with all sections completed: Subsystem is specified, Motivation references the issue ticket (KTOR-9595) and explains the problem, and Solution describes the approach with a reference to the similar implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch osipxd/ktor-network-wasm-browser-compatibility

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@osipxd
Osip Fatkullin (osipxd) force-pushed the osipxd/ktor-network-wasm-browser-compatibility branch from cb82ccb to cdbd1ec Compare May 26, 2026 11:35
@osipxd Osip Fatkullin (osipxd) changed the title KTOR-9595 Fix ktor-network compatibility with wasmJsBrowser KTOR-9595 Fix ktor-network compatibility with jsBrowser and wasmJsBrowser May 26, 2026
@osipxd
Osip Fatkullin (osipxd) marked this pull request as ready for review May 26, 2026 13:29
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt`:
- Around line 22-27: The `@JsFun` snippet uses "await import(...)" in a
non-suspend external function (loadNodeNetModule), which is invalid; change the
JS snippet to return the dynamic import Promise (remove await and return
import(...) or Promise.resolve(null) in the false branch) and make the Kotlin
side suspend-bridge by turning loadNodeNetModule into a suspend function (or
expose a Promise-returning external and add a suspend wrapper) and await the
returned Promise using the Promise→coroutine await pattern (e.g., kotlinx
coroutines Promise.await) so the module is resolved in a proper suspend context.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0b57f4c4-4abc-4c46-8784-0a4eadaf0e47

📥 Commits

Reviewing files that changed from the base of the PR and between 1bb7247 and cdbd1ec.

📒 Files selected for processing (6)
  • karma/chrome_bin.js
  • karma/config.js
  • ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt
  • ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt
  • ktor-network/web/src/io/ktor/network/sockets/SocketEngine.web.kt
  • ktor-network/web/src/io/ktor/network/sockets/nodejs/node.net.kt

Comment on lines +24 to +25
"moduleName => ((typeof process !== 'undefined') && process.release && (process.release.name === 'node'))" +
" ? import(moduleName) : Promise.resolve(null)"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could use optional chaining to clean up these functions a little process?.release?.name == 'node'

@osipxd Osip Fatkullin (osipxd) May 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I've managed to replace it with (typeof process !== 'undefined') && process.release?.name === 'node', but can't get rid of typeof process !== 'undefined'

UPD: Ooops. JsFun fails to parse optional chaining :(

val socket = nodeNet.createConnection(CreateConnectionOptions(remoteAddress, socketOptions))
SocketContext(socket, remoteAddress, null).initiate(cont)
): Socket {
val nodeNet = loadNodeNet()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also use a lazy value here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately not as I failed to make loadNodeNet non suspending in JS. But nodeNetPromise is lazy, so it'll be evaluated only once.

@osipxd
Osip Fatkullin (osipxd) force-pushed the osipxd/ktor-network-wasm-browser-compatibility branch from cdbd1ec to 9a71730 Compare May 26, 2026 14:43

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt`:
- Around line 22-26: The JS interop currently returns a thunk because the JsFun
expression uses "((module) => () => module)(...)" so loadNodeNetModule() yields
a zero-arg function rather than the Node `net` module; update the JsFun to
return the module itself (e.g., change the wrapper to "((module) =>
module)(...)" or otherwise invoke the thunk so loadNodeNetModule() returns the
actual Node `net` object) so the Kotlin code that treats the result as NodeNet
will receive the real module; adjust the annotation on loadNodeNetModule()
accordingly and keep the external signature as returning JsAny?/NodeNet as used
elsewhere.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 692f6abf-b716-4ae2-a717-0515edcb072c

📥 Commits

Reviewing files that changed from the base of the PR and between cdbd1ec and 9a71730.

📒 Files selected for processing (5)
  • karma/config.js
  • ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt
  • ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt
  • ktor-network/web/src/io/ktor/network/sockets/SocketEngine.web.kt
  • ktor-network/web/src/io/ktor/network/sockets/nodejs/node.net.kt
💤 Files with no reviewable changes (1)
  • karma/config.js

@osipxd
Osip Fatkullin (osipxd) force-pushed the osipxd/ktor-network-wasm-browser-compatibility branch from 9a71730 to 4970302 Compare May 26, 2026 14:54

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (2)
ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt (1)

24-25: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Harden Node detection to avoid runtime crashes outside Node.

process.release.name can throw when process exists but release is missing, so the fallback path may fail before returning null.

Proposed fix
 `@JsFun`(
-    "moduleName => ((typeof process !== 'undefined') && process.release.name === 'node')" +
+    "moduleName => ((typeof process !== 'undefined') && process.release?.name === 'node')" +
         " ? import(moduleName) : Promise.resolve(null)"
 )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt` around
lines 24 - 25, The Node detection expression can throw if process.release is
undefined; update the conditional that uses process.release.name (the dynamic
import guard string) to first verify process.release exists and is an object
(e.g., check typeof process !== 'undefined' && process.release && typeof
process.release.name !== 'undefined' or use a safe typeof check for
process.release.name) or wrap the check in a safe runtime guard so the ternary
returns Promise.resolve(null) instead of throwing; locate the expression that
builds the import string referencing process.release.name and change it to use
this defensive check (or a try/catch wrapper) to avoid runtime crashes outside
Node.
ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt (1)

22-26: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

loadNodeNetModule() currently returns a thunk instead of the node:net module.

((module) => () => module)(...) returns a zero-arg function, so the casted value is not NodeNet and fails later on socket API calls.

Proposed fix
 `@JsFun`(
-    "((module) => () => module)(((typeof process !== 'undefined') && process.release.name === 'node')" +
+    "((module) => module)(((typeof process !== 'undefined') && process.release?.name === 'node')" +
         " ? await import(/* webpackIgnore: true */'node:net') : null)"
 )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt`
around lines 22 - 26, The current `@JsFun` wrapper in loadNodeNetModule() returns
a zero-arg thunk instead of the actual node:net module; remove the outer IIFE
that produces a ()=>module and return the module (or null) directly so the
external function yields the NodeNet object (matching the expected cast/use in
socket APIs). Edit the `@JsFun` string expression for loadNodeNetModule to
evaluate to the imported module itself (or null when not running in Node) rather
than a function, so subsequent casts/uses treating the result as NodeNet
succeed.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt`:
- Around line 24-25: The Node detection expression can throw if process.release
is undefined; update the conditional that uses process.release.name (the dynamic
import guard string) to first verify process.release exists and is an object
(e.g., check typeof process !== 'undefined' && process.release && typeof
process.release.name !== 'undefined' or use a safe typeof check for
process.release.name) or wrap the check in a safe runtime guard so the ternary
returns Promise.resolve(null) instead of throwing; locate the expression that
builds the import string referencing process.release.name and change it to use
this defensive check (or a try/catch wrapper) to avoid runtime crashes outside
Node.

In `@ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt`:
- Around line 22-26: The current `@JsFun` wrapper in loadNodeNetModule() returns a
zero-arg thunk instead of the actual node:net module; remove the outer IIFE that
produces a ()=>module and return the module (or null) directly so the external
function yields the NodeNet object (matching the expected cast/use in socket
APIs). Edit the `@JsFun` string expression for loadNodeNetModule to evaluate to
the imported module itself (or null when not running in Node) rather than a
function, so subsequent casts/uses treating the result as NodeNet succeed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 60d545ea-c117-40ec-bf14-711ca8e98467

📥 Commits

Reviewing files that changed from the base of the PR and between 9a71730 and 4970302.

📒 Files selected for processing (5)
  • karma/config.js
  • ktor-network/js/src/io/ktor/network/sockets/nodejs/node.net.js.kt
  • ktor-network/wasmJs/src/io/ktor/network/sockets/nodejs/node.net.wasmJs.kt
  • ktor-network/web/src/io/ktor/network/sockets/SocketEngine.web.kt
  • ktor-network/web/src/io/ktor/network/sockets/nodejs/node.net.kt
💤 Files with no reviewable changes (1)
  • karma/config.js

@osipxd
Osip Fatkullin (osipxd) merged commit 30906de into release/3.x May 27, 2026
20 checks passed
@osipxd
Osip Fatkullin (osipxd) deleted the osipxd/ktor-network-wasm-browser-compatibility branch May 27, 2026 12:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants