diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 641818f59..b4112c60f 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,11 +993,11 @@ not the raw header. ### HTTP caching -The loader fetches modules the way a browser fetches module scripts: the -request carries no cache directives of its own (no `Cache-Control`, no -`Pragma`), the URL is requested exactly as resolved, and connections are -persistent. Whether a stored response may answer a request is decided by the -**response** headers, so a dev server must send: +The loader fetches modules the way a browser fetches module scripts: while +the cache is on, the request carries no cache directives of its own (no +`Cache-Control`, no `Pragma`), the URL is requested exactly as resolved, and +connections are persistent. Whether a stored response may answer a request is +decided by the **response** headers, so a dev server must send: - `Cache-Control: no-cache` (ideally with an `ETag` or `Last-Modified` validator, so an unchanged module costs a `304`) or `Cache-Control: no-store` @@ -1033,10 +1036,102 @@ remain: burst of fetches fewer of them are reused than with OkHttp. - OkHttp negotiates HTTP/2 with https servers that offer it, and then runs concurrent fetches as streams on one connection. + The OkHttp cache can answer a fresh response without a request, even after an app restart, and revalidates a stored response with its validator. The synchronous fallback fetch uses the same transport as the graph walk. +#### Turning the cache off and clearing it + +These controls act on the cache the module loader keeps for `http(s)` modules +and nothing else: never on an HTTP cache the app uses for its own requests, +and never on V8's code cache. + +The cache is **on** unless something turns it off: + +| control | effect | +|---|---| +| app config `"moduleHttpCache": false` (top level, next to `security`) | the process starts with the cache off | +| launch option `--nativescript-no-module-cache` | this launch starts with the cache off | +| launch option `--nativescript-clear-module-cache` | wipes the cache before the launch's first fetch | +| `setHttpCacheEnabled(enabled)` from `ns:module` | turns it on or off from then on | +| `clearHttpCache()` from `ns:module` | wipes it | +| inspector `Network.setCacheDisabled {cacheDisabled: true}` | turns it off while that client stays connected | +| inspector `Network.clearBrowserCache` | wipes it | +| response header `Clear-Site-Data: "cache"` (or `"*"`) on a module response | clears what the cache holds for that response's origin | + +The app config and the launch options are read once per process, at startup. +A numeric `moduleHttpCache` counts as `false` when it is `0` and as `true` +otherwise; any other value that is not a boolean logs a warning and leaves the +cache on. The process starts with the cache off when either the app config or +the launch option says so; `setHttpCacheEnabled` overrides both from then on. +`setHttpCacheEnabled` and `clearHttpCache` exist in debug and release builds. + +While the cache is off, a module fetch neither reads from nor writes to it, +and its request carries `Cache-Control: no-cache` and `Pragma: no-cache` (what +Fetch's `no-store` mode sends) on either transport, so a cache between the app +and the server revalidates too. The switch is process-wide: the main isolate +and every worker share it, the graph walk and the synchronous fallback fetch +alike. Each fetch reads it when it is issued; fetches already in flight keep +the value they started with. + +`clearHttpCache()` empties the cache before it returns, durably: the next +fetch reaches the origin, and so does the first fetch after the process is +killed right after the call. Without OkHttp, or before the loader's OkHttp +client exists, it deletes the cache directory's contents, so it also clears +what an earlier run stored. It does not touch the module registry: a module +already loaded stays loaded until `invalidateModules` evicts it. + +A module response whose `Clear-Site-Data` header names the `"cache"` or `"*"` +type clears the cache's entries for the response's origin (its final URL's, +after redirects) before the loader receives the response. The types are +quoted strings, and an unquoted one is ignored, as in browsers. Plain `http` +origins count, since dev servers use them. The response's own entry goes too, +so a cacheable carrier does not clear the cache again on every cache hit. On +Android the cache can clear one origin only while the loader's OkHttp client +is open; otherwise (no OkHttp, or the platform transport fetched first) the +header clears the whole cache directory. Only the final response's header is +read, never one on a redirect, and an entry still being written when the +header arrives, such as a same-origin module fetched concurrently, survives. + +The cache is in effect when the setting above is on **and** no connected +inspector client has it disabled, so DevTools' "Disable cache" turns it off +without changing the setting, and its effect ends when that client +disconnects; with several clients it stays off while any of them has it +disabled. The runtime applies both inspector commands first, from any +session and even while paused, then passes a main-session command on to the +JS `Network` domain handler registered with `__registerDomainDispatcher` +(@nativescript/core registers one), which answers it. A command no JS handler +answers, a worker session's command, and any command arriving while paused +get `{}` from the runtime: every command gets exactly one response. A JS +handler that throws makes that response an error (`-32000`) with the thrown +message, and a command for a worker session that does not exist gets the +`Session not found` error (`-32001`) and changes nothing. A +`Network.setCacheDisabled` without a boolean `cacheDisabled` changes nothing, +and where the runtime answers it, the answer is an invalid-parameters error +(`-32602`). On Android the inspector serves one client at a time and exists +only in debuggable apps. + +On Android a launch option is a file in `/data/local/tmp`, named after the +application id, that the CLI creates **empty** before it starts the app, the +way it requests `--debug-brk` with `-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. The files the CLI +creates there are writable by every app on the device, so another app can +empty one to re-arm its option for the next launch. Only the app's default +process reads the options, in debug builds and in release builds that set +`security.allowRemoteModules`; other release builds load no HTTP module and +never look. + ### Fetch concurrency The module-graph walk fetches modules concurrently, up to a cap shared by 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 7a900eddb..180aaffcf 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,324 @@ 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("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); + }); + }); + + // 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); + }); + }); + + 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); + } + + // 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"); + 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; + 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 () { + // 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("./httpCacheWorker.js"); + worker.onmessage = function (msg) { + 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(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; + 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("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 () { + 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/AndroidJsV8Inspector.java b/test-app/app/src/main/java/com/tns/AndroidJsV8Inspector.java index fd1ef7329..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,11 +33,13 @@ 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); - 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,13 +281,14 @@ 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() { if (currentRuntimeLogger.isEnabled()) { Log.d("V8Inspector", "Disconnecting"); } - disconnect(); + disconnect(JsV8InspectorWebSocket.this); } }); } @@ -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,7 +381,8 @@ protected void onException(IOException exception) { exception.printStackTrace(); } } - disconnect(); + socketClosed(JsV8InspectorWebSocket.this); + disconnect(JsV8InspectorWebSocket.this); } } } 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..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 @@ -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. @@ -299,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. @@ -332,11 +352,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 +680,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..a0433ced8 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -304,8 +304,63 @@ 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) { + env.ExceptionClear(); + return; + } + jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); + if (mid == nullptr) { + env.ExceptionClear(); + return; + } + 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"); + if (cls == nullptr) { + // Takes the ClassNotFoundException FindClass left pending. + throw NativeScriptException(env); + } + 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 +597,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 +670,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 +714,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 +729,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 +771,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 +810,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 +865,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); @@ -914,6 +980,21 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std: } } } + // Clear-Site-Data, now that the stream is closed, and whether or not + // the body arrived whole, as on the OkHttp transport. 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(); + } + // A truncated read only matters when the body is what the caller // needs: on a non-2xx the status alone decides the outcome, so keep // the answer rather than turning it into a retryable network error. @@ -1056,6 +1137,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 +1189,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 +1202,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 +1311,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..efe45c266 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -128,6 +128,24 @@ 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`, 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); +// +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/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index 5beb11a14..13dbeba59 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,87 @@ std::string FinishResponse(json& response, const std::string& sessionId) { return JsonDump(response); } +// CDP integers are int32: Chromium's protocol bindings reject anything else, +// though an integral double such as 5.0 still counts. +bool GetInt32(const json& value, long long& out) { + if (!value.is_number()) { + return false; + } + double number = value.get(); + if (number != std::trunc(number) || number < INT32_MIN || number > INT32_MAX) { + return false; + } + out = static_cast(number); + return true; +} + +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()}}; +} + +// `message` parsed, when it is a Network.setCacheDisabled or +// Network.clearBrowserCache command with an id for the main session, its id +// as an integer. Classified the way handleMessageOnSocketThread classifies +// it: the text check only skips the parse for messages that can't name either +// method, and a \u escape could spell the name. +std::optional ParseMainSessionNetworkCacheCommand(const std::string& message) { + if (message.find("Network.setCacheDisabled") == std::string::npos && + message.find("Network.clearBrowserCache") == std::string::npos && + message.find("\\u") == std::string::npos) { + return std::nullopt; + } + auto parsed = json::parse(message, nullptr, false); + long long id = -1; + if (parsed.is_discarded() || !parsed.is_object() || !parsed.contains("method") || + !parsed["method"].is_string() || !IsNetworkCacheMethod(parsed["method"].get()) || + !parsed.contains("id") || !GetInt32(parsed["id"], id) || + (parsed.contains("sessionId") && parsed["sessionId"].is_string() && + !parsed["sessionId"].get().empty())) { + return std::nullopt; + } + parsed["id"] = id; + 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. std::string BuildWorkerAttachedEvent(WorkerInspectorClient* client) { json attached = {{"method", "Target.attachedToTarget"}, @@ -176,20 +258,6 @@ size_t TruncateUTF8ToByteSize(const uint8_t* data, size_t length) { return 0; } -// CDP integers are int32: Chromium's protocol bindings reject anything else, -// though an integral double such as 5.0 still counts. -bool GetInt32(const json& value, long long& out) { - if (!value.is_number()) { - return false; - } - double number = value.get(); - if (number != std::trunc(number) || number < INT32_MIN || number > INT32_MAX) { - return false; - } - out = static_cast(number); - return true; -} - // Opt-out via nativescript.config.ts (serialized into the bundled // package.json): `android: { disableSourceMapURLRewrite: true }`, or the same // key at the top level. @@ -322,7 +390,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). @@ -349,11 +431,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; @@ -416,7 +497,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(); @@ -427,9 +510,22 @@ 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; } + + // 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; + } + } } @@ -476,6 +572,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; } @@ -495,7 +598,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; @@ -504,9 +608,10 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message std::string method = parsed.contains("method") && parsed["method"].is_string() ? parsed["method"].get() : ""; - long long msgId = parsed.contains("id") && parsed["id"].is_number() - ? parsed["id"].get() - : -1; + long long msgId = -1; + if (parsed.contains("id")) { + GetInt32(parsed["id"], msgId); + } std::string sessionId = parsed.contains("sessionId") && parsed["sessionId"].is_string() ? parsed["sessionId"].get() : ""; @@ -662,6 +767,46 @@ 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. + // Without an int32 id the message is no command: it has no effect and goes + // on to the normal routing below, where V8 rejects it. + long long cacheCommandId = 0; + if (IsNetworkCacheMethod(method) && parsed.contains("id") && + GetInt32(parsed["id"], cacheCommandId)) { + if (!sessionId.empty()) { + bool knownSession; + { + std::lock_guard lock(workerTargetsMutex_); + knownSession = workerTargets_.count(sessionId) != 0; + } + if (!knownSession) { + json error = SessionNotFoundReply(cacheCommandId, sessionId); + response = JsonDump(error); + return true; + } + } + if (method == "Network.clearBrowserCache") { + // A failed clear is answered here, for every session, so the JS + // handler can't report success for it. + if (std::optional failure = ClearModuleHttpCacheFromInspector()) { + json error = {{"id", cacheCommandId}, {"error", {{"code", -32000}, {"message", *failure}}}}; + response = FinishResponse(error, sessionId); + return true; + } + } else if (std::optional cacheDisabled = SetCacheDisabledParam(parsed)) { + SetCacheDisabledBy(socket, *cacheDisabled); + } + if (sessionId.empty()) { + return false; + } + json reply = NetworkCacheReply(cacheCommandId, 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 +833,48 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message return false; } +std::optional JsV8InspectorClient::ClearModuleHttpCacheFromInspector() { + std::string failure = "Could not clear the HTTP module cache"; + try { + ClearModuleHttpCache(); + return std::nullopt; + } catch (NativeScriptException& e) { + const std::string detail = e.GetErrorMessage(); + if (!detail.empty()) { + failure += ": " + detail; + } + } catch (...) { + } + DEBUG_WRITE_FORCE("Network.clearBrowserCache: %s", failure.c_str()); + return failure; +} + +void JsV8InspectorClient::SetCacheDisabledBy(jobject socket, bool cacheDisabled) { + if (socket == nullptr) { + return; + } + JEnv env; + std::lock_guard lock(connectionMutex_); + 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; + } + 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, long long msgId, const std::string& message) { // Built under the lock, sent after releasing it: a blocking socket write @@ -700,10 +887,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 @@ -1247,7 +1431,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; } @@ -1280,6 +1464,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 4e169cb40..d091ea437 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 @@ -48,11 +50,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(); @@ -120,6 +129,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. The clear returns the error message when it failed. + std::optional ClearModuleHttpCacheFromInspector(); + void SetCacheDisabledBy(jobject socket, bool cacheDisabled); void AnnounceWorkerTargets(); std::map workerTargets_; @@ -159,6 +174,12 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // memory location with the bitfields above, which the main thread // writes. std::atomic isConnected_; + // 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 @@ -166,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/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 9ee7081d3..4176a559d 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -4398,6 +4398,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) { @@ -4407,6 +4431,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/com_tns_AndroidJsV8Inspector.cpp b/test-app/runtime/src/main/cpp/com_tns_AndroidJsV8Inspector.cpp index 090a8db80..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,16 @@ 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) { + 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) { @@ -29,11 +37,11 @@ JNIEXPORT extern "C" void Java_com_tns_AndroidJsV8Inspector_dispatchMessage(JNIE 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()); } 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..67f77b302 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,17 @@ 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 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)))); + } + } // Parse security configuration if (rootObject.has(SecurityKey)) { @@ -239,6 +254,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..24e895265 --- /dev/null +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -0,0 +1,189 @@ +package com.tns; + +import android.util.Log; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.util.List; +import java.util.Map; + +/** + * 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. + * + * 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(); + + // 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. */ + static boolean isEnabledAtStartup() { + return enabledAtStartup; + } + + /** + * 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) { + 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. */ + static void clear() throws IOException { + synchronized (LOCK) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(null)) { + return; + } + File dir = Runtime.getModuleHttpCacheDir(); + if (dir != null) { + deleteContents(dir); + } + } + } + + /** + * 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 { + synchronized (LOCK) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(url)) { + 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 | RuntimeException 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; + } + + 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..5d14665e1 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,120 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle } } + /** + * 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 sameOriginAs) throws IOException { + try { + return Client.clearCache(sameOriginAs); + } 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; + // 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 volatile 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) { + Object created = client; + if (created == null) { + synchronized (ModuleHttpCache.LOCK) { + if (client == null) { + create(timeoutMs, maxIdleConnections); + } + created = client; } - client = builder.build(); - clientTimeoutMs = timeoutMs; } - return (okhttp3.OkHttpClient) client; + return (okhttp3.OkHttpClient) (useCache ? created : uncachedClient); } - static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections) - throws IOException { - okhttp3.OkHttpClient http = base(defaultTimeoutMs, maxIdleConnections); + 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)); + } + okhttp3.OkHttpClient built = builder.build(); + uncachedClient = built.newBuilder().cache(null).build(); + clientTimeoutMs = timeoutMs; + client = built; + } + + static boolean clearCache(String sameOriginAs) throws IOException { + Object created = client; + okhttp3.Cache cache = created != null ? ((okhttp3.OkHttpClient) created).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(); ) { + 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(); + } + } + } + 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(); + Result result; try { byte[] body; okhttp3.ResponseBody responseBody = response.body(); @@ -124,10 +196,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; } } } 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 013bca1fd..907671b24 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -547,6 +547,12 @@ static File getModuleHttpCacheDir() { return new File(new File(config.rootDir, "cache"), name); } + /** Whether this is the process named after the package rather than another process of the app. */ + static boolean isMainProcess(String appName) { + String process = currentProcessName(); + return process == null || process.equals(appName); + } + // Below API 28, ActivityThread.currentProcessName() (no hidden-API // restrictions there) gives the full name. argv[0] is only the fallback: // the platform truncates it to the zygote's argument block, so processes @@ -725,6 +731,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);