Skip to content

Commit 1fa2f60

Browse files
authored
perf(runtime): compile large HTTP modules off the JS thread (#2170)
### Description ES modules that the async graph walk fetches over HTTP are now parsed and compiled to bytecode on a background thread through V8's streaming API when their JavaScript body is 32 KiB or larger. The JS thread only finalizes the result. Smaller bodies, JSON modules, failed fetches and the synchronous fallback compile as before. Nothing JS-visible changes: module identity, evaluation order, error texts and positions all stay the same. During a dev-server load the JS thread compiled every fetched module itself, one after another, while other fetches had already completed. Large modules dominate that time, for example bundles and modules carrying inline source maps. #### How it works - **Issue (JS thread).** A `StreamedModuleCompile` is started when the fetch is issued (`ScriptCompiler::StartStreaming(..., kModule, ...)`) and parked in the isolate's `ModuleLoaderState`. The transport carries only a ticket and owns no V8 state. - **Transport completes.** An OK JavaScript body of at least 32 KiB is fed to the stream and run on a dedicated pool (`ScriptStreamingTask::Run`). Only then is the completion posted to the isolate's event loop. - **Finalize (JS thread).** `ScriptCompiler::CompileModule(context, StreamedSource*, ...)` finalizes the compile. Registration, request walking and error reporting are shared with the synchronous path through `CompileAndRegisterModule`. If two walks fetched one URL and the key was registered in the meantime, the existing module is reused and the streamed compile is discarded. - **Source strings.** A pure-ASCII body becomes an external one-byte string. It is charged to the isolate through `v8::ExternalMemoryAccounter` and released in the resource's `Unaccount()`. Anything else uses `NewFromUtf8` as before. - **Pool.** At most `min(4, cores - 1)` detached pthreads, started on demand, each with a 2 MB stack. V8's background parser checks for overflow at `--stack-size` (984 KB) below where `Run()` starts, so a default ~1 MB bionic thread leaves almost no margin. With a 512 KB stack, the deep-nesting spec crashed the process with a stack overflow on the pool thread instead of rejecting with a `RangeError`. The threads are not attached to the JVM. If no pool thread can start, the module compiles on the JS thread. - **`kEagerCompile`.** Streaming follows `--lazy-streaming`, not `--lazy`. So when the app's `v8Flags` turn lazy compilation off, streamed compiles pass `kEagerCompile`. V8 has no public flag getter, so `InitializeV8` reads the flag string it applies. - **BOM.** A body that starts with a UTF-8 BOM is not streamed: the stream drops the BOM, but the source string keeps it, which would shift every position. - **Teardown.** `QuiesceModuleLoadsForIsolate` (workers included) closes a gate and waits out running compiles. While it waits, it runs the event loop's nestable V8 tasks, which is where a background compile's GC request lands. It then destroys unfinalized compiles before the event loop stops. The wait runs with microtasks suppressed and JS execution disallowed, because a worker terminated mid-JS can still hold microtasks and the runtime is half torn down by then. Debug builds expose process-wide counters through `ns:module.streamedCompileStats()`: `finalized`, `discarded`, `fellBack`, `running` and `teardownWaits`. **An Android-only fix in the same PR: release a finished graph walk's context on the JS thread.** An async graph load's `v8::Global<v8::Context>` was reset only by isolate teardown. A fetch thread holds a reference to the load until its completion callback is destroyed, which happens after the completion is posted. So when the JS thread finished the walk first, the fetch thread dropped the last reference and destroyed the `Global` without the isolate's `Locker`. The walk now resets the `Global` as soon as it completes. No completion can arrive after that, so whichever thread drops the last reference destroys no V8 state. This is not part of NativeScript/ios#587 or NativeScript/ios#584. #### Notes for review - **No Android timing was taken.** The motivation and the measurements (device, simulator, CPU cost) are in NativeScript/ios#587 and were made on iOS. Android uses the same 32 KiB threshold. Specs confirm that large bodies take the streamed path, but not that it is faster here. - **NativeScript/ios#584's crash cannot happen on Android.** On iOS, teardown looked the loader state up after the isolate's caches had been invalidated, so in-flight loads were never marked dead. Android quiesces a worker's async graph loads in `DestroyRuntime` while the runtime's state is still reachable. Only the NativeScript/ios#584 spec is ported, as a guard. - **Each HTTP edge still pays a `StartStreaming` call when it is issued.** The body size is unknown until the response arrives. - The pool is shared by all isolates and does not grow past its cap. A compile parked on a GC request keeps its pool thread until that isolate's thread runs tasks. - **Not covered by a spec:** - the debugger with streamed modules (attach, `scriptParsed`, breakpoints); - the `kEagerCompile` branch, which only an app whose `v8Flags` turn lazy compilation off reaches (the test app's flags are `--expose_gc` only); - that the external-memory charge is released when V8 disposes the string. ### Does your commit message include the wording below to reference a specific issue in this repo? No issue. ### Related Pull Requests Mirrors NativeScript/ios#587. It also ports the worker-teardown spec of NativeScript/ios#584, on which NativeScript/ios#587 builds; the NativeScript/ios#584 code change has no Android counterpart (see above). Android-specific: the pool threads are not attached to the JVM, the teardown wait runs no JavaScript (microtasks suppressed, JS execution disallowed), and debug builds expose the `streamedCompileStats()` counters. Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers 2. #2169 `refactor/module-url-parse`: one URL parse for every http(s) entry point 3. #2170 `perf/http-module-streaming-compile`: compile large HTTP modules off the JS thread (**this PR**) 4. #2171 `fix/http-module-fetch-budget`: bound fetches by the graph walk's deadline 5. #2172 `perf/http-module-transport`: persistent connections, per-host-class caps, OkHttp transport 6. #2173 `feat/http-module-cache-controls`: HTTP module cache controls ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. `ModuleTestServer` gains these routes: - `/esm/big.mjs`, a generated module above the threshold, with options for non-ASCII literals, a trailing syntax error, deep nesting and a delay; - `/esm/big-parent.mjs`; - `/esm/slow/` (`leaf`, `child`, `parent`), which answer after `delayMs`, matching the iOS test server. New specs in `testEsmHttpLoader.js`: - **worker teardown** (port of NativeScript/ios#584's spec): five workers each start an `import()` of a 2 s delayed module and are terminated while the fetch is in flight. The main isolate then imports a module delayed past every worker response, and that import must resolve. - **large modules:** each spec asserts the `streamedCompileStats()` counters, so a module that silently compiles on the JS thread fails it. They cover: - modules loaded with `import()`, through a static import, and during a pumped `require()`; - non-ASCII string literals; - a syntax error, rejected with the text a small module produces; - pathologically deep nesting, rejected with a `RangeError` as a small module is; - one module for concurrent imports from several call sites; - workers terminated while their large modules compile. This sweep waits for each worker's thread to end and sizes itself from a wall-clock budget; - a worker terminated while spinning, with a microtask that would import a probe module and a fetch completion queued: its teardown wait must run no JavaScript. Full suite on the top of the stack (`./gradlew runtestsAndVerifyResults`): 2074 specs, 2068 passed, 0 failed, 6 skipped (the usual GC, native-module and environment skips), on an API 36 arm64 emulator with OkHttp in the test app, at `feat/http-module-cache-controls` 21f87a8. This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Large HTTP-loaded JavaScript modules can now compile in the background, with fallback compilation when background processing is unavailable. * Improved handling of module imports during worker termination and concurrent loading. * Debug builds expose statistics for background module compilation. * **Documentation** * Documented the debug-only compilation statistics and their availability. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent e0e89f2 commit 1fa2f60

12 files changed

Lines changed: 1231 additions & 32 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,12 @@ diagnostic that takes a string and throws
511511
build with `allowRemoteModules` on would fetch `url` under a
512512
`security.remoteModuleAllowlist` of `entries` (`true` for `[]`) and throws
513513
`remoteUrlMatchesAllowlist expects a URL string and an array of strings`
514-
otherwise; release builds omit both. Missing members are simply absent — never
514+
otherwise, and `streamedCompileStats()`, which returns process-wide counts of
515+
how HTTP module bodies large enough for a background compile were compiled
516+
(`finalized`, `discarded` after another walk registered the same key first,
517+
`fellBack` to the JS thread), the background compiles `running` now, and the
518+
isolate teardowns that waited one out (`teardownWaits`); release builds omit
519+
all three. Missing members are simply absent — never
515520
present-but-throwing — so feature checks work. The module is registered in
516521
every build: the security boundary for remote module loading sits at the
517522
network layer (`security.allowRemoteModules` in nativescript.config, enforced
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Local root whose only edge is "ns-big-leaf", a bare specifier the spec's
2+
// import map points at a generated ModuleTestServer module above the
3+
// streaming-compile threshold.
4+
export * as leaf from "ns-big-leaf";
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Starts a small and a large HTTP import, queues a microtask that imports
2+
// `probe`, reports "spinning" and spins until terminated: the small import's
3+
// fetch completion and the microtask are still pending when it is.
4+
onmessage = function (msg) {
5+
import(msg.data.small);
6+
import(msg.data.big);
7+
Promise.resolve().then(function () {
8+
import(msg.data.probe);
9+
});
10+
postMessage("spinning");
11+
for (;;) {}
12+
};
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// Starts an HTTP dynamic import, reports "fetching" as soon as it is issued
2+
// and "settled" once it resolves or rejects. A terminated worker never sends
3+
// "settled".
4+
onmessage = function (msg) {
5+
function settled() {
6+
postMessage("settled");
7+
}
8+
import(msg.data).then(settled, settled);
9+
postMessage("fetching");
10+
};
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Starts an HTTP dynamic import and reports as soon as its fetch is in flight,
2+
// without waiting for it to settle.
3+
onmessage = function (msg) {
4+
import(msg.data).catch(function () {});
5+
postMessage("fetching");
6+
};

‎test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js‎

Lines changed: 426 additions & 0 deletions
Large diffs are not rendered by default.

‎test-app/app/src/main/assets/app/tests/testNsModule.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ describe("ns:module", function () {
1616
var expected = ["configureLoader", "createPumpingRequire", "createRequire",
1717
"getLoadedModuleUrls", "invalidateModules"];
1818
if (typeof nsModule.canonicalizeHttpUrlKey === "function") {
19-
expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist");
19+
expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist",
20+
"streamedCompileStats");
2021
}
2122
expect(Object.keys(nsModule).sort()).toEqual(expected.sort());
2223
});

‎test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,99 @@ private static void route(Socket socket, String path, String query) throws IOExc
286286
return;
287287
}
288288

289+
// Simulates a dev server answering a cold module transform in
290+
// `delayMs`. The parent re-exports the child, a transitive HTTP edge
291+
// the graph walk discovers after the slow fetch lands.
292+
if (path.startsWith("/esm/slow/")) {
293+
int delayMs = intParam(query, "delayMs=", "/esm/slow/child.mjs".equals(path) ? 0 : 7000);
294+
String key = param(query, "k=");
295+
if (key == null) {
296+
key = "slow";
297+
}
298+
String body;
299+
if ("/esm/slow/parent.mjs".equals(path)) {
300+
body = "export { value } from \"./child.mjs?from=" + key + "\";\n"
301+
+ "export const parent = \"" + key + "\";\n";
302+
} else {
303+
body = "export const value = 42; export const name = \"" + key + "\";\n";
304+
}
305+
if (!sleepFor(delayMs)) {
306+
return;
307+
}
308+
respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8));
309+
return;
310+
}
311+
312+
// Generated modules of a requested size.
313+
// /esm/big.mjs: `lines` real declarations whose evaluation folds into
314+
// `total`, so a value depends on the whole body.
315+
// k module id (also the evaluation counter's key)
316+
// unicode 1 adds non-ASCII string literals (strs/first/last)
317+
// error 1 ends the body with a syntax error at line lines+3
318+
// nest appends an array literal nested `nest` deep
319+
// delayMs answers after a delay
320+
// /esm/big-parent.mjs?k=…&child=<encoded big.mjs query> statically
321+
// imports that big.mjs and re-exports it as `child`.
322+
if ("/esm/big.mjs".equals(path) || "/esm/big-parent.mjs".equals(path)) {
323+
String rawKey = decodedParam(query, "k=");
324+
StringBuilder keyBuilder = new StringBuilder();
325+
for (char c : (rawKey == null ? "x" : rawKey).toCharArray()) {
326+
if (Character.isLetterOrDigit(c) || c == '-') {
327+
keyBuilder.append(c);
328+
}
329+
}
330+
String key = keyBuilder.toString();
331+
int delayMs = intParam(query, "delayMs=", 0);
332+
StringBuilder body = new StringBuilder();
333+
if ("/esm/big-parent.mjs".equals(path)) {
334+
String child = decodedParam(query, "child=");
335+
child = child == null ? "" : child.replace("\"", "");
336+
body.append("export * as child from \"./big.mjs?").append(child).append("\";\n")
337+
.append("export const parent = \"").append(key).append("\";\n");
338+
} else {
339+
int lines = intParam(query, "lines=", 0);
340+
boolean unicode = "1".equals(param(query, "unicode="));
341+
body.append("let acc = 0;\nconst strs = [];\n");
342+
for (int i = 0; i < lines; i++) {
343+
body.append("function f").append(i).append("(x) { return (x * 3 + ").append(i)
344+
.append(") % 1000; } acc += f").append(i).append("(").append(i).append(");");
345+
if (unicode) {
346+
body.append(" strs.push(\"café 日本語 😀 ")
347+
.append(i).append("\");");
348+
}
349+
body.append("\n");
350+
}
351+
int depth = intParam(query, "nest=", 0);
352+
if (depth > 0) {
353+
body.append("export const deep = ");
354+
for (int i = 0; i < depth; i++) {
355+
body.append('[');
356+
}
357+
for (int i = 0; i < depth; i++) {
358+
body.append(']');
359+
}
360+
body.append(";\n");
361+
}
362+
if ("1".equals(param(query, "error="))) {
363+
body.append("export const broken = ;\n");
364+
}
365+
body.append("const evaluations = globalThis.__nsBigModuleEvaluations || (globalThis.__nsBigModuleEvaluations = {});\n")
366+
.append("evaluations[\"").append(key).append("\"] = (evaluations[\"").append(key).append("\"] || 0) + 1;\n")
367+
.append("export const id = \"").append(key).append("\";\n")
368+
.append("export const count = ").append(lines).append(";\n")
369+
.append("export const total = acc;\n")
370+
.append("export const first = strs[0];\n")
371+
.append("export const last = strs[strs.length - 1];\n")
372+
.append("export const joinedLength = strs.join(\"\").length;\n");
373+
body.append("export const bytes = ").append(body.toString().getBytes(UTF8).length).append(";\n");
374+
}
375+
if (!sleepFor(delayMs)) {
376+
return;
377+
}
378+
respond(socket, "200 OK", JS_MIME, body.toString().getBytes(UTF8));
379+
return;
380+
}
381+
289382
if ("/esm/timeout.mjs".equals(path)) {
290383
int delayMs = 12000;
291384
String raw = param(query, "delayMs=");
@@ -351,6 +444,44 @@ private static String param(String query, String prefix) {
351444
return null;
352445
}
353446

447+
private static String decodedParam(String query, String prefix) {
448+
String raw = param(query, prefix);
449+
if (raw == null) {
450+
return null;
451+
}
452+
try {
453+
return URLDecoder.decode(raw, "UTF-8");
454+
} catch (Exception e) {
455+
return raw;
456+
}
457+
}
458+
459+
private static int intParam(String query, String prefix, int fallback) {
460+
String raw = param(query, prefix);
461+
if (raw == null) {
462+
return fallback;
463+
}
464+
try {
465+
return Integer.parseInt(raw);
466+
} catch (NumberFormatException e) {
467+
return fallback;
468+
}
469+
}
470+
471+
/** False when the connection thread was interrupted (the server is stopping). */
472+
private static boolean sleepFor(int delayMs) {
473+
if (delayMs <= 0) {
474+
return true;
475+
}
476+
try {
477+
Thread.sleep(delayMs);
478+
return true;
479+
} catch (InterruptedException e) {
480+
Thread.currentThread().interrupt();
481+
return false;
482+
}
483+
}
484+
354485
private static String jsStringLiteral(String s) {
355486
return s.replace("\\", "\\\\")
356487
.replace("\"", "\\\"")

0 commit comments

Comments
 (0)