diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 42320c8fc..641818f59 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -426,8 +426,8 @@ apply, worker teardown) belongs to whatever tooling drives it. | export | description | |---|---| -| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings always re-fetched), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. | -| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry and marks them bust-next-fetch, so the next network fetch bypasses every HTTP cache layer. Takes an array of strings; throws `TypeError` otherwise. | +| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings re-requested on every import instead of reused from the registry; see [HTTP caching](#http-caching)), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. | +| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. That request 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). | | `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). | @@ -515,8 +515,16 @@ otherwise, and `streamedCompileStats()`, which returns process-wide counts of how HTTP module bodies large enough for a background compile were compiled (`finalized`, `discarded` after another walk registered the same key first, `fellBack` to the JS thread), the background compiles `running` now, and the -isolate teardowns that waited one out (`teardownWaits`); release builds omit -all three. Missing members are simply absent — never +isolate teardowns that waited one out (`teardownWaits`), and +`httpFetchDiagnostics(url)`, which returns how the loader would fetch `url`: +the active `transport` (`"okhttp"` or `"platform"`, see +[HTTP caching](#http-caching)), its `hostClass` (`"loopback"` or `"remote"`, +see [Fetch concurrency](#fetch-concurrency)) and that class's `concurrency`, and +throws `httpFetchDiagnostics expects a URL string` otherwise, and +`forcePlatformHttpTransport(force)`, which makes every isolate's later module +fetches use the platform transport even when the app ships OkHttp (`false` +undoes it) and throws `forcePlatformHttpTransport expects a boolean` +otherwise; release builds omit all five. Missing members are simply absent — never present-but-throwing — so feature checks work. The module is registered in every build: the security boundary for remote module loading sits at the network layer (`security.allowRemoteModules` in nativescript.config, enforced @@ -980,6 +988,89 @@ treats it as a network error for a module script rather than as an empty module. The `` in the foreign-MIME message is the normalized essence, 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: + +- `Cache-Control: no-cache` (ideally with an `ETag` or `Last-Modified` + validator, so an unchanged module costs a `304`) or `Cache-Control: no-store` + for source modules. Either guarantees that a module re-requested after + `invalidateModules` reflects what the server serves now. +- A long `max-age` with `immutable` only for content-addressed URLs (a hash in + the path or query). + +A response with neither `Cache-Control` nor `Expires` but with a +`Last-Modified` header is heuristically cacheable under HTTP and **can** be +served stale wherever a cache is in play: send explicit cache headers instead. + +`invalidateModules` and `volatilePatterns` act on the module registry only. +The request they cause is an ordinary one. + +On Android, which of the two transports fetches modules depends on whether the +app ships OkHttp (`com.squareup.okhttp3:okhttp`, 3.x to 5.x): + +| | OkHttp in the app | no OkHttp | +|---|---|---| +| client | a dedicated `OkHttpClient`, never one the app configured | `HttpURLConnection` | +| HTTP cache | its own, on disk: `ns-module-http-cache` in the app's cache directory, 256 MB | none: a `ResponseCache` the app installs is neither read nor written, and every request reaches the origin | + +Both send the same request headers, follow redirects within the same +protocol, apply the same timeouts and fetch deadline, pass the same security +gate and classify responses the same way. Besides caching, these differences +remain: + +- Process-wide `java.net` defaults reach only `HttpURLConnection`: a default + `CookieHandler`, `Authenticator`, and + `HttpsURLConnection.setDefaultSSLSocketFactory` / + `setDefaultHostnameVerifier`. The loader's OkHttp client uses none of them, + so an https dev server trusted only through those defaults loads modules + over `HttpURLConnection` but not over OkHttp. +- The platform connection pool keeps only a few idle connections, so after a + 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. + +### Fetch concurrency + +The module-graph walk fetches modules concurrently, up to a cap shared by +every isolate in the process. The cap depends on the module URL's host: + +| host class | hosts | default | +|---|---|---| +| `loopback` | `127.0.0.1`, `[::1]`, `localhost`, and the emulator host aliases `10.0.2.2` (Android Emulator) and `10.0.3.2` (Genymotion) | 6 | +| `remote` | any other | 32 | + +A loopback host on a device or emulator is almost always an `adb reverse` +tunnel (the Vite plugin sets one up for both), and adbd's listener overflows +when too many connections open at once; each overflow costs the client about +a second of SYN retry. The emulator host aliases go through the emulator's +NAT, which loads large graphs faster with few connections. A remote host is bound by its round trip instead, so +more fetches in flight load a graph faster. Fetches over the cap wait in a +queue for their class, and that wait counts against the graph walk's fetch +deadline. + +An app can override either value in its app config: + +```json +{ + "android": { + "moduleFetchConcurrency": { "loopback": 6, "remote": 32 } + } +} +``` + +Both keys are optional. Each must be a positive integer; a larger value than +64 is clamped to 64. Anything else (a non-object `moduleFetchConcurrency`, a +non-integer, zero or a negative number) logs a warning and keeps the default. +The values are read once, at the first module fetch. + ### App entries and bootstraps An app's entry can be either CommonJS or an ES module, and the choice decides diff --git a/test-app/app/src/main/assets/app/package.json b/test-app/app/src/main/assets/app/package.json index 310f5f307..7ab515143 100644 --- a/test-app/app/src/main/assets/app/package.json +++ b/test-app/app/src/main/assets/app/package.json @@ -12,7 +12,8 @@ "suppressCallJSMethodExceptions": false, "enableLineBreakpoints": false, "enableMultithreadedJavascript": true, - "interfaceProxies": false + "interfaceProxies": false, + "moduleFetchConcurrency": { "remote": 24 } }, "discardUncaughtJsExceptions": false, "security": { 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 6fc323042..7a900eddb 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -1331,6 +1331,243 @@ describe("HTTP ESM Loader", function () { }, 60000); }); + describe("connections and revalidation", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + // The revision route answers `Cache-Control: no-cache`, as a dev + // server does for source modules, and numbers each response, so a + // re-import answered without reaching the server would repeat + // revision 1. + it("re-imports the server's current body after invalidateModules", function (done) { + var url = origin + "/esm/revision.mjs?k=invalidate"; + import(url).then(function (first) { + nsModule.invalidateModules([url]); + return import(url).then(function (second) { + expect([first.revision, second.revision]).toEqual([1, 2]); + done(); + }); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + + // package.json sets android.moduleFetchConcurrency to { "remote": 24 }, + // so the loopback cap is the built-in default and the remote one is + // the app's override. + describe("fetch concurrency", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + + it("classifies loopback hosts apart from every other host", function () { + [origin + "/esm/a.mjs", "http://localhost:5173/a.mjs", + "http://[::1]:5173/a.mjs", "HTTP://LocalHost/a.mjs", + "http://user@127.0.0.1:5173/a.mjs", "http://10.0.2.2:5173/a.mjs", + "http://10.0.3.2:5173/a.mjs"].forEach(function (url) { + expect(nsModule.httpFetchDiagnostics(url).hostClass).toBe("loopback"); + }); + ["http://10.0.2.3:5173/a.mjs", "http://192.168.1.20:5173/a.mjs", + "https://esm.sh/a.mjs", "http://localhost.example.com/a.mjs", + "http://127.0.0.1.example.com/a.mjs"].forEach(function (url) { + expect(nsModule.httpFetchDiagnostics(url).hostClass).toBe("remote"); + }); + }); + + it("caps each host class at its default unless the app config overrides it", function () { + expect(nsModule.httpFetchDiagnostics(origin + "/esm/a.mjs").concurrency).toBe(6); + expect(nsModule.httpFetchDiagnostics("https://esm.sh/a.mjs").concurrency).toBe(24); + }); + + it("rejects a non-string URL", function () { + expect(function () { + nsModule.httpFetchDiagnostics(42); + }).toThrowError(TypeError, "httpFetchDiagnostics expects a URL string"); + }); + }); + + // The test app ships OkHttp, so the loader fetches through it unless a + // spec forces the platform transport. Only OkHttp caches responses. + describe("transports", function () { + useHttpTimeout(); + + var nsModule = require("ns:module"); + var server = com.tns.tests.ModuleTestServer; + var probeUrl = origin + "/esm/a.mjs"; + // The OkHttp cache is on disk and outlives the run; the server's + // port usually changes per run, and this makes sure. + var runTag = Date.now().toString(36); + // Read from the APK rather than the loader, so a loader that stops + // detecting OkHttp fails these specs instead of skipping them. + var appShipsOkHttp = (function () { + try { + java.lang.Class.forName("okhttp3.OkHttpClient"); + return true; + } catch (e) { + return false; + } + })(); + var defaultTransport = appShipsOkHttp ? "okhttp" : "platform"; + + function requireOkHttp() { + if (!appShipsOkHttp) { + pending("the app does not ship OkHttp"); + } + } + + afterEach(function () { + nsModule.forcePlatformHttpTransport(false); + }); + + function requestCount(target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)) + .then(function (m) { + return m.default.count; + }); + } + + // Imports `target`, evicts it from the registry and imports it + // again; resolves to both revisions and the server's request count. + function importTwice(target) { + var url = origin + target; + return import(url).then(function (first) { + nsModule.invalidateModules([url]); + return import(url).then(function (second) { + return requestCount(target).then(function (count) { + return { revisions: [first.revision, second.revision], requests: count }; + }); + }); + }); + } + + it("fetches through OkHttp exactly when the app ships it", function () { + expect(nsModule.httpFetchDiagnostics(probeUrl).transport).toBe(defaultTransport); + }); + + it("switches to the platform transport while forced", function () { + nsModule.forcePlatformHttpTransport(true); + expect(nsModule.httpFetchDiagnostics(probeUrl).transport).toBe("platform"); + nsModule.forcePlatformHttpTransport(false); + expect(nsModule.httpFetchDiagnostics(probeUrl).transport).toBe(defaultTransport); + }); + + it("rejects a non-boolean force flag", function () { + expect(function () { + nsModule.forcePlatformHttpTransport("yes"); + }).toThrowError(TypeError, "forcePlatformHttpTransport expects a boolean"); + }); + + ["okhttp", "platform"].forEach(function (transport) { + describe("over " + transport, function () { + beforeEach(function () { + nsModule.forcePlatformHttpTransport(transport === "platform"); + }); + + it("fetches consecutive modules over persistent connections", function (done) { + if (transport === "okhttp") { + requireOkHttp(); + } + expect(nsModule.httpFetchDiagnostics(probeUrl).transport).toBe(transport); + var count = 6; + var before = server.connectionCount(); + var chain = Promise.resolve(); + for (var i = 0; i < count; i++) { + (function (url) { + chain = chain.then(function () { + return import(url); + }); + })(origin + "/esm/revision.mjs?k=reuse-" + transport + "-" + i); + } + chain.then(function () { + expect(server.connectionCount() - before).not.toBeGreaterThan(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("never has more loopback fetches in flight than the loopback cap", function (done) { + if (transport === "okhttp") { + requireOkHttp(); + } + expect(nsModule.httpFetchDiagnostics(probeUrl).transport).toBe(transport); + var cap = nsModule.httpFetchDiagnostics(probeUrl).concurrency; + var imports = []; + server.resetPeakConcurrentRequests(); + for (var i = 0; i < cap * 2 + 2; i++) { + imports.push(import(origin + "/esm/concurrency.mjs?k=cap-" + transport + + "-" + i + "&delayMs=300")); + } + Promise.all(imports).then(function () { + var peak = server.peakConcurrentRequests(); + expect(peak).toBeGreaterThan(1); + expect(peak).not.toBeGreaterThan(cap); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + }); + + it("answers a fresh module from OkHttp's cache without a request", function (done) { + requireOkHttp(); + importTwice("/esm/cached.mjs?k=okhttp-" + runTag).then(function (r) { + expect(r.revisions).toEqual([1, 1]); + expect(r.requests).toBe(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("revalidates a no-cache module with its ETag over OkHttp", function (done) { + requireOkHttp(); + importTwice("/esm/etag.mjs?k=okhttp-" + runTag).then(function (r) { + // The second request reached the server and got a 304, so + // the stored first body was evaluated again. + expect(r.revisions).toEqual([1, 1]); + expect(r.requests).toBe(2); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("sends every platform-transport request to the origin, past an app's ResponseCache", function (done) { + nsModule.forcePlatformHttpTransport(true); + var appCache = android.net.http.HttpResponseCache.install( + new java.io.File(java.lang.System.getProperty("java.io.tmpdir"), + "ns-spec-app-response-cache-" + runTag), + 1024 * 1024); + function uninstall() { + try { + appCache.delete(); + } catch (e) { + // The spec's verdict stands either way. + } + } + importTwice("/esm/cached.mjs?k=platform-" + runTag).then(function (fresh) { + expect(fresh.revisions).toEqual([1, 2]); + expect(fresh.requests).toBe(2); + return importTwice("/esm/etag.mjs?k=platform-" + runTag); + }).then(function (validated) { + expect(validated.revisions).toEqual([1, 2]); + expect(validated.requests).toBe(2); + expect(appCache.getRequestCount()).toBe(0); + expect(appCache.getNetworkCount()).toBe(0); + uninstall(); + done(); + }).catch(function (error) { + uninstall(); + 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 cdc1552ca..6ca70b985 100644 --- a/test-app/app/src/main/assets/app/tests/testNsModule.js +++ b/test-app/app/src/main/assets/app/tests/testNsModule.js @@ -17,7 +17,8 @@ describe("ns:module", function () { "getLoadedModuleUrls", "invalidateModules"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist", - "streamedCompileStats"); + "streamedCompileStats", "httpFetchDiagnostics", + "forcePlatformHttpTransport"); } expect(Object.keys(nsModule).sort()).toEqual(expected.sort()); }); 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 9fcee0c20..303519266 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 @@ -18,6 +18,12 @@ * Loopback HTTP/1.1 fixture server for the in-app Jasmine suite. Mirrors the * module-serving routes of the iOS TestRunnerTests ModuleTestServer so the * HTTP ESM loader specs can run identically on both platforms. + * + * Connections are persistent unless the client sends `Connection: close`, so + * specs can observe the loader reusing sockets. Like a dev server, every + * response carries `Cache-Control: no-cache` unless its route sets its own: a + * cacheable answer could otherwise reach a later spec, or a later run through + * the loader's on-disk cache, instead of a request. */ public final class ModuleTestServer { private static final String JS_MIME = "application/javascript; charset=utf-8"; @@ -32,6 +38,23 @@ public final class ModuleTestServer { // fetched, or that it never was. private static final Map requestCounts = new HashMap(); + private static final List openSockets = new ArrayList(); + private static final Object connectionStatsLock = new Object(); + private static int connectionsAccepted = 0; + // /esm/concurrency.mjs requests being served now, and the most seen at once + // since the last resetPeakConcurrentRequests(). + private static int concurrencyRequestsInFlight = 0; + private static int peakRequestsInFlight = 0; + + /** Per connection: what the current request asked for and whether it was answered. */ + private static final class Exchange { + boolean clientWantsClose; + String ifNoneMatch; + boolean responded; + } + + private static final ThreadLocal currentExchange = new ThreadLocal(); + private ModuleTestServer() { } @@ -76,6 +99,16 @@ public static synchronized void stop() { } workers.clear(); } + // A worker parked reading an idle persistent connection ignores interrupts. + synchronized (openSockets) { + for (Socket socket : openSockets) { + try { + socket.close(); + } catch (IOException ignored) { + } + } + openSockets.clear(); + } acceptThread = null; boundPort = -1; } @@ -84,6 +117,26 @@ public static synchronized int getPort() { return boundPort; } + /** TCP connections accepted since the server started. */ + public static int connectionCount() { + synchronized (connectionStatsLock) { + return connectionsAccepted; + } + } + + /** The most /esm/concurrency.mjs requests served at once since the last reset. */ + public static int peakConcurrentRequests() { + synchronized (connectionStatsLock) { + return peakRequestsInFlight; + } + } + + public static void resetPeakConcurrentRequests() { + synchronized (connectionStatsLock) { + peakRequestsInFlight = concurrencyRequestsInFlight; + } + } + private static void acceptLoop(ServerSocket listener) { while (!listener.isClosed()) { final Socket socket; @@ -92,6 +145,12 @@ private static void acceptLoop(ServerSocket listener) { } catch (IOException e) { return; } + synchronized (connectionStatsLock) { + connectionsAccepted++; + } + synchronized (openSockets) { + openSockets.add(socket); + } // A thread per connection: the /esm/timeout.mjs route parks its own // thread for delayMs, and the module-graph walk fetches concurrently. Thread worker = new Thread(new Runnable() { @@ -105,6 +164,9 @@ public void run() { socket.close(); } catch (IOException ignored) { } + synchronized (openSockets) { + openSockets.remove(socket); + } synchronized (workers) { workers.remove(Thread.currentThread()); } @@ -120,13 +182,48 @@ public void run() { } private static void handle(Socket socket) throws IOException { - socket.setSoTimeout(30000); + // Outlives both clients' 5-minute pooled-connection keep-alive, so a + // reused socket is never one the server already closed. + socket.setSoTimeout(330000); socket.setTcpNoDelay(true); - String head = readHead(socket.getInputStream()); - if (head == null) { - return; + Exchange exchange = new Exchange(); + currentExchange.set(exchange); + try { + InputStream in = socket.getInputStream(); + while (true) { + String head = readHead(in); + if (head == null) { + return; + } + exchange.clientWantsClose = "close".equalsIgnoreCase(requestHeader(head, "Connection")); + exchange.ifNoneMatch = requestHeader(head, "If-None-Match"); + exchange.responded = false; + handleRequest(socket, head); + // A route that returned without answering (an interrupted + // delay) leaves nothing that could frame the next response. + if (!exchange.responded || exchange.clientWantsClose) { + return; + } + } + } finally { + currentExchange.remove(); } + } + + /** The first value of request header `name`, or null. */ + private static String requestHeader(String head, String name) { + String[] lines = head.split("\r\n"); + for (int i = 1; i < lines.length; i++) { + int colon = lines[i].indexOf(':'); + if (colon >= 0 && name.equalsIgnoreCase(lines[i].substring(0, colon).trim())) { + return lines[i].substring(colon + 1).trim(); + } + } + return null; + } + + private static void handleRequest(Socket socket, String head) throws IOException { int lineEnd = head.indexOf("\r\n"); String requestLine = lineEnd < 0 ? head : head.substring(0, lineEnd); String[] parts = requestLine.split(" "); @@ -152,13 +249,83 @@ private static void handle(Socket socket) throws IOException { } private static void route(Socket socket, String path, String query) throws IOException { - if (path.startsWith("/esm/") && !"/esm/request-stats.json".equals(path)) { - String target = query.isEmpty() ? path : path + "?" + query; - synchronized (requestCounts) { - Integer count = requestCounts.get(target); - requestCounts.put(target, count == null ? 1 : count + 1); + if (!path.startsWith("/esm/") || "/esm/request-stats.json".equals(path)) { + routeCounted(socket, path, query, 0); + return; + } + String target = query.isEmpty() ? path : path + "?" + query; + int ordinal; + synchronized (requestCounts) { + Integer count = requestCounts.get(target); + ordinal = count == null ? 1 : count + 1; + requestCounts.put(target, ordinal); + } + // Only the cap spec's route counts: a slow route an earlier spec gave + // up on can still hold a server thread. + final boolean tracked = "/esm/concurrency.mjs".equals(path); + if (tracked) { + synchronized (connectionStatsLock) { + concurrencyRequestsInFlight++; + if (concurrencyRequestsInFlight > peakRequestsInFlight) { + peakRequestsInFlight = concurrencyRequestsInFlight; + } + } + } + try { + routeCounted(socket, path, query, ordinal); + } finally { + if (tracked) { + synchronized (connectionStatsLock) { + concurrencyRequestsInFlight--; + } } } + } + + /** `ordinal` is how many times this target has been requested, this one included. */ + private static void routeCounted(Socket socket, String path, String query, int ordinal) + throws IOException { + if ("/esm/revision.mjs".equals(path)) { + String body = "export const revision = " + ordinal + ";\n"; + respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8), "Cache-Control", "no-cache"); + return; + } + + // Fresh for ten minutes, so an HTTP cache answers a repeat request + // without reaching the server; the body numbers the requests that did. + if ("/esm/cached.mjs".equals(path)) { + String body = "export const revision = " + ordinal + ";\n"; + respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8), "Cache-Control", "max-age=600"); + 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. + if ("/esm/etag.mjs".equals(path)) { + String etag = "\"" + path + "?" + query + "\""; + Exchange exchange = currentExchange.get(); + if (exchange != null && etag.equals(exchange.ifNoneMatch)) { + respond(socket, "304 Not Modified", null, new byte[0], + "Cache-Control", "no-cache", "ETag", etag); + return; + } + String body = "export const revision = " + ordinal + ";\n"; + respond(socket, "200 OK", JS_MIME, body.getBytes(UTF8), + "Cache-Control", "no-cache", "ETag", etag); + return; + } + + // Answers after `delayMs` (default 150), so a burst of these overlaps + // on the server and peakConcurrentRequests() shows how many the loader + // let through at once. + if ("/esm/concurrency.mjs".equals(path)) { + if (!sleepFor(intParam(query, "delayMs=", 150))) { + return; + } + respond(socket, "200 OK", JS_MIME, "export const ok = true;\n".getBytes(UTF8)); + return; + } if ("/esm/request-stats.json".equals(path)) { // `target` is the percent-encoded request target to count. @@ -429,8 +596,7 @@ private static String readHead(InputStream in) throws IOException { /** * Value of the first `&`-separated query component starting with `prefix`, - * undecoded. Unknown components (the loader appends cache-bust nonces) are - * ignored. + * undecoded. Unknown components are ignored. */ private static String param(String query, String prefix) { if (query == null || query.length() == 0) { @@ -490,17 +656,31 @@ private static String jsStringLiteral(String s) { .replace("\u0000", "\\u0000"); } - private static void respond(Socket socket, String status, String contentType, byte[] body) - throws IOException { + /** `extraHeaders` alternates names and values. */ + private static void respond(Socket socket, String status, String contentType, byte[] body, + String... extraHeaders) throws IOException { StringBuilder headers = new StringBuilder(); headers.append("HTTP/1.1 ").append(status).append("\r\n"); if (contentType != null) { headers.append("Content-Type: ").append(contentType).append("\r\n"); } + boolean hasCacheControl = false; + for (int i = 0; i + 1 < extraHeaders.length; i += 2) { + headers.append(extraHeaders[i]).append(": ").append(extraHeaders[i + 1]).append("\r\n"); + hasCacheControl |= "cache-control".equalsIgnoreCase(extraHeaders[i]); + } + if (!hasCacheControl) { + headers.append("Cache-Control: no-cache\r\n"); + } headers.append("Content-Length: ").append(body.length).append("\r\n"); - // One request per connection: the client is HttpURLConnection, which - // would otherwise pool a socket this server never services again. - headers.append("Connection: close\r\n\r\n"); + Exchange exchange = currentExchange.get(); + if (exchange == null || exchange.clientWantsClose) { + headers.append("Connection: close\r\n"); + } + headers.append("\r\n"); + if (exchange != null) { + exchange.responded = true; + } OutputStream out = socket.getOutputStream(); out.write(headers.toString().getBytes(UTF8)); diff --git a/test-app/runtime/build.gradle b/test-app/runtime/build.gradle index 2c0e95591..ecfc82c46 100644 --- a/test-app/runtime/build.gradle +++ b/test-app/runtime/build.gradle @@ -238,6 +238,9 @@ dependencies { // println "\t ~ [DEBUG][runtime] build.gradle - ns_default_junit_version = ${ns_default_junit_version}..." implementation fileTree(include: ['*.jar'], dir: 'libs') + // The HTTP module loader fetches through OkHttp only when the app ships it + // (com.tns.OkHttpModuleFetcher); consumer-rules.pro keeps R8 quiet otherwise. + compileOnly "com.squareup.okhttp3:okhttp:4.12.0" testImplementation "junit:junit:${ns_default_junit_version}" testImplementation "org.mockito:mockito-core:${ns_default_mockito_core_version}" } diff --git a/test-app/runtime/consumer-rules.pro b/test-app/runtime/consumer-rules.pro index 329ee7266..cc03d61f1 100644 --- a/test-app/runtime/consumer-rules.pro +++ b/test-app/runtime/consumer-rules.pro @@ -1,6 +1,9 @@ # Keep all runtime classes -keep class com.tns.* { *; } +# com.tns.OkHttpModuleFetcher uses OkHttp only when the app ships it. +-dontwarn okhttp3.** + # Keep SBG-generated classes -keep class com.tns.gen.** { *; } diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index 176df7c3c..a489397b4 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -17,15 +17,13 @@ #include "ArgConverter.h" #include "ExactUtf8.h" #include "JEnv.h" -// The transport carries canonical keys rather than computing them, but -// CanonicalizeHttpUrlKey itself reads the calling isolate's canonicalization -// vocabulary — the one loader dependency left here. +// CanonicalizeHttpUrlKey reads the calling isolate's canonicalization +// vocabulary — the one loader dependency here. #include "ModuleInternalCallbacks.h" #include "ModuleUrl.h" #include "NativeScriptException.h" #include "Runtime.h" #include "TraceLog.h" -#include "robin_hood.h" namespace tns { @@ -265,44 +263,6 @@ std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { return rebuilt; } -// ───────────────────────────────────────────────────────────── -// Eviction-driven fetch cache-bust -// -// Process-global because it belongs to the transport, not to any isolate: the -// HTTP cache layers it defeats are shared by the whole process. The set is -// keyed by canonical keys the callers compute on their own isolate's thread -// and pass in by value, so nothing here canonicalizes. - -static std::mutex g_bustNextFetchMutex; -static robin_hood::unordered_set g_bustNextFetchKeys; - -void MarkKeysForCacheBust(const std::vector& canonicalKeys) { - if (canonicalKeys.empty()) return; - std::lock_guard lock(g_bustNextFetchMutex); - for (const auto& key : canonicalKeys) { - if (key.empty()) continue; - if (!(StartsWith(key, "http://") || StartsWith(key, "https://"))) continue; - g_bustNextFetchKeys.insert(key); - } -} - -static bool IsUrlMarkedForCacheBust(const std::string& canonicalKey) { - std::lock_guard lock(g_bustNextFetchMutex); - if (g_bustNextFetchKeys.empty()) return false; - return g_bustNextFetchKeys.find(canonicalKey) != g_bustNextFetchKeys.end(); -} - -static void ClearCacheBustForUrl(const std::string& canonicalKey) { - std::lock_guard lock(g_bustNextFetchMutex); - if (g_bustNextFetchKeys.empty()) return; - g_bustNextFetchKeys.erase(canonicalKey); -} - -static void ClearAllCacheBustMarks() { - std::lock_guard lock(g_bustNextFetchMutex); - g_bustNextFetchKeys.clear(); -} - // ───────────────────────────────────────────────────────────── // JNI fetch diagnostics + request builder @@ -344,9 +304,8 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std:: return true; } -static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey, - int timeoutMs, std::string& out, std::string& contentType, - int& status, bool& bustApplied); +static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std::string& out, + std::string& contentType, int& status); // Each module-fetch attempt's connect timeout and read timeout, for both // transports, matching iOS. Debug builds talk to dev servers that transform @@ -358,27 +317,6 @@ static int ModuleFetchTimeoutMs() { static constexpr std::chrono::milliseconds kModuleFetchRetryDelay{120}; -static std::string ApplyCacheBustNonce(const std::string& url, const std::string& canonicalKey, - bool* outBustRequested) { - std::string fetchUrl = url; - const bool bustRequested = IsUrlMarkedForCacheBust(canonicalKey); - if (outBustRequested) *outBustRequested = bustRequested; - if (bustRequested) { - static std::atomic s_fetchSeq{0}; - const uint64_t seq = s_fetchSeq.fetch_add(1, std::memory_order_relaxed); - const uint64_t nowMs = static_cast( - std::chrono::duration_cast( - std::chrono::system_clock::now().time_since_epoch()) - .count()); - fetchUrl += (url.find('?') == std::string::npos) ? '?' : '&'; - fetchUrl += "__ns_dev_nonce="; - fetchUrl += std::to_string(nowMs); - fetchUrl += "-"; - fetchUrl += std::to_string(seq); - } - return fetchUrl; -} - // A blocking network call on the JS thread is exactly what StrictMode is meant // to flag, so the fetch relaxes the thread policy — but the policy belongs to // the app, not to this request: whatever runs next on this thread must get its @@ -583,8 +521,7 @@ static void ClassifyModuleResponse(const std::string& url, bool transportOk, int result.body = std::move(body); } -bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, - ModuleFetchResult& result) { +bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { result = ModuleFetchResult(); // Security gate: the single point of enforcement for all HTTP module @@ -604,29 +541,19 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, std::string body; std::string contentType; int status = 0; - bool bustApplied = false; const int timeoutMs = ModuleFetchTimeoutMs(); - bool transportOk = PerformHttpFetchOnceSync(url, canonicalKey, timeoutMs, body, contentType, - status, bustApplied); + bool transportOk = PerformHttpFetchOnceSync(url, timeoutMs, 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, canonicalKey, timeoutMs, body, contentType, - status, bustApplied); + transportOk = PerformHttpFetchOnceSync(url, timeoutMs, body, contentType, status); } ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - // A cache-bust mark is only satisfied by a response the loader can actually - // use: a 404, or a 200 that classified as something other than a module, - // leaves it armed for the next attempt. - if (result.ok && bustApplied) { - ClearCacheBustForUrl(canonicalKey); - } - if (!result.ok) { TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); return false; @@ -646,9 +573,138 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, return true; } +// ── OkHttp transport (see ActiveModuleTransportName) ───────── + +struct OkHttpBridge { + jclass fetcher = nullptr; + jmethodID fetch = nullptr; + jfieldID status = nullptr; + jfieldID contentType = nullptr; + jfieldID body = nullptr; +}; + +static std::atomic s_forcePlatformTransport{false}; +static std::atomic s_okHttpIncompatible{false}; + +// Null when the app does not ship OkHttp. isAvailable() is the first call into +// the bridge: nothing else there may run without okhttp3. +static const OkHttpBridge* OkHttpBridgeIfAvailable() { + static std::once_flag once; + static OkHttpBridge bridge; + static bool available = false; + std::call_once(once, [] { + try { + JEnv env; + JNIEnv* raw = env; + jclass fetcher = env.FindClass("com/tns/OkHttpModuleFetcher"); + jclass result = fetcher ? env.FindClass("com/tns/OkHttpModuleFetcher$Result") : nullptr; + if (!fetcher || !result) { + raw->ExceptionClear(); + return; + } + jmethodID isAvailable = raw->GetStaticMethodID(fetcher, "isAvailable", "()Z"); + if (!isAvailable) { + raw->ExceptionClear(); + return; + } + const jboolean okhttp = raw->CallStaticBooleanMethod(fetcher, isAvailable); + if (raw->ExceptionCheck() || okhttp != JNI_TRUE) { + raw->ExceptionClear(); + return; + } + bridge.fetch = raw->GetStaticMethodID( + fetcher, "fetch", "(Ljava/lang/String;III)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;") + : nullptr; + bridge.body = bridge.contentType ? raw->GetFieldID(result, "body", "[B") : nullptr; + if (!bridge.body) { + raw->ExceptionClear(); + return; + } + bridge.fetcher = fetcher; + available = true; + } catch (...) { + // Platform transport. + } + }); + return available ? &bridge : nullptr; +} + +static const OkHttpBridge* ActiveOkHttpBridge() { + if (s_forcePlatformTransport.load(std::memory_order_relaxed) || + s_okHttpIncompatible.load(std::memory_order_relaxed)) { + return nullptr; + } + return OkHttpBridgeIfAvailable(); +} + +const char* ActiveModuleTransportName() { + return ActiveOkHttpBridge() != nullptr ? "okhttp" : "platform"; +} + +void SetForcePlatformModuleTransport(bool force) { + s_forcePlatformTransport.store(force, std::memory_order_relaxed); +} + +// The OkHttp counterpart of the HttpURLConnection exchange in +// PerformHttpFetchOnceSync, with the same contract: false for a transport +// failure, true once a status arrived. A failed body read only fails the +// transport when the status is 2xx, since otherwise the status alone decides. +// Empty when the app's OkHttp turned out to lack a call the bridge makes; the +// caller then fetches through HttpURLConnection. +template +static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, + const std::string& url, int timeoutMs, + 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 + // that can run at once, so a burst's connections all survive to be reused. + const size_t maxIdle = std::max(ModuleFetchConcurrency(ModuleFetchHostClass::kLoopback), + ModuleFetchConcurrency(ModuleFetchHostClass::kRemote)); + jstring jUrl = raw->NewStringUTF(url.c_str()); + if (jUrl == nullptr) { + raw->ExceptionClear(); + return false; + } + jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, + static_cast(timeoutMs), + static_cast(ModuleFetchTimeoutMs()), + static_cast(maxIdle)); + { + std::string excClass, excMsg; + if (DrainPendingJniException(env, excClass, excMsg)) { + recordStageFailure("okhttp-execute", excClass, excMsg); + return false; + } + } + if (result == nullptr) { + s_okHttpIncompatible.store(true, std::memory_order_relaxed); + return std::nullopt; + } + + status = raw->GetIntField(result, bridge.status); + auto jct = static_cast(raw->GetObjectField(result, bridge.contentType)); + if (jct != nullptr) { + contentType = ArgConverter::jstringToString(jct); + } + auto bytes = static_cast(raw->GetObjectField(result, bridge.body)); + if (bytes == nullptr) { + recordStageFailure("read-body", "", "the response body could not be read"); + return !(status >= 200 && status < 300); + } + const jsize len = raw->GetArrayLength(bytes); + out.resize(static_cast(len)); + if (len > 0) { + raw->GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&out[0])); + } + return true; +} + // Runs on whichever thread drives the fetch — the JS thread for the sync path, -// a detached background thread for the async one. `canonicalKey` is computed -// by the caller on its isolate's thread; nothing here may canonicalize. +// a detached background thread for the async one. // // The network calls below go through the raw JNIEnv rather than JEnv's // wrappers: a wrapper converts a pending Java exception into a thrown @@ -657,16 +713,13 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // 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, const std::string& canonicalKey, - int timeoutMs, std::string& out, std::string& contentType, - int& status, bool& bustApplied) { +static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, std::string& out, + std::string& contentType, int& status) { out.clear(); contentType.clear(); status = 0; TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s timeoutMs=%d", url.c_str(), timeoutMs); - const std::string fetchUrl = ApplyCacheBustNonce(url, canonicalKey, &bustApplied); - auto recordStageFailure = [&url](const char* stage, const std::string& excClass, const std::string& excMsg) { TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=%s url=%s class=%s msg=%s", stage, @@ -697,12 +750,19 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& try { StrictModeScope strictMode(env); + if (const OkHttpBridge* okhttp = ActiveOkHttpBridge()) { + if (std::optional fetched = PerformOkHttpFetch( + env, *okhttp, url, timeoutMs, out, contentType, status, recordStageFailure)) { + return *fetched; + } + } + jclass clsURL = env.FindClass("java/net/URL"); if (!clsURL) return false; jmethodID urlCtor = env.GetMethodID(clsURL, "", "(Ljava/lang/String;)V"); jmethodID openConnection = env.GetMethodID(clsURL, "openConnection", "()Ljava/net/URLConnection;"); - jstring jUrlStr = env.NewStringUTF(fetchUrl.c_str()); + jstring jUrlStr = env.NewStringUTF(url.c_str()); jobject urlObj = raw->NewObject(clsURL, urlCtor, jUrlStr); { @@ -735,6 +795,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& if (setDoInput) { env.CallVoidMethod(conn, setDoInput, JNI_TRUE); } + // Never reads or writes a ResponseCache the app installed: module + // freshness is the origin's to decide on this transport. if (setUseCaches) { env.CallVoidMethod(conn, setUseCaches, JNI_FALSE); } @@ -742,12 +804,6 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& env.NewStringUTF("application/javascript, text/javascript, */*;q=0.1")); env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Accept-Encoding"), env.NewStringUTF("identity")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Cache-Control"), - env.NewStringUTF("no-cache, no-store, max-age=0")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Pragma"), - env.NewStringUTF("no-cache")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Connection"), - env.NewStringUTF("close")); env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("User-Agent"), env.NewStringUTF("NativeScript-HTTP-ESM")); @@ -898,6 +954,98 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& } } +// ── Fetch concurrency ──────────────────────────────────────── + +// The defaults per host class (see ModuleFetchHostClass). adbd's reverse +// listener has a backlog of 4, so a burst of new connections overflows it, and +// each overflow costs the client a 1 s SYN retry. Remote hosts are +// bound by their round trip, so more fetches in flight load faster. +static constexpr size_t kLoopbackModuleFetchConcurrency = 6; +static constexpr size_t kRemoteModuleFetchConcurrency = 32; + +static std::once_flag s_fetchConcurrencyInitFlag; +// 0 = not configured. +static size_t s_configuredLoopbackConcurrency = 0; +static size_t s_configuredRemoteConcurrency = 0; + +static void InitializeFetchConcurrencyConfig() { + std::call_once(s_fetchConcurrencyInitFlag, []() { + try { + JEnv env; + jclass runtimeClass = env.FindClass("com/tns/Runtime"); + if (runtimeClass == nullptr) { + return; + } + jmethodID getter = + env.GetStaticMethodID(runtimeClass, "getModuleFetchConcurrency", "()[I"); + if (getter == nullptr) { + return; + } + jintArray values = + static_cast(env.CallStaticObjectMethod(runtimeClass, getter)); + if (values == nullptr) { + return; + } + if (env.GetArrayLength(values) == 2) { + jint pair[2] = {0, 0}; + env.GetIntArrayRegion(values, 0, 2, pair); + s_configuredLoopbackConcurrency = pair[0] > 0 ? static_cast(pair[0]) : 0; + s_configuredRemoteConcurrency = pair[1] > 0 ? static_cast(pair[1]) : 0; + } + env.DeleteLocalRef(values); + } catch (...) { + // Keep the defaults. + } + }); +} + +static std::string LowercaseHostOf(const std::string& url) { + const size_t schemeEnd = url.find("://"); + if (schemeEnd == std::string::npos) return ""; + const size_t start = schemeEnd + 3; + const size_t end = url.find_first_of("/?#", start); + std::string authority = + url.substr(start, end == std::string::npos ? std::string::npos : end - start); + const size_t at = authority.rfind('@'); + if (at != std::string::npos) authority.erase(0, at + 1); + std::string host; + if (!authority.empty() && authority[0] == '[') { + const size_t close = authority.find(']'); + host = close == std::string::npos ? authority : authority.substr(0, close + 1); + } else { + host = authority.substr(0, authority.find(':')); + } + for (char& c : host) { + c = static_cast(tolower(static_cast(c))); + } + return host; +} + +ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url) { + const std::string host = LowercaseHostOf(url); + // 10.0.2.2 and 10.0.3.2 are the development machine as seen from the + // Android emulator and Genymotion. + if (host == "127.0.0.1" || host == "[::1]" || host == "localhost" || host == "10.0.2.2" || + host == "10.0.3.2") { + return ModuleFetchHostClass::kLoopback; + } + return ModuleFetchHostClass::kRemote; +} + +const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass) { + return hostClass == ModuleFetchHostClass::kLoopback ? "loopback" : "remote"; +} + +size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass) { + InitializeFetchConcurrencyConfig(); + if (hostClass == ModuleFetchHostClass::kLoopback) { + return s_configuredLoopbackConcurrency > 0 ? s_configuredLoopbackConcurrency + : kLoopbackModuleFetchConcurrency; + } + return s_configuredRemoteConcurrency > 0 ? s_configuredRemoteConcurrency + : kRemoteModuleFetchConcurrency; +} + // ── Bounded async fetch ────────────────────────────────────── // // One module fetch, with everything the fetch thread needs; nothing here @@ -906,7 +1054,7 @@ namespace { struct ModuleFetchJob { std::string url; - std::string canonicalKey; + ModuleFetchHostClass hostClass; ModuleFetchDeadline deadline; std::function completion; }; @@ -928,13 +1076,18 @@ bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) { return !deadline || *deadline - std::chrono::steady_clock::now() > kModuleFetchRetryDelay; } -// See the cap's rationale in HttpLoader.h. 16 matches iOS's -// HTTPMaximumConnectionsPerHost. -constexpr size_t kMaxConcurrentModuleFetches = 16; +// One queue and thread count per ModuleFetchHostClass, all under one mutex. +struct ModuleFetchLane { + std::deque queue; + size_t threadCount = 0; +}; std::mutex g_fetchQueueMutex; -std::deque g_fetchQueue; -size_t g_fetchThreadCount = 0; +ModuleFetchLane g_fetchLanes[2]; + +ModuleFetchLane& LaneFor(ModuleFetchHostClass hostClass) { + return g_fetchLanes[hostClass == ModuleFetchHostClass::kLoopback ? 0 : 1]; +} void RunModuleFetchJob(const ModuleFetchJob& job) { // Nothing may escape this function: it runs at the top of a detached @@ -950,12 +1103,11 @@ void RunModuleFetchJob(const ModuleFetchJob& job) { std::string contentType; int status = 0; const auto start = std::chrono::steady_clock::now(); - bool bustApplied = false; bool transportOk = false; std::optional timeoutMs = AttemptTimeoutMs(job.deadline); if (timeoutMs) { - transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs, body, - contentType, status, bustApplied); + transportOk = + PerformHttpFetchOnceSync(job.url, *timeoutMs, 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)) { @@ -967,17 +1119,14 @@ void RunModuleFetchJob(const ModuleFetchJob& job) { std::this_thread::sleep_for(kModuleFetchRetryDelay); timeoutMs = AttemptTimeoutMs(job.deadline); if (timeoutMs) { - transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs, - body, contentType, status, bustApplied); + transportOk = + PerformHttpFetchOnceSync(job.url, *timeoutMs, body, contentType, status); } } } if (timeoutMs) { ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result); - if (result.ok && bustApplied) { - ClearCacheBustForUrl(job.canonicalKey); - } } else { result.failureReason = "HTTP import failed: " + job.url + " (module graph fetch deadline exceeded)"; @@ -1046,23 +1195,23 @@ void ModuleFetchThreadMain(ModuleFetchJob job) { } } detachGuard{jvm, attachedHere}; + ModuleFetchLane& lane = LaneFor(job.hostClass); for (;;) { RunModuleFetchJob(job); std::lock_guard lock(g_fetchQueueMutex); - if (g_fetchQueue.empty()) { - g_fetchThreadCount--; + if (lane.queue.empty()) { + lane.threadCount--; return; } - job = std::move(g_fetchQueue.front()); - g_fetchQueue.pop_front(); + job = std::move(lane.queue.front()); + lane.queue.pop_front(); } } } // namespace -void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKey, - ModuleFetchDeadline fetchDeadline, +void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline fetchDeadline, std::function completion) { // Security gate: single point of enforcement, same as HttpFetchModule. if (!IsRemoteUrlAllowed(url)) { @@ -1075,14 +1224,18 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe return; } - ModuleFetchJob job{url, canonicalKey, fetchDeadline, std::move(completion)}; + const ModuleFetchHostClass hostClass = ModuleFetchHostClassOf(url); + // 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)}; { std::lock_guard lock(g_fetchQueueMutex); - if (g_fetchThreadCount >= kMaxConcurrentModuleFetches) { - g_fetchQueue.push_back(std::move(job)); + if (lane.threadCount >= cap) { + lane.queue.push_back(std::move(job)); return; } - g_fetchThreadCount++; + lane.threadCount++; } // Copied, not moved: a throwing std::thread constructor leaves its @@ -1100,9 +1253,9 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe std::deque orphaned; { std::lock_guard lock(g_fetchQueueMutex); - g_fetchThreadCount--; - if (g_fetchThreadCount == 0) { - orphaned.swap(g_fetchQueue); + lane.threadCount--; + if (lane.threadCount == 0) { + orphaned.swap(lane.queue); } } @@ -1123,8 +1276,4 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe } } -void CleanupHttpLoaderGlobals() { - ClearAllCacheBustMarks(); -} - } // namespace tns diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index 2a549d012..da9a8d047 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -18,8 +18,6 @@ namespace tns { // - the async background-thread fetch behind the phase-1 module-graph // walk (StartModuleGraphLoad), which is how module bodies // normally arrive, -// - eviction plumbing (an eviction-driven fetch nonce that defeats -// any HTTP cache layer between the runtime and the origin), // - the remote-module security gate, seeded once from nativescript.config // at boot and never exposed on ns:runtime getConfig/setConfig. @@ -35,9 +33,7 @@ namespace tns { // client via ns:module `configureLoader({ canonicalization: {...} })`. It is // per-isolate loader vocabulary — installed through SetCanonicalizationConfig // in ModuleInternalCallbacks.h — so CanonicalizeHttpUrlKey runs on the -// isolate's own thread only. The transport never canonicalizes: every entry -// point takes the canonical key as a parameter, so an off-thread key is -// impossible to produce by construction. +// isolate's own thread only. The transport never canonicalizes. // // When unconfigured, canonicalization is purely mechanical (fragment strip). struct CanonicalizationConfig { @@ -87,11 +83,7 @@ struct ModuleFetchResult { // Synchronous module fetch with one retry on transport error — the fallback // path for anything the module-graph walk missed. Blocks the calling thread. // Returns `result.ok`. -// `canonicalKey` is the module's canonical registry key, computed by the -// caller on its isolate's thread — the transport must never canonicalize, -// since that reads per-isolate loader vocabulary. -bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, - ModuleFetchResult& result); +bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); // An absolute bound on an async module fetch, retries included; nullopt = // unbounded. @@ -101,9 +93,9 @@ using ModuleFetchDeadline = std::optional // module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). // Same response policy as HttpFetchModule, minus the JS-thread block: // - security gate (IsRemoteUrlAllowed) checked up front, -// - a JNI HttpURLConnection GET on a background thread with the same -// request shape as the sync path (cache-bust nonce, zero-cache headers) -// and one retry on transport error. +// - a GET on a background thread through the active transport (see +// ActiveModuleTransportName) with the same request shape as the sync +// path, over persistent connections, and one retry on transport error. // `fetchDeadline` is the enclosing graph load's fetch budget: each attempt // clamps its connect and read timeouts to the time remaining, the // transport-error retry is skipped once the budget cannot fit it, and an @@ -113,36 +105,45 @@ using ModuleFetchDeadline = std::optional // trickling in can still finish past the deadline. // `completion(result)` is invoked exactly once, on an arbitrary thread — // callers must hop to their JS thread before touching V8. -// `canonicalKey` as for HttpFetchModule: computed on the calling isolate's -// thread and carried, because the fetch and its completion run on background -// threads that cannot read per-isolate vocabulary. // -// Concurrency is capped (kMaxConcurrentModuleFetches). iOS gets the same cap -// per host from NSURLSession; here it is process-wide, because the fetch -// threads are a process resource and a dev session's modules all come from -// one origin anyway. Over the cap the request is queued and picked up by a -// fetch thread as one frees — the CALLER never blocks, so this stays safe to -// call from the JS thread. +// Concurrency is capped per host class (ModuleFetchConcurrency), process-wide +// rather than per host as NSURLSession does on iOS: the fetch threads are a +// process resource, and a dev session's modules all come from one origin. Over +// the cap the request is queued and picked up by a fetch thread of its class +// as one frees — the CALLER never blocks, so this stays safe to call from the +// JS thread. void FetchModuleBodyAsync( - const std::string& url, const std::string& canonicalKey, ModuleFetchDeadline fetchDeadline, + const std::string& url, ModuleFetchDeadline fetchDeadline, std::function completion); -// Mark a set of canonical registry keys so that the NEXT network fetch of -// each carries a unique `__ns_dev_nonce` query parameter, guaranteeing no -// HTTP cache layer between the runtime and the origin can satisfy the -// request. Called by `InvalidateModules` for the eviction set; marks are -// consumed when a fresh body arrives. -// The keys are inserted verbatim: canonicalization belongs to the caller's -// isolate thread (see CanonicalizeHttpUrlKey), and the transport's own -// background threads have no isolate to read the vocabulary from. -// The nonce is transport-only and never affects module identity. -void MarkKeysForCacheBust(const std::vector& canonicalKeys); - -// Clear the transport's process-wide state (cache-bust marks). MUST be -// called inside Runtime::DestroyRuntime() before isolate -// disposal — and only for the MAIN isolate (worker teardown must not wipe -// shared state the main isolate still uses). -void CleanupHttpLoaderGlobals(); +// The transport both fetch paths use: "okhttp" when the app ships OkHttp +// (com.tns.OkHttpModuleFetcher: a dedicated client with an on-disk HTTP cache +// under /ns-module-http-cache), otherwise "platform" +// (HttpURLConnection, uncached). Request headers, timeouts, redirects, the +// security gate and response classification are the same on both. +const char* ActiveModuleTransportName(); + +// Debug builds only (ns:module forcePlatformHttpTransport): fetch through the +// platform transport even when OkHttp is available, so that fallback stays +// testable in an app that ships OkHttp. +void SetForcePlatformModuleTransport(bool force); + +// 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 +// of connects; every overflow costs the client a ~1 s SYN retry. +// kRemote: any other host, where a fetch is bound by its round trip and +// more connections in flight hide more of it. +enum class ModuleFetchHostClass { kLoopback, kRemote }; + +ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url); + +const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass); + +// How many fetches of `hostClass` run at once: `android.moduleFetchConcurrency` +// from the app config when set (validated by AppConfig.java), otherwise the +// built-in default for the class. Read from the config once per process. +size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass); // ───────────────────────────────────────────────────────────── // Remote-module security gate diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 1395857a5..9ee7081d3 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -869,7 +869,7 @@ v8::MaybeLocal LoadHttpModuleForUrl(v8::Isolate* isolate, requestedUrl.c_str()); ModuleFetchResult fetched; - if (!HttpFetchModule(requestedUrl, registryKey, fetched)) { + if (!HttpFetchModule(requestedUrl, fetched)) { TNS_DEBUG(Esm, "[http-esm][load][fetch-fail] request=%s key=%s status=%d", requestedUrl.c_str(), registryKey.c_str(), fetched.status); // The classifier's reason names the URL and the cause (status, MIME or @@ -2312,10 +2312,8 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, std::shared_ptr loadRef = load; const std::string url = target; std::shared_ptr ticket = BeginStreamedCompile(isolate, *moduleState); - // The canonical key is computed here, on the isolate's thread; the fetch - // carries it so background threads never touch per-isolate vocabulary. const ModuleFetchDeadline deadline = load->fetchDeadline; - FetchModuleBodyAsync(url, key, deadline, [loadRef, url, ticket](ModuleFetchResult result) { + FetchModuleBodyAsync(url, deadline, [loadRef, url, ticket](ModuleFetchResult result) { // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 // foreground task — delivery is a property of the isolate, not of the // thread that started the fetch, and the pumped walk's @@ -2561,14 +2559,6 @@ void InvalidateModules(v8::Isolate* isolate, v8::Local context, RemoveModuleFromRegistry(isolate, url); } - // Second layer: the OS HTTP cache is outside our control and may serve - // a previous save's body even with no-store headers. Mark every - // invalidated key so the NEXT network fetch carries a unique - // `__ns_dev_nonce` query param — the network sees a URL it has never - // cached and must go to origin. The nonce is transport-only; module - // identity stays the canonical URL. - MarkKeysForCacheBust(uniqueUrls); - TNS_DEBUG(Registry, "invalidate summary unique=%lu hits=%lu misses=%lu " "(registry now=%lu)", (unsigned long)uniqueUrls.size(), (unsigned long)hits, @@ -3638,8 +3628,8 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( std::string key = CanonicalizeNormalizedHttpUrlKey(normalizedSpec); // Volatile-pattern eviction: if the URL matches any configured volatile - // pattern, evict the cached module so we always re-fetch. Policy is - // supplied exclusively by JS via ns:module `configureLoader({ + // pattern, evict the registered module so every import requests it + // again. Policy is supplied exclusively by JS via ns:module `configureLoader({ // volatilePatterns })` — the runtime carries no framework or server URL // vocabulary of its own. bool isVolatile = IsVolatileUrl(vocabulary, normalizedSpec); @@ -4368,6 +4358,46 @@ void GetLoadedModuleUrlsCallback(const v8::FunctionCallbackInfo& info } } +// Debug-only: how the loader would fetch `url` — the active transport, the +// URL's host class and that class's concurrency cap. +void HttpFetchDiagnosticsCallback(const v8::FunctionCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + v8::Local context = isolate->GetCurrentContext(); + if (info.Length() < 1 || !info[0]->IsString()) { + isolate->ThrowException(v8::Exception::TypeError( + ToV8String(isolate, "httpFetchDiagnostics expects a URL string"))); + return; + } + const ModuleFetchHostClass hostClass = + ModuleFetchHostClassOf(ArgConverter::ToString(isolate, info[0])); + v8::Local result = v8::Object::New(isolate); + if (!result->CreateDataProperty(context, ToV8String(isolate, "transport"), + ToV8String(isolate, ActiveModuleTransportName())) + .FromMaybe(false) || + !result->CreateDataProperty(context, ToV8String(isolate, "hostClass"), + ToV8String(isolate, ModuleFetchHostClassName(hostClass))) + .FromMaybe(false) || + !result->CreateDataProperty( + context, ToV8String(isolate, "concurrency"), + v8::Number::New(isolate, (double) ModuleFetchConcurrency(hostClass))) + .FromMaybe(false)) { + return; + } + info.GetReturnValue().Set(result); +} + +// Debug-only: forcePlatformHttpTransport(force) — process-wide, for every +// isolate, from the next fetch on. +void ForcePlatformHttpTransportCallback(const v8::FunctionCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + if (info.Length() < 1 || !info[0]->IsBoolean()) { + isolate->ThrowException(v8::Exception::TypeError( + ToV8String(isolate, "forcePlatformHttpTransport expects a boolean"))); + return; + } + SetForcePlatformModuleTransport(info[0]->BooleanValue(isolate)); +} + } // namespace bool BuildNsModuleBinding(v8::Local context, v8::Local binding) { @@ -4383,6 +4413,11 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local } if (IsDebuggable()) { + InstallDevFunction(isolate, context, binding, "httpFetchDiagnostics", + HttpFetchDiagnosticsCallback); + InstallDevFunction(isolate, context, binding, "forcePlatformHttpTransport", + ForcePlatformHttpTransportCallback); + auto canonicalizeCb = [](const v8::FunctionCallbackInfo& info) { v8::Isolate* iso = info.GetIsolate(); try { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 5a10ed9d9..09639a6b0 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -46,9 +46,10 @@ struct LoaderVocabulary { // code is served as-is. ParsedImportMap importMap; - // URLs matching any of these substrings are always re-fetched (the cache is - // evicted before loading). The vocabulary is server/framework policy, so - // the runtime carries no framework-specific URL strings of its own. + // URLs matching any of these substrings are re-requested on every import + // instead of being reused from the registry. The vocabulary is + // server/framework policy, so the runtime carries no framework-specific URL + // strings of its own. std::vector volatilePatterns; CanonicalizationConfig canonicalization; @@ -243,7 +244,7 @@ void InitializeImportMetaObject(v8::Local context, // through the copy taken at spawn. bool SetImportMap(const std::string& json, std::string* error); -// Set URL patterns that should bypass module cache (e.g. "?v=", "/hot/") +// Set URL patterns that should bypass the module registry (e.g. "?v=", "/hot/") // on the calling isolate. void SetVolatilePatterns(const std::vector& patterns); @@ -284,6 +285,11 @@ void SetCanonicalizationConfig(CanonicalizationConfig config); // - streamedCompileStats() (debug builds only; test diagnostic: // process-wide counts of the paths large // HTTP module bodies took) +// - httpFetchDiagnostics(url) (debug builds only; test diagnostic: +// the active transport, the fetch's +// host class and cap) +// - forcePlatformHttpTransport(force) +// (debug builds only; test switch) // // Worker teardown across HMR cycles is userland: the dev client intercepts // the global `Worker` constructor and terminates tracked instances diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index c45763ee1..ce708f91a 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -1324,13 +1324,6 @@ void Runtime::DestroyRuntime() { CallbackHandlers::RemoveIsolateEntries(m_isolate); FrameCallbacks::RemoveIsolateEntries(m_isolate); - // The transport's process-wide state (the cache-bust marks) is shared - // across isolates; only the main isolate may clear it (worker teardown must - // not wipe the main isolate's session). - if (m_isMainThread) { - tns::CleanupHttpLoaderGlobals(); - } - // V8 does not run weak callbacks when an isolate is disposed, so anything // still bound to one has to be deleted explicitly, here, while the isolate // is alive and its destructors can still touch v8::Global handles. 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 e92aba504..b25bf531d 100644 --- a/test-app/runtime/src/main/cpp/js/ns-module.js +++ b/test-app/runtime/src/main/cpp/js/ns-module.js @@ -6,8 +6,10 @@ // and freezes the exports. // // Membership varies by build: -// - `canonicalizeHttpUrlKey`, `remoteUrlMatchesAllowlist` and -// `streamedCompileStats` exist only in debug builds (test diagnostics). +// - `canonicalizeHttpUrlKey`, `remoteUrlMatchesAllowlist`, +// `streamedCompileStats`, `httpFetchDiagnostics` and +// `forcePlatformHttpTransport` exist only in debug builds (test +// diagnostics and switches). // Missing members are simply absent — never present-but-throwing — so // feature checks work. @@ -186,5 +188,11 @@ if (binding.remoteUrlMatchesAllowlist !== undefined) { if (binding.streamedCompileStats !== undefined) { surface.streamedCompileStats = binding.streamedCompileStats; } +if (binding.httpFetchDiagnostics !== undefined) { + surface.httpFetchDiagnostics = binding.httpFetchDiagnostics; +} +if (binding.forcePlatformHttpTransport !== undefined) { + surface.forcePlatformHttpTransport = binding.forcePlatformHttpTransport; +} module.exports = ObjectFreeze(surface); 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 ae826d5ab..542980cf6 100644 --- a/test-app/runtime/src/main/java/com/tns/AppConfig.java +++ b/test-app/runtime/src/main/java/com/tns/AppConfig.java @@ -56,6 +56,11 @@ public Object getDefaultValue() { // Items are kept raw: the native gate decides what each one matches. private String[] remoteModuleAllowlist = null; + private final static String ModuleFetchConcurrencyKey = "moduleFetchConcurrency"; + private final static int MaxModuleFetchConcurrency = 64; + // { loopback, remote }; 0 leaves the runtime's default for that host class. + private final int[] moduleFetchConcurrency = {0, 0}; + public AppConfig(File appDir) { values = makeDefaultOptions(); File packageInfo = new File(appDir, "/app/package.json"); @@ -118,6 +123,11 @@ public AppConfig(File appDir) { } if (rootObject.has(AndroidKey)) { JSONObject androidObject = rootObject.getJSONObject(AndroidKey); + // First, and never throwing: a malformed key further down + // ends the whole read. + if (androidObject.has(ModuleFetchConcurrencyKey)) { + readModuleFetchConcurrency(androidObject.opt(ModuleFetchConcurrencyKey)); + } if (androidObject.has(KnownKeys.V8FlagsKey.getName())) { values[KnownKeys.V8FlagsKey.ordinal()] = androidObject.getString(KnownKeys.V8FlagsKey.getName()); } @@ -194,6 +204,46 @@ private void readWrapperLifetime(Object config) { } } + private void readModuleFetchConcurrency(Object config) { + if (!(config instanceof JSONObject)) { + Log.w("JS", "android.moduleFetchConcurrency must be an object like { \"loopback\": 6, \"remote\": 32 }; using the defaults."); + return; + } + JSONObject object = (JSONObject) config; + moduleFetchConcurrency[0] = readModuleFetchConcurrencyValue(object, "loopback"); + moduleFetchConcurrency[1] = readModuleFetchConcurrencyValue(object, "remote"); + } + + private static int readModuleFetchConcurrencyValue(JSONObject object, String key) { + if (!object.has(key)) { + return 0; + } + Object value = object.opt(key); + long count = 0; + if (value instanceof Integer || value instanceof Long) { + count = ((Number) value).longValue(); + } else if (value instanceof Number) { + double d = ((Number) value).doubleValue(); + if (d == Math.rint(d) && !Double.isInfinite(d)) { + count = (long) d; + } + } + if (count <= 0) { + Log.w("JS", String.format("android.moduleFetchConcurrency.%s must be a positive integer, not %s; using the default.", key, JSONObject.quote(String.valueOf(value)))); + return 0; + } + if (count > MaxModuleFetchConcurrency) { + Log.w("JS", String.format("android.moduleFetchConcurrency.%s is %d; using the maximum, %d.", key, count, MaxModuleFetchConcurrency)); + return MaxModuleFetchConcurrency; + } + return (int) count; + } + + /** { loopback, remote }, each 0 when not configured. */ + public int[] getModuleFetchConcurrency() { + return moduleFetchConcurrency.clone(); + } + public String getWrapperLifetimeMode() { return (String)values[KnownKeys.WrapperLifetimeMode.ordinal()]; } diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java new file mode 100644 index 000000000..9d48ab061 --- /dev/null +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -0,0 +1,133 @@ +package com.tns; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * The HTTP module loader's transport when the app ships OkHttp (okhttp3), driven + * synchronously from HttpLoader's fetch threads over JNI. + * + * okhttp3 is compileOnly: {@link #isAvailable()} must answer true before + * anything else here runs. Outside the private nested Client class no field or + * method signature names an okhttp3 type, and Client loads only once a fetch + * runs. Only calls present in OkHttp 3.x through 5.x are used. + */ +final class OkHttpModuleFetcher { + private OkHttpModuleFetcher() { + } + + private static final long CACHE_MAX_BYTES = 256L * 1024 * 1024; + + /** Read by HttpLoader through JNI. {@code body} is null when reading the body failed. */ + static final class Result { + final int status; + final String contentType; + final byte[] body; + + Result(int status, String contentType, byte[] body) { + this.status = status; + this.contentType = contentType; + this.body = body; + } + } + + // Cleared when a fetch hits a LinkageError: the app's OkHttp lacks a call + // used here, and the loader falls back to HttpURLConnection for good. + private static volatile boolean available = detect(); + + // A class literal rather than Class.forName("okhttp3..."): R8 renames + // okhttp3 classes in apps that shrink, and the literal is renamed with them. + private static boolean detect() { + try { + return okhttp3.OkHttpClient.class != null; + } catch (LinkageError e) { + return false; + } + } + + static boolean isAvailable() { + return available; + } + + /** + * 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. + */ + static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections) + throws IOException { + try { + return Client.fetch(url, timeoutMs, defaultTimeoutMs, maxIdleConnections); + } catch (LinkageError e) { + available = false; + android.util.Log.w("JS", "HTTP modules: the app's OkHttp is incompatible; using HttpURLConnection instead: " + e); + return null; + } + } + + 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; + 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)); + } + client = builder.build(); + clientTimeoutMs = timeoutMs; + } + return (okhttp3.OkHttpClient) client; + } + + static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections) + throws IOException { + okhttp3.OkHttpClient http = base(defaultTimeoutMs, maxIdleConnections); + if (timeoutMs != clientTimeoutMs) { + // Shares the pool and the cache with the base client. + http = http.newBuilder() + .connectTimeout(timeoutMs, TimeUnit.MILLISECONDS) + .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) + .build(); + } + okhttp3.Request 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(); + try { + byte[] body; + okhttp3.ResponseBody responseBody = response.body(); + if (responseBody == null) { + body = new byte[0]; + } else { + try { + body = responseBody.bytes(); + } catch (IOException e) { + body = null; + } + } + return new Result(response.code(), response.header("Content-Type"), body); + } finally { + response.close(); + } + } + } +} 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 6a0b7d95a..013bca1fd 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -492,6 +492,99 @@ public static String[] getRemoteModuleAllowlist() { return null; } + /** + * android.moduleFetchConcurrency for JNI: { loopback, remote }, each 0 when + * the app config leaves that host class at the runtime's default. + */ + public static int[] getModuleFetchConcurrency() { + Runtime runtime = com.tns.Runtime.getCurrentRuntime(); + if (runtime != null && runtime.config != null && runtime.config.appConfig != null) { + return runtime.config.appConfig.getModuleFetchConcurrency(); + } + if (staticConfiguration != null && staticConfiguration.appConfig != null) { + return staticConfiguration.appConfig.getModuleFetchConcurrency(); + } + return new int[] {0, 0}; + } + + /** + * Where the HTTP module loader's OkHttp transport keeps its HTTP cache: + * {@code ns-module-http-cache} under the app's cache directory (the app's + * data directory's {@code cache}, which is what Context.getCacheDir() + * returns), or null before the runtime is configured or when the process + * name cannot be read. A process other than the one named after the + * package gets a directory of its own, named by a digest of the full + * process name (fixed length, so any name fits a file name), since an + * OkHttp cache directory must not be shared between processes. + */ + static File getModuleHttpCacheDir() { + Runtime runtime = com.tns.Runtime.getCurrentRuntime(); + StaticConfiguration config = runtime != null && runtime.config != null + ? runtime.config + : staticConfiguration; + if (config == null || config.rootDir == null) { + return null; + } + String process = currentProcessName(); + if (process == null || process.isEmpty()) { + return null; + } + String name = "ns-module-http-cache"; + if (!process.equals(config.appName)) { + try { + byte[] digest = java.security.MessageDigest.getInstance("SHA-256") + .digest(process.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + StringBuilder hex = new StringBuilder("-"); + for (int i = 0; i < 16; i++) { + hex.append(Character.forDigit((digest[i] >> 4) & 0xf, 16)) + .append(Character.forDigit(digest[i] & 0xf, 16)); + } + name += hex; + } catch (java.security.NoSuchAlgorithmException e) { + return null; + } + } + return new File(new File(config.rootDir, "cache"), name); + } + + // 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 + // whose names differ past that point can't be told apart by it. + private static String currentProcessName() { + if (android.os.Build.VERSION.SDK_INT >= 28) { + return android.app.Application.getProcessName(); + } + try { + Object name = Class.forName("android.app.ActivityThread") + .getMethod("currentProcessName") + .invoke(null); + if (name instanceof String && !((String) name).isEmpty()) { + return (String) name; + } + } catch (ReflectiveOperationException | RuntimeException e) { + // Fall through to argv[0]. + } + try (java.io.FileInputStream in = new java.io.FileInputStream("/proc/self/cmdline")) { + java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + byte[] buffer = new byte[256]; + int read; + while ((read = in.read(buffer)) > 0) { + int end = 0; + while (end < read && buffer[end] != 0) { + end++; + } + out.write(buffer, 0, end); + if (end < read) { + break; + } + } + return out.size() == 0 ? null : new String(out.toByteArray(), java.nio.charset.StandardCharsets.UTF_8); + } catch (IOException e) { + return null; + } + } + private static final int NO_OWNING_RUNTIME = -1; /* diff --git a/test-app/test-runner-deps/package.json b/test-app/test-runner-deps/package.json index 47b6fae96..62b52357c 100644 --- a/test-app/test-runner-deps/package.json +++ b/test-app/test-runner-deps/package.json @@ -1,5 +1,5 @@ { "name": "test-runner-deps", "private": true, - "description": "Test app only: stages the npm packages the Jasmine harness loads at runtime into the APK's assets." + "description": "Test app only: stages the npm packages the Jasmine harness loads at runtime into the APK's assets, and adds the dependencies only the test app ships." } diff --git a/test-app/test-runner-deps/platforms/android/include.gradle b/test-app/test-runner-deps/platforms/android/include.gradle index 7733e59f8..46ba31d3f 100644 --- a/test-app/test-runner-deps/platforms/android/include.gradle +++ b/test-app/test-runner-deps/platforms/android/include.gradle @@ -37,6 +37,13 @@ def stageTestRunnerDeps = project.tasks.register("stageTestRunnerDeps") { } android.sourceSets.main.assets.srcDir(testRunnerDepsAssetsDir) + +// The test app ships OkHttp the way an app or plugin would, so the HTTP module +// loader runs its OkHttp transport. Not in app/build.gradle: that file ships +// to every app. +dependencies { + implementation "com.squareup.okhttp3:okhttp:4.12.0" +} project.tasks.matching { it.name == "preBuild" }.configureEach { dependsOn stageTestRunnerDeps }