Skip to content

Commit e8bb0fd

Browse files
authored
feat(runtime): HTTP module cache controls (#2173)
### 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`: ```sh 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. #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 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 (**this PR**) ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? 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. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Added runtime controls to enable or disable HTTP module caching and clear cached data. * HTTP module caching is enabled by default, with startup configuration and launch options available to change or clear it. * Cache settings apply to requests across the app and workers. Responses can clear cached data with `Clear-Site-Data`. * Added inspector commands to disable caching or clear the browser cache. * **Documentation** * Documented cache defaults, configuration options, runtime controls, and cache-clearing behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 840f23a commit e8bb0fd

18 files changed

Lines changed: 1223 additions & 96 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 100 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -429,6 +429,8 @@ apply, worker teardown) belongs to whatever tooling drives it.
429429
| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings re-requested on every import instead of reused from the registry; see [HTTP caching](#http-caching)), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. |
430430
| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. That request is an ordinary one: the server's caching headers decide whether a cache may answer it; see [HTTP caching](#http-caching). Takes an array of strings; throws `TypeError` otherwise. |
431431
| `getLoadedModuleUrls()` | The URL-like keys currently in the module registry, as an array of strings (used to compute full-reload eviction sets). |
432+
| `setHttpCacheEnabled(enabled)` | Turns the HTTP module cache on or off for the whole process: every isolate, workers included, from each one's next fetch on. Throws `TypeError` unless `enabled` is a boolean. See [Turning the cache off and clearing it](#turning-the-cache-off-and-clearing-it). |
433+
| `clearHttpCache()` | Wipes the HTTP module cache before returning. See [Turning the cache off and clearing it](#turning-the-cache-off-and-clearing-it). |
432434
| `createRequire(filenameOrURL)` | A `require` resolving against `filenameOrURL`'s directory (a trailing slash names the directory itself). Accepts an absolute path string, a `file:` URL string, or a URL object; anything else throws `TypeError`, and an `http(s)` base is refused outright because `require()` of a dev-served module is not supported — import those. ES module graphs load under Node's `require(esm)` rule: a graph containing top-level await is refused before it evaluates. |
433435
| `createPumpingRequire(filenameOrURL, options?)` | Same argument contract and same resolution, but an ES module graph with top-level await is evaluated by driving the loop until it settles, instead of being refused. **Callable only from a task context.** See [Pumping requires](#pumping-requires). |
434436

@@ -453,6 +455,7 @@ becoming a config that quietly does nothing.
453455
| a non-string in a `canonicalization` sub-key | `configureLoader: canonicalization.<key>[<index>] must be a string` |
454456
| `invalidateModules` argument not an array | `invalidateModules expects an array of URL strings` |
455457
| a non-string in that array | `invalidateModules: urls[<index>] must be a string` |
458+
| `setHttpCacheEnabled` argument not a boolean | `setHttpCacheEnabled expects a boolean` |
456459

457460
`configureLoader` validates the **entire** config — every section plus the key
458461
names — before installing any of it. A call that throws therefore leaves all
@@ -990,11 +993,11 @@ not the raw header.
990993

991994
### HTTP caching
992995

993-
The loader fetches modules the way a browser fetches module scripts: the
994-
request carries no cache directives of its own (no `Cache-Control`, no
995-
`Pragma`), the URL is requested exactly as resolved, and connections are
996-
persistent. Whether a stored response may answer a request is decided by the
997-
**response** headers, so a dev server must send:
996+
The loader fetches modules the way a browser fetches module scripts: while
997+
the cache is on, the request carries no cache directives of its own (no
998+
`Cache-Control`, no `Pragma`), the URL is requested exactly as resolved, and
999+
connections are persistent. Whether a stored response may answer a request is
1000+
decided by the **response** headers, so a dev server must send:
9981001

9991002
- `Cache-Control: no-cache` (ideally with an `ETag` or `Last-Modified`
10001003
validator, so an unchanged module costs a `304`) or `Cache-Control: no-store`
@@ -1033,10 +1036,102 @@ remain:
10331036
burst of fetches fewer of them are reused than with OkHttp.
10341037
- OkHttp negotiates HTTP/2 with https servers that offer it, and then runs
10351038
concurrent fetches as streams on one connection.
1039+
10361040
The OkHttp cache can answer a fresh response without a request, even after an
10371041
app restart, and revalidates a stored response with its validator. The
10381042
synchronous fallback fetch uses the same transport as the graph walk.
10391043

1044+
#### Turning the cache off and clearing it
1045+
1046+
These controls act on the cache the module loader keeps for `http(s)` modules
1047+
and nothing else: never on an HTTP cache the app uses for its own requests,
1048+
and never on V8's code cache.
1049+
1050+
The cache is **on** unless something turns it off:
1051+
1052+
| control | effect |
1053+
|---|---|
1054+
| app config `"moduleHttpCache": false` (top level, next to `security`) | the process starts with the cache off |
1055+
| launch option `--nativescript-no-module-cache` | this launch starts with the cache off |
1056+
| launch option `--nativescript-clear-module-cache` | wipes the cache before the launch's first fetch |
1057+
| `setHttpCacheEnabled(enabled)` from `ns:module` | turns it on or off from then on |
1058+
| `clearHttpCache()` from `ns:module` | wipes it |
1059+
| inspector `Network.setCacheDisabled {cacheDisabled: true}` | turns it off while that client stays connected |
1060+
| inspector `Network.clearBrowserCache` | wipes it |
1061+
| response header `Clear-Site-Data: "cache"` (or `"*"`) on a module response | clears what the cache holds for that response's origin |
1062+
1063+
The app config and the launch options are read once per process, at startup.
1064+
A numeric `moduleHttpCache` counts as `false` when it is `0` and as `true`
1065+
otherwise; any other value that is not a boolean logs a warning and leaves the
1066+
cache on. The process starts with the cache off when either the app config or
1067+
the launch option says so; `setHttpCacheEnabled` overrides both from then on.
1068+
`setHttpCacheEnabled` and `clearHttpCache` exist in debug and release builds.
1069+
1070+
While the cache is off, a module fetch neither reads from nor writes to it,
1071+
and its request carries `Cache-Control: no-cache` and `Pragma: no-cache` (what
1072+
Fetch's `no-store` mode sends) on either transport, so a cache between the app
1073+
and the server revalidates too. The switch is process-wide: the main isolate
1074+
and every worker share it, the graph walk and the synchronous fallback fetch
1075+
alike. Each fetch reads it when it is issued; fetches already in flight keep
1076+
the value they started with.
1077+
1078+
`clearHttpCache()` empties the cache before it returns, durably: the next
1079+
fetch reaches the origin, and so does the first fetch after the process is
1080+
killed right after the call. Without OkHttp, or before the loader's OkHttp
1081+
client exists, it deletes the cache directory's contents, so it also clears
1082+
what an earlier run stored. It does not touch the module registry: a module
1083+
already loaded stays loaded until `invalidateModules` evicts it.
1084+
1085+
A module response whose `Clear-Site-Data` header names the `"cache"` or `"*"`
1086+
type clears the cache's entries for the response's origin (its final URL's,
1087+
after redirects) before the loader receives the response. The types are
1088+
quoted strings, and an unquoted one is ignored, as in browsers. Plain `http`
1089+
origins count, since dev servers use them. The response's own entry goes too,
1090+
so a cacheable carrier does not clear the cache again on every cache hit. On
1091+
Android the cache can clear one origin only while the loader's OkHttp client
1092+
is open; otherwise (no OkHttp, or the platform transport fetched first) the
1093+
header clears the whole cache directory. Only the final response's header is
1094+
read, never one on a redirect, and an entry still being written when the
1095+
header arrives, such as a same-origin module fetched concurrently, survives.
1096+
1097+
The cache is in effect when the setting above is on **and** no connected
1098+
inspector client has it disabled, so DevTools' "Disable cache" turns it off
1099+
without changing the setting, and its effect ends when that client
1100+
disconnects; with several clients it stays off while any of them has it
1101+
disabled. The runtime applies both inspector commands first, from any
1102+
session and even while paused, then passes a main-session command on to the
1103+
JS `Network` domain handler registered with `__registerDomainDispatcher`
1104+
(@nativescript/core registers one), which answers it. A command no JS handler
1105+
answers, a worker session's command, and any command arriving while paused
1106+
get `{}` from the runtime: every command gets exactly one response. A JS
1107+
handler that throws makes that response an error (`-32000`) with the thrown
1108+
message, and a command for a worker session that does not exist gets the
1109+
`Session not found` error (`-32001`) and changes nothing. A
1110+
`Network.setCacheDisabled` without a boolean `cacheDisabled` changes nothing,
1111+
and where the runtime answers it, the answer is an invalid-parameters error
1112+
(`-32602`). On Android the inspector serves one client at a time and exists
1113+
only in debuggable apps.
1114+
1115+
On Android a launch option is a file in `/data/local/tmp`, named after the
1116+
application id, that the CLI creates **empty** before it starts the app, the
1117+
way it requests `--debug-brk` with `<appId>-debugbreak`:
1118+
1119+
```sh
1120+
adb shell "cat /dev/null > /data/local/tmp/<appId>-nativescript-no-module-cache"
1121+
adb shell "cat /dev/null > /data/local/tmp/<appId>-nativescript-clear-module-cache"
1122+
adb shell am start -n <appId>/<activity>
1123+
```
1124+
1125+
Only an empty file is in effect. The runtime consumes it at startup by
1126+
writing to it (an app cannot delete a file there), so it applies to one launch
1127+
and the CLI recreates it for the next. When the write fails the option still
1128+
applies, and keeps applying until the file is removed. The files the CLI
1129+
creates there are writable by every app on the device, so another app can
1130+
empty one to re-arm its option for the next launch. Only the app's default
1131+
process reads the options, in debug builds and in release builds that set
1132+
`security.allowRemoteModules`; other release builds load no HTTP module and
1133+
never look.
1134+
10401135
### Fetch concurrency
10411136
10421137
The module-graph walk fetches modules concurrently, up to a cap shared by
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// {import: url} imports url; {setHttpCacheEnabled: enabled} flips the
2+
// process-wide HTTP module cache switch from this isolate. Either answers
3+
// {ok: true}, or {ok: false, error} with the failure's message.
4+
onmessage = function (msg) {
5+
function failed(error) {
6+
postMessage({ ok: false, error: String((error && error.message) || error) });
7+
}
8+
var request = msg.data;
9+
if (typeof request.setHttpCacheEnabled === "boolean") {
10+
try {
11+
require("ns:module").setHttpCacheEnabled(request.setHttpCacheEnabled);
12+
} catch (error) {
13+
failed(error);
14+
return;
15+
}
16+
postMessage({ ok: true });
17+
return;
18+
}
19+
import(request.import).then(function () {
20+
postMessage({ ok: true });
21+
}, failed);
22+
};

0 commit comments

Comments
 (0)