From 0080ac0f1cf4c43c0ae31c171d589f76c62cfc98 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 09:53:34 -0300 Subject: [PATCH 01/12] feat(runtime): switch and clear the HTTP module cache 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. --- docs/ns-builtin-modules.md | 42 +++- .../assets/app/tests/testEsmHttpLoader.js | 195 ++++++++++++++++++ .../src/main/assets/app/tests/testNsModule.js | 7 +- .../java/com/tns/tests/ModuleTestServer.java | 21 +- test-app/runtime/src/main/cpp/HttpLoader.cpp | 92 +++++++-- test-app/runtime/src/main/cpp/HttpLoader.h | 17 ++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 27 +++ .../src/main/cpp/ModuleInternalCallbacks.h | 3 + test-app/runtime/src/main/cpp/js/ns-module.js | 2 + .../src/main/java/com/tns/AppConfig.java | 17 ++ .../main/java/com/tns/ModuleHttpCache.java | 75 +++++++ .../java/com/tns/OkHttpModuleFetcher.java | 98 ++++++--- .../src/main/java/com/tns/Runtime.java | 1 + 13 files changed, 548 insertions(+), 49 deletions(-) create mode 100644 test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 641818f59..1c30b2606 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -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). | @@ -453,6 +455,7 @@ becoming a config that quietly does nothing. | a non-string in a `canonicalization` sub-key | `configureLoader: canonicalization.[] must be a string` | | `invalidateModules` argument not an array | `invalidateModules expects an array of URL strings` | | a non-string in that array | `invalidateModules: urls[] 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 @@ -990,9 +993,9 @@ 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 +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: @@ -1037,6 +1040,39 @@ 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 | +| `setHttpCacheEnabled(enabled)` from `ns:module` | turns it on or off from then on | +| `clearHttpCache()` from `ns:module` | wipes it | + +The app config is read once per process; a `moduleHttpCache` that is not a +boolean logs a warning and leaves the cache 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. + ### Fetch concurrency The module-graph walk fetches modules concurrently, up to a cap shared by diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 7a900eddb..f262f76a6 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1568,6 +1568,201 @@ describe("HTTP ESM Loader", function () { }); }); + // Specs that flip the switch restore it: it is process-wide. + describe("HTTP cache controls", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + var runTag = Date.now().toString(36); + var appShipsOkHttp = (function () { + try { + java.lang.Class.forName("okhttp3.OkHttpClient"); + return true; + } catch (e) { + return false; + } + })(); + + function requireOkHttp() { + if (!appShipsOkHttp) { + pending("the app does not ship OkHttp"); + } + } + + afterEach(function () { + nsModule.setHttpCacheEnabled(true); + nsModule.forcePlatformHttpTransport(false); + }); + + // The server's view of `target`: { count, cacheControl, pragma }, + // the last two from the latest request (null when absent). + function requestStats(target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)) + .then(function (m) { + return m.default; + }); + } + + // Evicts `target` from the registry and imports it again; resolves + // to its revision. + function reimport(target) { + var url = origin + target; + nsModule.invalidateModules([url]); + return import(url).then(function (m) { + return m.revision; + }); + } + + it("rejects a non-boolean switch", function () { + expect(function () { + nsModule.setHttpCacheEnabled("no"); + }).toThrowError(TypeError, "setHttpCacheEnabled expects a boolean"); + expect(function () { + nsModule.setHttpCacheEnabled(); + }).toThrowError(TypeError, "setHttpCacheEnabled expects a boolean"); + }); + + it("sends no cache directives while the cache is on", function (done) { + var target = "/esm/revision.mjs?k=directives-on-" + runTag; + import(origin + target).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(1); + expect(stats.cacheControl).toBeNull(); + expect(stats.pragma).toBeNull(); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("makes the next import reach the origin after clearHttpCache()", function (done) { + requireOkHttp(); + var target = "/esm/cached.mjs?k=clear-" + runTag; + var revisions = []; + import(origin + target).then(function (m) { + revisions.push(m.revision); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + nsModule.clearHttpCache(); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + // The cache still stores after a wipe. + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + return requestStats(target); + }).then(function (stats) { + expect(revisions).toEqual([1, 1, 2, 2]); + expect(stats.count).toBe(2); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("clears without throwing when the platform transport is in use", function () { + nsModule.forcePlatformHttpTransport(true); + expect(function () { + nsModule.clearHttpCache(); + }).not.toThrow(); + }); + + ["okhttp", "platform"].forEach(function (transport) { + it("reaches the origin every time and stores nothing while off, over " + transport, function (done) { + if (transport === "okhttp") { + requireOkHttp(); + } + nsModule.forcePlatformHttpTransport(transport === "platform"); + var target = "/esm/cached.mjs?k=off-" + transport + "-" + runTag; + var revisions = []; + nsModule.setHttpCacheEnabled(false); + import(origin + target).then(function (m) { + revisions.push(m.revision); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.cacheControl).toBe("no-cache"); + expect(stats.pragma).toBe("no-cache"); + // Nothing was stored while off, so the next fetch with + // the cache back on reaches the origin too. + nsModule.setHttpCacheEnabled(true); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + return requestStats(target); + }).then(function (stats) { + expect(revisions).toEqual([1, 2, 3]); + expect(stats.count).toBe(3); + expect(stats.cacheControl).toBeNull(); + expect(stats.pragma).toBeNull(); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + + describe("in workers", function () { + // Imports `url` in a new worker and resolves once that import + // settled, terminating the worker. + function importInWorker(url) { + return new Promise(function (resolve, reject) { + var worker = new Worker("./httpImportSettleWorker.js"); + worker.onmessage = function (msg) { + if (msg.data === "settled") { + worker.terminate(); + resolve(); + } + }; + worker.onerror = function (error) { + worker.terminate(); + reject(error); + }; + worker.postMessage(url); + }); + } + + it("share the main isolate's cache", function (done) { + requireOkHttp(); + var target = "/esm/cached.mjs?k=worker-shared-" + runTag; + import(origin + target).then(function () { + return importInWorker(origin + target); + }).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("see the switch the main isolate turned off", function (done) { + var target = "/esm/cached.mjs?k=worker-off-" + runTag; + import(origin + target).then(function () { + nsModule.setHttpCacheEnabled(false); + return importInWorker(origin + target); + }).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.cacheControl).toBe("no-cache"); + expect(stats.pragma).toBe("no-cache"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + }); + // Each present configureLoader section replaces its state wholesale, so // an empty array is explicit policy — "nothing is volatile any more" — // not a no-op. diff --git a/test-app/app/src/main/assets/app/tests/testNsModule.js b/test-app/app/src/main/assets/app/tests/testNsModule.js index 6ca70b985..a34e5efe5 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -7,14 +7,17 @@ describe("ns:module", function () { expect(typeof nsModule.getLoadedModuleUrls).toBe("function"); expect(typeof nsModule.createRequire).toBe("function"); expect(typeof nsModule.createPumpingRequire).toBe("function"); + expect(typeof nsModule.setHttpCacheEnabled).toBe("function"); + expect(typeof nsModule.clearHttpCache).toBe("function"); expect(nsModule.terminateAllWorkers).toBeUndefined(); expect(global.__NS_DEV__).toBeUndefined(); }); it("exposes exactly the declared surface", function () { var nsModule = require("ns:module"); - var expected = ["configureLoader", "createPumpingRequire", "createRequire", - "getLoadedModuleUrls", "invalidateModules"]; + var expected = ["clearHttpCache", "configureLoader", "createPumpingRequire", + "createRequire", "getLoadedModuleUrls", "invalidateModules", + "setHttpCacheEnabled"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist", "streamedCompileStats", "httpFetchDiagnostics", diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index 303519266..a5624537c 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -37,6 +37,9 @@ public final class ModuleTestServer { // /esm/request-stats.json so a spec can prove how often a module was // fetched, or that it never was. private static final Map requestCounts = new HashMap(); + // The latest request's Cache-Control and Pragma per target (null when + // absent), guarded by requestCounts. + private static final Map lastCacheDirectives = new HashMap(); private static final List openSockets = new ArrayList(); private static final Object connectionStatsLock = new Object(); @@ -50,6 +53,8 @@ public final class ModuleTestServer { private static final class Exchange { boolean clientWantsClose; String ifNoneMatch; + String cacheControl; + String pragma; boolean responded; } @@ -198,6 +203,8 @@ private static void handle(Socket socket) throws IOException { } exchange.clientWantsClose = "close".equalsIgnoreCase(requestHeader(head, "Connection")); exchange.ifNoneMatch = requestHeader(head, "If-None-Match"); + exchange.cacheControl = requestHeader(head, "Cache-Control"); + exchange.pragma = requestHeader(head, "Pragma"); exchange.responded = false; handleRequest(socket, head); // A route that returned without answering (an interrupted @@ -259,6 +266,10 @@ private static void route(Socket socket, String path, String query) throws IOExc Integer count = requestCounts.get(target); ordinal = count == null ? 1 : count + 1; requestCounts.put(target, ordinal); + Exchange exchange = currentExchange.get(); + if (exchange != null) { + lastCacheDirectives.put(target, new String[] {exchange.cacheControl, exchange.pragma}); + } } // Only the cap spec's route counts: a slow route an earlier spec gave // up on can still hold a server thread. @@ -332,11 +343,15 @@ private static void routeCounted(Socket socket, String path, String query, int o String raw = param(query, "target="); String wanted = raw == null ? "" : URLDecoder.decode(raw, "UTF-8"); int count; + String[] directives; synchronized (requestCounts) { Integer c = requestCounts.get(wanted); count = c == null ? 0 : c; + directives = lastCacheDirectives.get(wanted); } - String body = "{\"target\":\"" + jsStringLiteral(wanted) + "\",\"count\":" + count + "}"; + String body = "{\"target\":\"" + jsStringLiteral(wanted) + "\",\"count\":" + count + + ",\"cacheControl\":" + jsonStringOrNull(directives == null ? null : directives[0]) + + ",\"pragma\":" + jsonStringOrNull(directives == null ? null : directives[1]) + "}"; respond(socket, "200 OK", "application/json; charset=utf-8", body.getBytes(UTF8)); return; } @@ -656,6 +671,10 @@ private static String jsStringLiteral(String s) { .replace("\u0000", "\\u0000"); } + private static String jsonStringOrNull(String s) { + return s == null ? "null" : "\"" + jsStringLiteral(s) + "\""; + } + /** `extraHeaders` alternates names and values. */ private static void respond(Socket socket, String status, String contentType, byte[] body, String... extraHeaders) throws IOException { diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index a489397b4..82fe01b31 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -304,8 +304,56 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std:: return true; } -static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std::string& out, - std::string& contentType, int& status); +static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool useCache, + std::string& out, std::string& contentType, int& status); + +// ── The HTTP module cache switch ───────────────────────────── + +static std::once_flag s_moduleHttpCacheInitFlag; +static std::atomic s_moduleHttpCacheSetting{true}; +static std::atomic s_moduleHttpCacheInspectorDisables{0}; + +// The app config's and launch options' answer, read once. Every writer of the +// setting runs this first, so a later first read cannot overwrite a setter. +static void InitializeModuleHttpCacheSetting() { + std::call_once(s_moduleHttpCacheInitFlag, []() { + try { + JEnv env; + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { + return; + } + jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); + if (mid != nullptr) { + s_moduleHttpCacheSetting.store(env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE); + } + } catch (...) { + // Enabled. + } + }); +} + +bool ModuleHttpCacheEnabled() { + InitializeModuleHttpCacheSetting(); + return s_moduleHttpCacheSetting.load() && s_moduleHttpCacheInspectorDisables.load() == 0; +} + +void SetModuleHttpCacheEnabled(bool enabled) { + InitializeModuleHttpCacheSetting(); + s_moduleHttpCacheSetting.store(enabled); +} + +void AddModuleHttpCacheInspectorDisable(int delta) { + InitializeModuleHttpCacheSetting(); + s_moduleHttpCacheInspectorDisables.fetch_add(delta); +} + +void ClearModuleHttpCache() { + JEnv env; + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + jmethodID mid = env.GetStaticMethodID(cls, "clear", "()V"); + env.CallStaticVoidMethod(cls, mid); +} // Each module-fetch attempt's connect timeout and read timeout, for both // transports, matching iOS. Debug builds talk to dev servers that transform @@ -542,14 +590,16 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { std::string contentType; int status = 0; const int timeoutMs = ModuleFetchTimeoutMs(); - bool transportOk = PerformHttpFetchOnceSync(url, timeoutMs, body, contentType, status); + const bool useCache = ModuleHttpCacheEnabled(); + bool transportOk = + PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); if (!transportOk) { // One retry, and only for a transport error: an HTTP status is an // answer, not a failure to communicate, so asking again would just // repeat it. TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); std::this_thread::sleep_for(kModuleFetchRetryDelay); - transportOk = PerformHttpFetchOnceSync(url, timeoutMs, body, contentType, status); + transportOk = PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); } ClassifyModuleResponse(url, transportOk, status, contentType, body, result); @@ -613,7 +663,7 @@ static const OkHttpBridge* OkHttpBridgeIfAvailable() { return; } bridge.fetch = raw->GetStaticMethodID( - fetcher, "fetch", "(Ljava/lang/String;III)Lcom/tns/OkHttpModuleFetcher$Result;"); + fetcher, "fetch", "(Ljava/lang/String;IIIZ)Lcom/tns/OkHttpModuleFetcher$Result;"); bridge.status = bridge.fetch ? raw->GetFieldID(result, "status", "I") : nullptr; bridge.contentType = bridge.status ? raw->GetFieldID(result, "contentType", "Ljava/lang/String;") @@ -657,7 +707,7 @@ void SetForcePlatformModuleTransport(bool force) { template static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, const std::string& url, int timeoutMs, - std::string& out, std::string& contentType, + bool useCache, std::string& out, std::string& contentType, int& status, OnFailure recordStageFailure) { JNIEnv* raw = env; // The pool keeps at least as many idle connections as the most fetches @@ -672,7 +722,8 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, static_cast(timeoutMs), static_cast(ModuleFetchTimeoutMs()), - static_cast(maxIdle)); + static_cast(maxIdle), + useCache ? JNI_TRUE : JNI_FALSE); { std::string excClass, excMsg; if (DrainPendingJniException(env, excClass, excMsg)) { @@ -713,8 +764,8 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri // and past the InputStream close. The wrappers stay on the setup calls, whose // failures have no per-stage verdict and are caught below. // `timeoutMs` must be positive: HttpURLConnection reads 0 as no timeout. -static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std::string& out, - std::string& contentType, int& status) { +static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool useCache, + std::string& out, std::string& contentType, int& status) { out.clear(); contentType.clear(); status = 0; @@ -752,7 +803,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std: if (const OkHttpBridge* okhttp = ActiveOkHttpBridge()) { if (std::optional fetched = PerformOkHttpFetch( - env, *okhttp, url, timeoutMs, out, contentType, status, recordStageFailure)) { + env, *okhttp, url, timeoutMs, useCache, out, contentType, status, + recordStageFailure)) { return *fetched; } } @@ -806,6 +858,13 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std: env.NewStringUTF("identity")); env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("User-Agent"), env.NewStringUTF("NativeScript-HTTP-ESM")); + // This transport has no cache, but a proxy on the way may. + if (!useCache) { + env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Cache-Control"), + env.NewStringUTF("no-cache")); + env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Pragma"), + env.NewStringUTF("no-cache")); + } jclass clsHttp = env.FindClass("java/net/HttpURLConnection"); bool isHttp = clsHttp && env.IsInstanceOf(conn, clsHttp); @@ -1056,6 +1115,8 @@ struct ModuleFetchJob { std::string url; ModuleFetchHostClass hostClass; ModuleFetchDeadline deadline; + // The cache switch as it was when the fetch was issued. + bool useCache; std::function completion; }; @@ -1106,8 +1167,8 @@ void RunModuleFetchJob(const ModuleFetchJob& job) { bool transportOk = false; std::optional timeoutMs = AttemptTimeoutMs(job.deadline); if (timeoutMs) { - transportOk = - PerformHttpFetchOnceSync(job.url, *timeoutMs, body, contentType, status); + transportOk = PerformHttpFetchOnceSync(job.url, *timeoutMs, job.useCache, body, + contentType, status); // Transport error → one retry, the same single-retry policy the // sync path applies, while the deadline can still fit the delay. if (!transportOk && !RetryFitsDeadline(job.deadline)) { @@ -1119,8 +1180,8 @@ void RunModuleFetchJob(const ModuleFetchJob& job) { std::this_thread::sleep_for(kModuleFetchRetryDelay); timeoutMs = AttemptTimeoutMs(job.deadline); if (timeoutMs) { - transportOk = - PerformHttpFetchOnceSync(job.url, *timeoutMs, body, contentType, status); + transportOk = PerformHttpFetchOnceSync(job.url, *timeoutMs, job.useCache, + body, contentType, status); } } } @@ -1228,7 +1289,8 @@ void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline fetchDeadl // Outside the lock: the first call reads the app config over JNI. const size_t cap = ModuleFetchConcurrency(hostClass); ModuleFetchLane& lane = LaneFor(hostClass); - ModuleFetchJob job{url, hostClass, fetchDeadline, std::move(completion)}; + ModuleFetchJob job{url, hostClass, fetchDeadline, ModuleHttpCacheEnabled(), + std::move(completion)}; { std::lock_guard lock(g_fetchQueueMutex); if (lane.threadCount >= cap) { diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index da9a8d047..70873a46f 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -128,6 +128,23 @@ const char* ActiveModuleTransportName(); // testable in an app that ships OkHttp. void SetForcePlatformModuleTransport(bool force); +// The HTTP module cache switch, process-wide: every isolate and both fetch +// paths. A fetch reads it once, when it is issued. Off, a fetch neither reads +// nor writes the cache and sends `Cache-Control: no-cache` and +// `Pragma: no-cache`, on either transport. +// +// Enabled = the setting (app config `moduleHttpCache`, then ns:module +// setHttpCacheEnabled) AND no inspector client has the cache disabled. +bool ModuleHttpCacheEnabled(); +void SetModuleHttpCacheEnabled(bool enabled); +// +1 when an inspector client disables the cache, -1 when it re-enables it or +// disconnects. +void AddModuleHttpCacheInspectorDisable(int delta); + +// Wipes the module cache (ModuleHttpCache.clear()), durably, before returning. +// Throws NativeScriptException when Java reports a failure. +void ClearModuleHttpCache(); + // Which concurrency cap a module URL's fetches share. // kLoopback: the host is 127.0.0.1, [::1] or localhost. On a device that // is almost always `adb reverse`, whose listener overflows under a burst diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 75230d356..35af34cb6 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -4343,6 +4343,30 @@ void ForcePlatformHttpTransportCallback(const v8::FunctionCallbackInfoBooleanValue(isolate)); } +void SetHttpCacheEnabledCallback(const v8::FunctionCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + if (info.Length() < 1 || !info[0]->IsBoolean()) { + isolate->ThrowException(v8::Exception::TypeError( + ToV8String(isolate, "setHttpCacheEnabled expects a boolean"))); + return; + } + SetModuleHttpCacheEnabled(info[0]->BooleanValue(isolate)); +} + +void ClearHttpCacheCallback(const v8::FunctionCallbackInfo& info) { + try { + ClearModuleHttpCache(); + } catch (NativeScriptException& e) { + e.ReThrowToV8(); + } catch (std::exception& e) { + NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); + nsEx.ReThrowToV8(); + } catch (...) { + NativeScriptException nsEx(std::string("Error: c++ exception!")); + nsEx.ReThrowToV8(); + } +} + } // namespace bool BuildNsModuleBinding(v8::Local context, v8::Local binding) { @@ -4352,6 +4376,9 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local InstallDevFunction(isolate, context, binding, "invalidateModules", InvalidateModulesCallback); InstallDevFunction(isolate, context, binding, "getLoadedModuleUrls", GetLoadedModuleUrlsCallback); + InstallDevFunction(isolate, context, binding, "setHttpCacheEnabled", + SetHttpCacheEnabledCallback); + InstallDevFunction(isolate, context, binding, "clearHttpCache", ClearHttpCacheCallback); if (!ModuleInternal::InstallCreateRequireBinding(context, binding)) { return false; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 09639a6b0..61970aedb 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -279,6 +279,9 @@ void SetCanonicalizationConfig(CanonicalizationConfig config); // - invalidateModules(urls) (registry + cache eviction) // - getLoadedModuleUrls() (registry introspection) // - createRequire(path) (a CommonJS require for `path`) +// - setHttpCacheEnabled(enabled) (the process-wide HTTP module cache +// switch; see HttpLoader.h) +// - clearHttpCache() (wipes the HTTP module cache) // - canonicalizeHttpUrlKey(url) (debug builds only; test diagnostic) // - remoteUrlMatchesAllowlist(url, entries) // (debug builds only; test diagnostic) diff --git a/test-app/runtime/src/main/cpp/js/ns-module.js b/test-app/runtime/src/main/cpp/js/ns-module.js index b25bf531d..866d0b5ed 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -176,6 +176,8 @@ const surface = { configureLoader: binding.configureLoader, invalidateModules: binding.invalidateModules, getLoadedModuleUrls: binding.getLoadedModuleUrls, + setHttpCacheEnabled: binding.setHttpCacheEnabled, + clearHttpCache: binding.clearHttpCache, createRequire, createPumpingRequire, }; diff --git a/test-app/runtime/src/main/java/com/tns/AppConfig.java b/test-app/runtime/src/main/java/com/tns/AppConfig.java index 542980cf6..d48a66653 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -46,6 +46,8 @@ public Object getDefaultValue() { private final static String SecurityKey = "security"; // Top level, like iOS, so one app config selects the mode on both platforms. private final static String WrapperLifetimeKey = "wrapperLifetime"; + // Top level, next to security, like iOS. + private final static String ModuleHttpCacheKey = "moduleHttpCache"; private final Object[] values; @@ -56,6 +58,8 @@ public Object getDefaultValue() { // Items are kept raw: the native gate decides what each one matches. private String[] remoteModuleAllowlist = null; + private boolean moduleHttpCache = true; + private final static String ModuleFetchConcurrencyKey = "moduleFetchConcurrency"; private final static int MaxModuleFetchConcurrency = 64; // { loopback, remote }; 0 leaves the runtime's default for that host class. @@ -77,6 +81,14 @@ public AppConfig(File appDir) { if (rootObject.has(WrapperLifetimeKey)) { readWrapperLifetime(rootObject.opt(WrapperLifetimeKey)); } + if (rootObject.has(ModuleHttpCacheKey)) { + Object value = rootObject.opt(ModuleHttpCacheKey); + if (value instanceof Boolean) { + moduleHttpCache = (Boolean) value; + } else { + Log.w("JS", String.format("moduleHttpCache must be a boolean, not %s; the HTTP module cache stays enabled.", JSONObject.quote(String.valueOf(value)))); + } + } // Parse security configuration if (rootObject.has(SecurityKey)) { @@ -239,6 +251,11 @@ private static int readModuleFetchConcurrencyValue(JSONObject object, String key return (int) count; } + /** The top-level moduleHttpCache: false starts the HTTP module cache disabled. */ + public boolean getModuleHttpCache() { + return moduleHttpCache; + } + /** { loopback, remote }, each 0 when not configured. */ public int[] getModuleFetchConcurrency() { return moduleFetchConcurrency.clone(); diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java new file mode 100644 index 000000000..ded50a7dd --- /dev/null +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -0,0 +1,75 @@ +package com.tns; + +import java.io.File; +import java.io.IOException; + +/** + * The HTTP module loader's cache controls on the Java side: the startup state + * and wiping the cache. The live on/off switch is native (HttpLoader.cpp), + * which reads {@link #isEnabledAtStartup()} once. + * + * Only the OkHttp transport has a cache. Wipes still clear the on-disk + * directory when OkHttp is absent or its client was never created, since an + * earlier run may have filled it. + */ +final class ModuleHttpCache { + private ModuleHttpCache() { + } + + /** + * Guards creating the OkHttp client and every wipe, so a wipe never deletes + * files under a cache that is being opened. + */ + static final Object LOCK = new Object(); + + private static volatile boolean enabledAtStartup = true; + + /** Read through JNI by HttpLoader, once per process. */ + static boolean isEnabledAtStartup() { + return enabledAtStartup; + } + + /** + * Applies the app config. Runs once, on the main thread, before the + * runtime can fetch anything. + */ + static void readStartupOptions(StaticConfiguration config) { + enabledAtStartup = config.appConfig == null || config.appConfig.getModuleHttpCache(); + } + + /** Wipes the whole module cache. Durable once this returns. */ + static void clear() throws IOException { + synchronized (LOCK) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache()) { + return; + } + File dir = Runtime.getModuleHttpCacheDir(); + if (dir != null) { + deleteContents(dir); + } + } + } + + private static void deleteContents(File dir) throws IOException { + File[] children = dir.listFiles(); + if (children == null) { + return; + } + IOException failure = null; + for (File child : children) { + if (child.isDirectory()) { + try { + deleteContents(child); + } catch (IOException e) { + failure = e; + } + } + if (!child.delete() && child.exists()) { + failure = new IOException("could not delete " + child); + } + } + if (failure != null) { + throw failure; + } + } +} diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java index 9d48ab061..afa145beb 100644 --- a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -54,13 +54,15 @@ static boolean isAvailable() { * One GET of {@code url}, following redirects within the same protocol. * {@code timeoutMs} bounds the connect and each read; {@code defaultTimeoutMs} * and {@code maxIdleConnections} configure the shared client on the first call - * only. Null, without throwing, when this OkHttp version is missing a call used - * here; {@link #isAvailable()} is false from then on. + * only. {@code useCache} false neither reads nor writes the cache and asks + * every cache on the way for a fresh response. Null, without throwing, when + * this OkHttp version is missing a call used here; {@link #isAvailable()} is + * false from then on. */ - static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections) - throws IOException { + static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections, + boolean useCache) throws IOException { try { - return Client.fetch(url, timeoutMs, defaultTimeoutMs, maxIdleConnections); + return Client.fetch(url, timeoutMs, defaultTimeoutMs, maxIdleConnections, useCache); } catch (LinkageError e) { available = false; android.util.Log.w("JS", "HTTP modules: the app's OkHttp is incompatible; using HttpURLConnection instead: " + e); @@ -68,50 +70,90 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle } } + /** + * Empties the client's cache. False when there is no client yet, or no + * cache to clear through it; the caller then deletes the files itself. + * Call under {@link ModuleHttpCache#LOCK}. + */ + static boolean clearClientCache() throws IOException { + try { + return Client.clearCache(); + } catch (LinkageError e) { + available = false; + return false; + } + } + private static final class Client { // An okhttp3.OkHttpClient, typed Object to keep okhttp3 out of member // signatures. Never an app-configured client: its interceptors, cache // or pool would change what a module fetch does. private static Object client; + // The same client without the cache, sharing its pool: a fetch with the + // cache off. A per-request no-store directive would also keep a response + // out of the cache, but it would put no-store on the wire. + private static Object uncachedClient; private static int clientTimeoutMs; - private static synchronized okhttp3.OkHttpClient base(int timeoutMs, int maxIdleConnections) { - if (client == null) { - okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient.Builder() - .connectionPool(new okhttp3.ConnectionPool(maxIdleConnections, 5, TimeUnit.MINUTES)) - .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS) - .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) - .followRedirects(true) - // HttpURLConnection never follows a redirect that changes protocol. - .followSslRedirects(false); - File cacheDir = Runtime.getModuleHttpCacheDir(); - if (cacheDir != null) { - builder.cache(new okhttp3.Cache(cacheDir, CACHE_MAX_BYTES)); + private static okhttp3.OkHttpClient base(int timeoutMs, int maxIdleConnections, boolean useCache) { + synchronized (ModuleHttpCache.LOCK) { + if (client == null) { + create(timeoutMs, maxIdleConnections); } - client = builder.build(); - clientTimeoutMs = timeoutMs; + return (okhttp3.OkHttpClient) (useCache ? client : uncachedClient); + } + } + + private static void create(int timeoutMs, int maxIdleConnections) { + okhttp3.OkHttpClient.Builder builder = new okhttp3.OkHttpClient.Builder() + .connectionPool(new okhttp3.ConnectionPool(maxIdleConnections, 5, TimeUnit.MINUTES)) + .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS) + .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) + .followRedirects(true) + // HttpURLConnection never follows a redirect that changes protocol. + .followSslRedirects(false); + File cacheDir = Runtime.getModuleHttpCacheDir(); + if (cacheDir != null) { + builder.cache(new okhttp3.Cache(cacheDir, CACHE_MAX_BYTES)); } - return (okhttp3.OkHttpClient) client; + okhttp3.OkHttpClient built = builder.build(); + uncachedClient = built.newBuilder().cache(null).build(); + client = built; + clientTimeoutMs = timeoutMs; } - static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections) - throws IOException { - okhttp3.OkHttpClient http = base(defaultTimeoutMs, maxIdleConnections); + static boolean clearCache() throws IOException { + okhttp3.Cache cache = client != null ? ((okhttp3.OkHttpClient) client).cache() : null; + if (cache == null) { + return false; + } + // Removing an entry deletes its files at once, so the wipe outlives + // a process kill; the flush also persists the journal's record of it. + cache.evictAll(); + cache.flush(); + return true; + } + + static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections, + boolean useCache) throws IOException { + okhttp3.OkHttpClient http = base(defaultTimeoutMs, maxIdleConnections, useCache); if (timeoutMs != clientTimeoutMs) { - // Shares the pool and the cache with the base client. + // Shares the pool, and the cache if any, with the base client. http = http.newBuilder() .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS) .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) .build(); } - okhttp3.Request request = new okhttp3.Request.Builder() + okhttp3.Request.Builder request = new okhttp3.Request.Builder() .url(url) .header("Accept", "application/javascript, text/javascript, */*;q=0.1") // Also turns off OkHttp's transparent gzip. .header("Accept-Encoding", "identity") - .header("User-Agent", "NativeScript-HTTP-ESM") - .build(); - okhttp3.Response response = http.newCall(request).execute(); + .header("User-Agent", "NativeScript-HTTP-ESM"); + if (!useCache) { + request.header("Cache-Control", "no-cache").header("Pragma", "no-cache"); + } + okhttp3.Response response = http.newCall(request.build()).execute(); try { byte[] body; okhttp3.ResponseBody responseBody = response.body(); diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index 526f357b5..031414adf 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -689,6 +689,7 @@ public void releaseNativeCounterpart(int nativeObjectId) { */ public static Runtime initializeRuntimeWithConfiguration(StaticConfiguration config) { staticConfiguration = config; + ModuleHttpCache.readStartupOptions(config); WorkThreadScheduler mainThreadScheduler = new WorkThreadScheduler(new Handler(Looper.myLooper())); DynamicConfiguration dynamicConfiguration = new DynamicConfiguration(0, mainThreadScheduler, null); Runtime runtime = initRuntime(dynamicConfiguration); From ef9354f5f6edb75dc672fab0c9dc5cc6ee60d3c5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 09:55:00 -0300 Subject: [PATCH 02/12] feat(runtime): launch options for the HTTP module cache --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/-nativescript-no-module-cache or -nativescript-clear-module-cache before starting the app, the convention --debug-brk already uses with -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. --- docs/ns-builtin-modules.md | 26 ++++++++- test-app/runtime/src/main/cpp/HttpLoader.h | 3 +- .../main/java/com/tns/ModuleHttpCache.java | 54 +++++++++++++++++-- .../src/main/java/com/tns/Runtime.java | 6 +++ 4 files changed, 81 insertions(+), 8 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 1c30b2606..3dae791e5 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1051,11 +1051,15 @@ 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 | -The app config is read once per process; a `moduleHttpCache` that is not a -boolean logs a warning and leaves the cache on. `setHttpCacheEnabled` and +The app config and the launch options are read once per process, at startup; +a `moduleHttpCache` 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, @@ -1073,6 +1077,24 @@ 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. +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 `-debugbreak`: + +```sh +adb shell "cat /dev/null > /data/local/tmp/-nativescript-no-module-cache" +adb shell "cat /dev/null > /data/local/tmp/-nativescript-clear-module-cache" +adb shell am start -n / +``` + +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. 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 diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index 70873a46f..efe45c266 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -133,7 +133,8 @@ void SetForcePlatformModuleTransport(bool force); // nor writes the cache and sends `Cache-Control: no-cache` and // `Pragma: no-cache`, on either transport. // -// Enabled = the setting (app config `moduleHttpCache`, then ns:module +// Enabled = the setting (app config `moduleHttpCache`, the +// nativescript-no-module-cache launch option, then ns:module // setHttpCacheEnabled) AND no inspector client has the cache disabled. bool ModuleHttpCacheEnabled(); void SetModuleHttpCacheEnabled(bool enabled); diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java index ded50a7dd..605dfa4f9 100644 --- a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -1,12 +1,15 @@ package com.tns; +import android.util.Log; + import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; /** * The HTTP module loader's cache controls on the Java side: the startup state - * and wiping the cache. The live on/off switch is native (HttpLoader.cpp), - * which reads {@link #isEnabledAtStartup()} once. + * (app config + launch options) and wiping the cache. The live on/off switch + * is native (HttpLoader.cpp), which reads {@link #isEnabledAtStartup()} once. * * Only the OkHttp transport has a cache. Wipes still clear the on-disk * directory when OkHttp is absent or its client was never created, since an @@ -22,6 +25,14 @@ private ModuleHttpCache() { */ static final Object LOCK = new Object(); + // Launch options are files the CLI creates empty in /data/local/tmp, the + // convention of -debugbreak: the app can open such a file but not + // delete it, so it consumes an option by writing to it, and only an empty + // file is in effect. + static final String NO_CACHE_LAUNCH_OPTION = "nativescript-no-module-cache"; + static final String CLEAR_CACHE_LAUNCH_OPTION = "nativescript-clear-module-cache"; + private static final File LAUNCH_OPTION_DIR = new File("/data/local/tmp"); + private static volatile boolean enabledAtStartup = true; /** Read through JNI by HttpLoader, once per process. */ @@ -30,11 +41,44 @@ static boolean isEnabledAtStartup() { } /** - * Applies the app config. Runs once, on the main thread, before the - * runtime can fetch anything. + * Applies the app config and consumes the launch options. Runs once, on the + * main thread, before the runtime can fetch anything: a later read could + * consume an option the CLI wrote for the next launch. */ static void readStartupOptions(StaticConfiguration config) { - enabledAtStartup = config.appConfig == null || config.appConfig.getModuleHttpCache(); + boolean enabled = config.appConfig == null || config.appConfig.getModuleHttpCache(); + // A release app without allowRemoteModules loads no HTTP module, so it + // skips looking for launch options at every start. + boolean loadsHttpModules = config.isDebuggable + || (config.appConfig != null && config.appConfig.getAllowRemoteModules()); + if (loadsHttpModules && config.appName != null && Runtime.isMainProcess(config.appName)) { + if (consumeLaunchOption(config.appName, NO_CACHE_LAUNCH_OPTION)) { + enabled = false; + } + if (consumeLaunchOption(config.appName, CLEAR_CACHE_LAUNCH_OPTION)) { + try { + clear(); + } catch (IOException e) { + Log.w("JS", "HTTP modules: could not clear the module cache at launch: " + e); + } + } + } + enabledAtStartup = enabled; + } + + private static boolean consumeLaunchOption(String appName, String option) { + File file = new File(LAUNCH_OPTION_DIR, appName + "-" + option); + if (!file.isFile() || file.length() != 0) { + return false; + } + try (FileOutputStream out = new FileOutputStream(file)) { + out.write('1'); + } catch (IOException | SecurityException e) { + // Applied anyway; it stays in effect at later launches until the + // CLI removes or rewrites the file. + Log.w("JS", "HTTP modules: could not consume launch option " + file + ": " + e); + } + return true; } /** Wipes the whole module cache. Durable once this returns. */ diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index 031414adf..beae193dc 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -532,6 +532,12 @@ static File getModuleHttpCacheDir() { return new File(new File(config.rootDir, "cache"), name); } + /** Whether this is the app's default process rather than a {@code package:name} one. */ + static boolean isMainProcess(String appName) { + String process = currentProcessName(); + return process == null || process.equals(appName); + } + private static String currentProcessName() { try (java.io.FileInputStream in = new java.io.FileInputStream("/proc/self/cmdline")) { byte[] buffer = new byte[256]; From 0fb09e502870c1503e883bd61bfbd3e4dc315cb0 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 09:55:12 -0300 Subject: [PATCH 03/12] feat(inspector): Network.setCacheDisabled and clearBrowserCache control 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. --- docs/ns-builtin-modules.md | 17 ++++ .../src/main/cpp/JsV8InspectorClient.cpp | 99 +++++++++++++++++++ .../src/main/cpp/JsV8InspectorClient.h | 9 ++ 3 files changed, 125 insertions(+) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 3dae791e5..534b806e0 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1055,6 +1055,8 @@ The cache is **on** unless something turns it 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 | The app config and the launch options are read once per process, at startup; a `moduleHttpCache` that is not a boolean logs a warning and leaves the cache @@ -1077,6 +1079,21 @@ 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. +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 +`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 `-debugbreak`: diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 5beb11a14..fb7470ee0 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -19,6 +19,7 @@ #include "ArgConverter.h" #include "Constants.h" #include "File.h" +#include "HttpLoader.h" #include "Util.h" #include "Utils.h" #include "WorkerInspectorClient.h" @@ -64,6 +65,50 @@ std::string FinishResponse(json& response, const std::string& sessionId) { return JsonDump(response); } +bool IsNetworkCacheMethod(const std::string& method) { + return method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache"; +} + +// Network.setCacheDisabled's required boolean `cacheDisabled`, if present. +std::optional SetCacheDisabledParam(const json& message) { + if (!message.contains("params") || !message["params"].is_object()) { + return std::nullopt; + } + const json& params = message["params"]; + if (!params.contains("cacheDisabled") || !params["cacheDisabled"].is_boolean()) { + return std::nullopt; + } + return params["cacheDisabled"].get(); +} + +// What the runtime answers a Network cache command with when no JS handler +// does: `{}`, or an invalid-parameters error for a setCacheDisabled without a +// boolean `cacheDisabled`. +json NetworkCacheReply(long long id, const std::string& method, const json& message) { + if (method == "Network.setCacheDisabled" && !SetCacheDisabledParam(message).has_value()) { + return {{"id", id}, {"error", {{"code", -32602}, {"message", "Invalid parameters"}}}}; + } + return {{"id", id}, {"result", json::object()}}; +} + +// The runtime's reply to `message` when it is a Network.setCacheDisabled or +// Network.clearBrowserCache command for the main session. +std::optional MainSessionNetworkCacheReply(const std::string& message) { + if (message.find("Network.") == std::string::npos) { + return std::nullopt; + } + auto parsed = json::parse(message, nullptr, false); + if (parsed.is_discarded() || !parsed.is_object() || !parsed.contains("method") || + !parsed["method"].is_string() || !IsNetworkCacheMethod(parsed["method"].get()) || + !parsed.contains("id") || !parsed["id"].is_number_integer() || + (parsed.contains("sessionId") && parsed["sessionId"].is_string() && + !parsed["sessionId"].get().empty())) { + return std::nullopt; + } + return JsonDump(NetworkCacheReply(parsed["id"].get(), + parsed["method"].get(), parsed)); +} + // Target.attachedToTarget event announcing a worker as a child target. std::string BuildWorkerAttachedEvent(WorkerInspectorClient* client) { json attached = {{"method", "Target.attachedToTarget"}, @@ -349,6 +394,11 @@ void JsV8InspectorClient::disconnect() { { std::lock_guard lock(connectionMutex_); + // A client's Network.setCacheDisabled ends with its connection. + if (frontendCacheDisabled_) { + frontendCacheDisabled_ = false; + AddModuleHttpCacheInspectorDisable(-1); + } if (connection_ == nullptr) { return; } @@ -427,6 +477,8 @@ void JsV8InspectorClient::dispatchMessage(const std::string& message) { StringView messageView_(vector_.data(), vector_.size()); auto msg = StringBuffer::create(messageView_); this->sendNotification(std::move(msg)); + } else if (auto reply = MainSessionNetworkCacheReply(message)) { + this->SendRawToFrontend(*reply); } return; } @@ -476,6 +528,13 @@ v8::Local JsV8InspectorClient::ensureDefaultContextInGroup(int cont } void JsV8InspectorClient::doDispatchMessage(const std::string& message) { + // V8 has no Network domain. These two reach here when no JS handler took + // them, or while paused, where JS handlers do not run; the runtime already + // applied them on the socket thread. + if (auto reply = MainSessionNetworkCacheReply(message)) { + this->SendRawToFrontend(*reply); + return; + } if (session_ == nullptr) { return; } @@ -662,6 +721,26 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message return true; } + // The runtime's part of the HTTP module cache commands, from any session + // and even while paused. A main-session command then continues to the JS + // Network domain handler, if one is registered, for the response. Workers + // have no JS domain handlers, so a worker session is answered here. + if (IsNetworkCacheMethod(method)) { + if (method == "Network.clearBrowserCache") { + ClearModuleHttpCacheFromInspector(); + } else if (std::optional cacheDisabled = SetCacheDisabledParam(parsed)) { + SetFrontendCacheDisabled(*cacheDisabled); + } + if (sessionId.empty()) { + return false; + } + if (msgId >= 0) { + json reply = NetworkCacheReply(msgId, method, parsed); + response = FinishResponse(reply, sessionId); + } + return true; + } + // Flat-session protocol: a top-level sessionId addresses a worker target. if (!sessionId.empty()) { this->RouteToWorker(sessionId, method, msgId, message); @@ -688,6 +767,26 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message return false; } +void JsV8InspectorClient::ClearModuleHttpCacheFromInspector() { + try { + ClearModuleHttpCache(); + } catch (NativeScriptException& e) { + DEBUG_WRITE_FORCE("Network.clearBrowserCache: could not clear the HTTP module cache: %s", + e.GetErrorMessage().c_str()); + } catch (...) { + DEBUG_WRITE_FORCE("Network.clearBrowserCache: could not clear the HTTP module cache"); + } +} + +void JsV8InspectorClient::SetFrontendCacheDisabled(bool cacheDisabled) { + std::lock_guard lock(connectionMutex_); + if (connection_ == nullptr || cacheDisabled == frontendCacheDisabled_) { + return; + } + frontendCacheDisabled_ = cacheDisabled; + AddModuleHttpCacheInspectorDisable(cacheDisabled ? 1 : -1); +} + void JsV8InspectorClient::RouteToWorker(const std::string& sessionId, const std::string& method, long long msgId, const std::string& message) { // Built under the lock, sent after releasing it: a blocking socket write diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index 4e169cb40..4afff74ed 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -120,6 +120,12 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe void RouteToWorker(const std::string& sessionId, const std::string& method, long long msgId, const std::string& message); + + // The runtime's effect of Network.clearBrowserCache and + // Network.setCacheDisabled on the HTTP module cache (HttpLoader.h). + // Socket thread. + void ClearModuleHttpCacheFromInspector(); + void SetFrontendCacheDisabled(bool cacheDisabled); void AnnounceWorkerTargets(); std::map workerTargets_; @@ -159,6 +165,9 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // memory location with the bitfields above, which the main thread // writes. std::atomic isConnected_; + // The connected frontend has the HTTP module cache disabled, holding one + // AddModuleHttpCacheInspectorDisable count. Guarded by connectionMutex_. + bool frontendCacheDisabled_ = false; // {N} specific helpers From 5aeb3d7a93962a581df542e33221c07fc88e6a8c Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 09:58:03 -0300 Subject: [PATCH 04/12] feat(runtime): honour Clear-Site-Data on HTTP module responses 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. --- docs/ns-builtin-modules.md | 11 +++ .../assets/app/tests/testEsmHttpLoader.js | 77 +++++++++++++++ .../java/com/tns/tests/ModuleTestServer.java | 9 ++ test-app/runtime/src/main/cpp/HttpLoader.cpp | 14 +++ .../main/java/com/tns/ModuleHttpCache.java | 99 ++++++++++++++++++- .../java/com/tns/OkHttpModuleFetcher.java | 29 ++++-- 6 files changed, 229 insertions(+), 10 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 534b806e0..faf56dab3 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1057,6 +1057,7 @@ The cache is **on** unless something turns it off: | `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 `moduleHttpCache` that is not a boolean logs a warning and leaves the cache @@ -1079,6 +1080,16 @@ 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. + 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 diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index f262f76a6..189cc0580 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1709,6 +1709,83 @@ describe("HTTP ESM Loader", function () { }); }); + describe("Clear-Site-Data", function () { + var localhostOrigin = origin.replace("127.0.0.1", "localhost"); + + function reimportFrom(base, target) { + var url = base + target; + nsModule.invalidateModules([url]); + return import(url); + } + + ['"cache"', '"*"'].forEach(function (types) { + it("with " + types + " clears its origin's entries and its own", function (done) { + requireOkHttp(); + var tag = runTag + "-" + (types === '"*"' ? "star" : "cache"); + var kept = "/esm/cached.mjs?k=csd-other-origin-" + tag; + var cleared = "/esm/cached.mjs?k=csd-same-origin-" + tag; + var carrier = "/esm/clear-site-data.mjs?k=csd-" + tag + + "&types=" + encodeURIComponent(types); + Promise.all([import(localhostOrigin + kept), import(origin + cleared)]).then(function () { + return import(origin + carrier); + }).then(function () { + return reimportFrom(origin, cleared); + }).then(function () { + return reimportFrom(localhostOrigin, kept); + }).then(function () { + return reimportFrom(origin, carrier); + }).then(function () { + return Promise.all([requestStats(cleared), requestStats(kept), + requestStats(carrier)]); + }).then(function (stats) { + expect(stats[0].count).toBe(2); + expect(stats[1].count).toBe(1); + expect(stats[2].count).toBe(2); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + + it("ignores an unquoted type", function (done) { + requireOkHttp(); + var target = "/esm/cached.mjs?k=csd-unquoted-" + runTag; + import(origin + target).then(function () { + return import(origin + "/esm/clear-site-data.mjs?k=csd-unquoted-" + runTag + + "&types=cache"); + }).then(function () { + return reimport(target); + }).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("is honoured on a platform-transport response", function (done) { + requireOkHttp(); + var target = "/esm/cached.mjs?k=csd-platform-" + runTag; + import(origin + target).then(function () { + nsModule.forcePlatformHttpTransport(true); + return import(origin + "/esm/clear-site-data.mjs?k=csd-platform-" + runTag); + }).then(function () { + nsModule.forcePlatformHttpTransport(false); + return reimport(target); + }).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(2); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + describe("in workers", function () { // Imports `url` in a new worker and resolves once that import // settled, terminating the worker. diff --git a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java index a5624537c..6f82650c5 100644 --- a/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java +++ b/test-app/app/src/main/java/com/tns/tests/ModuleTestServer.java @@ -310,6 +310,15 @@ private static void routeCounted(Socket socket, String path, String query, int o return; } + // As cached.mjs, plus `Clear-Site-Data: ` (default `"cache"`). + if ("/esm/clear-site-data.mjs".equals(path)) { + String types = decodedParam(query, "types="); + String body = "export const revision = " + ordinal + ";\n"; + respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8), "Cache-Control", "max-age=600", + "Clear-Site-Data", types == null ? "\"cache\"" : types); + return; + } + // `no-cache` with a validator: a conditional request that still holds // the current ETag gets a bodiless 304, so a revalidated module keeps // the revision of the response that was stored. diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index 82fe01b31..cec458923 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -980,6 +980,20 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool return false; } + // Clear-Site-Data, now that the stream is closed. A failure here costs + // only the clear, never the module. + if (isHttp) { + jclass clsCache = env.FindClass("com/tns/ModuleHttpCache"); + jmethodID onResponse = + clsCache ? raw->GetStaticMethodID(clsCache, "onPlatformResponse", + "(Ljava/net/HttpURLConnection;)V") + : nullptr; + if (onResponse) { + raw->CallStaticVoidMethod(clsCache, onResponse, conn); + } + raw->ExceptionClear(); + } + jmethodID getContentType = env.GetMethodID(clsConn, "getContentType", "()Ljava/lang/String;"); jstring jct = static_cast(env.CallObjectMethod(conn, getContentType)); diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java index 605dfa4f9..e29d631b9 100644 --- a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -5,10 +5,17 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Locale; +import java.util.Map; /** * The HTTP module loader's cache controls on the Java side: the startup state - * (app config + launch options) and wiping the cache. The live on/off switch + * (app config + launch options), wiping the cache, and the Clear-Site-Data + * response header. The live on/off switch * is native (HttpLoader.cpp), which reads {@link #isEnabledAtStartup()} once. * * Only the OkHttp transport has a cache. Wipes still clear the on-disk @@ -84,7 +91,7 @@ private static boolean consumeLaunchOption(String appName, String option) { /** Wipes the whole module cache. Durable once this returns. */ static void clear() throws IOException { synchronized (LOCK) { - if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache()) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(null)) { return; } File dir = Runtime.getModuleHttpCacheDir(); @@ -94,6 +101,94 @@ static void clear() throws IOException { } } + /** + * Clears what the cache holds for {@code url}'s origin, or the whole cache + * when there is no open cache to pick one origin's entries from. + */ + static void clearOrigin(String url) throws IOException { + String origin = originOf(url); + synchronized (LOCK) { + if (origin != null && OkHttpModuleFetcher.isAvailable() + && OkHttpModuleFetcher.clearClientCache(origin)) { + return; + } + clear(); + } + } + + /** + * Honours Clear-Site-Data on a module response. Call once the response body + * was read and closed: the cache commits an entry when its body closes, and + * the carrier's own entry must not survive, or every hit on it would clear + * the cache again. + */ + static void onClearSiteData(List headerValues, String responseUrl) { + if (!clearSiteDataClearsCache(headerValues)) { + return; + } + try { + clearOrigin(responseUrl); + } catch (IOException e) { + Log.w("JS", "HTTP modules: could not honour Clear-Site-Data from " + responseUrl + ": " + e); + } + } + + /** {@link #onClearSiteData} for the platform transport. */ + static void onPlatformResponse(HttpURLConnection connection) { + Map> fields = connection.getHeaderFields(); + if (fields == null) { + return; + } + for (Map.Entry> field : fields.entrySet()) { + if ("Clear-Site-Data".equalsIgnoreCase(field.getKey())) { + onClearSiteData(field.getValue(), connection.getURL().toString()); + } + } + } + + /** + * Whether Clear-Site-Data header lines name the {@code "cache"} or + * {@code "*"} type. Types are quoted strings; an unquoted one is ignored, + * as browsers do. + */ + static boolean clearSiteDataClearsCache(List values) { + if (values == null) { + return false; + } + for (String value : values) { + if (value == null) { + continue; + } + for (String type : value.split(",")) { + String trimmed = type.trim(); + if (trimmed.equals("\"cache\"") || trimmed.equals("\"*\"")) { + return true; + } + } + } + return false; + } + + /** "scheme://host:port", the port spelled out even when it is the default, or null. */ + static String originOf(String url) { + try { + URI uri = new URI(url); + String scheme = uri.getScheme(); + String host = uri.getHost(); + if (scheme == null || host == null) { + return null; + } + scheme = scheme.toLowerCase(Locale.ROOT); + int port = uri.getPort(); + if (port < 0) { + port = "https".equals(scheme) ? 443 : "http".equals(scheme) ? 80 : -1; + } + return scheme + "://" + host.toLowerCase(Locale.ROOT) + ":" + port; + } catch (URISyntaxException e) { + return null; + } + } + private static void deleteContents(File dir) throws IOException { File[] children = dir.listFiles(); if (children == null) { diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java index afa145beb..ae769b987 100644 --- a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -71,13 +71,14 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle } /** - * Empties the client's cache. False when there is no client yet, or no - * cache to clear through it; the caller then deletes the files itself. - * Call under {@link ModuleHttpCache#LOCK}. + * Empties the client's cache, or only its entries for {@code origin} + * (see {@link ModuleHttpCache#originOf}) when that is not null. False when + * there is no client yet, or no cache to clear through it; the caller then + * deletes the files itself. Call under {@link ModuleHttpCache#LOCK}. */ - static boolean clearClientCache() throws IOException { + static boolean clearClientCache(String origin) throws IOException { try { - return Client.clearCache(); + return Client.clearCache(origin); } catch (LinkageError e) { available = false; return false; @@ -122,14 +123,22 @@ private static void create(int timeoutMs, int maxIdleConnections) { clientTimeoutMs = timeoutMs; } - static boolean clearCache() throws IOException { + static boolean clearCache(String origin) throws IOException { okhttp3.Cache cache = client != null ? ((okhttp3.OkHttpClient) client).cache() : null; if (cache == null) { return false; } // Removing an entry deletes its files at once, so the wipe outlives // a process kill; the flush also persists the journal's record of it. - cache.evictAll(); + if (origin == null) { + cache.evictAll(); + } else { + for (java.util.Iterator urls = cache.urls(); urls.hasNext(); ) { + if (origin.equals(ModuleHttpCache.originOf(urls.next()))) { + urls.remove(); + } + } + } cache.flush(); return true; } @@ -154,6 +163,7 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle request.header("Cache-Control", "no-cache").header("Pragma", "no-cache"); } okhttp3.Response response = http.newCall(request.build()).execute(); + Result result; try { byte[] body; okhttp3.ResponseBody responseBody = response.body(); @@ -166,10 +176,13 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle body = null; } } - return new Result(response.code(), response.header("Content-Type"), body); + result = new Result(response.code(), response.header("Content-Type"), body); } finally { response.close(); } + ModuleHttpCache.onClearSiteData(response.headers("Clear-Site-Data"), + response.request().url().toString()); + return result; } } } From 5c843165c914ab5a92f8e0d18b4c2e788fc5a215 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:56:53 -0300 Subject: [PATCH 05/12] fix(http-cache): match Clear-Site-Data origins with OkHttp's own URL 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. --- .../assets/app/tests/testEsmHttpLoader.js | 63 ++++++++++++------- .../main/java/com/tns/ModuleHttpCache.java | 27 +------- .../java/com/tns/OkHttpModuleFetcher.java | 29 ++++++--- 3 files changed, 62 insertions(+), 57 deletions(-) diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 189cc0580..d4741617d 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1718,36 +1718,53 @@ describe("HTTP ESM Loader", function () { return import(url); } + // Caches `kept` from another origin and `cleared` from the + // carrier's, imports the carrier, then re-imports all three: + // only `cleared` and the carrier reach the server again. + function expectCarrierClearsItsOrigin(kept, cleared, carrier, done) { + Promise.all([import(localhostOrigin + kept), import(origin + cleared)]).then(function () { + return import(origin + carrier); + }).then(function () { + return reimportFrom(origin, cleared); + }).then(function () { + return reimportFrom(localhostOrigin, kept); + }).then(function () { + return reimportFrom(origin, carrier); + }).then(function () { + return Promise.all([requestStats(cleared), requestStats(kept), + requestStats(carrier)]); + }).then(function (stats) { + expect(stats[0].count).toBe(2); + expect(stats[1].count).toBe(1); + expect(stats[2].count).toBe(2); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + } + ['"cache"', '"*"'].forEach(function (types) { it("with " + types + " clears its origin's entries and its own", function (done) { requireOkHttp(); var tag = runTag + "-" + (types === '"*"' ? "star" : "cache"); - var kept = "/esm/cached.mjs?k=csd-other-origin-" + tag; - var cleared = "/esm/cached.mjs?k=csd-same-origin-" + tag; - var carrier = "/esm/clear-site-data.mjs?k=csd-" + tag + - "&types=" + encodeURIComponent(types); - Promise.all([import(localhostOrigin + kept), import(origin + cleared)]).then(function () { - return import(origin + carrier); - }).then(function () { - return reimportFrom(origin, cleared); - }).then(function () { - return reimportFrom(localhostOrigin, kept); - }).then(function () { - return reimportFrom(origin, carrier); - }).then(function () { - return Promise.all([requestStats(cleared), requestStats(kept), - requestStats(carrier)]); - }).then(function (stats) { - expect(stats[0].count).toBe(2); - expect(stats[1].count).toBe(1); - expect(stats[2].count).toBe(2); - done(); - }).catch(function (error) { - reportRejection(error, done); - }); + expectCarrierClearsItsOrigin("/esm/cached.mjs?k=csd-other-origin-" + tag, + "/esm/cached.mjs?k=csd-same-origin-" + tag, + "/esm/clear-site-data.mjs?k=csd-" + tag + + "&types=" + encodeURIComponent(types), + done); }); }); + // OkHttp keeps a raw | in a query, which java.net.URI rejects. + it("matches origins of URLs with a raw | in the query", function (done) { + requireOkHttp(); + var tag = runTag + "-pipe"; + expectCarrierClearsItsOrigin("/esm/cached.mjs?k=csd-pipe-other-origin|" + tag, + "/esm/cached.mjs?k=csd-pipe-same-origin|" + tag, + "/esm/clear-site-data.mjs?k=csd-pipe|" + tag, + done); + }); + it("ignores an unquoted type", function (done) { requireOkHttp(); var target = "/esm/cached.mjs?k=csd-unquoted-" + runTag; diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java index e29d631b9..f2d2dd75a 100644 --- a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -6,10 +6,7 @@ import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; -import java.net.URI; -import java.net.URISyntaxException; import java.util.List; -import java.util.Locale; import java.util.Map; /** @@ -106,10 +103,8 @@ static void clear() throws IOException { * when there is no open cache to pick one origin's entries from. */ static void clearOrigin(String url) throws IOException { - String origin = originOf(url); synchronized (LOCK) { - if (origin != null && OkHttpModuleFetcher.isAvailable() - && OkHttpModuleFetcher.clearClientCache(origin)) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(url)) { return; } clear(); @@ -169,26 +164,6 @@ static boolean clearSiteDataClearsCache(List values) { return false; } - /** "scheme://host:port", the port spelled out even when it is the default, or null. */ - static String originOf(String url) { - try { - URI uri = new URI(url); - String scheme = uri.getScheme(); - String host = uri.getHost(); - if (scheme == null || host == null) { - return null; - } - scheme = scheme.toLowerCase(Locale.ROOT); - int port = uri.getPort(); - if (port < 0) { - port = "https".equals(scheme) ? 443 : "http".equals(scheme) ? 80 : -1; - } - return scheme + "://" + host.toLowerCase(Locale.ROOT) + ":" + port; - } catch (URISyntaxException e) { - return null; - } - } - private static void deleteContents(File dir) throws IOException { File[] children = dir.listFiles(); if (children == null) { diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java index ae769b987..41d2281e5 100644 --- a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -71,14 +71,15 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle } /** - * Empties the client's cache, or only its entries for {@code origin} - * (see {@link ModuleHttpCache#originOf}) when that is not null. False when - * there is no client yet, or no cache to clear through it; the caller then - * deletes the files itself. Call under {@link ModuleHttpCache#LOCK}. + * Empties the client's cache, or only its entries with the same scheme, host + * and port as {@code sameOriginAs} when that is not null. False when there is + * no client yet, no cache to clear through it, or {@code sameOriginAs} is not + * an HTTP URL; the caller then deletes the files itself. Call under + * {@link ModuleHttpCache#LOCK}. */ - static boolean clearClientCache(String origin) throws IOException { + static boolean clearClientCache(String sameOriginAs) throws IOException { try { - return Client.clearCache(origin); + return Client.clearCache(sameOriginAs); } catch (LinkageError e) { available = false; return false; @@ -123,18 +124,30 @@ private static void create(int timeoutMs, int maxIdleConnections) { clientTimeoutMs = timeoutMs; } - static boolean clearCache(String origin) throws IOException { + static boolean clearCache(String sameOriginAs) throws IOException { okhttp3.Cache cache = client != null ? ((okhttp3.OkHttpClient) client).cache() : null; if (cache == null) { return false; } + // Cache keys are HttpUrl strings, which can hold characters + // java.net.URI rejects, such as a raw | in the query. + okhttp3.HttpUrl origin = null; + if (sameOriginAs != null) { + origin = okhttp3.HttpUrl.parse(sameOriginAs); + if (origin == null) { + return false; + } + } // Removing an entry deletes its files at once, so the wipe outlives // a process kill; the flush also persists the journal's record of it. if (origin == null) { cache.evictAll(); } else { for (java.util.Iterator urls = cache.urls(); urls.hasNext(); ) { - if (origin.equals(ModuleHttpCache.originOf(urls.next()))) { + okhttp3.HttpUrl entry = okhttp3.HttpUrl.parse(urls.next()); + if (entry != null && entry.port() == origin.port() + && entry.scheme().equals(origin.scheme()) + && entry.host().equals(origin.host())) { urls.remove(); } } From ee6feaf80efd95ebbac544b4f5ce99fd97ff5832 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:56:59 -0300 Subject: [PATCH 06/12] fix(http-cache): keep fetches off the cache lock and survive a failed 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. --- .../main/java/com/tns/ModuleHttpCache.java | 6 ++--- .../java/com/tns/OkHttpModuleFetcher.java | 23 ++++++++++++------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java index f2d2dd75a..24e895265 100644 --- a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -12,8 +12,8 @@ /** * The HTTP module loader's cache controls on the Java side: the startup state * (app config + launch options), wiping the cache, and the Clear-Site-Data - * response header. The live on/off switch - * is native (HttpLoader.cpp), which reads {@link #isEnabledAtStartup()} once. + * response header. The live on/off switch is native (HttpLoader.cpp), which + * reads {@link #isEnabledAtStartup()} once. * * Only the OkHttp transport has a cache. Wipes still clear the on-disk * directory when OkHttp is absent or its client was never created, since an @@ -123,7 +123,7 @@ static void onClearSiteData(List headerValues, String responseUrl) { } try { clearOrigin(responseUrl); - } catch (IOException e) { + } catch (IOException | RuntimeException e) { Log.w("JS", "HTTP modules: could not honour Clear-Site-Data from " + responseUrl + ": " + e); } } diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java index 41d2281e5..5d14665e1 100644 --- a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -90,20 +90,26 @@ private static final class Client { // An okhttp3.OkHttpClient, typed Object to keep okhttp3 out of member // signatures. Never an app-configured client: its interceptors, cache // or pool would change what a module fetch does. - private static Object client; + // Created under ModuleHttpCache.LOCK and published last, after the + // fields below, so a fetch that reads it non-null needs no lock. + private static volatile Object client; // The same client without the cache, sharing its pool: a fetch with the // cache off. A per-request no-store directive would also keep a response // out of the cache, but it would put no-store on the wire. - private static Object uncachedClient; + private static volatile Object uncachedClient; private static int clientTimeoutMs; private static okhttp3.OkHttpClient base(int timeoutMs, int maxIdleConnections, boolean useCache) { - synchronized (ModuleHttpCache.LOCK) { - if (client == null) { - create(timeoutMs, maxIdleConnections); + Object created = client; + if (created == null) { + synchronized (ModuleHttpCache.LOCK) { + if (client == null) { + create(timeoutMs, maxIdleConnections); + } + created = client; } - return (okhttp3.OkHttpClient) (useCache ? client : uncachedClient); } + return (okhttp3.OkHttpClient) (useCache ? created : uncachedClient); } private static void create(int timeoutMs, int maxIdleConnections) { @@ -120,12 +126,13 @@ private static void create(int timeoutMs, int maxIdleConnections) { } okhttp3.OkHttpClient built = builder.build(); uncachedClient = built.newBuilder().cache(null).build(); - client = built; clientTimeoutMs = timeoutMs; + client = built; } static boolean clearCache(String sameOriginAs) throws IOException { - okhttp3.Cache cache = client != null ? ((okhttp3.OkHttpClient) client).cache() : null; + Object created = client; + okhttp3.Cache cache = created != null ? ((okhttp3.OkHttpClient) created).cache() : null; if (cache == null) { return false; } From e89c40c4f817fe64fb6603dc43b49272847d77fe Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:58:16 -0300 Subject: [PATCH 07/12] fix(inspector): tie Network.setCacheDisabled to the websocket that sent 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_. --- .../java/com/tns/AndroidJsV8Inspector.java | 8 +++-- .../src/main/cpp/JsV8InspectorClient.cpp | 35 +++++++++++++------ .../src/main/cpp/JsV8InspectorClient.h | 28 ++++++++++----- .../main/cpp/com_tns_AndroidJsV8Inspector.cpp | 12 +++++-- 4 files changed, 59 insertions(+), 24 deletions(-) diff --git a/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java b/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java index fd1ef7329..d5103a9f5 100644 --- a/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java +++ b/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java @@ -37,7 +37,9 @@ class AndroidJsV8Inspector { protected native final void dispatchMessage(String message); - private native String handleMessageOnSocketThread(String message); + private native String handleMessageOnSocketThread(String message, Object socket); + + private static native void socketClosed(Object socket); private Handler mainHandler; @@ -279,6 +281,7 @@ protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boo Log.d("V8Inspector", "onClose"); } + socketClosed(JsV8InspectorWebSocket.this); mainHandler.post(new Runnable() { @Override public void run() { @@ -303,7 +306,7 @@ protected void onMessage(final NanoWSD.WebSocketFrame message) { // too. Debugger.pause schedules a V8 interrupt and still flows // through the queue. A null return means "not handled" (queue it); // an empty string means handled with nothing left to send. - String fastPathResponse = handleMessageOnSocketThread(message.getTextPayload()); + String fastPathResponse = handleMessageOnSocketThread(message.getTextPayload(), JsV8InspectorWebSocket.this); if (fastPathResponse != null) { if (!fastPathResponse.isEmpty()) { try { @@ -378,6 +381,7 @@ protected void onException(IOException exception) { exception.printStackTrace(); } } + socketClosed(JsV8InspectorWebSocket.this); disconnect(); } } diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index fb7470ee0..7f2747e13 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -394,11 +394,6 @@ void JsV8InspectorClient::disconnect() { { std::lock_guard lock(connectionMutex_); - // A client's Network.setCacheDisabled ends with its connection. - if (frontendCacheDisabled_) { - frontendCacheDisabled_ = false; - AddModuleHttpCacheInspectorDisable(-1); - } if (connection_ == nullptr) { return; } @@ -554,7 +549,8 @@ void JsV8InspectorClient::doDispatchMessage(const std::string& message) { // method handling never runs, and a worker must stay debuggable while the // main isolate is paused (and vice versa). None of this touches V8 except // the thread-safe RequestInterrupt. -bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message, std::string& response) { +bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message, jobject socket, + std::string& response) { auto parsed = json::parse(message, nullptr, false); if (parsed.is_discarded() || !parsed.is_object()) { return false; @@ -729,7 +725,7 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message if (method == "Network.clearBrowserCache") { ClearModuleHttpCacheFromInspector(); } else if (std::optional cacheDisabled = SetCacheDisabledParam(parsed)) { - SetFrontendCacheDisabled(*cacheDisabled); + SetCacheDisabledBy(socket, *cacheDisabled); } if (sessionId.empty()) { return false; @@ -778,13 +774,30 @@ void JsV8InspectorClient::ClearModuleHttpCacheFromInspector() { } } -void JsV8InspectorClient::SetFrontendCacheDisabled(bool cacheDisabled) { +void JsV8InspectorClient::SetCacheDisabledBy(jobject socket, bool cacheDisabled) { + if (socket == nullptr) { + return; + } + JEnv env; std::lock_guard lock(connectionMutex_); - if (connection_ == nullptr || cacheDisabled == frontendCacheDisabled_) { + auto holder = std::find_if(cacheDisabledBy_.begin(), cacheDisabledBy_.end(), + [&](jobject held) { return env.isSameObject(held, socket); }); + const bool holds = holder != cacheDisabledBy_.end(); + if (cacheDisabled == holds) { return; } - frontendCacheDisabled_ = cacheDisabled; - AddModuleHttpCacheInspectorDisable(cacheDisabled ? 1 : -1); + if (cacheDisabled) { + cacheDisabledBy_.push_back(env.NewGlobalRef(socket)); + AddModuleHttpCacheInspectorDisable(1); + } else { + env.DeleteGlobalRef(*holder); + cacheDisabledBy_.erase(holder); + AddModuleHttpCacheInspectorDisable(-1); + } +} + +void JsV8InspectorClient::SocketClosed(jobject socket) { + SetCacheDisabledBy(socket, false); } void JsV8InspectorClient::RouteToWorker(const std::string& sessionId, const std::string& method, diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index 4afff74ed..01f6230da 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -48,11 +48,18 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe void UnregisterWorkerTarget(int workerId); void SchedulePauseInWorker(int workerId); - // Runs on the websocket read thread. Returns true when the message was - // handled there (response, possibly empty when replies were already - // sent or none is needed, goes back to the socket); false routes the - // message through the normal main-thread dispatch queue. - bool handleMessageOnSocketThread(const std::string& message, std::string& response); + // Runs on the websocket read thread of `socket`, the websocket the + // message arrived on. Returns true when the message was handled there + // (response, possibly empty when replies were already sent or none is + // needed, goes back to the socket); false routes the message through + // the normal main-thread dispatch queue. + bool handleMessageOnSocketThread(const std::string& message, jobject socket, + std::string& response); + + // On `socket`'s read thread, once it closed or failed: ends what that + // frontend held. Takes only connectionMutex_, so it never waits for a + // paused or busy isolate. + void SocketClosed(jobject socket); void registerModules(); @@ -125,7 +132,7 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // Network.setCacheDisabled on the HTTP module cache (HttpLoader.h). // Socket thread. void ClearModuleHttpCacheFromInspector(); - void SetFrontendCacheDisabled(bool cacheDisabled); + void SetCacheDisabledBy(jobject socket, bool cacheDisabled); void AnnounceWorkerTargets(); std::map workerTargets_; @@ -165,9 +172,12 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // memory location with the bitfields above, which the main thread // writes. std::atomic isConnected_; - // The connected frontend has the HTTP module cache disabled, holding one - // AddModuleHttpCacheInspectorDisable count. Guarded by connectionMutex_. - bool frontendCacheDisabled_ = false; + // Global refs to the websockets whose frontend has the HTTP module cache + // disabled, each holding one AddModuleHttpCacheInspectorDisable count + // until it re-enables it or its socket closes. A replaced frontend's + // socket can outlive connection_, so this is not tied to it. Guarded by + // connectionMutex_. + std::vector cacheDisabledBy_; // {N} specific helpers diff --git a/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp b/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp index 090a8db80..2d6b4bb6a 100644 --- a/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp @@ -24,16 +24,24 @@ JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_disconnect(JNIEnv* e JsV8InspectorClient::GetInstance()->disconnect(); } +JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_socketClosed(JNIEnv* env, jclass clazz, jobject socket) { + try { + JsV8InspectorClient::GetInstance()->SocketClosed(socket); + } catch (...) { + // must never propagate a native exception into the websocket thread + } +} + JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_dispatchMessage(JNIEnv* env, jobject instance, jstring jMessage) { std::string message = ArgConverter::jstringToString(jMessage); JsV8InspectorClient::GetInstance()->dispatchMessage(message); } -JNIEXPORT extern "C" jstring Java_com_tns_AndroidJsV8Inspector_handleMessageOnSocketThread(JNIEnv* env, jobject instance, jstring jMessage) { +JNIEXPORT extern "C" jstring Java_com_tns_AndroidJsV8Inspector_handleMessageOnSocketThread(JNIEnv* env, jobject instance, jstring jMessage, jobject socket) { try { std::string message = ArgConverter::jstringToString(jMessage); std::string response; - if (JsV8InspectorClient::GetInstance()->handleMessageOnSocketThread(message, response)) { + if (JsV8InspectorClient::GetInstance()->handleMessageOnSocketThread(message, socket, response)) { // Handled; an empty string means any replies were already sent. return env->NewStringUTF(response.c_str()); } From 30952bebca1c3a6a5cae9e51a37ff39f90069d49 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:58:41 -0300 Subject: [PATCH 08/12] fix(inspector): skip a closed socket's disconnect once a newer frontend 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. --- .../java/com/tns/AndroidJsV8Inspector.java | 6 +++--- .../src/main/cpp/JsV8InspectorClient.cpp | 19 ++++++++++++++++--- .../src/main/cpp/JsV8InspectorClient.h | 4 +++- .../main/cpp/com_tns_AndroidJsV8Inspector.cpp | 4 ++-- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java b/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java index d5103a9f5..b1efe1126 100644 --- a/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java +++ b/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java @@ -33,7 +33,7 @@ class AndroidJsV8Inspector { private native void scheduleBreak(); - protected static native void disconnect(); + protected static native void disconnect(Object socket); protected native final void dispatchMessage(String message); @@ -288,7 +288,7 @@ public void run() { if (currentRuntimeLogger.isEnabled()) { Log.d("V8Inspector", "Disconnecting"); } - disconnect(); + disconnect(JsV8InspectorWebSocket.this); } }); } @@ -382,7 +382,7 @@ protected void onException(IOException exception) { } } socketClosed(JsV8InspectorWebSocket.this); - disconnect(); + disconnect(JsV8InspectorWebSocket.this); } } } diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 7f2747e13..360b9f794 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -367,7 +367,21 @@ void JsV8InspectorClient::createInspectorSession() { v8_inspector::V8Inspector::kFullyTrusted); } -void JsV8InspectorClient::disconnect() { +void JsV8InspectorClient::disconnect(jobject closingSocket) { + JEnv env; + // A socket's close is posted to the main thread, so it can run after a + // newer frontend connected; that connect already tore the old one down. + auto replaced = [&]() { + return closingSocket != nullptr && connection_ != nullptr && + !env.isSameObject(connection_, closingSocket); + }; + { + std::lock_guard lock(connectionMutex_); + if (replaced()) { + return; + } + } + { // Streams only have meaning to the frontend that opened them; drop any // the old connection never read to the end (or never IO.close-d). @@ -394,11 +408,10 @@ void JsV8InspectorClient::disconnect() { { std::lock_guard lock(connectionMutex_); - if (connection_ == nullptr) { + if (connection_ == nullptr || replaced()) { return; } - JEnv env; env.DeleteGlobalRef(connection_); connection_ = nullptr; isConnected_ = false; diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index 01f6230da..d5ea15a32 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -29,7 +29,9 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe void init(); void connect(jobject connection); void scheduleBreak(); - void disconnect(); + // `closingSocket` null tears down whatever frontend is connected; + // otherwise only that websocket's, if it is still the connected one. + void disconnect(jobject closingSocket = nullptr); void dispatchMessage(const std::string& message); // Any thread. Rewrites source map urls and writes to the frontend diff --git a/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp b/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp index 2d6b4bb6a..5b4bc9352 100644 --- a/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp @@ -20,8 +20,8 @@ JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_scheduleBreak(JNIEnv JsV8InspectorClient::GetInstance()->scheduleBreak(); } -JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_disconnect(JNIEnv* env, jobject instance) { - JsV8InspectorClient::GetInstance()->disconnect(); +JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_disconnect(JNIEnv* env, jclass clazz, jobject socket) { + JsV8InspectorClient::GetInstance()->disconnect(socket); } JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_socketClosed(JNIEnv* env, jclass clazz, jobject socket) { From f00182f7a14b467484d0cbfb230fd6bc553a2208 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:59:21 -0300 Subject: [PATCH 09/12] fix(http-cache): match iOS on throwing cache handlers, unknown sessions 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. --- .../src/main/cpp/JsV8InspectorClient.cpp | 83 ++++++++++++++++--- .../src/main/cpp/JsV8InspectorClient.h | 3 +- .../src/main/java/com/tns/AppConfig.java | 3 + 3 files changed, 76 insertions(+), 13 deletions(-) diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 360b9f794..b07a4ccac 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -91,10 +91,11 @@ json NetworkCacheReply(long long id, const std::string& method, const json& mess return {{"id", id}, {"result", json::object()}}; } -// The runtime's reply to `message` when it is a Network.setCacheDisabled or -// Network.clearBrowserCache command for the main session. -std::optional MainSessionNetworkCacheReply(const std::string& message) { - if (message.find("Network.") == std::string::npos) { +// `message` parsed, when it is a Network.setCacheDisabled or +// Network.clearBrowserCache command with an id for the main session. +std::optional ParseMainSessionNetworkCacheCommand(const std::string& message) { + if (message.find("Network.setCacheDisabled") == std::string::npos && + message.find("Network.clearBrowserCache") == std::string::npos) { return std::nullopt; } auto parsed = json::parse(message, nullptr, false); @@ -105,8 +106,24 @@ std::optional MainSessionNetworkCacheReply(const std::string& messa !parsed["sessionId"].get().empty())) { return std::nullopt; } - return JsonDump(NetworkCacheReply(parsed["id"].get(), - parsed["method"].get(), parsed)); + return parsed; +} + +// The runtime's reply to `message` when it is a main-session +// Network.setCacheDisabled or Network.clearBrowserCache command. +std::optional MainSessionNetworkCacheReply(const std::string& message) { + std::optional parsed = ParseMainSessionNetworkCacheCommand(message); + if (!parsed) { + return std::nullopt; + } + return JsonDump(NetworkCacheReply((*parsed)["id"].get(), + (*parsed)["method"].get(), *parsed)); +} + +json SessionNotFoundReply(long long id, const std::string& sessionId) { + return {{"id", id}, + {"sessionId", sessionId}, + {"error", {{"code", -32001}, {"message", "Session not found"}}}}; } // Target.attachedToTarget event announcing a worker as a child target. @@ -474,7 +491,9 @@ void JsV8InspectorClient::dispatchMessage(const std::string& message) { Local domainMethodFunc = GetDebuggerFunctionFromObject(context, argObject, domainDebugger); Local result; - success = this->CallDomainHandlerFunction(context, domainMethodFunc, argObject, domainDebugger, result); + std::optional thrownMessage; + success = this->CallDomainHandlerFunction(context, domainMethodFunc, argObject, + domainDebugger, result, thrownMessage); if(success) { auto requestId = arg.As()->Get(context, tns::ArgConverter::ConvertToV8String(isolate_, "id")).ToLocalChecked(); @@ -490,6 +509,17 @@ void JsV8InspectorClient::dispatchMessage(const std::string& message) { } return; } + + // The handler owns these commands, so the runtime's own reply in + // doDispatchMessage must not answer them as well. + if (thrownMessage) { + if (std::optional command = ParseMainSessionNetworkCacheCommand(message)) { + json error = {{"id", (*command)["id"]}, + {"error", {{"code", -32000}, {"message", *thrownMessage}}}}; + this->SendRawToFrontend(JsonDump(error)); + return; + } + } } @@ -735,6 +765,20 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message // Network domain handler, if one is registered, for the response. Workers // have no JS domain handlers, so a worker session is answered here. if (IsNetworkCacheMethod(method)) { + if (!sessionId.empty()) { + bool knownSession; + { + std::lock_guard lock(workerTargetsMutex_); + knownSession = workerTargets_.count(sessionId) != 0; + } + if (!knownSession) { + if (msgId >= 0) { + json error = SessionNotFoundReply(msgId, sessionId); + response = JsonDump(error); + } + return true; + } + } if (method == "Network.clearBrowserCache") { ClearModuleHttpCacheFromInspector(); } else if (std::optional cacheDisabled = SetCacheDisabledParam(parsed)) { @@ -825,10 +869,7 @@ void JsV8InspectorClient::RouteToWorker(const std::string& sessionId, const std: // The worker died (or never existed): answer commands so the // frontend does not wait forever. if (msgId >= 0) { - json error = {{"id", msgId}, - {"sessionId", sessionId}, - {"error", {{"code", -32001}, {"message", "Session not found"}}}}; - errorPayload = JsonDump(error); + errorPayload = JsonDump(SessionNotFoundReply(msgId, sessionId)); } } else { // The lock keeps the client alive against a concurrent @@ -1372,7 +1413,7 @@ void JsV8InspectorClient::InspectorIsConnectedGetterCallback(v8::Local JsV8InspectorClient::instance{nullptr}; -bool JsV8InspectorClient::CallDomainHandlerFunction(Local context, Local domainMethodFunc, const Local& arg, Local& domainDebugger, Local& result) { +bool JsV8InspectorClient::CallDomainHandlerFunction(Local context, Local domainMethodFunc, const Local& arg, Local& domainDebugger, Local& result, std::optional& thrownMessage) { if(domainMethodFunc.IsEmpty() || !domainMethodFunc->IsFunction()) { return false; } @@ -1405,6 +1446,24 @@ bool JsV8InspectorClient::CallDomainHandlerFunction(Local context, Loca // log any other errors - they are caught, but still make them visible to the user. // tns::LogError(isolate, tc); + // The error's message, as Chromium reports a failed command; the whole + // text for anything else that was thrown. + if (!tc.HasTerminated()) { + Local exception = tc.Exception(); + TryCatch messageTc(isolate); + Local message; + if (exception->IsNativeError() && + exception.As()->Get(context, tns::ArgConverter::ConvertToV8String(isolate, "message")).ToLocal(&message) && + message->IsString()) { + thrownMessage = tns::ArgConverter::ToString(isolate, message); + } else if (exception->ToString(context).ToLocal(&message)) { + thrownMessage = tns::ArgConverter::ToString(isolate, message); + } + if (!thrownMessage) { + thrownMessage = std::string(); + } + } + return false; } diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index d5ea15a32..3ed0b973f 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -187,7 +187,8 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe v8::Local domainMethodFunc, const v8::Local& arg, v8::Local& domainDebugger, - v8::Local& result); + v8::Local& result, + std::optional& thrownMessage); std::string GetReturnMessageFromDomainHandlerResult(const v8::Local& result, const v8::Local& requestId); }; } diff --git a/test-app/runtime/src/main/java/com/tns/AppConfig.java b/test-app/runtime/src/main/java/com/tns/AppConfig.java index d48a66653..67f77b302 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -85,6 +85,9 @@ public AppConfig(File appDir) { Object value = rootObject.opt(ModuleHttpCacheKey); if (value instanceof Boolean) { moduleHttpCache = (Boolean) value; + } else if (value instanceof Number) { + // As iOS reads it: 0 is false, any other number true. + moduleHttpCache = ((Number) value).doubleValue() != 0; } else { Log.w("JS", String.format("moduleHttpCache must be a boolean, not %s; the HTTP module cache stays enabled.", JSONObject.quote(String.valueOf(value)))); } From 9715517d76691b48acba6e2388febb8d07c381bf Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 11:01:07 -0300 Subject: [PATCH 10/12] fix(http-cache): clear the exception a failed ModuleHttpCache lookup 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. --- test-app/runtime/src/main/cpp/HttpLoader.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index cec458923..d9ceddf7d 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -321,12 +321,15 @@ static void InitializeModuleHttpCacheSetting() { JEnv env; jclass cls = env.FindClass("com/tns/ModuleHttpCache"); if (cls == nullptr) { + env.ExceptionClear(); return; } jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); - if (mid != nullptr) { - s_moduleHttpCacheSetting.store(env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE); + if (mid == nullptr) { + env.ExceptionClear(); + return; } + s_moduleHttpCacheSetting.store(env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE); } catch (...) { // Enabled. } @@ -351,6 +354,10 @@ void AddModuleHttpCacheInspectorDisable(int delta) { void ClearModuleHttpCache() { JEnv env; jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { + // Takes the ClassNotFoundException FindClass left pending. + throw NativeScriptException(env); + } jmethodID mid = env.GetStaticMethodID(cls, "clear", "()V"); env.CallStaticVoidMethod(cls, mid); } From 02e2b72747a304672a8306004236fc67d708d945 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 11:01:07 -0300 Subject: [PATCH 11/12] test(http-cache): tighten the cache-control specs and cover a worker 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. --- .../main/assets/app/tests/httpCacheWorker.js | 22 ++++ .../assets/app/tests/testEsmHttpLoader.js | 123 +++++++++++------- 2 files changed, 98 insertions(+), 47 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/httpCacheWorker.js diff --git a/test-app/app/src/main/assets/app/tests/httpCacheWorker.js b/test-app/app/src/main/assets/app/tests/httpCacheWorker.js new file mode 100644 index 000000000..6a7ef95cd --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/httpCacheWorker.js @@ -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); +}; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index d4741617d..180aaffcf 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1664,48 +1664,53 @@ describe("HTTP ESM Loader", function () { }); }); - it("clears without throwing when the platform transport is in use", function () { - nsModule.forcePlatformHttpTransport(true); - expect(function () { - nsModule.clearHttpCache(); - }).not.toThrow(); + it("reaches the origin every time and stores nothing while off", function (done) { + requireOkHttp(); + var target = "/esm/cached.mjs?k=off-" + runTag; + var revisions = []; + nsModule.setHttpCacheEnabled(false); + import(origin + target).then(function (m) { + revisions.push(m.revision); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.cacheControl).toBe("no-cache"); + expect(stats.pragma).toBe("no-cache"); + // Nothing was stored while off, so the next fetch with + // the cache back on reaches the origin too. + nsModule.setHttpCacheEnabled(true); + return reimport(target); + }).then(function (revision) { + revisions.push(revision); + return requestStats(target); + }).then(function (stats) { + expect(revisions).toEqual([1, 2, 3]); + expect(stats.count).toBe(3); + expect(stats.cacheControl).toBeNull(); + expect(stats.pragma).toBeNull(); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); }); - ["okhttp", "platform"].forEach(function (transport) { - it("reaches the origin every time and stores nothing while off, over " + transport, function (done) { - if (transport === "okhttp") { - requireOkHttp(); - } - nsModule.forcePlatformHttpTransport(transport === "platform"); - var target = "/esm/cached.mjs?k=off-" + transport + "-" + runTag; - var revisions = []; - nsModule.setHttpCacheEnabled(false); - import(origin + target).then(function (m) { - revisions.push(m.revision); - return reimport(target); - }).then(function (revision) { - revisions.push(revision); - return requestStats(target); - }).then(function (stats) { - expect(stats.count).toBe(2); - expect(stats.cacheControl).toBe("no-cache"); - expect(stats.pragma).toBe("no-cache"); - // Nothing was stored while off, so the next fetch with - // the cache back on reaches the origin too. - nsModule.setHttpCacheEnabled(true); - return reimport(target); - }).then(function (revision) { - revisions.push(revision); - return requestStats(target); - }).then(function (stats) { - expect(revisions).toEqual([1, 2, 3]); - expect(stats.count).toBe(3); - expect(stats.cacheControl).toBeNull(); - expect(stats.pragma).toBeNull(); - done(); - }).catch(function (error) { - reportRejection(error, done); - }); + // The platform transport has no cache; a cache on the way may. + it("sends no-cache directives while off, over the platform transport", function (done) { + nsModule.forcePlatformHttpTransport(true); + nsModule.setHttpCacheEnabled(false); + var target = "/esm/cached.mjs?k=off-platform-" + runTag; + import(origin + target).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(1); + expect(stats.cacheControl).toBe("no-cache"); + expect(stats.pragma).toBe("no-cache"); + done(); + }).catch(function (error) { + reportRejection(error, done); }); }); @@ -1804,25 +1809,31 @@ describe("HTTP ESM Loader", function () { }); describe("in workers", function () { - // Imports `url` in a new worker and resolves once that import - // settled, terminating the worker. - function importInWorker(url) { + // Sends `request` (see httpCacheWorker.js) to a new worker and + // settles with its answer, terminating the worker. + function askWorker(request) { return new Promise(function (resolve, reject) { - var worker = new Worker("./httpImportSettleWorker.js"); + var worker = new Worker("./httpCacheWorker.js"); worker.onmessage = function (msg) { - if (msg.data === "settled") { - worker.terminate(); + worker.terminate(); + if (msg.data.ok) { resolve(); + } else { + reject(new Error("in the worker: " + msg.data.error)); } }; worker.onerror = function (error) { worker.terminate(); reject(error); }; - worker.postMessage(url); + worker.postMessage(request); }); } + function importInWorker(url) { + return askWorker({ import: url }); + } + it("share the main isolate's cache", function (done) { requireOkHttp(); var target = "/esm/cached.mjs?k=worker-shared-" + runTag; @@ -1838,6 +1849,24 @@ describe("HTTP ESM Loader", function () { }); }); + it("turn the switch off for the main isolate too", function (done) { + var target = "/esm/cached.mjs?k=worker-switch-" + runTag; + import(origin + target).then(function () { + return askWorker({ setHttpCacheEnabled: false }); + }).then(function () { + return reimport(target); + }).then(function () { + return requestStats(target); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.cacheControl).toBe("no-cache"); + expect(stats.pragma).toBe("no-cache"); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + it("see the switch the main isolate turned off", function (done) { var target = "/esm/cached.mjs?k=worker-off-" + runTag; import(origin + target).then(function () { From 908fc2d03066484ca8502839e544702c7e239749 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 11:01:07 -0300 Subject: [PATCH 12/12] docs(http-cache): Clear-Site-Data limits, numeric config, inspector errors, 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. --- docs/ns-builtin-modules.md | 39 +++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index faf56dab3..b4112c60f 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -993,11 +993,11 @@ not the raw header. ### HTTP caching -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: +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` @@ -1036,6 +1036,7 @@ 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. @@ -1059,11 +1060,12 @@ The cache is **on** unless something turns it off: | 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 `moduleHttpCache` 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. +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 @@ -1088,7 +1090,9 @@ 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. +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 @@ -1099,11 +1103,14 @@ 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 +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. +(`-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 @@ -1118,7 +1125,9 @@ adb shell am start -n / 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. Only the app's default +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.