Skip to content
Merged
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
34 changes: 5 additions & 29 deletions NativeScript/runtime/HttpLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ namespace tns {
// - the async NSURLSession fetch behind the phase-1 module-graph walk
// (StartModuleGraphLoad), which is how module bodies
// normally arrive,
// - eviction plumbing (an eviction-driven fetch nonce that defeats
// CFNetwork's HTTP cache),
// - the boot-evaluation flag that arms the cold-boot runloop pump only
// while an entry module is evaluating (derived by the runtime itself),
// - the remote-module security gate, seeded once from nativescript.config
Expand All @@ -39,7 +37,7 @@ namespace tns {
// `CanonicalizeHttpUrlKey`. It is per-isolate loader vocabulary — installed
// through SetCanonicalizationConfig in ModuleInternalCallbacks.h — so
// CanonicalizeHttpUrlKey runs on the isolate's own thread only. The transport
// never canonicalizes; it carries keys computed for it.
// never canonicalizes.
//
// When unconfigured, canonicalization is purely mechanical (fragment strip).
struct CanonicalizationConfig {
Expand Down Expand Up @@ -87,48 +85,26 @@ struct ModuleFetchResult {
// Synchronous module fetch with one retry on transport error — the fallback
// path for anything the async module-graph walk missed. Blocks the calling
// thread. Returns `result.ok`.
// `canonicalKey` is the module's canonical registry key, computed by the
// caller on its isolate's thread — the transport must never canonicalize,
// since that reads per-isolate loader vocabulary.
bool HttpFetchModule(const std::string& url, const std::string& canonicalKey,
ModuleFetchResult& result);
bool HttpFetchModule(const std::string& url, ModuleFetchResult& result);

// Asynchronous single-URL module fetch — the I/O primitive behind the
// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h).
// Same response policy as HttpFetchModule, minus the JS-thread block:
// - security gate (IsRemoteUrlAllowed) checked up front,
// - an NSURLSession GET on a background queue with the same request shape
// as the sync path (cache-bust nonce, zero-cache headers, no cookies) and
// one retry on transport error.
// as the sync path (no cookies, HTTP caching as the response headers
// allow) and one retry on transport error.
// `fetchDeadline` is the enclosing graph load's fetch budget as an absolute
// CFAbsoluteTime (double; 0 = unbounded): attempts clamp their request
// timeout to the time remaining and the transport-error retry is skipped
// once no budget is left, so a bounded fetch can never outlive the wait
// that is pumping for it.
// `completion(result)` is invoked exactly once, on an arbitrary thread —
// callers must hop to their JS thread before touching V8.
// `canonicalKey` as for HttpFetchModule: computed on the calling isolate's
// thread and carried, because the fetch and its completion run on background
// threads that cannot read per-isolate vocabulary.
void FetchModuleBodyAsync(
const std::string& url, const std::string& canonicalKey,
double fetchDeadline,
const std::string& url, double fetchDeadline,
std::function<void(ModuleFetchResult result)> completion);

// Mark a URL set (canonicalized internally) so that the NEXT network
// fetch of each URL carries a unique `__ns_dev_nonce` query parameter,
// guaranteeing CFNetwork cannot satisfy the request from any HTTP cache
// layer (observed on iOS 18+/26+ Simulator even with `no-store` headers
// and a reload-ignoring cache policy). Called by `InvalidateModules` for
// the eviction set; marks are consumed when a fresh body arrives.
// The nonce is transport-only and never affects module identity.
//
// Takes canonical registry keys, already computed by the caller on its
// isolate's thread: the mark set guards the process-global CFNetwork cache
// and is consulted from background fetch threads, which must never
// canonicalize (that reads per-isolate vocabulary).
void MarkKeysForCacheBust(const std::vector<std::string>& canonicalKeys);

// ─────────────────────────────────────────────────────────────
// Remote-module security gate
//
Expand Down
234 changes: 41 additions & 193 deletions NativeScript/runtime/HttpLoader.mm

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions NativeScript/runtime/ModuleInternalCallbacks.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ struct LoaderVocabulary {
// Distinguishes "no vocabulary supplied" (mechanical canonicalization only)
// from "supplied, and empty" — an empty vocabulary is explicit policy.
bool canonicalizationConfigured = false;
// URL substrings whose modules are always re-fetched, never cached.
// URL substrings whose modules are re-requested on every import instead of
// being reused from the registry.
std::vector<std::string> volatilePatterns;
};

Expand Down Expand Up @@ -214,8 +215,8 @@ v8::MaybeLocal<v8::Promise> ImportModuleDynamicallyCallback(
// calling isolate only.
bool SetImportMap(const std::string& json, std::string* error);

// Set URL patterns that should bypass module cache (e.g. "?v=", "/hot/") on
// the calling isolate.
// Set URL patterns that should bypass the module registry (e.g. "?v=", "/hot/")
// on the calling isolate.
void SetVolatilePatterns(const std::vector<std::string>& patterns);

// ─────────────────────────────────────────────────────────────
Expand Down
25 changes: 6 additions & 19 deletions NativeScript/runtime/ModuleInternalCallbacks.mm
Original file line number Diff line number Diff line change
Expand Up @@ -846,7 +846,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string&
requestedUrl.c_str());

ModuleFetchResult fetched;
if (!HttpFetchModule(requestedUrl, registryKey, fetched)) {
if (!HttpFetchModule(requestedUrl, fetched)) {
TNS_DEBUG(Esm, "[http-esm][load][fetch-fail] request=%s key=%s status=%d", requestedUrl.c_str(),
registryKey.c_str(), fetched.status);
// The classifier's reason names the URL and the cause (status, MIME, or
Expand Down Expand Up @@ -1094,7 +1094,7 @@ void SetVolatilePatterns(const std::vector<std::string>& patterns) {
(unsigned long)vocabulary->volatilePatterns.size());
}

// Check if a URL matches any volatile pattern (should bypass cache).
// Check if a URL matches any volatile pattern (never reused from the registry).
static bool IsVolatileUrl(const std::string& url) {
const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate();
if (vocabulary == nullptr) {
Expand Down Expand Up @@ -2159,10 +2159,8 @@ static void AsyncGraphEnqueue(const std::shared_ptr<AsyncGraphLoad>& load,
std::shared_ptr<AsyncGraphLoad> loadRef = load;
const std::string url = target;
std::shared_ptr<StreamTicket> ticket = BeginStreamedCompile(isolate, *moduleState);
// The canonical key is computed here, on the isolate's thread; the fetch
// carries it so background threads never touch per-isolate vocabulary.
FetchModuleBodyAsync(
url, key, load->fetchDeadline, [loadRef, url, ticket](ModuleFetchResult result) {
url, load->fetchDeadline, [loadRef, url, ticket](ModuleFetchResult result) {
// Arbitrary thread. Hop to the isolate's home thread as a nestable v8
// foreground task — thread-independent delivery, so an import() issued
// from a background thread still lands on the isolate's own event loop,
Expand Down Expand Up @@ -2424,18 +2422,6 @@ void InvalidateModules(v8::Isolate* isolate, v8::Local<v8::Context> context,
RemoveModuleFromRegistry(isolate, url);
}

// Second layer: the OS/CFNetwork HTTP cache is outside the runtime's
// direct control and has been observed serving a previous save's body
// even with `no-store` headers + a reload-ignoring cache policy
// (iOS 18+/26+ Simulator). Mark every invalidated key so the NEXT
// network fetch of that URL carries a unique `__ns_dev_nonce` query
// param — CFNetwork sees a URL it has never cached and must go to
// origin. The nonce is transport-only; module identity stays the
// canonical URL.
// `uniqueUrls` already holds canonical registry keys, computed above on
// this isolate's thread — which is what the transport's mark set needs.
MarkKeysForCacheBust(uniqueUrls);

TNS_DEBUG(Registry, "invalidate summary unique=%lu hits=%lu misses=%lu (registry now=%lu)",
(unsigned long)uniqueUrls.size(), (unsigned long)hits, (unsigned long)misses,
(unsigned long)registry.size());
Expand Down Expand Up @@ -3479,8 +3465,9 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local<v8::Context>
TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str());
std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec);
// Volatile pattern check: if the URL matches any configured volatile
// pattern, evict the cached module so we always re-fetch. The pattern
// list is policy and is supplied exclusively by the dev client via
// pattern, evict the registered module so every import requests it
// again (through the HTTP cache, which the server's headers govern).
// The pattern list is policy and is supplied exclusively by the dev client via
// ns:module `configureLoader({ volatilePatterns })` — the runtime
// carries no framework or server URL vocabulary of its own. (Framework
// strategies ship their own endpoints, e.g. Angular's `/@ng/component`
Expand Down
24 changes: 24 additions & 0 deletions TestRunner/app/tests/HttpEsmLoaderTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,30 @@ describe("HTTP ESM Loader", function() {
});
});

// The revision route answers `Cache-Control: no-cache`, as a dev
// server does for source modules, and numbers each response, so a
// re-import served from the HTTP cache would repeat revision 1.
it("re-imports the server's current body after invalidateModules", function (done) {
var origin = getHostOrigin();
if (!origin) {
pending("REPORT_BASEURL not set; skipping host HTTP tests");
done();
return;
}
var nsModule = require("ns:module");
var url = origin + "/esm/revision.mjs?k=invalidate";
import(url).then(function (first) {
nsModule.invalidateModules([url]);
return import(url).then(function (second) {
expect([first.revision, second.revision]).toEqual([1, 2]);
done();
});
}).catch(function (error) {
expect("rejected: " + formatError(error)).toBe("resolved");
done();
});
});

// The module-fetch budget is build-dependent: 30s per request attempt
// in debug runtimes, 5s in release (HttpLoader.mm). A module whose
// response lands between the two — the measured 5–9s dev-server
Expand Down
8 changes: 8 additions & 0 deletions TestRunnerTests/ModuleTestServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ typealias ModuleTestServerInput = (@escaping (Data) -> Void) -> Void
/// fallback) and the Jasmine reporter — so the HTTP surface is deliberately
/// small: one request per connection, full body buffered before dispatch,
/// `Connection: close` on every response.
///
/// Like a dev server, it answers `Cache-Control: no-cache` unless the handler
/// sets its own: the loader caches module responses on disk, and that cache
/// outlives the app process, so a cacheable answer could reach a later spec or
/// a later run instead of a request.
final class ModuleTestServer {
typealias StartResponse = (String, [(String, String)]) -> Void
typealias SendBody = (Data) -> Void
Expand Down Expand Up @@ -203,6 +208,9 @@ final class ModuleTestServer {
for (name, value) in headers {
response += "\(name): \(value)\r\n"
}
if !headers.contains(where: { $0.0.lowercased() == "cache-control" }) {
response += "Cache-Control: no-cache\r\n"
}
response += "Content-Length: \(body.count)\r\nConnection: close\r\n\r\n"
var payload = Data(response.utf8)
payload.append(body)
Expand Down
12 changes: 12 additions & 0 deletions TestRunnerTests/TestRunnerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,18 @@ class TestRunnerTests: XCTestCase {
return
}

if path == "/esm/revision.mjs" {
// Each request of a target gets a new body: its ordinal.
let target = query.isEmpty ? path : "\(path)?\(query)"
let body = "export const revision = \(self.requestCounts[target] ?? 0);\n"
startResponse("200 OK", [
("Content-Type", "application/javascript; charset=utf-8"),
("Cache-Control", "no-cache"),
])
sendBody(body.data(using: .utf8) ?? Data())
return
}

if path == "/esm/syntax-error.mjs" {
// Deliberately unparseable: pins that the loader surfaces
// V8's real compile error instead of a generic failure.
Expand Down
36 changes: 34 additions & 2 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -547,8 +547,8 @@ apply, worker teardown) belongs to whatever tooling drives it.

| export | description |
|---|---|
| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings always re-fetched), `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 and marks them bust-next-fetch, so the next network fetch bypasses every HTTP cache layer. Takes an array of strings; throws `TypeError` otherwise. |
| `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 goes through the loader's HTTP cache, so the server's caching headers decide whether it reaches the network; 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). A key qualifies when it starts with `blob:` or contains `://` — plain filesystem paths are deliberately excluded, because a reload computes its eviction set from what a server can re-serve. |
| `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 Down Expand Up @@ -1173,6 +1173,29 @@ treats it as a network error for a module script rather than as an empty
module. The `<essence>` in the foreign-MIME message is the normalized essence,
not the raw header.

### HTTP caching

The loader fetches modules through an HTTP cache the way a browser fetches
module scripts: the request carries no cache directives of its own, and the
**response** headers decide what is reused. Connections are persistent.

- 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` for source modules. Either one guarantees that a
module re-requested after `invalidateModules` reflects what the server
serves now.
- Content-addressed URLs (a hash in the path or query) may be served with a
long `max-age` and `immutable`; they are then reused without a request,
across app restarts too.
- A response with no `Cache-Control` and no `Expires` but with a
`Last-Modified` header is heuristically cacheable. It **can** be served
stale, including after an app restart. That is standard HTTP behavior, not
a loader bug: send explicit cache headers instead.

`invalidateModules` and `volatilePatterns` act on the module registry only.
The request they cause is an ordinary one and is answered from the HTTP cache
whenever the server's headers allow it.

### App entries and bootstraps

An app's entry can be either CommonJS or an ES module, and the choice decides
Expand Down Expand Up @@ -1342,6 +1365,15 @@ deadline < boot backstop. The local entry's short yield is one second with
full deadline, throws on expiry, and does slice the runloop, because the tooling
driving it needs the rejection reason synchronously.

The async module fetch uses an ephemeral `NSURLSession` (no persistent cookies
or credentials) with an on-disk `NSURLCache` of its own, in
`Library/Caches/ns-module-http-cache` (8 MB memory, 256 MB disk); the loader
never replaces or resizes the app's shared `NSURLCache`. Requests use the default
protocol cache policy. The synchronous fallback (`NSURLConnection`) goes
through the shared cache with the same policy. To make every module fetch go
to the origin instead, set the session's `URLCache` to `nil` and give the
request `NSURLRequestReloadIgnoringLocalAndRemoteCacheData`.

Type declarations for the `ns:` modules live in `types/` — one `.d.ts` per
module, referenced from `types/index.d.ts`. The `node:` shims are deliberately
*not* declared there: programs that include `@types/node` already have
Expand Down
14 changes: 10 additions & 4 deletions types/ns-module.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,12 @@ declare module "ns:module" {
export interface LoaderConfig {
/** Replaces the whole map. */
importMap?: ImportMap;
/** URL substrings identifying modules that are always re-fetched, never cached. */
/**
* URL substrings identifying modules that are re-requested on every import
* instead of being reused from the module registry. The request still goes
* through the loader's HTTP cache, so the server's caching headers decide
* whether it reaches the network.
*/
volatilePatterns?: string[];
canonicalization?: CanonicalizationConfig;
}
Expand All @@ -80,9 +85,10 @@ declare module "ns:module" {
export function configureLoader(config: LoaderConfig): void;

/**
* Evicts the given URLs (canonicalized) from the module registry and marks
* them bust-next-fetch, so the next network fetch bypasses every HTTP
* cache layer.
* Evicts the given URLs (canonicalized) from the module registry, so the
* next import of each requests it again. That request goes through the
* loader's HTTP cache: the server's caching headers decide whether it
* reaches the network.
*
* Throws `TypeError` if `urls` is not an array or holds a non-string, naming
* the offending index.
Expand Down
Loading