Skip to content

Commit 9eb64e5

Browse files
authored
feat(runtime): controls for the HTTP module cache (#620)
* refactor(runtime): fetch synchronous-fallback modules through the loader's session The resolver's synchronous fallback fetched with +[NSURLConnection sendSynchronousRequest:], which goes through the app's shared NSURLCache. It now issues its request on the same NSURLSession as the module-graph walk, so both paths read and write one HTTP cache, and blocks on a semaphore for at most the request timeout plus five seconds per attempt. A wait that runs out cancels the task and fails the import with "(no response within Ns)", without the transport retry. The fallback runs when the graph walk could not fetch a dependency: the walk leaves dependency failures to the resolver. A new test route answers a dependency's first request with 503, so the resolver fetches it synchronously inside InstantiateModule, on the iOS main thread after UIApplicationMain. Nested synchronous fetches in that position, over keep-alive connections, all completed on the iOS 26.3 simulator; the NSURLSession hang recorded for that position did not reproduce. * feat(runtime): switch and clear the HTTP module cache The loader's HTTP cache can now be turned off and cleared, process-wide (the main isolate and every worker): - ns:module setHttpCacheEnabled(enabled) and clearHttpCache(), in Debug and Release. A non-boolean argument to setHttpCacheEnabled throws a TypeError. - Launch arguments --nativescript-no-module-cache (start with the cache off) and --nativescript-clear-module-cache (clear it before the first fetch). - App config key "moduleHttpCache" (top level): false starts with the cache off. Off means the Fetch no-store mode: nothing is read from or written to the cache, requests go through a session without a URLCache, ignore local cache data and carry Cache-Control: no-cache and Pragma: no-cache. The switch is read when each fetch is issued, by the graph walk and the synchronous fallback alike; fetches in flight are unaffected. Launch arguments and the config key are read once per process. The cache is now partitioned by origin (the URL-standard origin from ada, used only for this): one session and NSURLCache directory per origin under Library/Caches/ns-module-http-cache/origins, opened on first use. A clear moves the directory into a trash directory emptied in the background and opens the next generation, instead of calling removeAllCachedResponses: after removeAllCachedResponses and an immediate kill, the next launch still found the entry on disk. The flat cache files the previous layout kept at the root are removed at the first fetch. * feat(runtime): honour Clear-Site-Data on HTTP module responses A module response carrying Clear-Site-Data with "cache" or "*" (a comma-separated list of quoted strings; other directives are ignored) clears the loader's HTTP cache for the origin of the response URL. It is applied in the fetch completion, before the response reaches the graph walk or the synchronous fallback, so nothing requested afterwards comes from the old cache. Plain http: origins are honoured too. The partition the response was fetched through is dropped with it, which also covers a redirect across origins: the carrier is stored there, and kept it would be replayed from the cache and clear again on every hit. The header is therefore acted on once per network response. A 304 that carries it reaches the loader too: on the iOS 26.3 simulator, a revalidation answered by such a 304 cleared the origin's cache. * feat(inspector): Network.setCacheDisabled and clearBrowserCache control the module cache Network.setCacheDisabled {cacheDisabled} records the state for the sending connection; the loader's HTTP cache is off while any connected frontend has it disabled, and a connection's state ends when it disconnects. Network.clearBrowserCache clears the loader's cache for every origin. Both take effect on the inspector socket thread as the message arrives, so they work while an isolate is paused and from worker sessions. A main-session message then continues to the JS Network domain handler as before, whose reply is the frontend's answer, so app handlers (such as @nativescript/core's) still run; without a handler the runtime replies {} instead of V8's method-not-found. Worker sessions have no JS domain handlers and get {} from the socket thread. A setCacheDisabled without a boolean cacheDisabled changes nothing and, when no handler answers it, gets an Invalid parameters error. * feat(runtime): bound the HTTP module cache to the most recently used origins Every new dev-server address or port is a new origin and so a new cache partition, which nothing removed. Opening an origin's cache now stamps its directory's modification date, and the one-time initialisation, before any session exists, keeps the 8 most recently opened origin directories and moves the rest to trash. A directory whose date cannot be read counts as the oldest. Origins opened later in the same process are not pruned until the next launch. The docs mention the bound with the on-disk layout and no longer carry the platform note. * fix(inspector): leave the module cache alone for unknown worker sessions Network.setCacheDisabled and Network.clearBrowserCache sent with a sessionId applied their process-wide effect and replied {} whatever the session was. They now act only when the sessionId names a worker session the connection can reach, by the same test RouteToWorker uses; for any other sessionId, a made-up one or that of a worker that terminated, nothing changes and the routing answers "Session not found", as for any other method. The registry lock is released before the cache is called. The docs also state a limitation: a module reached through a redirect from another origin is cached with the origin the import requested, so a Clear-Site-Data from the serving origin does not remove it, while clearHttpCache(), the launch argument and Network.clearBrowserCache do. * perf(runtime): give the synchronous fallback its own sessions over the same cache The resolver's synchronous fallback shared the graph walk's session, so with every connection to a host held by walk fetches it waited for one to free up while blocking the JS thread. Each origin partition now has two sessions configured alike over its one NSURLCache instance: one for the graph walk and one, created on first use, for the synchronous fallback. With the cache off, each path likewise has its own uncached session. StartModuleFetchTask takes the path asking and stays the only place requests are issued, so the switch, clears, Clear-Site-Data and the origin bound apply to both, and dropping a partition retires both sessions. A response stored by either path is read by the other.
1 parent 93de8cc commit 9eb64e5

