Repository navigation
feat(runtime): HTTP module cache controls - #2173
Draft
edusperoni wants to merge 12 commits into
Draft
edusperoni wants to merge 12 commits into
edusperoni wants to merge 12 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 -->
Adds process-wide controls for the cache the ES module loader keeps for http(s) modules: - ns:module setHttpCacheEnabled(enabled) and clearHttpCache(), in debug and release builds. - A top-level moduleHttpCache app config boolean; false starts the process with the cache off. Off, a module fetch neither reads nor writes the cache and sends Cache-Control: no-cache and Pragma: no-cache, on both transports. Every fetch path (graph walk, synchronous fallback, workers) reads the switch when the fetch is issued. OkHttp fetches with the cache off go through a cache-less client sharing the pool, so no-store never reaches the wire. clearHttpCache() evicts through the live OkHttp cache, or deletes the cache directory's contents when no client is open, so the wipe holds for the next fetch and across a process kill.
--nativescript-no-module-cache starts a launch with the HTTP module cache off, and --nativescript-clear-module-cache wipes it before the launch's first fetch. On Android each is an empty file the CLI creates as /data/local/tmp/<appId>-nativescript-no-module-cache or -nativescript-clear-module-cache before starting the app, the convention --debug-brk already uses with <appId>-debugbreak. The runtime reads them once at startup and consumes each by writing to it, so it applies to one launch. Only the default process reads them, in debug builds and in release builds that allow remote modules.
…ol the HTTP module cache
The socket thread applies both commands to the HTTP module cache before
anything else sees them, from any session and while paused:
setCacheDisabled turns the cache off while the connected client keeps it
disabled (released on disconnect), and clearBrowserCache wipes it.
A main-session command then goes on to the JS Network domain handler
registered with __registerDomainDispatcher, which answers it. When no
handler answers (none registered, it threw, or it returned no response),
when the main thread is paused, or for a worker session, the runtime
answers {} itself instead of letting V8 report an unknown method, so
every command gets exactly one response.
A module response whose Clear-Site-Data header names the "cache" or "*" type clears the HTTP module cache's entries for the response's final origin, plain http included, before the loader receives the response. The clear runs once the body is read and closed, so the carrier's own entry, committed at that point, goes with the rest and a cacheable carrier does not wipe again on every hit. Per-origin clearing goes through the open OkHttp cache. Without one (no OkHttp, or nothing fetched through it yet) the header clears the whole cache directory instead.
…parser
The OkHttp cache keys its entries by HttpUrl strings, which keep raw
characters such as | { } ^ ` in the query and [ ] in the path. Parsing
them with java.net.URI failed, so such an entry survived a per-origin
clear, and a carrier with such a URL wiped the whole cache instead of
its origin. Compare scheme, host and effective port of HttpUrl.parse
results instead, inside the OkHttp-only client class.
… clear A fetch took ModuleHttpCache.LOCK to look up the OkHttp client, so every fetch waited while a Clear-Site-Data scan held it. The clients are now published through volatile fields after creation; the lock still covers creating them and every wipe, which keeps creation and directory deletion mutually exclusive. Clear-Site-Data handling also catches RuntimeException (for example an IllegalStateException from the cache), logging it, so a failed clear never fails the module fetch or triggers its retry.
…nt it A frontend's cache disable was a single flag on the client, released by disconnect(), which onClose posts to the main thread. While the main isolate was paused or busy, the cache stayed off with no frontend connected, and a stale disconnect() from an old socket cleared the flag of the frontend that had replaced it. The socket thread now passes its websocket along with each message, and the client keeps one holder per websocket that disabled the cache. onClose and onException release that socket's holder on the socket thread through socketClosed(), which takes only connectionMutex_.
…nd connected onClose posts disconnect() to the main thread. When a new frontend connected before it ran, that late disconnect() nulled the new connection and reset its V8 session, worker sessions, tracing and resource streams. disconnect() now takes the closing websocket and returns early when a different websocket is connected, checked again where the connection is dropped. A connect that lands while a stale disconnect() is already past the first check can still lose the stream, tracing and worker resets done before the second.
…ns and numeric config
- A JS Network domain handler that throws on Network.setCacheDisabled or
Network.clearBrowserCache is answered with a -32000 error carrying the
thrown message, as iOS does, instead of the runtime's own {}.
- A cache command for a worker sessionId with no target gets the same
"Session not found" error as other commands and changes nothing.
- "moduleHttpCache": 0 turns the cache off and any other number leaves
it on, as iOS's NSNumber boolValue reads it; other non-boolean values
still warn and leave it on.
- The main-thread check for these commands matches their two method
names, so other Network messages are not parsed a second time.
…leaves pending JEnv::FindClass returns null with the lookup's exception pending. Reading the startup setting now clears it and keeps the default, and ClearModuleHttpCache throws it as a NativeScriptException instead of passing a null class on to GetStaticMethodID.
…flipping the switch - Drop the platform-transport clear spec: clearHttpCache() ignores the forced transport, so it only repeated the previous spec. - The platform transport stores nothing, so its "off" spec checks only the no-cache request headers. - Worker imports report success or the failure's message, and the shared-cache spec requires success. - A worker that turns the switch off makes the main isolate's next fetch bypass the cache.
…rrors, launch-option files Documents that only the final response's Clear-Site-Data is read and an entry still being written survives it, how a numeric moduleHttpCache reads, the inspector's -32000 and Session not found answers, and that other apps can re-arm a launch-option file. Reflows the HTTP caching section's uneven lines.
edusperoni
force-pushed
the
feat/http-module-cache-controls
branch
from
December 2, 2026 17:36
9ba565b to
908fc2d
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
The previous PR in the stack gives the module loader its own HTTP cache when the app ships OkHttp. This PR adds the controls that dev tooling and apps need over that cache. The names and semantics are a cross-platform contract shared with the iOS runtime, because the CLI and the Vite plugin hard-code them.
The controls act only on the cache the module loader keeps for
http(s)modules. They never touch an HTTP cache the app uses for its own requests, and never V8's code cache. The cache is on unless one of these turns it off:"moduleHttpCache": false(top level, next tosecurity)--nativescript-no-module-cache--nativescript-clear-module-cachens:modulesetHttpCacheEnabled(enabled)ns:moduleclearHttpCache()Network.setCacheDisabled {cacheDisabled: true}Network.clearBrowserCacheClear-Site-Data: "cache"(or"*") on a module responseSwitch and clear (
ns:module, app config)setHttpCacheEnabledandclearHttpCacheexist in debug and release builds.setHttpCacheEnabledthrowsTypeErrorunless it gets a boolean.0is off). Any other non-booleanmoduleHttpCachelogs a warning and leaves the cache on. The process starts with the cache off when either source says so, andsetHttpCacheEnabledoverrides both from then on.Cache-Control: no-cacheandPragma: no-cache, which is what Fetch'sno-storemode sends, so an intermediate cache revalidates too. OkHttp fetches with the cache off go through a cache-less client that shares the connection pool. A request-sideno-cachealone would still store the response, andno-storewould putno-storeon the wire.clearHttpCache()clears durably. With an OkHttp client open, it evicts through the live cache (evictAll+flush). Otherwise it deletes the cache directory's contents, which also clears what an earlier OkHttp run stored. Either way the next fetch reaches the origin, including the first fetch after the process is killed right after the call. It doesn't touch the module registry: a loaded module stays loaded untilinvalidateModulesevicts it.Launch options on Android
A launch option is an empty file that the CLI creates before
am start, the same convention--debug-brkuses with<appId>-debugbreak:/data/local/tmp, so the runtime reads the options at startup and consumes each one by writing1to it. An option therefore applies to one launch, and the CLI recreates the file for the next one. If the write fails, the option still applies, and keeps applying until the file is removed.security.allowRemoteModules. Other release builds load no HTTP module and never look.Inspector
Network.setCacheDisabledandNetwork.clearBrowserCacheare applied to the cache on the inspector socket thread before anything else sees them, from any session and even while paused.The disable is per client, keyed by the websocket that sent it. The cache is in effect when the setting is on and no connected client has disabled it, so DevTools' "Disable cache" doesn't change the setting. It ends when that client's socket closes, released on the socket thread, so it also ends while the main isolate is paused or busy.
Exactly one response per command. A main-session command then goes on to the JS
Networkdomain handler registered with__registerDomainDispatcher(@nativescript/coreregisters one), which answers it. The runtime answers{}itself when:A handler that throws gets the iOS answer instead: a
-32000error carrying the thrown message. A command for an unknown worker session applies nothing and gets-32001"Session not found", like any other command for that session.A
setCacheDisabledwithout a booleancacheDisabledchanges nothing. Where the runtime answers it, the answer is-32602.On Android the inspector serves one client at a time and exists only in debuggable apps.
Clear-Site-DataClear-Site-Datanames"cache"or"*"clears the cache's entries for the response's final origin (after redirects) before the loader receives the response. Plainhttporigins count, since dev servers use them. Unquoted types are ignored, as in browsers.java.net.URIrejects (raw|in a query,[id]in a path) are cleared too.On the platform transport (no OkHttp)
There is no cache, but the controls still behave consistently:
no-cacherequest headers;clearHttpCache()andClear-Site-Datadelete any cache directory an earlier OkHttp run left on disk;clearHttpCache()doesn't throw.Notes for review
1dbd5cb54, separable). A connect that lands between its two checks can still lose that client's streams and worker sessions; closing that fully needs the teardown reordered. The cache disable no longer depends on it.connectreleases nothing). Every socket gets its close callback, so nothing leaks. Releasing the other sockets' holds inconnectis the alternative, since Android serves one client at a time.304response carryingClear-Site-Data;Clear-Site-Dataresponse fetched by the synchronous fallback. iOS covers the last two with specs; Android doesn't yet.-32001and nothing applied;setCacheDisabled true→{}and requests carryno-cache; a throwing handler → one-32000reply; a second client stays connected after the first one's socket closed, and the first one's disable is released. That check ran with the main thread idle, so release while paused rests on reading the code.Does your commit message include the wording below to reference a specific issue in this repo?
No issue.
Related Pull Requests
Cross-platform contract with the matching iOS change, which is still in progress. The names are shared with the iOS runtime: the
ns:modulemembers, the launch flags,moduleHttpCache, the inspector commands andClear-Site-Datahandling. Android-specific:/data/local/tmp, not process arguments;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 transportfeat/http-module-cache-controls: HTTP module cache controls (this PR)Does your pull request have unit tests?
Yes. A new "HTTP cache controls" group in
testEsmHttpLoader.jscovers:clearHttpCache();no-cacheheaders are sent.Clear-Site-Data:"cache"and"*"each clear the origin's entries and the carrier's own, including an entry whose URL has a raw|in its query;Workers share the main isolate's cache (the worker reports its import's success or error) and see the switch the main isolate turned off; a worker turning the switch off is seen by the main isolate.
ModuleTestServergains a/esm/clear-site-data.mjsroute.By hand, on an emulator, with a temporary boot script and a fixed-port module origin on the host, every check behaved as the contract above specifies. Each check is a relaunch:
moduleHttpCache: false;clearHttpCache()followed immediately by a process kill: the next launch reaches the origin.The full suite on this branch, before the last rebase onto
main:With the review fixes (
9ba565bbd): 2075 specs, 0 failed, 6 skipped, read from the app's results (the harness step itself failed when the host ran out of disk and paused the emulator mid-run).After the rebase, before the review fixes (
./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.