Repository navigation
perf(runtime): fetch HTTP modules over persistent connections, through OkHttp when the app ships it - #2172
Draft
edusperoni wants to merge 3 commits into
Draft
perf(runtime): fetch HTTP modules over persistent connections, through OkHttp when the app ships it#2172edusperoni wants to merge 3 commits into
edusperoni wants to merge 3 commits into
Conversation
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
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. |
This was referenced Dec 2, 2026
edusperoni
added a commit
that referenced
this pull request
Dec 2, 2026
…er URL (#2168) ### Description A module loaded over `http(s)` now resolves the specifiers it imports the way a browser does, for static `import` and `import()` alike, and it can no longer reach the app's filesystem implicitly. **Resolution follows the HTML module-specifier rules, through the WHATWG URL parser** (ada, the parser behind `new URL()`): - Only `/`, `./` and `../` prefixes are relative (`//host/x` is a `/` form). Anything else is an absolute URL if it parses as one, and a bare specifier otherwise. So `.x`, `.` and `..` are bare. - Dot segments and `\` resolve as in a browser, and the scheme is lowercased, so `HTTP://host/x` is an http URL. - The authority (userinfo, host, port) keeps the spelling the importer's URL, or the specifier, wrote. Dev tooling compares the module URLs the runtime reports against the origin it was configured with, verbatim. - The query is kept: `import('./x.js?v=1')` and `import('./x.js?v=2')` are two modules, as they are for a static import. **No implicit filesystem fallback from an HTTP module.** The shared resolver (graph walk, static resolve callback, `import()` callback) refuses these before anything is fetched or probed on disk: - a relative, root-relative or scheme-relative specifier that does not form an `http(s)` URL against the importer's URL; - an unmapped bare specifier, instead of falling back to `<app root>/<spec>`; - `~/x`. The errors name the specifier, the importer and what to use instead, e.g.: ``` Cannot resolve module specifier "lodash" imported from http://host/src/app.js: it is not in the import map (bare specifiers from an HTTP module must be mapped). ``` An unmapped specifier with another scheme (`data:`, `foo:bar`, `file:/x`) fails as `Cannot find module` without a disk lookup. Still allowed from an HTTP module: `ns:`/`node:` builtins, absolute `http(s)` URLs, an explicit `file:///…` URL, `blob:nativescript/…` URLs, and anything the import map maps. A mapped target is never refused, and a relative or root-relative target resolves against the importer's URL. `createRequire(<file path>)` stays the explicit way for an HTTP module to reach on-disk modules. **An import-map entry keyed by a module's own URL** never changes how that module's imports resolve. An HTTP module mapped to a file stays an HTTP importer, and a file module whose `file:///app/…` URL (or a prefix of it) is a map key stays a file importer. `docs/ns-builtin-modules.md` gains a "Specifier resolution" section for HTTP importers. #### Notes for review - **Import-map lookup of a query, from a file module.** On Android, a file module's static `import 'pkg?x'` and its `import('pkg?x')` both look `pkg?x` up in the map as written. The map is consulted before the query is dropped for the on-disk path, which is already how `main` works. A new spec pins it, and the docs state it. On iOS after NativeScript/ios#586, `import()` from a file module drops the query before the lookup, while a static import does not. The two platforms therefore differ for `import()` from a file module. This is one of the cross-platform decisions tracked in #2020; this PR doesn't change it. Note that #2020's description of the Android side predates this check. - File modules resolve exactly as before. ### Does your commit message include the wording below to reference a specific issue in this repo? No issue. ### Related Pull Requests Mirrors NativeScript/ios#586 (code, specs and the docs section). Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers (**this PR**, base `main`) 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 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. 21 new specs in `testEsmHttpLoader.js`, served by new `ModuleTestServer` routes and `esm/http-importer/`, `esm/self-mapped-*/` and `esm/query-map/` fixtures: - `./`, `../`, root- and scheme-relative `import()` load the URLs a browser computes, and the query is part of the module's identity. - Unmapped static and dynamic bare imports, `~/` and an other-scheme `import()` are refused. Same-named fixtures exist on disk, and an evaluation flag in each proves nothing was read. - Builtins, an explicit `file://` URL, import-map entries (any target form, including a relative one) and `blob:nativescript` URLs still load. - A module whose own URL is a map key (HTTP mapped to a file; a file module's exact and prefix entries) keeps its importer kind. - `.x`, `.` and `..` are refused as bare, statically and from `import()`. - Every spelling of one URL is one module, from `import()` and from a static import. Dot segments, `\` and an uppercase scheme normalize as the URL parser does. An importer served from a non-canonically spelled origin keeps that spelling in what it resolves. - A file module looks a static import's and an `import()`'s query up in the map as written. 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** * HTTP(S) modules now resolve relative and root-absolute imports against their URL, while import maps can rewrite specifiers and provide URL-relative targets. * Import resolution now handles built-in modules, file and blob URLs, and URL normalization consistently. * **Bug Fixes** * Unmapped bare and `~/` imports from HTTP modules are rejected with clearer errors instead of being treated as file paths. * File-based modules retain file-based resolution when their own URL is mapped. * **Documentation** * Clarified import-map behavior and documented HTTP module specifier resolution. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
… cache busting Mirrors NativeScript/ios#585 for the HTTP module loader's request shape: - Requests no longer send Connection: close, Cache-Control or Pragma, so the platform connection pool reuses sockets across module fetches. Accept, Accept-Encoding: identity, User-Agent and the timeouts are unchanged. - The __ns_dev_nonce cache-bust machinery is gone: MarkKeysForCacheBust and its call from invalidateModules, the mark set, ApplyCacheBustNonce, ClearCacheBustForUrl and CleanupHttpLoaderGlobals. The canonical key is no longer passed into the fetch functions, since only the nonce needed it. invalidateModules still evicts from the registry exactly as before; the refetch is an ordinary request for the plain URL. - HttpURLConnection keeps setUseCaches(false): it never reads or writes a ResponseCache the app installed, so every module request reaches the origin. - docs: an "HTTP caching" section on what a server must send, and the invalidateModules / volatilePatterns descriptions no longer claim to bypass caches. - ModuleTestServer keeps connections alive unless the client asks to close, answers Cache-Control: no-cache by default as a dev server does, counts accepted connections and concurrent requests, and serves /esm/revision.mjs (a new body per request) and /esm/concurrency.mjs. - Specs: a no-cache module is imported fresh after invalidateModules, and consecutive module fetches reuse connections.
The process-wide cap of 16 concurrent module fetches becomes one cap per
host class:
- loopback (127.0.0.1, [::1], localhost, and the emulator host aliases
10.0.2.2 and 10.0.3.2): 6. A loopback host on a device or emulator is
almost always adb reverse, whose listener has a backlog of 4 and overflows
under a burst of connects; each overflow costs the client a ~1 s SYN retry.
Through the emulator's NAT alias, 6 loaded multi-megabyte graphs 1.5-3.5x
faster than 16 or 32.
- remote (any other host): 32, matching iOS's HTTPMaximumConnectionsPerHost.
Over Wi-Fi a 670-module graph loaded ~3.7x faster at 32 than at 6.
Each class has its own queue and fetch threads, so a remote graph never waits
behind loopback fetches or the other way round.
Apps can override either value with android.moduleFetchConcurrency
({ "loopback": n, "remote": n }, both optional). AppConfig.java validates it:
positive integers, clamped to 64; anything else logs a warning and keeps the
default. The runtime reads it once over JNI, like the remote-module
allowlist.
Debug builds gain ns:module httpFetchDiagnostics(url), returning the URL's
host class and that class's cap. The test app overrides the remote cap, and
specs cover the host classification, defaults and override, and that a burst
of loopback fetches never exceeds the loopback cap at the server.
When the app ships OkHttp, both module fetch paths go through com.tns.OkHttpModuleFetcher instead of HttpURLConnection: - One dedicated OkHttpClient (never the app's), with an idle pool at least as large as the largest fetch cap, so a burst's connections are all reused. - An on-disk HTTP cache of its own, ns-module-http-cache in the app's cache directory (256 MB, like iOS's NSURLCache), so fresh responses are reused without a request and stored ones are revalidated with their validators, also across app restarts. - Same request headers, per-attempt timeouts clamped to the graph walk's deadline, same-protocol redirects, security gate, retry, body handling and response classification as the platform transport. The platform transport stays uncached. Process-wide java.net defaults (CookieHandler, Authenticator, HttpsURLConnection's default socket factory and hostname verifier) reach only the platform transport; the docs list them. - A secondary process (package:name) keeps its own cache directory, since an OkHttp cache directory can't be shared between processes. - If the app's OkHttp lacks a call the bridge makes (a LinkageError), that fetch and every later one go through HttpURLConnection instead. OkHttp is compileOnly in the runtime and detected with a statically linked class literal, which R8 renames along with okhttp3 in apps that shrink. Only the bridge's private nested client class names okhttp3 types in member signatures, and it loads only once a fetch runs. consumer-rules.pro adds -dontwarn okhttp3.** so apps without OkHttp pass R8's missing-class check. Only calls present in OkHttp 3.x through 5.x are used. Debug builds gain ns:module forcePlatformHttpTransport(force), and httpFetchDiagnostics(url) reports the active transport. The test app ships okhttp 4.12.0 through its test-only test-runner-deps plugin, not app/build.gradle, which ships to every app. ModuleTestServer keeps idle sockets longer than either client's pool keep-alive and counts only /esm/concurrency.mjs toward the concurrency peak. Specs cover the active transport, the forced fallback, connection reuse and the loopback cap on each transport, a fresh response answered from the cache, ETag revalidation, and the platform transport reaching the origin for both, past a ResponseCache the app installed.
edusperoni
force-pushed
the
perf/http-module-transport
branch
from
December 2, 2026 17:36
3ec21a4 to
58f4733
Compare
NathanWalker
approved these changes
Dec 2, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Three commits change how the HTTP module loader talks to the server.
1. Persistent connections, no cache busting (port of NativeScript/ios#585)
Connection: close,Cache-ControlorPragma, so the connection pool reuses sockets across module fetches.Accept,Accept-Encoding: identity,User-Agentand the timeouts are unchanged.__ns_dev_noncecache-bust machinery is gone:MarkKeysForCacheBustand its call frominvalidateModules, the mark set,ApplyCacheBustNonce,ClearCacheBustForUrlandCleanupHttpLoaderGlobals. The fetch functions no longer take the canonical key, since only the nonce needed it.invalidateModulesstill evicts from the registry exactly as before. The refetch is an ordinary request for the plain URL, and the server's cache headers decide whether a cache may answer it. This applies to HMR refetches too, as on iOS. Getting dev-server headers right is the server's job. The Vite plugin sendsno-cachewith anETagfor source modules. A fix for its pre-bundles being markedimmutableis in progress on the plugin side.HttpURLConnectionkeepssetUseCaches(false): it never reads or writes aResponseCachethe app installed.invalidateModulesandvolatilePatternsdescriptions no longer claim to bypass caches.2. Fetch caps per host class (Android-specific)
The process-wide cap of 16 concurrent module fetches becomes one cap per host class, each with its own queue and fetch threads. A remote graph never waits behind loopback fetches, or the other way round.
loopback127.0.0.1,[::1],localhost, and the emulator host aliases10.0.2.2and10.0.3.2remoteHTTPMaximumConnectionsPerHostAn app can override either value with
android.moduleFetchConcurrency({ "loopback": n, "remote": n }, both optional).AppConfigvalidates it: values must be positive integers and are clamped to 64. Anything else logs a warning and keeps the default. The runtime reads it once over JNI, like the remote-module allowlist.3. OkHttp transport with its own cache, when the app ships OkHttp
When
okhttp3is on the app's classpath, both module fetch paths (graph walk and synchronous fallback) go throughcom.tns.OkHttpModuleFetcherinstead ofHttpURLConnection:OkHttpClient, never the app's. Its idle pool is at least as large as the largest fetch cap, so all of a burst's connections are reused.ns-module-http-cachein the app's cache directory, 256 MB like iOS'sNSURLCache. A fresh response is reused without a request, and a stored one is revalidated with its validators, also across app restarts. A secondary process (package:name) gets its own cache directory, since OkHttp's cache can't be shared between processes.LinkageError), that fetch and every later one go throughHttpURLConnection.compileOnlyin the runtime. It is detected with a statically linked class literal, which R8 renames along withokhttp3in apps that shrink.okhttp3types in member signatures, and that class loads only when a fetch runs.consumer-rules.proadds-dontwarn okhttp3.**, so apps without OkHttp pass R8's missing-class check.test-runner-depsplugin. It is deliberately not inapp/build.gradle, which ships to every app.Debug builds gain two
ns:modulemembers:httpFetchDiagnostics(url): the URL's host class, that class's cap, and the active transport;forcePlatformHttpTransport(force).Why these defaults: measurements
All numbers come from a benchmark build of
mainwith variant switches (keep-alive on/off, cap, client), not from the code in this PR. The setup:adb reverse) and over LAN Wi-Fi (5–39 ms ping);adb reverseand over10.0.2.2.Keep-alive is a large win. The phone, warm loads:
Connection: close, cap 16 (shipping)Most of the USB figure for the shipping config is connect stalls rather than transfer: about 11.7 of its 14.7 s per small-graph load are ~1 s gaps, each ending on a freshly opened socket. On the emulator over
10.0.2.2,Connection: closetook ~44 s per small-graph load, against ~0.3 s warm with keep-alive at any cap.The platform pool keeps only 5 idle sockets. Every keep-alive variant started its warm loads with exactly 5 surviving sockets, and at caps above 5 the client closes and reopens the rest on every wave.
http.maxConnectionscan't raise this in-process: the pool classes are in the zygote's preloaded classes, so the property is read before app code runs. A variant that set it behaved identically.Loopback is capped at 6 because of
adb reverse. On the emulator, adbd's reverse listener has a backlog of 4:listen(fd, 4), confirmed underadb root. One cap-32 launch there raised the device'sListenOverflowsby 30. A burst of connects overflows that backlog, and each dropped SYN costs the client a ~1 s retry. Results:The cost of 6 is small. On emulator
adb reverse, a warm 670-module load takes 178 ms at cap 6 against 136 ms with OkHttp at cap 16, about 45–50 ms more per load.The emulator aliases
10.0.2.2/10.0.3.2join the loopback class. Over the emulator's NAT, small graphs load the same at any cap, but large graphs load 1.5–3.5x slower at caps 16–32 than at 6.10.0.2.2had 0 failed requests out of about 207,000 across all variants, but even at its best it was 2–21x slower thanadb reverse.Wi-Fi is round-trip-bound, so remote gets 32. On the phone over Wi-Fi there were no connect stalls at all. Small-graph time tracks requests ÷ cap × RTT:
Keep-alive at cap 6 is about 8% slower than the shipping config on Wi-Fi warm loads. The cap, not keep-alive, decides there.
OkHttp vs the platform client at the same cap:
Class.forName("okhttp3.OkHttpClient")median 11.3 ms, building the client 2.7 ms.Notes for review
ResponseCache, so every request reaches the origin.java.netdefaults reach only the platform transport. These are a defaultCookieHandler,Authenticator, andHttpsURLConnection's default SSL socket factory and hostname verifier. An https dev server that is trusted only through those defaults loads overHttpURLConnectionbut not over OkHttp. The docs list this.-dontwarnrule and the class-literal detection are meant to cover it.refactor/module-url-parsePR. This is already true onmain, and OkHttp is configured (followRedirects(true),followSslRedirects(false)) to matchHttpURLConnection.package.json, so the override path is exercised.ModuleTestServerchanges:Cache-Control: no-cacheby default, as a dev server does;/esm/concurrency.mjs);/esm/revision.mjs, which returns a new body per request.Does your commit message include the wording below to reference a specific issue in this repo?
No issue.
Related Pull Requests
The first commit mirrors NativeScript/ios#585 (request shape, nonce removal, docs, and the
no-cache+ revision spec).The Android transport differs from iOS's:
NSURLCacheon every fetch. Android caches only when the app ships OkHttp.Part of a stack of six; each PR targets the branch below it:
fix/http-importer-specifiers: specifier resolution from HTTP importersrefactor/module-url-parse: one URL parse for every http(s) entry pointperf/http-module-streaming-compile: compile large HTTP modules off the JS threadfix/http-module-fetch-budget: bound fetches by the graph walk's deadlineperf/http-module-transport: persistent connections, per-host-class caps, OkHttp transport (this PR)feat/http-module-cache-controls: HTTP module cache controlsDoes your pull request have unit tests?
Yes, in
testEsmHttpLoader.js:no-cachemodule is imported fresh afterinvalidateModules.httpFetchDiagnosticsargument checks.no-cachemodule is revalidated with itsETagover OkHttp;ResponseCachethe app installed.The OkHttp-specific specs skip themselves when the app does not ship OkHttp. The full suite was run on the top of the stack before the last rebase onto
main:After the rebase (
./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, atfeat/http-module-cache-controls21f87a8.This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet.