diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 7c9a9d5f3..be17e0a75 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -16,8 +16,6 @@ namespace tns { // - the async NSURLSession fetch behind the phase-1 module-graph walk // (StartModuleGraphLoad), which is how module bodies // normally arrive, -// - eviction plumbing (an eviction-driven fetch nonce that defeats -// CFNetwork's HTTP cache), // - the boot-evaluation flag that arms the cold-boot runloop pump only // while an entry module is evaluating (derived by the runtime itself), // - the remote-module security gate, seeded once from nativescript.config @@ -39,7 +37,7 @@ namespace tns { // `CanonicalizeHttpUrlKey`. It is per-isolate loader vocabulary — installed // through SetCanonicalizationConfig in ModuleInternalCallbacks.h — so // CanonicalizeHttpUrlKey runs on the isolate's own thread only. The transport -// never canonicalizes; it carries keys computed for it. +// never canonicalizes. // // When unconfigured, canonicalization is purely mechanical (fragment strip). struct CanonicalizationConfig { @@ -63,7 +61,7 @@ std::string CanonicalizeHttpUrlKey(const std::string& url); // tests the scheme — otherwise the collapsed form fails the test, is passed // through verbatim, and the same module ends up with two registry identities: // one from the resolver (which repairs) and one from whatever came in through -// invalidateModules or a cache-bust mark (which did not). +// invalidateModules (which did not). std::string RepairCollapsedUrlScheme(const std::string& url); // What a module response turned out to be. Decided once, by the shared @@ -92,19 +90,15 @@ struct ModuleFetchResult { // Synchronous module fetch with one retry on transport error — the fallback // path for anything the async module-graph walk missed. Blocks the calling // thread. Returns `result.ok`. -// `canonicalKey` is the module's canonical registry key, computed by the -// caller on its isolate's thread — the transport must never canonicalize, -// since that reads per-isolate loader vocabulary. -bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, - ModuleFetchResult& result); +bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); // Asynchronous single-URL module fetch — the I/O primitive behind the // module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). // Same response policy as HttpFetchModule, minus the JS-thread block: // - security gate (IsRemoteUrlAllowed) checked up front, // - an NSURLSession GET on a background queue with the same request shape -// as the sync path (cache-bust nonce, zero-cache headers, no cookies) and -// one retry on transport error. +// as the sync path (no cookies, HTTP caching as the response headers +// allow) and one retry on transport error. // `fetchDeadline` is the enclosing graph load's fetch budget as an absolute // CFAbsoluteTime (double; 0 = unbounded): attempts clamp their request // timeout to the time remaining and the transport-error retry is skipped @@ -112,28 +106,10 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // that is pumping for it. // `completion(result)` is invoked exactly once, on an arbitrary thread — // callers must hop to their JS thread before touching V8. -// `canonicalKey` as for HttpFetchModule: computed on the calling isolate's -// thread and carried, because the fetch and its completion run on background -// threads that cannot read per-isolate vocabulary. void FetchModuleBodyAsync( - const std::string& url, const std::string& canonicalKey, - double fetchDeadline, + const std::string& url, double fetchDeadline, std::function completion); -// Mark a URL set (canonicalized internally) so that the NEXT network -// fetch of each URL carries a unique `__ns_dev_nonce` query parameter, -// guaranteeing CFNetwork cannot satisfy the request from any HTTP cache -// layer (observed on iOS 18+/26+ Simulator even with `no-store` headers -// and a reload-ignoring cache policy). Called by `InvalidateModules` for -// the eviction set; marks are consumed when a fresh body arrives. -// The nonce is transport-only and never affects module identity. -// -// Takes canonical registry keys, already computed by the caller on its -// isolate's thread: the mark set guards the process-global CFNetwork cache -// and is consulted from background fetch threads, which must never -// canonicalize (that reads per-isolate vocabulary). -void MarkKeysForCacheBust(const std::vector& canonicalKeys); - // ───────────────────────────────────────────────────────────── // Remote-module security gate // diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 533da2a99..3b9f9c509 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -14,7 +14,6 @@ #include "ModuleInternalCallbacks.h" #include "Runtime.h" #include "RuntimeConfig.h" -#include "robin_hood.h" namespace tns { @@ -142,8 +141,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { } std::string CanonicalizeHttpUrlKey(const std::string& url) { - // Per-isolate vocabulary, so this runs on the isolate's own thread. Fetch - // threads never reach here — they carry keys computed for them. + // Per-isolate vocabulary, so this runs on the isolate's own thread only. const CanonicalizationConfig* canonConfig = CanonicalizationConfigForCurrentIsolate(); // Some loaders wrap HTTP module URLs as file://http(s)://... // Repaired before any scheme test, so a collapsed `http:/host` keys the same @@ -188,9 +186,9 @@ bool IsRemoteUrlAllowed(const std::string& url) { // // The dev server serves every module under ONE canonical URL — module // identity IS the URL string. Freshness after an HMR edit is handled by - // ns:module `invalidateModules` (registry evict) plus the - // eviction-driven fetch nonce in `PerformHttpFetchOnceSync`, never by URL - // variation. There is deliberately no path-tag vocabulary to collapse here. + // ns:module `invalidateModules` (registry evict) and the server's own + // response caching headers, never by URL variation. There is deliberately + // no path-tag vocabulary to collapse here. // // Why `preserveQueryFor` exists (and is checked BEFORE the dev-endpoint // prefix test, so it covers endpoints nested under a dev prefix): for some @@ -256,67 +254,6 @@ bool IsRemoteUrlAllowed(const std::string& url) { return rebuilt; } -// ───────────────────────────────────────────────────────────── -// Eviction-driven fetch cache-bust -// -// When the HMR client invalidates a module, the NEXT network fetch of -// that module must not be satisfiable by any OS-level HTTP cache -// (CFNetwork's fsCachedData has been observed serving a previous -// save's body on iOS 18+/26+ Simulator even with `no-store` headers -// and a reload-ignoring cache policy). `InvalidateModules` marks the -// canonical keys of the eviction set here; `PerformHttpFetchOnceSync` -// then appends a unique `__ns_dev_nonce` query parameter to the -// wire-level request for any marked URL, guaranteeing CFNetwork sees -// a URL it has never cached. The nonce is transport-only — it never -// enters the module registry key (identity stays the canonical URL), -// and the server and the registry never see a varied URL. -// -// Marks carry a generation rather than being plain set membership. A fetch -// records the generation it observed and clears only that one, so an -// invalidation raised while a fetch was already in flight survives that -// fetch's completion instead of being erased by it — which would have left the -// next fetch with no nonce and CFNetwork free to serve the body the -// invalidation was raised to discard. -// -// Generation 0 is reserved for "not marked", so a captured 0 clears nothing. -static std::mutex g_bustNextFetchMutex; -static robin_hood::unordered_map g_bustNextFetchKeys; -static uint64_t g_bustNextFetchGeneration = 0; - -void MarkKeysForCacheBust(const std::vector& canonicalKeys) { - if (canonicalKeys.empty()) return; - std::lock_guard lock(g_bustNextFetchMutex); - const uint64_t generation = ++g_bustNextFetchGeneration; - for (const auto& key : canonicalKeys) { - if (key.empty()) continue; - if (!(StartsWith(key, "http://") || StartsWith(key, "https://"))) continue; - // Assigned, not inserted: re-marking an already-marked key has to move it - // to the new generation, or the in-flight fetch would clear it. - g_bustNextFetchKeys[key] = generation; - } -} - -// Peek (do not consume) — the fetch may be retried on transient failure and the -// retry must still carry a nonce. Returns the generation to carry, or 0 when -// the key is not marked. Cleared on fetch success, by generation. -static uint64_t CacheBustGenerationForKey(const std::string& canonicalKey) { - std::lock_guard lock(g_bustNextFetchMutex); - if (g_bustNextFetchKeys.empty()) return 0; - auto it = g_bustNextFetchKeys.find(canonicalKey); - return it == g_bustNextFetchKeys.end() ? 0 : it->second; -} - -// Clears the mark this fetch actually satisfied. A newer mark has a newer -// generation and is left standing for the fetch that will carry it. -static void ClearCacheBustForKey(const std::string& canonicalKey, uint64_t observedGeneration) { - if (observedGeneration == 0) return; - std::lock_guard lock(g_bustNextFetchMutex); - auto it = g_bustNextFetchKeys.find(canonicalKey); - if (it != g_bustNextFetchKeys.end() && it->second == observedGeneration) { - g_bustNextFetchKeys.erase(it); - } -} - // ============================================================================ // HTTP module fetching // ============================================================================ @@ -342,9 +279,8 @@ static void ClearCacheBustForKey(const std::string& canonicalKey, uint64_t obser // Forward declarations — these helpers are defined below their first use, // matching the existing convention in this file. -static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey, - std::string& out, std::string& contentType, int& status, - uint64_t* outBustGeneration = nullptr); +static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, + std::string& contentType, int& status); // ── The module-fetch timeout policy ────────────────────────────────────────── // @@ -514,8 +450,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 @@ -541,18 +476,13 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, std::string body; std::string contentType; int status = 0; - uint64_t bustGeneration = 0; - bool transportOk = - PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, &bustGeneration); + bool transportOk = PerformHttpFetchOnceSync(url, 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()); usleep((useconds_t)(kModuleFetchRetryDelaySeconds * 1000.0 * 1000.0)); - // The retry re-peeks, so the generation it carries — the one whose nonce is - // on the wire for the body we end up with — replaces the first attempt's. - transportOk = - PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, &bustGeneration); + transportOk = PerformHttpFetchOnceSync(url, body, contentType, status); } // NOTE: no long dev-server-startup retry loop here on purpose. The CLI's // `compileWithWatch` gates app deploy/restart on its `vite serve` @@ -561,14 +491,6 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - // The mark is spent only once a response classifies as a usable module. A - // 2xx alone is not enough: an SPA fallback answering 200 text/html would - // otherwise consume the eviction nonce and leave the next fetch cacheable. - // Same rule as the async path. - if (result.ok) { - ClearCacheBustForKey(canonicalKey, bustGeneration); - } - if (!result.ok) { TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); return false; @@ -623,51 +545,11 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // API that gives us a runloop-independent synchronous fetch with a // real HTTP status code. // Shared request builder for the sync (NSURLConnection) and async -// (NSURLSession) module fetch paths so both carry identical cache-defeat -// semantics. Returns an autoreleased NSMutableURLRequest (nil for -// unparseable URLs) and reports via `outBustGeneration` which mark the URL was -// marked for an eviction-driven cache-bust nonce (the caller clears the -// mark once a fresh body actually arrives). -static NSMutableURLRequest* BuildModuleFetchRequest(const std::string& url, - const std::string& canonicalKey, - uint64_t* outBustGeneration) { - // One-time: replace the shared NSURLCache with a zero-capacity one - // so CFNetwork has no on-disk store to satisfy fetches from. Per- - // request cache policy + `removeCachedResponseForRequest:` were - // empirically insufficient on iOS 18+/26+ Simulator — fsCachedData - // would still serve a previous save's body for a just-updated URL. - static dispatch_once_t s_cacheDisableOnce; - dispatch_once(&s_cacheDisableOnce, ^{ - NSURLCache* nullCache = [[NSURLCache alloc] initWithMemoryCapacity:0 - diskCapacity:0 - directoryURL:nil]; - [NSURLCache setSharedURLCache:nullCache]; - }); - - // Eviction-driven cache-bust: if this URL's canonical key was marked - // by `InvalidateModules` (via `MarkKeysForCacheBust`), append a - // unique nonce query parameter so CFNetwork sees a different URL - // and cannot satisfy the request from any cache layer. The dev - // server ignores unknown query params on module routes, so the - // response body is unchanged. First-touch fetches don't need - // busting — nothing has cached them yet — so unmarked URLs go out - // verbatim (some Vite virtual routes require exact-match URLs and - // 404 on unknown query params). - std::string fetchUrl = url; - const uint64_t bustGeneration = CacheBustGenerationForKey(canonicalKey); - if (outBustGeneration) *outBustGeneration = bustGeneration; - if (bustGeneration != 0) { - static std::atomic s_fetchSeq{0}; - const uint64_t seq = s_fetchSeq.fetch_add(1, std::memory_order_relaxed); - const uint64_t nowMs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0); - fetchUrl += (url.find('?') == std::string::npos) ? '?' : '&'; - fetchUrl += "__ns_dev_nonce="; - fetchUrl += std::to_string(nowMs); - fetchUrl += "-"; - fetchUrl += std::to_string(seq); - } - - NSURL* u = [NSURL URLWithString:[NSString stringWithUTF8String:fetchUrl.c_str()]]; +// (NSURLSession) module fetch paths. Caching follows the protocol policy, so +// the server's response headers decide freshness. Returns an autoreleased +// NSMutableURLRequest (nil for unparseable URLs). +static NSMutableURLRequest* BuildModuleFetchRequest(const std::string& url) { + NSURL* u = [NSURL URLWithString:[NSString stringWithUTF8String:url.c_str()]]; if (!u) { return nil; } @@ -678,40 +560,14 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, forHTTPHeaderField:@"Accept"]; [request setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; [request setTimeoutInterval:ModuleFetchTimeoutInterval()]; - // CRITICAL for HMR: layered defense to bypass CFNetwork's URL cache. - // `setCachePolicy:` alone is insufficient on iOS 18+/26+ Simulator — - // CFNetwork still serves a previous save's body from fsCachedData. - // Combined with the zero-capacity sharedURLCache and the eviction- - // driven URL nonce above, these give us a reliable "always go to - // origin" path for the dev runtime. - [request setValue:@"no-cache, no-store, max-age=0" forHTTPHeaderField:@"Cache-Control"]; - [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; - // Force a fresh TCP connection per fetch. CFNetwork has been - // observed to serve a body buffered on a kept-alive HTTP/1.1 - // connection for a prior fetch when a new fetch reuses it. - [request setValue:@"close" forHTTPHeaderField:@"Connection"]; - [request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData]; [request setHTTPShouldHandleCookies:NO]; - // `setHTTPShouldUsePipelining:` is deprecated on visionOS 2.4+ (classic - // loader only). Passing NO matches the default — pipelining is already - // off — so this is intent-preserving on every platform; suppress the - // deprecation so the -Werror visionOS build keeps compiling. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - [request setHTTPShouldUsePipelining:NO]; -#pragma clang diagnostic pop - [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request]; - return request; } -static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey, - std::string& out, std::string& contentType, int& status, - uint64_t* outBustGeneration) { +static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, + std::string& contentType, int& status) { @autoreleasepool { - uint64_t bustGeneration = 0; - NSMutableURLRequest* request = BuildModuleFetchRequest(url, canonicalKey, &bustGeneration); - if (outBustGeneration) *outBustGeneration = bustGeneration; + NSMutableURLRequest* request = BuildModuleFetchRequest(url); if (!request) { status = 0; return false; @@ -732,10 +588,6 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& error:&err]; #pragma clang diagnostic pop - // Drop any response sendSynchronousRequest: implicitly stored so it - // cannot poison a later fetch of the same URL. - [[NSURLCache sharedURLCache] removeCachedResponseForRequest:request]; - if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; httpStatusLocal = [httpResp statusCode]; @@ -809,23 +661,30 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& // NSURLSession task from the iOS main thread. Fire-and-forget tasks with a // background delegate queue are the intended NSURLSession usage. // -// The session is ephemeral with a nil URLCache — the layered cache defeats -// in BuildModuleFetchRequest assume CFNetwork cannot satisfy any module -// request from a cache, and an ephemeral cacheless session is the strongest -// form of that guarantee. +// Ephemeral, so no cookies or credentials persist, but with an on-disk HTTP +// cache of its own: module responses are cached as the server's headers allow, +// and this session never reads or resizes the app's shared NSURLCache. static NSURLSession* ModuleFetchSession() { static NSURLSession* s_session = nil; static dispatch_once_t s_once; dispatch_once(&s_once, ^{ NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; - config.URLCache = nil; - config.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData; + NSURL* cachesDirectory = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory + inDomains:NSUserDomainMask] + .firstObject; + NSURL* cacheDirectory = [cachesDirectory URLByAppendingPathComponent:@"ns-module-http-cache" + isDirectory:YES]; + NSURLCache* cache = [[NSURLCache alloc] initWithMemoryCapacity:8 * 1024 * 1024 + diskCapacity:256 * 1024 * 1024 + directoryURL:cacheDirectory]; + config.URLCache = cache; + [cache release]; config.HTTPShouldSetCookies = NO; // Every module request overrides this (BuildModuleFetchRequest sets the // same policy value); the session default exists so the two settings can // never disagree about the budget again. config.timeoutIntervalForRequest = ModuleFetchTimeoutInterval(); - config.HTTPMaximumConnectionsPerHost = 16; + config.HTTPMaximumConnectionsPerHost = 32; // ARC is disabled in this file: sessionWithConfiguration: returns an // autoreleased object; retain it for the process-lifetime singleton. s_session = [[NSURLSession sessionWithConfiguration:config] retain]; @@ -847,8 +706,7 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& // lands late is still reported — a dep failure stays on the designed path — // but no request is issued that could only complete past the deadline. static void PerformModuleFetchAsyncAttempt( - const std::string& url, const std::string& canonicalKey, int attempt, - CFAbsoluteTime fetchDeadline, + const std::string& url, int attempt, CFAbsoluteTime fetchDeadline, std::function* completionHeap) { @autoreleasepool { const double remaining = @@ -862,8 +720,7 @@ static void PerformModuleFetchAsyncAttempt( return; } - uint64_t bustGeneration = 0; - NSMutableURLRequest* request = BuildModuleFetchRequest(url, canonicalKey, &bustGeneration); + NSMutableURLRequest* request = BuildModuleFetchRequest(url); if (!request) { ModuleFetchResult failed; failed.failureReason = "HTTP import failed: " + url + " (malformed request URL)"; @@ -877,8 +734,6 @@ static void PerformModuleFetchAsyncAttempt( } const std::string urlCopy = url; - const std::string keyCopy = canonicalKey; - const uint64_t bust = bustGeneration; const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); NSURLSessionDataTask* task = [ModuleFetchSession() dataTaskWithRequest:request @@ -924,9 +779,7 @@ static void PerformModuleFetchAsyncAttempt( (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - // Background thread: the carried key is the - // only way this attempt can consult the bust set. - PerformModuleFetchAsyncAttempt(urlCopy, keyCopy, 1, fetchDeadline, + PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, completionHeap); }); // Set only once the retry is actually queued: it now owns the @@ -935,9 +788,6 @@ static void PerformModuleFetchAsyncAttempt( } else { ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); - if (result.ok) { - ClearCacheBustForKey(keyCopy, bust); - } if (!result.ok) { TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, result.failureReason.c_str()); @@ -977,8 +827,7 @@ static void PerformModuleFetchAsyncAttempt( } } -void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKey, - CFAbsoluteTime fetchDeadline, +void FetchModuleBodyAsync(const std::string& url, CFAbsoluteTime fetchDeadline, std::function completion) { // Security gate: single point of enforcement, same as HttpFetchModule. if (!IsRemoteUrlAllowed(url)) { @@ -991,7 +840,7 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe } auto* completionHeap = new std::function(std::move(completion)); - PerformModuleFetchAsyncAttempt(url, canonicalKey, 0, fetchDeadline, completionHeap); + PerformModuleFetchAsyncAttempt(url, 0, fetchDeadline, completionHeap); } // Cold-boot JS-thread runloop pump. diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index f0211dd0b..b57ba463e 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -44,7 +44,8 @@ struct LoaderVocabulary { // Distinguishes "no vocabulary supplied" (mechanical canonicalization only) // from "supplied, and empty" — an empty vocabulary is explicit policy. bool canonicalizationConfigured = false; - // URL substrings whose modules are always re-fetched, never cached. + // URL substrings whose modules are re-requested on every import instead of + // being reused from the registry. std::vector volatilePatterns; }; @@ -212,7 +213,7 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( // calling isolate only. bool SetImportMap(const std::string& json, std::string* error); -// Set URL patterns that should bypass module cache (e.g. "?v=", "/hot/") on +// Set URL patterns that should bypass the module registry (e.g. "?v=", "/hot/") on // the calling isolate. void SetVolatilePatterns(const std::vector& patterns); diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 51f41ebe9..cd51b73b7 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -641,7 +641,7 @@ static bool ShouldTraceRegistryKey(const std::string& rawKey, const std::string& requestedUrl.c_str()); ModuleFetchResult fetched; - if (!HttpFetchModule(requestedUrl, registryKey, fetched)) { + if (!HttpFetchModule(requestedUrl, fetched)) { TNS_DEBUG(Esm, "[http-esm][load][fetch-fail] request=%s key=%s status=%d", requestedUrl.c_str(), registryKey.c_str(), fetched.status); // The classifier's reason names the URL and the cause (status, MIME, or @@ -861,7 +861,7 @@ void SetVolatilePatterns(const std::vector& patterns) { (unsigned long)vocabulary->volatilePatterns.size()); } -// Check if a URL matches any volatile pattern (should bypass cache). +// Check if a URL matches any volatile pattern (never reused from the registry). static bool IsVolatileUrl(const std::string& url) { const LoaderVocabulary* vocabulary = VocabularyForCurrentIsolate(); if (vocabulary == nullptr) { @@ -1650,9 +1650,7 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, load->pendingFetches++; std::shared_ptr loadRef = load; const std::string url = target; - // The canonical key is computed here, on the isolate's thread; the fetch - // carries it so background threads never touch per-isolate vocabulary. - FetchModuleBodyAsync(url, key, load->fetchDeadline, [loadRef, url](ModuleFetchResult result) { + FetchModuleBodyAsync(url, load->fetchDeadline, [loadRef, url](ModuleFetchResult result) { // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 // foreground task — thread-independent delivery, so an import() issued // from a background thread still lands on the isolate's own event loop, @@ -1903,18 +1901,6 @@ void InvalidateModules(v8::Isolate* isolate, v8::Local context, RemoveModuleFromRegistry(isolate, url); } - // Second layer: the OS/CFNetwork HTTP cache is outside the runtime's - // direct control and has been observed serving a previous save's body - // even with `no-store` headers + a reload-ignoring cache policy - // (iOS 18+/26+ Simulator). Mark every invalidated key so the NEXT - // network fetch of that URL carries a unique `__ns_dev_nonce` query - // param — CFNetwork sees a URL it has never cached and must go to - // origin. The nonce is transport-only; module identity stays the - // canonical URL. - // `uniqueUrls` already holds canonical registry keys, computed above on - // this isolate's thread — which is what the transport's mark set needs. - MarkKeysForCacheBust(uniqueUrls); - TNS_DEBUG(Registry, "invalidate summary unique=%lu hits=%lu misses=%lu (registry now=%lu)", (unsigned long)uniqueUrls.size(), (unsigned long)hits, (unsigned long)misses, (unsigned long)registry.size()); @@ -2940,8 +2926,9 @@ static void FinishHttpDynamicImport(v8::Isolate* isolate, v8::Local TNS_DEBUG(Esm, "[dyn-import][http-loader] trying URL %s", normalizedSpec.c_str()); std::string key = CanonicalizeHttpUrlKey(normalizedSpec); // Volatile pattern check: if the URL matches any configured volatile - // pattern, evict the cached module so we always re-fetch. The pattern - // list is policy and is supplied exclusively by the dev client via + // pattern, evict the registered module so every import requests it + // again (through the HTTP cache, which the server's headers govern). + // The pattern list is policy and is supplied exclusively by the dev client via // ns:module `configureLoader({ volatilePatterns })` — the runtime // carries no framework or server URL vocabulary of its own. (Framework // strategies ship their own endpoints, e.g. Angular's `/@ng/component` diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 8f398dea0..ffa393b57 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -227,6 +227,30 @@ describe("HTTP ESM Loader", function() { }); }); + // The revision route answers `Cache-Control: no-cache`, as a dev + // server does for source modules, and numbers each response, so a + // re-import served from the HTTP cache would repeat revision 1. + it("re-imports the server's current body after invalidateModules", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var nsModule = require("ns:module"); + var url = origin + "/esm/revision.mjs?k=invalidate"; + import(url).then(function (first) { + nsModule.invalidateModules([url]); + return import(url).then(function (second) { + expect([first.revision, second.revision]).toEqual([1, 2]); + done(); + }); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + // The module-fetch budget is build-dependent: 30s per request attempt // in debug runtimes, 5s in release (HttpLoader.mm). A module whose // response lands between the two — the measured 5–9s dev-server @@ -1284,7 +1308,7 @@ describe("HTTP canonical key (ns:module canonicalizeHttpUrlKey)", function () { // Upstream path joins collapse `http://` to `http:/`. Every key // derivation repairs that before it tests the scheme, so a key that - // arrives collapsed — through invalidateModules or a cache-bust mark — + // arrives collapsed — through invalidateModules — // lands on the same identity the resolver produces. it("repairs a collapsed scheme to one identity", function () { checkKey("http:/h/ns/core", "http://h/ns/core"); diff --git a/TestRunnerTests/ModuleTestServer.swift b/TestRunnerTests/ModuleTestServer.swift index 12950f19a..62440049d 100644 --- a/TestRunnerTests/ModuleTestServer.swift +++ b/TestRunnerTests/ModuleTestServer.swift @@ -12,6 +12,11 @@ typealias ModuleTestServerInput = (@escaping (Data) -> Void) -> Void /// fallback) and the Jasmine reporter — so the HTTP surface is deliberately /// small: one request per connection, full body buffered before dispatch, /// `Connection: close` on every response. +/// +/// Like a dev server, it answers `Cache-Control: no-cache` unless the handler +/// sets its own: the loader caches module responses on disk, and that cache +/// outlives the app process, so a cacheable answer could reach a later spec or +/// a later run instead of a request. final class ModuleTestServer { typealias StartResponse = (String, [(String, String)]) -> Void typealias SendBody = (Data) -> Void @@ -203,6 +208,9 @@ final class ModuleTestServer { for (name, value) in headers { response += "\(name): \(value)\r\n" } + if !headers.contains(where: { $0.0.lowercased() == "cache-control" }) { + response += "Cache-Control: no-cache\r\n" + } response += "Content-Length: \(body.count)\r\nConnection: close\r\n\r\n" var payload = Data(response.utf8) payload.append(body) diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 24593e0c6..736bdfc7a 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -181,6 +181,18 @@ class TestRunnerTests: XCTestCase { return } + if path == "/esm/revision.mjs" { + // Each request of a target gets a new body: its ordinal. + let target = query.isEmpty ? path : "\(path)?\(query)" + let body = "export const revision = \(self.requestCounts[target] ?? 0);\n" + startResponse("200 OK", [ + ("Content-Type", "application/javascript; charset=utf-8"), + ("Cache-Control", "no-cache"), + ]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + if path == "/esm/syntax-error.mjs" { // Deliberately unparseable: pins that the loader surfaces // V8's real compile error instead of a generic failure. diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 72030cab8..8ab744f50 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -362,8 +362,8 @@ apply, worker teardown) belongs to whatever tooling drives it. | export | description | |---|---| -| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings always re-fetched), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. | -| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry and marks them bust-next-fetch, so the next network fetch bypasses every HTTP cache layer. Takes an array of strings; throws `TypeError` otherwise. | +| `configureLoader(config)` | Installs loader policy for the calling isolate. Sections: `importMap` (`imports` + `scopes`), `volatilePatterns` (URL substrings re-requested on every import instead of reused from the registry; see [HTTP caching](#http-caching)), `canonicalization` (registry-keying vocabulary). Each **present** section replaces its state wholesale, an empty array included. Throws `TypeError` on any malformed input, having validated the whole config first, so a rejected call installs nothing. | +| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. That request goes through the loader's HTTP cache, so the server's caching headers decide whether it reaches the network; see [HTTP caching](#http-caching). Takes an array of strings; throws `TypeError` otherwise. | | `getLoadedModuleUrls()` | The **URL-like** keys currently in the module registry, as an array of strings (used to compute full-reload eviction sets). A key qualifies when it starts with `blob:` or contains `://` — plain filesystem paths are deliberately excluded, because a reload computes its eviction set from what a server can re-serve. | | `createRequire(filenameOrURL)` | A `require` resolving against `filenameOrURL`'s directory (a trailing slash names the directory itself). Accepts an absolute path string, a `file:` URL string, or a URL object; anything else throws `TypeError`, and an `http(s)` base is refused outright because `require()` of a dev-served module is not supported — import those. ES module graphs load under Node's `require(esm)` rule: a graph containing top-level await is refused before it evaluates. | | `createPumpingRequire(filenameOrURL, options?)` | Same argument contract and same resolution, but an ES module graph with top-level await is evaluated by driving the loop until it settles, instead of being refused. **Callable only from a task context.** See [Pumping requires](#pumping-requires). | @@ -924,6 +924,29 @@ 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 through an HTTP cache the way a browser fetches +module scripts: the request carries no cache directives of its own, and the +**response** headers decide what is reused. Connections are persistent. + +- A dev server must send `Cache-Control: no-cache` (ideally with an `ETag` or + `Last-Modified` validator, so an unchanged module costs a `304`) or + `Cache-Control: no-store` for source modules. Either one guarantees that a + module re-requested after `invalidateModules` reflects what the server + serves now. +- Content-addressed URLs (a hash in the path or query) may be served with a + long `max-age` and `immutable`; they are then reused without a request, + across app restarts too. +- A response with no `Cache-Control` and no `Expires` but with a + `Last-Modified` header is heuristically cacheable. It **can** be served + stale, including after an app restart. That is standard HTTP behavior, not + a loader bug: send explicit cache headers instead. + +`invalidateModules` and `volatilePatterns` act on the module registry only. +The request they cause is an ordinary one and is answered from the HTTP cache +whenever the server's headers allow it. + ### App entries and bootstraps An app's entry can be either CommonJS or an ES module, and the choice decides @@ -1093,6 +1116,15 @@ deadline < boot backstop. The local entry's short yield is one second with full deadline, throws on expiry, and does slice the runloop, because the tooling driving it needs the rejection reason synchronously. +The async module fetch uses an ephemeral `NSURLSession` (no persistent cookies +or credentials) with an on-disk `NSURLCache` of its own, in +`Library/Caches/ns-module-http-cache` (8 MB memory, 256 MB disk); the loader +never replaces or resizes the app's shared `NSURLCache`. Requests use the default +protocol cache policy. The synchronous fallback (`NSURLConnection`) goes +through the shared cache with the same policy. To make every module fetch go +to the origin instead, set the session's `URLCache` to `nil` and give the +request `NSURLRequestReloadIgnoringLocalAndRemoteCacheData`. + Type declarations for the `ns:` modules live in `types/` — one `.d.ts` per module, referenced from `types/index.d.ts`. The `node:` shims are deliberately *not* declared there: programs that include `@types/node` already have diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index 348f4485a..ae4e974d0 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -61,7 +61,12 @@ declare module "ns:module" { export interface LoaderConfig { /** Replaces the whole map. */ importMap?: ImportMap; - /** URL substrings identifying modules that are always re-fetched, never cached. */ + /** + * URL substrings identifying modules that are re-requested on every import + * instead of being reused from the module registry. The request still goes + * through the loader's HTTP cache, so the server's caching headers decide + * whether it reaches the network. + */ volatilePatterns?: string[]; canonicalization?: CanonicalizationConfig; } @@ -79,9 +84,10 @@ declare module "ns:module" { export function configureLoader(config: LoaderConfig): void; /** - * Evicts the given URLs (canonicalized) from the module registry and marks - * them bust-next-fetch, so the next network fetch bypasses every HTTP - * cache layer. + * Evicts the given URLs (canonicalized) from the module registry, so the + * next import of each requests it again. That request goes through the + * loader's HTTP cache: the server's caching headers decide whether it + * reaches the network. * * Throws `TypeError` if `urls` is not an array or holds a non-string, naming * the offending index.