15 files changed

Lines changed: 1495 additions & 248 deletions

‎NativeScript/inspector/JsV8InspectorClient.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,9 @@ class JsV8InspectorClient : V8InspectorClient {
185185
void RouteToWorker(uint64_t connectionId, const std::string& sessionId,
186186
const std::string& method, long long msgId,
187187
const std::string& message);
188+
// Whether RouteToWorker would deliver a message from this frontend to
189+
// `sessionId` rather than answer "Session not found".
190+
bool HasWorkerSession(uint64_t connectionId, const std::string& sessionId);
188191
// Announces every worker not yet announced to the frontend. Requires
189192
// workerTargetsMutex_.
190193
void AnnounceWorkerTargetsLocked(uint64_t connectionId, TargetState& state);

‎NativeScript/inspector/JsV8InspectorClient.mm‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
#include "Caches.h"
1616
#include "Helpers.h"
17+
#include "HttpLoader.h"
1718
#include "InspectorServer.h"
1819
#include "JsV8InspectorClient.h"
1920
#include "NativeScriptException.h"
@@ -213,6 +214,18 @@ bool GetInt32(const json& value, long long& out) {
213214
out = static_cast<long long>(number);
214215
return true;
215216
}
217+
218+
// Network.setCacheDisabled's required boolean `cacheDisabled`, if present.
219+
std::optional<bool> SetCacheDisabledParam(const json& message) {
220+
if (!message.is_object() || !message.contains("params") || !message["params"].is_object()) {
221+
return std::nullopt;
222+
}
223+
const json& params = message["params"];
224+
if (!params.contains("cacheDisabled") || !params["cacheDisabled"].is_boolean()) {
225+
return std::nullopt;
226+
}
227+
return params["cacheDisabled"].get<bool>();
228+
}
216229
} // namespace
217230
218231
#define NOTIFICATION(name) \
@@ -419,6 +432,9 @@ bool GetInt32(const json& value, long long& out) {
419432
}
420433
}
421434
435+
// Its Network.setCacheDisabled lasts only as long as the connection.
436+
tns::SetModuleHttpCacheDisabledByInspector(connectionId, false);
437+
422438
// Free the process-global trace controller for other frontends.
423439
{
424440
std::lock_guard<std::mutex> lock(this->tracingMutex_);
@@ -498,6 +514,33 @@ bool GetInt32(const json& value, long long& out) {
498514
return;
499515
}
500516
517+
// The module HTTP cache is process-wide, so these take effect here, from
518+
// any session and while any isolate is paused. A main-session message then
519+
// goes on to the JS Network domain handler as usual, which answers it;
520+
// DispatchFrontendMessage answers it when there is none. Worker sessions
521+
// have no JS domain handlers, so they are answered here. A sessionId that
522+
// names no worker of this frontend changes nothing and is left to
523+
// RouteToWorker's "Session not found".
524+
if ((method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") &&
525+
(sessionId.empty() || this->HasWorkerSession(connectionId, sessionId))) {
526+
const std::optional<bool> cacheDisabled = SetCacheDisabledParam(parsed);
527+
const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value();
528+
if (method == "Network.clearBrowserCache") {
529+
tns::ClearModuleHttpCache();
530+
} else if (valid) {
531+
tns::SetModuleHttpCacheDisabledByInspector(connectionId, *cacheDisabled);
532+
}
533+
if (!sessionId.empty()) {
534+
if (msgId >= 0) {
535+
json reply = valid ? json{{"id", msgId}, {"result", json::object()}}
536+
: json{{"id", msgId},
537+
{"error", {{"code", -32602}, {"message", "Invalid parameters"}}}};
538+
this->SendRawToConnection(connectionId, WithSessionId(reply, sessionId).dump());
539+
}
540+
return;
541+
}
542+
}
543+
501544
// The Tracing domain never touches the isolate, so it is answered here
502545
// instead of on the main-thread message queue: flushing a large trace to the
503546
// frontend must not wait for (or block) JS. The dataCollected chunks are
@@ -685,6 +728,11 @@ bool GetInt32(const json& value, long long& out) {
685728
}
686729
}
687730
731+
bool JsV8InspectorClient::HasWorkerSession(uint64_t connectionId, const std::string& sessionId) {
732+
std::lock_guard<std::mutex> lock(this->workerTargetsMutex_);
733+
return this->targetStates_.count(connectionId) != 0 && this->workerTargets_.count(sessionId) != 0;
734+
}
735+
688736
void JsV8InspectorClient::RouteToWorker(uint64_t connectionId, const std::string& sessionId,
689737
const std::string& method, long long msgId,
690738
const std::string& message) {
@@ -986,6 +1034,21 @@ bool GetInt32(const json& value, long long& out) {
9861034
}
9871035
}
9881036
1037+
// Applied in onFrontendMessageReceived. V8 does not know the Network domain
1038+
// and would answer method-not-found.
1039+
if (method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") {
1040+
if (!json_message.contains("id")) {
1041+
return;
1042+
}
1043+
const bool valid =
1044+
method == "Network.clearBrowserCache" || SetCacheDisabledParam(json_message).has_value();
1045+
json reply = valid ? json{{"id", json_message["id"]}, {"result", json::object()}}
1046+
: json{{"id", json_message["id"]},
1047+
{"error", {{"code", -32602}, {"message", "Invalid parameters"}}}};
1048+
this->SendRawToConnection(connectionId, reply.dump());
1049+
return;
1050+
}
1051+
9891052
// if no handler handled the message successfully, fall-through to the default V8 implementation
9901053
sessions_->Dispatch(connectionId, method, message);
9911054

‎NativeScript/runtime/HttpLoader.h‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22

3+
#include <cstdint>
34
#include <functional>
45
#include <string>
56
#include <vector>
@@ -84,7 +85,10 @@ struct ModuleFetchResult {
8485

8586
// Synchronous module fetch with one retry on transport error — the fallback
8687
// path for anything the async module-graph walk missed. Blocks the calling
87-
// thread. Returns `result.ok`.
88+
// thread, for at most a few seconds past the request timeout per attempt: a
89+
// response that has not arrived by then fails the fetch. Uses the same HTTP
90+
// cache as FetchModuleBodyAsync, through sessions (and so connections) of its
91+
// own. Returns `result.ok`.
8892
bool HttpFetchModule(const std::string& url, ModuleFetchResult& result);
8993

9094
// Asynchronous single-URL module fetch — the I/O primitive behind the
@@ -108,10 +112,11 @@ void FetchModuleBodyAsync(
108112
// ─────────────────────────────────────────────────────────────
109113
// Remote-module security gate
110114
//
111-
// Seeded once from nativescript.config / package.json (`security.allowRemoteModules`,
112-
// `security.remoteModuleAllowlist`) the first time a fetch is gated. Debug
113-
// builds always allow. These values are not readable or writable through
114-
// ns:runtime getConfig/setConfig — only nativescript.config at boot.
115+
// Seeded once from nativescript.config / package.json
116+
// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) the first
117+
// time a fetch is gated. Debug builds always allow. These values are not
118+
// readable or writable through ns:runtime getConfig/setConfig — only
119+
// nativescript.config at boot.
115120

116121
// In debug mode (RuntimeConfig.IsDebug): always returns true.
117122
// Otherwise returns the boot-time `security.allowRemoteModules` value.
@@ -145,4 +150,27 @@ RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value);
145150
// at a URL-component boundary.
146151
bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist);
147152

153+
// ─────────────────────────────────────────────────────────────
154+
// Module HTTP cache controls
155+
//
156+
// Process-wide, shared by every isolate, callable from any thread. A fetch
157+
// uses the cache when it is enabled and no inspector connection has it
158+
// disabled; that is decided when the fetch is issued, so fetches in flight are
159+
// unaffected. Disabled means nothing is read from or written to it. The launch
160+
// arguments `--nativescript-no-module-cache` and
161+
// `--nativescript-clear-module-cache` and the `moduleHttpCache` app config key
162+
// are read once per process, before the first fetch.
163+
164+
void SetModuleHttpCacheEnabled(bool enabled);
165+
166+
// Records whether inspector connection `connectionId` has the cache disabled;
167+
// false also forgets the connection.
168+
void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId,
169+
bool disabled);
170+
171+
// Empties the cache of every origin before returning, durably: a process
172+
// killed right after the call does not find the old entries at its next
173+
// launch.
174+
void ClearModuleHttpCache();
175+
148176
} // namespace tns

0 commit comments

Comments
 (0)