Skip to content

feat(runtime): HTTP module cache controls - #2173

Draft
edusperoni wants to merge 12 commits into
perf/http-module-transportfrom
feat/http-module-cache-controls
Draft

edusperoni wants to merge 12 commits into
perf/http-module-transportfrom
feat/http-module-cache-controls

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

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:

control effect
app config "moduleHttpCache": false (top level, next to security) the process starts with the cache off
launch option --nativescript-no-module-cache this launch starts with the cache off
launch option --nativescript-clear-module-cache wipes the cache before the launch's first fetch
ns:module setHttpCacheEnabled(enabled) turns it on or off from then on, for the whole process
ns:module clearHttpCache() wipes it before returning
inspector Network.setCacheDisabled {cacheDisabled: true} turns it off while that client stays connected
inspector Network.clearBrowserCache wipes it
Clear-Site-Data: "cache" (or "*") on a module response clears that response's origin

Switch and clear (ns:module, app config)

  • setHttpCacheEnabled and clearHttpCache exist in debug and release builds. setHttpCacheEnabled throws TypeError unless it gets a boolean.
  • The app config and the launch options are read once per process, at startup. A number counts as a boolean, as on iOS (0 is off). Any other non-boolean moduleHttpCache logs a warning and leaves the cache on. The process starts with the cache off when either source says so, and setHttpCacheEnabled overrides both from then on.
  • With the cache off, a fetch neither reads from nor writes to the cache, on both transports. Its request carries Cache-Control: no-cache and Pragma: no-cache, which is what Fetch's no-store mode 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-side no-cache alone would still store the response, and no-store would put no-store on the wire.
  • The switch is process-wide. The main isolate and every worker share it, and so do the graph walk and the synchronous fallback. Each fetch reads it when it is issued; fetches already in flight keep the value they started with.
  • 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 until invalidateModules evicts it.

Launch options on Android

A launch option is an empty file that the CLI creates before am start, the same convention --debug-brk uses with <appId>-debugbreak:

adb shell "cat /dev/null > /data/local/tmp/<appId>-nativescript-no-module-cache"
adb shell "cat /dev/null > /data/local/tmp/<appId>-nativescript-clear-module-cache"
adb shell am start -n <appId>/<activity>
  • Only an empty file is in effect. An app can't delete a file in /data/local/tmp, so the runtime reads the options at startup and consumes each one by writing 1 to 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.
  • Only the app's default process reads them, in debug builds and in release builds that set security.allowRemoteModules. Other release builds load no HTTP module and never look.
  • A file the CLI created is world-writable, so another app on the device can empty a consumed file and re-arm it for the next launch. The worst case is a launch with the cache off or wiped.

Inspector

  • Network.setCacheDisabled and Network.clearBrowserCache are 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 Network domain handler registered with __registerDomainDispatcher (@nativescript/core registers one), which answers it. The runtime answers {} itself when:

    • no handler answers (none is registered, or it returned no response);
    • the main thread is paused;
    • the command came from a worker session.

    A handler that throws gets the iOS answer instead: a -32000 error 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 setCacheDisabled without a boolean cacheDisabled changes 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-Data

  • A module response whose Clear-Site-Data names "cache" or "*" clears the cache's entries for the response's final origin (after redirects) before the loader receives the response. Plain http origins count, since dev servers use them. Unquoted types are ignored, as in browsers.
  • The clear runs once the body has been read and closed, so the carrier's own entry, committed at that point, goes with the rest. A cacheable carrier therefore doesn't wipe the cache again on every hit.
  • Origins are compared by scheme, host and port as OkHttp parses the cached URLs, so entries whose URLs java.net.URI rejects (raw | in a query, [id] in a path) are cleared too.
  • Two limits: only the final response's header is read, so a header on a redirect hop is ignored; and an entry another fetch is still writing when the clear runs is committed afterwards and survives.
  • A failure inside the clear is logged and never fails the module that carried the header.
  • Clearing one origin goes through the open OkHttp cache. Without one, the header clears the whole cache directory instead. That happens with no OkHttp, or when nothing has been fetched through OkHttp yet.

On the platform transport (no OkHttp)

There is no cache, but the controls still behave consistently:

  • the switch still controls the two no-cache request headers;
  • clearHttpCache() and Clear-Site-Data delete any cache directory an earlier OkHttp run left on disk;
  • clearHttpCache() doesn't throw.

Notes for review

  • Open question for the CLI. Should the CLI create the launch-option files for debug runs only? The runtime currently also honours them in release builds that allow remote modules.
  • Pre-existing inspector reconnect bug, narrowed. The old connection's disconnect is posted to the main thread and could run after a newer client connected, tearing it down. It now skips when a different socket is connected (commit 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.
  • Open question: a replaced client. A frontend that was replaced while its socket stays open keeps the cache disabled until that socket closes (connect releases nothing). Every socket gets its close callback, so nothing leaks. Releasing the other sockets' holds in connect is the alternative, since Android serves one client at a time.
  • Not yet checked:
    • a release build;
    • a 304 response carrying Clear-Site-Data;
    • a Clear-Site-Data response fetched by the synchronous fallback. iOS covers the last two with specs; Android doesn't yet.
  • No spec covers the inspector commands or the launch-option files. The suite has no inspector client, and the option files are read only at process start. The inspector paths were checked once by hand with a websocket script against the test app: unknown session → -32001 and nothing applied; setCacheDisabled true → {} and requests carry no-cache; a throwing handler → one -32000 reply; 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:module members, the launch flags, moduleHttpCache, the inspector commands and Clear-Site-Data handling. Android-specific:

  • the launch options are files in /data/local/tmp, not process arguments;
  • per-origin clearing needs the OkHttp cache to be open;
  • the inspector is single-client.

Part of a stack of six; each PR targets the branch below it:

  1. fix(runtime): resolve specifiers from HTTP modules against the importer URL #2168 fix/http-importer-specifiers: specifier resolution from HTTP importers
  2. refactor(runtime): one URL parse for every http(s) module entry point #2169 refactor/module-url-parse: one URL parse for every http(s) entry point
  3. perf(runtime): compile large HTTP modules off the JS thread #2170 perf/http-module-streaming-compile: compile large HTTP modules off the JS thread
  4. fix(runtime): bound HTTP module fetches by the graph walk's deadline #2171 fix/http-module-fetch-budget: bound fetches by the graph walk's deadline
  5. perf(runtime): fetch HTTP modules over persistent connections, through OkHttp when the app ships it #2172 perf/http-module-transport: persistent connections, per-host-class caps, OkHttp transport
  6. feat(runtime): HTTP module cache controls #2173 feat/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.js covers:

  • the switch rejecting a non-boolean;
  • no cache directives being sent while the cache is on;
  • the next import reaching the origin after clearHttpCache();
  • with the cache off: over OkHttp the origin is reached every time and nothing is stored; over the platform transport the two no-cache headers 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;
  • an unquoted type is ignored;
  • the header is honoured on a platform-transport response.

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.

ModuleTestServer gains a /esm/clear-site-data.mjs route.

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;
  • each launch-option file: it applies to one launch, and the runtime consumes the file;
  • 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 OkHttp: 2051 specs, 0 failures;
  • without OkHttp: 0 failures, with the 11 OkHttp-only specs skipped.

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, 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.

@coderabbitai

coderabbitai Bot commented Dec 2, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@edusperoni
edusperoni added this pull request to stack #2174 December 2, 2026 16:13
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
edusperoni force-pushed the feat/http-module-cache-controls branch from 9ba565b to 908fc2d Compare December 2, 2026 17:36

This branch has not been deployed

No deployments
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.

2 participants