Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 100 additions & 5 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,8 @@ apply, worker teardown) belongs to whatever tooling drives it.
| `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. |
| `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. |
| `getLoadedModuleUrls()` | The URL-like keys currently in the module registry, as an array of strings (used to compute full-reload eviction sets). |
| `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). |
| `clearHttpCache()` | Wipes the HTTP module cache before returning. See [Turning the cache off and clearing it](#turning-the-cache-off-and-clearing-it). |
| `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. |
| `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). |

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

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

### HTTP caching

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

- `Cache-Control: no-cache` (ideally with an `ETag` or `Last-Modified`
validator, so an unchanged module costs a `304`) or `Cache-Control: no-store`
Expand Down Expand Up @@ -1033,10 +1036,102 @@ remain:
burst of fetches fewer of them are reused than with OkHttp.
- OkHttp negotiates HTTP/2 with https servers that offer it, and then runs
concurrent fetches as streams on one connection.

The OkHttp cache can answer a fresh response without a request, even after an
app restart, and revalidates a stored response with its validator. The
synchronous fallback fetch uses the same transport as the graph walk.

#### Turning the cache off and clearing it

These controls act on the cache the module loader keeps for `http(s)` modules
and nothing else: never on an HTTP cache the app uses for its own requests,
and never on V8's code cache.

The cache is **on** unless something 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 |
| `setHttpCacheEnabled(enabled)` from `ns:module` | turns it on or off from then on |
| `clearHttpCache()` from `ns:module` | wipes it |
| inspector `Network.setCacheDisabled {cacheDisabled: true}` | turns it off while that client stays connected |
| inspector `Network.clearBrowserCache` | wipes it |
| response header `Clear-Site-Data: "cache"` (or `"*"`) on a module response | clears what the cache holds for that response's origin |

The app config and the launch options are read once per process, at startup.
A numeric `moduleHttpCache` counts as `false` when it is `0` and as `true`
otherwise; any other value that is not a boolean logs a warning and leaves the
cache on. The process starts with the cache off when either the app config or
the launch option says so; `setHttpCacheEnabled` overrides both from then on.
`setHttpCacheEnabled` and `clearHttpCache` exist in debug and release builds.

While the cache is off, a module fetch neither reads from nor writes to it,
and its request carries `Cache-Control: no-cache` and `Pragma: no-cache` (what
Fetch's `no-store` mode sends) on either transport, so a cache between the app
and the server revalidates too. The switch is process-wide: the main isolate
and every worker share it, the graph walk and the synchronous fallback fetch
alike. Each fetch reads it when it is issued; fetches already in flight keep
the value they started with.

`clearHttpCache()` empties the cache before it returns, durably: the next
fetch reaches the origin, and so does the first fetch after the process is
killed right after the call. Without OkHttp, or before the loader's OkHttp
client exists, it deletes the cache directory's contents, so it also clears
what an earlier run stored. It does not touch the module registry: a module
already loaded stays loaded until `invalidateModules` evicts it.

A module response whose `Clear-Site-Data` header names the `"cache"` or `"*"`
type clears the cache's entries for the response's origin (its final URL's,
after redirects) before the loader receives the response. The types are
quoted strings, and an unquoted one is ignored, as in browsers. Plain `http`
origins count, since dev servers use them. The response's own entry goes too,
so a cacheable carrier does not clear the cache again on every cache hit. On
Android the cache can clear one origin only while the loader's OkHttp client
is open; otherwise (no OkHttp, or the platform transport fetched first) the
header clears the whole cache directory. Only the final response's header is
read, never one on a redirect, and an entry still being written when the
header arrives, such as a same-origin module fetched concurrently, survives.

The cache is in effect when the setting above is on **and** no connected
inspector client has it disabled, so DevTools' "Disable cache" turns it off
without changing the setting, and its effect ends when that client
disconnects; with several clients it stays off while any of them has it
disabled. The runtime applies both inspector commands first, from any
session and even while paused, then passes a main-session command on to the
JS `Network` domain handler registered with `__registerDomainDispatcher`
(@nativescript/core registers one), which answers it. A command no JS handler
answers, a worker session's command, and any command arriving while paused
get `{}` from the runtime: every command gets exactly one response. A JS
handler that throws makes that response an error (`-32000`) with the thrown
message, and a command for a worker session that does not exist gets the
`Session not found` error (`-32001`) and changes nothing. A
`Network.setCacheDisabled` without a boolean `cacheDisabled` changes nothing,
and where the runtime answers it, the answer is an invalid-parameters error
(`-32602`). On Android the inspector serves one client at a time and exists
only in debuggable apps.

On Android a launch option is a file in `/data/local/tmp`, named after the
application id, that the CLI creates **empty** before it starts the app, the
way it requests `--debug-brk` 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. The runtime consumes it at startup by
writing to it (an app cannot delete a file there), so it applies to one launch
and the CLI recreates it for the next. When the write fails the option still
applies, and keeps applying until the file is removed. The files the CLI
creates there are writable by every app on the device, so another app can
empty one to re-arm its option for the next launch. Only the app's default
process reads the options, in debug builds and in release builds that set
`security.allowRemoteModules`; other release builds load no HTTP module and
never look.

### Fetch concurrency

The module-graph walk fetches modules concurrently, up to a cap shared by
Expand Down
22 changes: 22 additions & 0 deletions test-app/app/src/main/assets/app/tests/httpCacheWorker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// {import: url} imports url; {setHttpCacheEnabled: enabled} flips the
// process-wide HTTP module cache switch from this isolate. Either answers
// {ok: true}, or {ok: false, error} with the failure's message.
onmessage = function (msg) {
function failed(error) {
postMessage({ ok: false, error: String((error && error.message) || error) });
}
var request = msg.data;
if (typeof request.setHttpCacheEnabled === "boolean") {
try {
require("ns:module").setHttpCacheEnabled(request.setHttpCacheEnabled);
} catch (error) {
failed(error);
return;
}
postMessage({ ok: true });
return;
}
import(request.import).then(function () {
postMessage({ ok: true });
}, failed);
};
Loading
Loading