From defda546fc3df80ff79aa5c699ce327ead3f9226 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:10:12 -0300 Subject: [PATCH 1/7] 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. --- NativeScript/runtime/HttpLoader.h | 4 +- NativeScript/runtime/HttpLoader.mm | 447 +++++++++++---------- TestRunner/app/tests/HttpEsmLoaderTests.js | 94 +++++ TestRunnerTests/ModuleTestServer.swift | 3 +- TestRunnerTests/TestRunnerTests.swift | 48 +++ docs/ns-builtin-modules.md | 13 +- 6 files changed, 380 insertions(+), 229 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 66b4161d..ffa62790 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -84,7 +84,9 @@ 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`. +// thread, for at most a few seconds past the request timeout per attempt: a +// response that has not arrived by then fails the fetch. Goes through the same +// session and HTTP cache as FetchModuleBodyAsync. Returns `result.ok`. bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); // Asynchronous single-URL module fetch — the I/O primitive behind the diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 68a2813a..f63cdb90 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -254,16 +255,14 @@ bool IsRemoteUrlAllowed(const std::string& url) { // falls back to for anything the module-graph walk missed // (the callback is synchronous — still true as of 14.9.207.39 — so // this fallback must be native and blocking). -// - `FetchModuleBodyAsync` — the NSURLSession-backed primitive behind -// the module-graph walk (StartModuleGraphLoad), which fetches the -// transitive closure concurrently off the JS thread before -// instantiation begins. +// - `FetchModuleBodyAsync` — the primitive behind the module-graph walk +// (StartModuleGraphLoad), which fetches the transitive closure +// concurrently off the JS thread before instantiation begins. // -// The two transports stay separate — the NSURLConnection deadlock note above -// PerformHttpFetchOnceSync is why — but they share both halves of the -// contract: BuildModuleFetchRequest shapes every request, and -// ClassifyModuleResponse judges every response. Neither can drift into its -// own idea of what a valid module response is. +// Both issue their requests through CreateModuleFetchTask, so they share one +// session and its HTTP cache, BuildModuleFetchRequest shapes every request, +// and ClassifyModuleResponse judges every response. Neither can drift into +// its own idea of what a valid module response is. // // Concurrent per-module fetches overlap with on-device compile, which // measured fastest on real apps (HMR_API_NECESSITY_REVIEW.md §8.3). @@ -271,15 +270,15 @@ bool IsRemoteUrlAllowed(const std::string& url) { // Forward declarations — these helpers are defined below their first use, // matching the existing convention in this file. static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status); + std::string& contentType, int& status, bool& waitExpired); // ── The module-fetch timeout policy ────────────────────────────────────────── // -// One request timeout for every module-fetch attempt, read by every transport: -// the synchronous NSURLConnection path, each NSURLSession attempt, and the -// async session's own default. It MUST live in exactly one place — the async -// session once said 10s while every NSMutableURLRequest overrode it to 5s, so -// raising the session alone would have changed nothing. +// One request timeout for every module-fetch attempt, read by every path: the +// synchronous fallback, each async attempt, and the session's own default. It +// MUST live in exactly one place — the async session once said 10s while every +// NSMutableURLRequest overrode it to 5s, so raising the session alone would +// have changed nothing. // // Debug runtimes get 30s: dev servers transform cold modules on demand, and // real toolchain responses have been measured at 5–9s — comfortably past the @@ -298,6 +297,12 @@ static NSTimeInterval ModuleFetchTimeoutInterval() { // request timeout. static constexpr double kModuleFetchRetryDelaySeconds = 0.12; +// How long the synchronous fallback waits past the request timeout before it +// gives up on a task whose completion never arrived. The request timeout is an +// idle timeout, so a response still trickling in can legitimately outlast it; +// this margin is what makes the blocking wait finite regardless. +static constexpr double kModuleFetchSyncWaitMarginSeconds = 5.0; + // synchronous-fetch timing histogram. // // The histogram is intentionally coarse — @@ -467,13 +472,16 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { std::string body; std::string contentType; int status = 0; - bool transportOk = PerformHttpFetchOnceSync(url, body, contentType, status); - if (!transportOk) { + bool waitExpired = false; + bool transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); + if (!transportOk && !waitExpired) { // 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. + // not a failure to communicate, so asking again would just repeat it. An + // expired wait is not retried: it already blocked this thread for longer + // than a request may take. TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); usleep((useconds_t)(kModuleFetchRetryDelaySeconds * 1000.0 * 1000.0)); - transportOk = PerformHttpFetchOnceSync(url, body, contentType, status); + transportOk = PerformHttpFetchOnceSync(url, body, contentType, status, waitExpired); } // NOTE: no long dev-server-startup retry loop here on purpose. The CLI's // `compileWithWatch` gates app deploy/restart on its `vite serve` @@ -481,6 +489,12 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // boot is a real failure, not a startup race — surface it immediately. ClassifyModuleResponse(url, transportOk, status, contentType, body, result); + if (waitExpired) { + result.failureReason = + "HTTP import failed: " + url + " (no response within " + + std::to_string((int)(ModuleFetchTimeoutInterval() + kModuleFetchSyncWaitMarginSeconds)) + + "s)"; + } if (!result.ok) { TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); @@ -502,43 +516,46 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { return true; } -// Synchronous HTTP fetcher implementation. -// -// We use `+[NSURLConnection sendSynchronousRequest:returningResponse:error:]` -// (deprecated but functional on every shipping iOS version) instead of -// the modern NSURLSession API. NSURLSession exhibits a deadlock when the -// JS thread is the iOS main thread (post-Angular bootstrap): -// -// - JS calls `import('foo')` (dynamic import). -// - The runtime sync-fetches `foo`'s body on the main thread, blocking -// on `dispatch_semaphore_wait`. This first fetch lands normally -// (e.g. `hmr/client/index.js` arrives in ~60ms). -// - V8 then synchronously calls `InstantiateModule`, which invokes our -// `ResolveModuleCallback` for each static dependency. That callback -// issues another sync fetch (e.g. `hmr/client/utils.js`). -// - For this second sync fetch, NSURLSessionDataTask transitions to -// NSURLSessionTaskStateRunning, but the completion handler **never -// fires** within 6 seconds. NSURLSession's own -// `timeoutIntervalForRequest` does not trip either — `task.error` -// stays nil. The task remains stuck in Running state. Cancelling -// it synchronously does not produce a completion-handler callback. -// -// The deadlock reproduces with both an implicit delegate queue and an -// explicit non-main `NSOperationQueue`. Boot-time sync fetches -// (thousands of them) succeed because they happen before the iOS main -// thread becomes the JS executor. +// ───────────────────────────────────────────────────────────── +// The module fetch session // -// `NSURLConnection.sendSynchronousRequest` uses CFNetwork directly, -// bypassing NSURLSession's task lifecycle, and returns the NSURLResponse -// so we can read HTTP status and Content-Type. The deprecation warning -// is suppressed locally because every published Apple SDK still ships -// a working implementation, and there is currently no non-deprecated -// 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. Caching follows the protocol policy, so -// the server's response headers decide freshness. Returns an autoreleased -// NSMutableURLRequest (nil for unparseable URLs). +// 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. Its +// delegate queue is the session's own background queue, never the main queue, +// so a thread blocked waiting on one of its tasks does not hold up the +// completion it waits for. +static NSURLSession* ModuleFetchSession() { + static NSURLSession* s_session = nil; + static dispatch_once_t s_once; + dispatch_once(&s_once, ^{ + NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + 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 = 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]; + }); + return s_session; +} + +// Shared request builder for every module fetch. 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) { @@ -555,8 +572,50 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { return request; } +// What a finished module fetch task produced, read off the NSURLResponse. +// `transportOk` means a response arrived at all; whether it is a usable module +// is ClassifyModuleResponse's call. +struct ModuleFetchOutcome { + bool transportOk = false; + int status = 0; + std::string contentType; + std::string body; +}; + +static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* response, + NSError* error) { + ModuleFetchOutcome outcome; + outcome.transportOk = error == nil; + if ([response isKindOfClass:[NSHTTPURLResponse class]]) { + NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; + outcome.status = (int)[httpResp statusCode]; + NSString* ct = [httpResp allHeaderFields][@"Content-Type"]; + if (ct) { + const char* utf8 = [ct UTF8String]; + if (utf8) outcome.contentType = std::string(utf8); + } + } + if (data && [data length] > 0) { + outcome.body.assign(static_cast([data bytes]), static_cast([data length])); + } + return outcome; +} + +// Every module request goes out through here, whichever path issued it. +// `handler` runs exactly once, on the session's delegate queue. Returns an +// autoreleased task the caller must resume. +static NSURLSessionDataTask* CreateModuleFetchTask(NSMutableURLRequest* request, + void (^handler)(NSData*, NSURLResponse*, + NSError*)) { + return [ModuleFetchSession() dataTaskWithRequest:request completionHandler:handler]; +} + +// One blocking fetch attempt for the synchronous fallback, on the same session +// and cache as the async path. The wait is bounded: `waitExpired` reports a +// task that had not completed when it ran out, which is then cancelled. static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, - std::string& contentType, int& status) { + std::string& contentType, int& status, bool& waitExpired) { + waitExpired = false; @autoreleasepool { NSMutableURLRequest* request = BuildModuleFetchRequest(url); if (!request) { @@ -564,35 +623,46 @@ static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, return false; } - NSError* err = nil; - NSInteger httpStatusLocal = 0; - std::string contentTypeLocal; - std::string bodyLocal; + // Shared with the completion handler, which can outlive this frame when + // the wait expires. + struct SyncFetchState { + dispatch_semaphore_t done = dispatch_semaphore_create(0); + ModuleFetchOutcome outcome; + std::string errorDescription; + ~SyncFetchState() { dispatch_release(done); } + }; + auto state = std::make_shared(); const auto fetchStartUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - NSURLResponse* response = nil; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - NSData* data = [NSURLConnection sendSynchronousRequest:request - returningResponse:&response - error:&err]; -#pragma clang diagnostic pop - - if ([response isKindOfClass:[NSHTTPURLResponse class]]) { - NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; - httpStatusLocal = [httpResp statusCode]; - NSString* ct = [httpResp allHeaderFields][@"Content-Type"]; - if (ct) { - const char* utf8 = [ct UTF8String]; - if (utf8) contentTypeLocal = std::string(utf8); - } - } + NSURLSessionDataTask* task = + CreateModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { + try { + state->outcome = ReadModuleFetchOutcome(data, response, error); + if (error != nil) { + NSString* desc = error.localizedDescription ?: @""; + NSString* domain = error.domain ?: @""; + state->errorDescription = std::string(domain.UTF8String) + + " code=" + std::to_string((long)error.code) + " " + + desc.UTF8String; + } + } catch (...) { + state->outcome = ModuleFetchOutcome(); + } + dispatch_semaphore_signal(state->done); + }); + [task resume]; - if (data && [data length] > 0) { - const void* bytes = [data bytes]; - NSUInteger len = [data length]; - bodyLocal.assign(static_cast(bytes), static_cast(len)); + const double waitSeconds = request.timeoutInterval + kModuleFetchSyncWaitMarginSeconds; + if (dispatch_semaphore_wait( + state->done, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitSeconds * NSEC_PER_SEC))) != + 0) { + [task cancel]; + waitExpired = true; + status = 0; + Log(@"NativeScript: synchronous module fetch of %s got no response within %.0fs", url.c_str(), + waitSeconds); + return false; } const auto fetchEndUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); @@ -621,68 +691,20 @@ static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, (unsigned long)medium, (unsigned long)slow); } - status = (int)httpStatusLocal; - contentType = contentTypeLocal; - // Pure transport: true means a response arrived. Whether that response is - // a usable module — status, MIME, emptiness — is ClassifyModuleResponse's - // call, so both fetch paths answer it the same way. - if (err != nil) { - if (tns::LogCategoryEnabled(tns::LogCategory::Esm)) { - NSString* desc = err.localizedDescription ?: @""; - NSString* domain = err.domain ?: @""; - TNS_DEBUG(Esm, - "[http-loader][fetch-error] url=%s domain=%s code=%ld desc=%s status=%ld " - "bodyEmpty=%d ms=%llu", - url.c_str(), domain.UTF8String, (long)err.code, desc.UTF8String, - (long)httpStatusLocal, bodyLocal.empty() ? 1 : 0, (unsigned long long)fetchMs); - } + ModuleFetchOutcome& outcome = state->outcome; + status = outcome.status; + contentType = outcome.contentType; + if (!outcome.transportOk) { + TNS_DEBUG(Esm, "[http-loader][fetch-error] url=%s %s status=%d bodyEmpty=%d ms=%llu", + url.c_str(), state->errorDescription.c_str(), outcome.status, + outcome.body.empty() ? 1 : 0, (unsigned long long)fetchMs); return false; } - out.swap(bodyLocal); + out.swap(outcome.body); return true; } } -// ───────────────────────────────────────────────────────────── -// Async module fetch (NSURLSession) -// -// The async pipeline's fetches never block the JS thread, so the -// NSURLConnection workaround documented above PerformHttpFetchOnceSync does -// not apply here: that deadlock is specific to *synchronously waiting* on an -// NSURLSession task from the iOS main thread. Fire-and-forget tasks with a -// background delegate queue are the intended NSURLSession usage. -// -// 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]; - 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 = 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]; - }); - return s_session; -} - // One network attempt for FetchModuleBodyAsync. Takes ownership of // `completionHeap` (heap-allocated so the ObjC block can carry the // std::function across threads without ARC) and guarantees exactly one @@ -726,93 +748,80 @@ static void PerformModuleFetchAsyncAttempt( const std::string urlCopy = url; const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - NSURLSessionDataTask* task = [ModuleFetchSession() - dataTaskWithRequest:request - completionHandler:^(NSData* data, NSURLResponse* response, NSError* error) { - // NSURLSession invokes this block, so a C++ exception leaving it is - // an std::terminate rather than a failure anyone can report. Nothing - // here runs JS — the compile is posted to the isolate's own thread — - // so an escape could only come from an allocation failure, but the - // containment is structural on purpose: the graph load must hear - // back exactly once or it waits out its entire deadline. - bool retrying = false; - ModuleFetchResult result; - try { - int status = 0; - std::string contentType; - if ([response isKindOfClass:[NSHTTPURLResponse class]]) { - NSHTTPURLResponse* httpResp = (NSHTTPURLResponse*)response; - status = (int)[httpResp statusCode]; - NSString* ct = [httpResp allHeaderFields][@"Content-Type"]; - if (ct) { - const char* utf8 = [ct UTF8String]; - if (utf8) contentType = std::string(utf8); - } - } - std::string body; - if (data && [data length] > 0) { - body.assign(static_cast([data bytes]), - static_cast([data length])); + NSURLSessionDataTask* task = + CreateModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { + // NSURLSession invokes this block, so a C++ exception leaving it is + // an std::terminate rather than a failure anyone can report. Nothing + // here runs JS — the compile is posted to the isolate's own thread — + // so an escape could only come from an allocation failure, but the + // containment is structural on purpose: the graph load must hear + // back exactly once or it waits out its entire deadline. + bool retrying = false; + ModuleFetchResult result; + try { + ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); + int status = outcome.status; + std::string contentType = std::move(outcome.contentType); + std::string body = std::move(outcome.body); + + // Transport error → one retry while the enclosing load's budget + // can still fit the delay — the same single-retry policy the + // sync path applies, without blocking any thread. The retry's + // own request clamps to whatever remains when it fires. + const bool retryFitsDeadline = + fetchDeadline <= 0 || + fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; + if (error != nil && attempt == 0 && retryFitsDeadline) { + TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", + urlCopy.c_str(), + (error.localizedDescription ?: @"").UTF8String); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, + (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), + dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, + completionHeap); + }); + // Set only once the retry is actually queued: it now owns the + // completion, and this attempt must not settle it too. + retrying = true; + } else { + ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); + + if (!result.ok) { + TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, + result.failureReason.c_str()); + } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { + const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); + const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; + TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", + urlCopy.c_str(), (unsigned long)result.body.size(), + (unsigned long long)ms); } - - // Transport error → one retry while the enclosing load's budget - // can still fit the delay — the same single-retry policy the - // sync path applies, without blocking any thread. The retry's - // own request clamps to whatever remains when it fires. - const bool retryFitsDeadline = - fetchDeadline <= 0 || - fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; - if (error != nil && attempt == 0 && retryFitsDeadline) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", - urlCopy.c_str(), - (error.localizedDescription ?: @"").UTF8String); - dispatch_after( - dispatch_time(DISPATCH_TIME_NOW, - (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), - dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, completionHeap); - }); - // Set only once the retry is actually queued: it now owns the - // completion, and this attempt must not settle it too. - retrying = true; - } else { - ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, - result.failureReason.c_str()); - } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { - const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", - urlCopy.c_str(), (unsigned long)result.body.size(), - (unsigned long long)ms); - } - } - } catch (...) { - if (retrying) { - // The retry owns the completion and will settle it; nothing to - // report from here. - return; - } - result = ModuleFetchResult(); - result.failureReason = - "HTTP import failed: " + urlCopy + " (internal error handling the response)"; } - + } catch (...) { if (retrying) { + // The retry owns the completion and will settle it; nothing to + // report from here. return; } - // Guarded for the same reason: the completion posts to the - // isolate's loop, and a throw on the way out would cross the - // ObjC boundary instead of failing the load. - try { - (*completionHeap)(std::move(result)); - } catch (...) { - Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); - } - delete completionHeap; - }]; + result = ModuleFetchResult(); + result.failureReason = + "HTTP import failed: " + urlCopy + " (internal error handling the response)"; + } + + if (retrying) { + return; + } + // Guarded for the same reason: the completion posts to the + // isolate's loop, and a throw on the way out would cross the + // ObjC boundary instead of failing the load. + try { + (*completionHeap)(std::move(result)); + } catch (...) { + Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); + } + delete completionHeap; + }); [task resume]; } } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index d636e1bc..87e50abe 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -3021,4 +3021,98 @@ describe("invalid module specifiers", function () { }); }); +// The loader's HTTP cache lives on disk and outlives the app process, so every +// spec here keys its modules with a value unique to this run. +describe("HTTP module cache", function () { + var nsModule = require("ns:module"); + var originalTimeout; + var statsNonce = 0; + + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function hostOrigin() { + try { + var reportUrl = NSProcessInfo.processInfo.environment.objectForKey("REPORT_BASEURL"); + return reportUrl ? new URL(String(reportUrl)).origin : null; + } catch (e) { + return null; + } + } + + function uniqueKey(label) { + return label + "-" + Date.now() + "-" + Math.floor(Math.random() * 1e9); + } + + function formatError(error) { + return String((error && error.message) || error); + } + + // How many requests for `target` (path plus query) reached the server. + function requestCount(origin, target) { + statsNonce++; + return import(origin + "/esm/request-stats.json?target=" + encodeURIComponent(target) + + "&n=" + statsNonce).then(function (m) { + return m.default.count; + }); + } + + function requestCounts(origin, targets) { + return Promise.all(targets.map(function (target) { + return requestCount(origin, target); + })); + } + + describe("the synchronous fallback", function () { + // The entry's dependencies fail in the graph walk (503) and are then + // fetched by the resolver's synchronous fallback (200, immutable). + function fallbackGraph(origin, key) { + var query = "?k=" + key + "&cache=immutable"; + return { + entry: origin + "/esm/fallback/entry.mjs" + query, + deps: ["dep-a.mjs", "dep-a2.mjs", "dep-b.mjs"].map(function (name) { + return "/esm/fallback/" + name + query; + }), + }; + } + + it("stores what it fetches in the cache the graph walk reads", function (done) { + var origin = hostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var graph = fallbackGraph(origin, uniqueKey("sync-shared")); + import(graph.entry).then(function (mod) { + expect([mod.a, mod.b]).toEqual(["a", "b"]); + return requestCounts(origin, graph.deps); + }).then(function (counts) { + // dep-a and dep-b: the walk's 503, then the fallback's 200. + // dep-a2: the fallback's request only. + expect(counts).toEqual([2, 1, 2]); + nsModule.invalidateModules([graph.entry].concat(graph.deps.map(function (dep) { + return origin + dep; + }))); + return import(graph.entry); + }).then(function (mod) { + expect([mod.a, mod.b]).toEqual(["a", "b"]); + return requestCounts(origin, graph.deps); + }).then(function (counts) { + // The walk found the fallback's responses in its cache. + expect(counts).toEqual([2, 1, 2]); + done(); + }).catch(function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }); + }); + }); +}); + console.log("HTTP ESM Loader tests loaded"); \ No newline at end of file diff --git a/TestRunnerTests/ModuleTestServer.swift b/TestRunnerTests/ModuleTestServer.swift index 62440049..39f13fc5 100644 --- a/TestRunnerTests/ModuleTestServer.swift +++ b/TestRunnerTests/ModuleTestServer.swift @@ -8,8 +8,7 @@ typealias ModuleTestServerInput = (@escaping (Data) -> Void) -> Void /// Minimal loopback HTTP/1.1 server for the runtime test suite, built on /// Network.framework so request handling rides ordinary GCD instead of a /// vendored selector event loop. It exists to answer exactly two clients — -/// the runtime's module loader (NSURLSession + the synchronous NSURLConnection -/// fallback) and the Jasmine reporter — so the HTTP surface is deliberately +/// the runtime's module loader 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. /// diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 2f99bf8f..996acd23 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -251,6 +251,54 @@ class TestRunnerTests: XCTestCase { return } + // ── Synchronous-fallback routes ── + // `…/entry.mjs` statically imports `dep-a.mjs` and `dep-b.mjs`, + // and `dep-a.mjs` imports `dep-a2.mjs`. `dep-a.mjs` and + // `dep-b.mjs` answer their first request with 503 and later ones + // with the module, so the graph walk's fetch fails and the + // resolver's synchronous fallback fetches them. The walk never + // sees `dep-a2.mjs`, so the fallback fetches it too, first time + // round. `cache` sets the 200's Cache-Control. + if path.hasPrefix("/esm/fallback/") { + var cacheControl = "no-cache" + for pair in query.split(separator: "&") where pair.hasPrefix("cache=") { + if pair.dropFirst("cache=".count) == "immutable" { + cacheControl = "max-age=31536000, immutable" + } + } + let name = path.dropFirst("/esm/fallback/".count) + let target = query.isEmpty ? path : "\(path)?\(query)" + if (name == "dep-a.mjs" || name == "dep-b.mjs") && + self.requestCounts[target] == 1 { + startResponse("503 Service Unavailable", [ + ("Content-Type", "text/plain; charset=utf-8"), + ("Cache-Control", "no-store"), + ]) + sendBody(Data("try again".utf8)) + return + } + let q = query.isEmpty ? "" : "?\(query)" + let body: String + switch name { + case "entry.mjs": + body = "export { a } from \"./dep-a.mjs\(q)\";\n" + + "export { b } from \"./dep-b.mjs\(q)\";\n" + case "dep-a.mjs": + body = "export { a2 } from \"./dep-a2.mjs\(q)\";\n" + + "export const a = \"a\";\n" + default: + let id = name.replacingOccurrences(of: "dep-", with: "") + .replacingOccurrences(of: ".mjs", with: "") + body = "export const \(id) = \"\(id)\";\n" + } + startResponse("200 OK", [ + ("Content-Type", "application/javascript; charset=utf-8"), + ("Cache-Control", cacheControl), + ]) + 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 8aaf580c..4d37e435 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1365,14 +1365,13 @@ 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 +Module fetches use 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`. +never reads, replaces or resizes the app's shared `NSURLCache`. Requests use +the default protocol cache policy. The synchronous fallback issues its request +on the same session and blocks for at most the request timeout plus five +seconds per attempt. 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 From 1f00b4c92b696842a2a6e5a835d9ee51a3369c8f Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:22:18 -0300 Subject: [PATCH 2/7] 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. --- NativeScript/runtime/HttpLoader.h | 33 +- NativeScript/runtime/HttpLoader.mm | 504 ++++++++++++++---- .../runtime/ModuleInternalCallbacks.h | 2 + .../runtime/ModuleInternalCallbacks.mm | 16 + NativeScript/runtime/ModuleUrl.cpp | 8 + NativeScript/runtime/ModuleUrl.h | 5 + NativeScript/runtime/js/ns-module.js | 2 + TestRunner/app/tests/HttpEsmLoaderTests.js | 234 +++++++- TestRunner/app/tests/httpCacheWorker.js | 14 + TestRunnerTests/ModuleTestServer.swift | 17 +- TestRunnerTests/TestRunnerTests.swift | 37 +- docs/ns-builtin-modules.md | 68 ++- types/ns-module.d.ts | 32 +- 13 files changed, 829 insertions(+), 143 deletions(-) create mode 100644 TestRunner/app/tests/httpCacheWorker.js diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index ffa62790..546110f6 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -110,10 +111,11 @@ void FetchModuleBodyAsync( // ───────────────────────────────────────────────────────────── // Remote-module security gate // -// Seeded once from nativescript.config / package.json (`security.allowRemoteModules`, -// `security.remoteModuleAllowlist`) the first time a fetch is gated. Debug -// builds always allow. These values are not readable or writable through -// ns:runtime getConfig/setConfig — only nativescript.config at boot. +// Seeded once from nativescript.config / package.json +// (`security.allowRemoteModules`, `security.remoteModuleAllowlist`) the first +// time a fetch is gated. Debug builds always allow. These values are not +// readable or writable through ns:runtime getConfig/setConfig — only +// nativescript.config at boot. // In debug mode (RuntimeConfig.IsDebug): always returns true. // Otherwise returns the boot-time `security.allowRemoteModules` value. @@ -147,4 +149,27 @@ RemoteModuleAllowlist RemoteModuleAllowlistFromConfig(id value); // at a URL-component boundary. bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); +// ───────────────────────────────────────────────────────────── +// Module HTTP cache controls +// +// Process-wide, shared by every isolate, callable from any thread. A fetch +// uses the cache when it is enabled and no inspector connection has it +// disabled; that is decided when the fetch is issued, so fetches in flight are +// unaffected. Disabled means nothing is read from or written to it. The launch +// arguments `--nativescript-no-module-cache` and +// `--nativescript-clear-module-cache` and the `moduleHttpCache` app config key +// are read once per process, before the first fetch. + +void SetModuleHttpCacheEnabled(bool enabled); + +// Records whether inspector connection `connectionId` has the cache disabled; +// false also forgets the connection. +void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, + bool disabled); + +// Empties the cache of every origin before returning, durably: a process +// killed right after the call does not find the old entries at its next +// launch. +void ClearModuleHttpCache(); + } // namespace tns diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index f63cdb90..f867f92b 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -5,8 +5,10 @@ #include #include +#include #include #include +#include #include #include #include "Caches.h" @@ -259,7 +261,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { // (StartModuleGraphLoad), which fetches the transitive closure // concurrently off the JS thread before instantiation begins. // -// Both issue their requests through CreateModuleFetchTask, so they share one +// Both issue their requests through StartModuleFetchTask, so they share one // session and its HTTP cache, BuildModuleFetchRequest shapes every request, // and ClassifyModuleResponse judges every response. Neither can drift into // its own idea of what a valid module response is. @@ -517,40 +519,297 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { } // ───────────────────────────────────────────────────────────── -// The module fetch session +// The module HTTP cache // -// 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. Its -// delegate queue is the session's own background queue, never the main queue, -// so a thread blocked waiting on one of its tasks does not hold up the +// Module fetches use ephemeral sessions, so no cookies or credentials persist. +// While the cache is enabled each origin gets a session of its own with an +// on-disk NSURLCache in its own directory, so one origin's cache can be +// dropped without touching another's; the app's shared NSURLCache is never +// read, replaced or resized. While it is disabled every fetch goes through one +// session without a cache. +// +// Every session's delegate queue is its own background queue, never the main +// queue, so a thread blocked waiting on one of its tasks does not hold up the // completion it waits for. -static NSURLSession* ModuleFetchSession() { - static NSURLSession* s_session = nil; - static dispatch_once_t s_once; - dispatch_once(&s_once, ^{ - NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; - 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 = 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]; +// +// On disk, under Library/Caches/ns-module-http-cache: +// origins/// one NSURLCache directory +// trash/ deleted in the background +// A cache is dropped by moving its directory into trash, which is atomic; its +// session finishes the tasks it has in flight, and anything those tasks store +// lands in the moved directory or, should a write recreate the old path, in a +// generation older than the one the origin uses next. An origin always opens +// its highest generation, and removes the others when it does. +// +// All of it is process-wide, guarded by one mutex: fetch threads, every +// isolate's thread and the inspector's socket thread read and change it. + +static constexpr NSUInteger kModuleCacheMemoryCapacity = 8 * 1024 * 1024; +static constexpr NSUInteger kModuleCacheDiskCapacity = 256 * 1024 * 1024; + +// Top-level app config key; `false` starts the process with the cache off. +static constexpr const char* kModuleHttpCacheConfigKey = "moduleHttpCache"; + +namespace { + +struct ModuleCachePartition { + NSURLSession* session = nil; // retained + NSURL* directory = nil; // retained + uint64_t generation = 0; +}; + +struct ModuleHttpCacheState { + std::mutex mutex; + bool initialized = false; + bool userEnabled = true; + std::set inspectorDisabledConnections; + std::map partitions; + // The generation each origin must open next, set when its cache is dropped + // in this process. + std::map reservedGenerations; + NSURLSession* uncachedSession = nil; // retained + NSURL* root = nil; // retained +}; + +ModuleHttpCacheState& CacheState() { + static auto* state = new ModuleHttpCacheState(); + return *state; +} + +} // namespace + +static NSURLSessionConfiguration* ModuleSessionConfiguration(NSURLCache* cache) { + NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + // nil, not the ephemeral configuration's default in-memory cache: an + // uncached session must not cache at all. + config.URLCache = cache; + 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 = 32; + return config; +} + +static NSURL* OriginsDirectory(ModuleHttpCacheState& state) { + return [state.root URLByAppendingPathComponent:@"origins" isDirectory:YES]; +} + +static NSURL* TrashDirectory(ModuleHttpCacheState& state) { + return [state.root URLByAppendingPathComponent:@"trash" isDirectory:YES]; +} + +// Moves `item` into trash under a fresh name. Returns false only when `item` +// still exists afterwards. +static bool MoveToTrash(ModuleHttpCacheState& state, NSURL* item) { + NSFileManager* fm = [NSFileManager defaultManager]; + NSURL* trash = TrashDirectory(state); + [fm createDirectoryAtURL:trash withIntermediateDirectories:YES attributes:nil error:nil]; + NSURL* destination = [trash URLByAppendingPathComponent:[NSUUID UUID].UUIDString]; + if ([fm moveItemAtURL:item toURL:destination error:nil]) { + return true; + } + if (![fm fileExistsAtPath:item.path]) { + return true; + } + return [fm removeItemAtURL:item error:nil]; +} + +static void PurgeTrashInBackground(ModuleHttpCacheState& state) { + NSURL* trash = TrashDirectory(state); + dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ + @autoreleasepool { + NSFileManager* fm = [NSFileManager defaultManager]; + for (NSURL* item in [fm contentsOfDirectoryAtURL:trash + includingPropertiesForKeys:nil + options:0 + error:nil]) { + [fm removeItemAtURL:item error:nil]; + } + } }); - return s_session; +} + +// "http://127.0.0.1:8080" → "http%3A%2F%2F127.0.0.1%3A8080": collision-free +// and a single path component. +static NSString* OriginDirectoryName(const std::string& origin) { + static const char kHex[] = "0123456789ABCDEF"; + std::string name; + for (unsigned char c : origin) { + if (isalnum(c) || c == '.' || c == '-') { + name += (char)c; + } else { + name += '%'; + name += kHex[c >> 4]; + name += kHex[c & 0xF]; + } + } + return [NSString stringWithUTF8String:name.c_str()]; +} + +static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { + if (state.initialized) { + return; + } + state.initialized = true; + + NSURL* caches = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory + inDomains:NSUserDomainMask] + .firstObject; + state.root = [[caches URLByAppendingPathComponent:@"ns-module-http-cache" + isDirectory:YES] retain]; + + NSArray* arguments = [NSProcessInfo processInfo].arguments; + id configured = Runtime::GetAppConfigValue(kModuleHttpCacheConfigKey); + if ([configured isKindOfClass:[NSNumber class]] && ![(NSNumber*)configured boolValue]) { + state.userEnabled = false; + } + if ([arguments containsObject:@"--nativescript-no-module-cache"]) { + state.userEnabled = false; + } + + // Anything at the root besides the two directories above is not a cache + // this runtime opens, so it goes too. + NSFileManager* fm = [NSFileManager defaultManager]; + const bool clearAtLaunch = [arguments containsObject:@"--nativescript-clear-module-cache"]; + for (NSURL* item in [fm contentsOfDirectoryAtURL:state.root + includingPropertiesForKeys:nil + options:0 + error:nil]) { + NSString* name = item.lastPathComponent; + if ([name isEqualToString:@"trash"] || ([name isEqualToString:@"origins"] && !clearAtLaunch)) { + continue; + } + MoveToTrash(state, item); + } + PurgeTrashInBackground(state); + + NSURLSessionConfiguration* config = ModuleSessionConfiguration(nil); + state.uncachedSession = [[NSURLSession sessionWithConfiguration:config] retain]; +} + +// The partition for `origin`, opened on first use in this process. Opening +// reuses the origin's highest generation on disk unless its cache was dropped +// in this process, and removes every other generation. +static ModuleCachePartition& PartitionLocked(ModuleHttpCacheState& state, + const std::string& origin) { + auto it = state.partitions.find(origin); + if (it != state.partitions.end()) { + return it->second; + } + + NSFileManager* fm = [NSFileManager defaultManager]; + NSURL* originDirectory = + [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) + isDirectory:YES]; + uint64_t highest = 0; + NSArray* entries = [fm contentsOfDirectoryAtURL:originDirectory + includingPropertiesForKeys:nil + options:0 + error:nil]; + for (NSURL* entry in entries) { + const char* name = entry.lastPathComponent.UTF8String; + char* end = nullptr; + const unsigned long long generation = strtoull(name, &end, 10); + if (end != name && *end == '\0') { + highest = std::max(highest, generation); + } + } + auto reserved = state.reservedGenerations.find(origin); + const uint64_t generation = reserved != state.reservedGenerations.end() + ? reserved->second + : std::max(highest, 1); + + NSString* generationName = [NSString stringWithFormat:@"%llu", (unsigned long long)generation]; + for (NSURL* entry in entries) { + if (![entry.lastPathComponent isEqualToString:generationName]) { + MoveToTrash(state, entry); + } + } + + NSURL* directory = [originDirectory URLByAppendingPathComponent:generationName isDirectory:YES]; + [fm createDirectoryAtURL:directory withIntermediateDirectories:YES attributes:nil error:nil]; + NSURLCache* cache = [[NSURLCache alloc] initWithMemoryCapacity:kModuleCacheMemoryCapacity + diskCapacity:kModuleCacheDiskCapacity + directoryURL:directory]; + NSURLSessionConfiguration* config = ModuleSessionConfiguration(cache); + [cache release]; + + ModuleCachePartition& partition = state.partitions[origin]; + partition.session = [[NSURLSession sessionWithConfiguration:config] retain]; + partition.directory = [directory retain]; + partition.generation = generation; + return partition; +} + +// Drops the cache of one open partition: its directory moves to trash, an +// empty directory for the next generation takes its place, and the session +// finishes what it has in flight without being used again. +static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { + auto it = state.partitions.find(origin); + if (it == state.partitions.end()) { + return; + } + ModuleCachePartition partition = it->second; + state.partitions.erase(it); + + MoveToTrash(state, partition.directory); + const uint64_t next = partition.generation + 1; + state.reservedGenerations[origin] = next; + NSURL* nextDirectory = [[partition.directory URLByDeletingLastPathComponent] + URLByAppendingPathComponent:[NSString stringWithFormat:@"%llu", (unsigned long long)next] + isDirectory:YES]; + [[NSFileManager defaultManager] createDirectoryAtURL:nextDirectory + withIntermediateDirectories:YES + attributes:nil + error:nil]; + + [partition.session finishTasksAndInvalidate]; + [partition.session release]; + [partition.directory release]; +} + +static void ClearModuleHttpCacheLocked(ModuleHttpCacheState& state) { + // Every origin at once, opened in this process or not; the open ones then + // get their next-generation directory back. + MoveToTrash(state, OriginsDirectory(state)); + std::vector open; + for (const auto& entry : state.partitions) { + open.push_back(entry.first); + } + for (const std::string& origin : open) { + DropPartitionLocked(state, origin); + } + PurgeTrashInBackground(state); +} + +void SetModuleHttpCacheEnabled(bool enabled) { + ModuleHttpCacheState& state = CacheState(); + std::lock_guard lock(state.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state); + } + state.userEnabled = enabled; +} + +void SetModuleHttpCacheDisabledByInspector(uint64_t connectionId, bool disabled) { + ModuleHttpCacheState& state = CacheState(); + std::lock_guard lock(state.mutex); + if (disabled) { + state.inspectorDisabledConnections.insert(connectionId); + } else { + state.inspectorDisabledConnections.erase(connectionId); + } +} + +void ClearModuleHttpCache() { + ModuleHttpCacheState& state = CacheState(); + std::lock_guard lock(state.mutex); + @autoreleasepool { + InitializeModuleHttpCacheLocked(state); + ClearModuleHttpCacheLocked(state); + } } // Shared request builder for every module fetch. Caching follows the protocol @@ -601,13 +860,34 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re return outcome; } -// Every module request goes out through here, whichever path issued it. -// `handler` runs exactly once, on the session's delegate queue. Returns an -// autoreleased task the caller must resume. -static NSURLSessionDataTask* CreateModuleFetchTask(NSMutableURLRequest* request, - void (^handler)(NSData*, NSURLResponse*, - NSError*)) { - return [ModuleFetchSession() dataTaskWithRequest:request completionHandler:handler]; +// Every module request goes out through here, whichever path issued it: the +// cache switch is read now, so it decides this request alone. `handler` runs +// exactly once, on the session's delegate queue. Returns the resumed task, +// autoreleased. +static NSURLSessionDataTask* StartModuleFetchTask(NSMutableURLRequest* request, + void (^handler)(NSData*, NSURLResponse*, + NSError*)) { + ModuleHttpCacheState& state = CacheState(); + std::lock_guard lock(state.mutex); + InitializeModuleHttpCacheLocked(state); + + const bool enabled = state.userEnabled && state.inspectorDisabledConnections.empty(); + const std::string origin = + enabled ? HttpUrlOrigin(request.URL.absoluteString.UTF8String ?: "") : std::string(); + NSURLSession* session = nil; + if (!origin.empty()) { + session = PartitionLocked(state, origin).session; + } else { + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; + [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; + session = state.uncachedSession; + } + // Created and resumed under the lock: a cache dropped on another thread + // invalidates its session, which then refuses new tasks. + NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:handler]; + [task resume]; + return task; } // One blocking fetch attempt for the synchronous fallback, on the same session @@ -636,7 +916,7 @@ static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, const auto fetchStartUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); NSURLSessionDataTask* task = - CreateModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { + StartModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { try { state->outcome = ReadModuleFetchOutcome(data, response, error); if (error != nil) { @@ -651,7 +931,6 @@ static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, } dispatch_semaphore_signal(state->done); }); - [task resume]; const double waitSeconds = request.timeoutInterval + kModuleFetchSyncWaitMarginSeconds; if (dispatch_semaphore_wait( @@ -748,81 +1027,78 @@ static void PerformModuleFetchAsyncAttempt( const std::string urlCopy = url; const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - NSURLSessionDataTask* task = - CreateModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { - // NSURLSession invokes this block, so a C++ exception leaving it is - // an std::terminate rather than a failure anyone can report. Nothing - // here runs JS — the compile is posted to the isolate's own thread — - // so an escape could only come from an allocation failure, but the - // containment is structural on purpose: the graph load must hear - // back exactly once or it waits out its entire deadline. - bool retrying = false; - ModuleFetchResult result; - try { - ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); - int status = outcome.status; - std::string contentType = std::move(outcome.contentType); - std::string body = std::move(outcome.body); - - // Transport error → one retry while the enclosing load's budget - // can still fit the delay — the same single-retry policy the - // sync path applies, without blocking any thread. The retry's - // own request clamps to whatever remains when it fires. - const bool retryFitsDeadline = - fetchDeadline <= 0 || - fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; - if (error != nil && attempt == 0 && retryFitsDeadline) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", - urlCopy.c_str(), - (error.localizedDescription ?: @"").UTF8String); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, - (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), - dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, - completionHeap); - }); - // Set only once the retry is actually queued: it now owns the - // completion, and this attempt must not settle it too. - retrying = true; - } else { - ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, - result.failureReason.c_str()); - } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { - const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", - urlCopy.c_str(), (unsigned long)result.body.size(), - (unsigned long long)ms); - } - } - } catch (...) { - if (retrying) { - // The retry owns the completion and will settle it; nothing to - // report from here. - return; - } - result = ModuleFetchResult(); - result.failureReason = - "HTTP import failed: " + urlCopy + " (internal error handling the response)"; + StartModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { + // NSURLSession invokes this block, so a C++ exception leaving it is + // an std::terminate rather than a failure anyone can report. Nothing + // here runs JS — the compile is posted to the isolate's own thread — + // so an escape could only come from an allocation failure, but the + // containment is structural on purpose: the graph load must hear + // back exactly once or it waits out its entire deadline. + bool retrying = false; + ModuleFetchResult result; + try { + ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); + int status = outcome.status; + std::string contentType = std::move(outcome.contentType); + std::string body = std::move(outcome.body); + + // Transport error → one retry while the enclosing load's budget + // can still fit the delay — the same single-retry policy the + // sync path applies, without blocking any thread. The retry's + // own request clamps to whatever remains when it fires. + const bool retryFitsDeadline = + fetchDeadline <= 0 || + fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; + if (error != nil && attempt == 0 && retryFitsDeadline) { + TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", + urlCopy.c_str(), + (error.localizedDescription ?: @"").UTF8String); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, + (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), + dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, + completionHeap); + }); + // Set only once the retry is actually queued: it now owns the + // completion, and this attempt must not settle it too. + retrying = true; + } else { + ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); + + if (!result.ok) { + TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, + result.failureReason.c_str()); + } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { + const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); + const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; + TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", urlCopy.c_str(), + (unsigned long)result.body.size(), (unsigned long long)ms); } + } + } catch (...) { + if (retrying) { + // The retry owns the completion and will settle it; nothing to + // report from here. + return; + } + result = ModuleFetchResult(); + result.failureReason = + "HTTP import failed: " + urlCopy + " (internal error handling the response)"; + } - if (retrying) { - return; - } - // Guarded for the same reason: the completion posts to the - // isolate's loop, and a throw on the way out would cross the - // ObjC boundary instead of failing the load. - try { - (*completionHeap)(std::move(result)); - } catch (...) { - Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); - } - delete completionHeap; - }); - [task resume]; + if (retrying) { + return; + } + // Guarded for the same reason: the completion posts to the + // isolate's loop, and a throw on the way out would cross the + // ObjC boundary instead of failing the load. + try { + (*completionHeap)(std::move(result)); + } catch (...) { + Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); + } + delete completionHeap; + }); } } diff --git a/NativeScript/runtime/ModuleInternalCallbacks.h b/NativeScript/runtime/ModuleInternalCallbacks.h index ca23d328..92a0b38c 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.h +++ b/NativeScript/runtime/ModuleInternalCallbacks.h @@ -234,6 +234,8 @@ void SetVolatilePatterns(const std::vector& patterns); // the calling isolate) // - invalidateModules(urls) (registry + cache eviction) // - getLoadedModuleUrls() (registry introspection) +// - setHttpCacheEnabled(enabled) (process-wide HTTP cache switch) +// - clearHttpCache() (empties the process-wide HTTP cache) // - createRequire(baseDir, pumping) (a require bound to baseDir; the JS half // in ns-module.js validates the caller's // filename/URL and splits the two diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 42f38953..89d24113 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -4230,6 +4230,20 @@ void GetLoadedModuleUrlsCallback(const v8::FunctionCallbackInfo& info info.GetReturnValue().Set(result); } +void SetHttpCacheEnabledCallback(const v8::FunctionCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + if (info.Length() < 1 || !info[0]->IsBoolean()) { + isolate->ThrowException(v8::Exception::TypeError( + tns::ToV8String(isolate, "setHttpCacheEnabled expects a boolean"))); + return; + } + tns::SetModuleHttpCacheEnabled(info[0]->BooleanValue(isolate)); +} + +void ClearHttpCacheCallback(const v8::FunctionCallbackInfo& info) { + tns::ClearModuleHttpCache(); +} + } // namespace bool BuildNsModuleBinding(v8::Local context, v8::Local binding) { @@ -4238,6 +4252,8 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local InstallDevFunction(isolate, context, binding, "configureLoader", ConfigureLoaderCallback); InstallDevFunction(isolate, context, binding, "invalidateModules", InvalidateModulesCallback); InstallDevFunction(isolate, context, binding, "getLoadedModuleUrls", GetLoadedModuleUrlsCallback); + InstallDevFunction(isolate, context, binding, "setHttpCacheEnabled", SetHttpCacheEnabledCallback); + InstallDevFunction(isolate, context, binding, "clearHttpCache", ClearHttpCacheCallback); if (!ModuleInternal::InstallCreateRequireBinding(context, binding)) { return false; diff --git a/NativeScript/runtime/ModuleUrl.cpp b/NativeScript/runtime/ModuleUrl.cpp index 62340321..8476eb98 100644 --- a/NativeScript/runtime/ModuleUrl.cpp +++ b/NativeScript/runtime/ModuleUrl.cpp @@ -53,6 +53,14 @@ bool IsHttpRegistryKey(const std::string& key) { return key.compare(schemeEnd, 3, "://") == 0; } +std::string HttpUrlOrigin(const std::string& url) { + auto parsed = ada::parse(url, nullptr); + if (!parsed || !HasHttpScheme(*parsed)) { + return std::string(); + } + return parsed->get_origin(); +} + ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { ModuleUrl result; ada::result url; diff --git a/NativeScript/runtime/ModuleUrl.h b/NativeScript/runtime/ModuleUrl.h index 359d429b..a1476c1e 100644 --- a/NativeScript/runtime/ModuleUrl.h +++ b/NativeScript/runtime/ModuleUrl.h @@ -34,6 +34,11 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); // not an http(s) URL. std::string NormalizeHttpModuleUrl(const std::string& input); +// The WHATWG origin (`scheme://host[:port]`, default port omitted, host +// lowercased) of an absolute http(s) URL; empty for anything else. Never part +// of a module's identity, which keeps the authority as written. +std::string HttpUrlOrigin(const std::string& url); + // Whether `s` starts with a URL scheme and ':' (`node:fs`, `blob:…`, // `http://…`) rather than being a filesystem path. bool HasUrlScheme(const std::string& s); diff --git a/NativeScript/runtime/js/ns-module.js b/NativeScript/runtime/js/ns-module.js index 9d57e30e..def3f17f 100644 --- a/NativeScript/runtime/js/ns-module.js +++ b/NativeScript/runtime/js/ns-module.js @@ -174,6 +174,8 @@ const surface = { configureLoader: binding.configureLoader, invalidateModules: binding.invalidateModules, getLoadedModuleUrls: binding.getLoadedModuleUrls, + setHttpCacheEnabled: binding.setHttpCacheEnabled, + clearHttpCache: binding.clearHttpCache, createRequire, createPumpingRequire, }; diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 87e50abe..ac49ad7f 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -1548,8 +1548,9 @@ describe("HTTP ESM Loader", function() { // builds), so the expected set varies by build. it("exposes exactly the declared surface", function () { var nsModule = require("ns:module"); - var expected = ["configureLoader", "createPumpingRequire", "createRequire", - "getLoadedModuleUrls", "invalidateModules"]; + var expected = ["clearHttpCache", "configureLoader", "createPumpingRequire", + "createRequire", "getLoadedModuleUrls", "invalidateModules", + "setHttpCacheEnabled"]; if (typeof nsModule.canonicalizeHttpUrlKey === "function") { expected.push("canonicalizeHttpUrlKey", "remoteUrlMatchesAllowlist"); } @@ -3034,6 +3035,8 @@ describe("HTTP module cache", function () { }); afterEach(function () { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + // The switch is process-wide: leave it as every other spec expects. + nsModule.setHttpCacheEnabled(true); }); function hostOrigin() { @@ -3053,15 +3056,210 @@ describe("HTTP module cache", function () { return String((error && error.message) || error); } - // How many requests for `target` (path plus query) reached the server. - function requestCount(origin, target) { + // What the server saw for `target` (path plus query): `count` requests, + // the latest carrying the cache-related `headers` (lowercased names). + function requestStats(origin, target) { statsNonce++; return import(origin + "/esm/request-stats.json?target=" + encodeURIComponent(target) + "&n=" + statsNonce).then(function (m) { - return m.default.count; + return m.default; + }); + } + + function requestCount(origin, target) { + return requestStats(origin, target).then(function (stats) { + return stats.count; }); } + // A `/esm/cache/` module target; `mode` is "immutable" or omitted for + // `no-cache`. + function cacheTarget(name, key, mode) { + return "/esm/cache/" + name + ".mjs?k=" + key + (mode ? "&cache=" + mode : ""); + } + + function evaluations(target) { + return (globalThis.__nsCacheEvaluations || {})[target] || 0; + } + + // Evicts the module from the registry and imports it again, so the import + // goes through the HTTP cache. + function reimport(origin, target) { + nsModule.invalidateModules([origin + target]); + return import(origin + target); + } + + function skipWithoutHost(origin, done) { + if (origin) { + return false; + } + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return true; + } + + function failWith(done) { + return function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }; + } + + describe("controls", function () { + it("reuses an immutable module after invalidateModules", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var target = cacheTarget("reuse", uniqueKey("reuse"), "immutable"); + import(origin + target).then(function () { + return reimport(origin, target); + }).then(function () { + expect(evaluations(target)).toBe(2); + return requestCount(origin, target); + }).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(failWith(done)); + }); + + it("requests a cached module again after clearHttpCache()", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var target = cacheTarget("clear", uniqueKey("clear"), "immutable"); + import(origin + target).then(function () { + nsModule.clearHttpCache(); + return reimport(origin, target); + }).then(function () { + return requestCount(origin, target); + }).then(function (count) { + expect(count).toBe(2); + done(); + }).catch(failWith(done)); + }); + + it("neither reads nor writes the cache while it is disabled", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var cached = cacheTarget("off-read", uniqueKey("off-read"), "immutable"); + var fresh = cacheTarget("off-write", uniqueKey("off-write"), "immutable"); + import(origin + cached).then(function () { + nsModule.setHttpCacheEnabled(false); + return reimport(origin, cached); + }).then(function () { + return import(origin + fresh); + }).then(function () { + return reimport(origin, fresh); + }).then(function () { + return Promise.all([requestStats(origin, cached), requestStats(origin, fresh)]); + }).then(function (stats) { + // Not read: the cached module went to the server again. + // Every disabled request carried both no-cache headers. + expect(stats[0].count).toBe(2); + expect(stats[1].count).toBe(2); + expect(stats[1].headers["cache-control"]).toBe("no-cache"); + expect(stats[1].headers.pragma).toBe("no-cache"); + nsModule.setHttpCacheEnabled(true); + return reimport(origin, fresh); + }).then(function () { + return reimport(origin, fresh); + }).then(function () { + return requestStats(origin, fresh); + }).then(function (stats) { + // Not written: enabled again, the first import still went to + // the server, and only that response was then reused. + expect(stats.count).toBe(3); + expect(stats.headers["cache-control"]).toBeUndefined(); + expect(stats.headers.pragma).toBeUndefined(); + done(); + }).catch(failWith(done)); + }); + + it("clears while disabled, so re-enabling finds the cache empty", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var target = cacheTarget("off-clear", uniqueKey("off-clear"), "immutable"); + import(origin + target).then(function () { + nsModule.setHttpCacheEnabled(false); + nsModule.clearHttpCache(); + nsModule.setHttpCacheEnabled(true); + return reimport(origin, target); + }).then(function () { + return requestCount(origin, target); + }).then(function (count) { + expect(count).toBe(2); + done(); + }).catch(failWith(done)); + }); + + it("rejects a non-boolean in setHttpCacheEnabled with a TypeError", function () { + [undefined, null, 0, 1, "false", {}].forEach(function (value) { + var error = null; + try { + nsModule.setHttpCacheEnabled(value); + } catch (e) { + error = e; + } + expect(error instanceof TypeError ? error.message : String(error)) + .toBe("setHttpCacheEnabled expects a boolean"); + }); + }); + + it("applies a worker's switch to the main isolate and the main's to workers", + function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var target = cacheTarget("worker", uniqueKey("worker"), "immutable"); + var worker = new Worker("./httpCacheWorker.js"); + function ask(message) { + return new Promise(function (resolve, reject) { + worker.onmessage = function (msg) { + if (msg.data.ok) { + resolve(); + } else { + reject(new Error(msg.data.error)); + } + }; + worker.postMessage(message); + }); + } + function finish(error) { + worker.terminate(); + if (error) { + failWith(done)(error); + } else { + done(); + } + } + import(origin + target).then(function () { + nsModule.setHttpCacheEnabled(false); + // The worker's own registry has never seen the module, so it + // fetches; the main isolate's switch keeps that off the cache. + return ask({ url: origin + target }); + }).then(function () { + return requestStats(origin, target); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.headers.pragma).toBe("no-cache"); + return ask({ setEnabled: true }); + }).then(function () { + return reimport(origin, target); + }).then(function () { + return requestCount(origin, target); + }).then(function (count) { + // Enabled by the worker: the main isolate reads the entry its + // first import stored. + expect(count).toBe(2); + return ask({ setEnabled: false }); + }).then(function () { + return reimport(origin, target); + }).then(function () { + return requestCount(origin, target); + }).then(function (count) { + expect(count).toBe(3); + finish(); + }).catch(finish); + }); + }); + function requestCounts(origin, targets) { return Promise.all(targets.map(function (target) { return requestCount(origin, target); @@ -3112,6 +3310,32 @@ describe("HTTP module cache", function () { done(); }); }); + + it("follows the cache switch", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var graph = fallbackGraph(origin, uniqueKey("sync-off")); + nsModule.setHttpCacheEnabled(false); + import(graph.entry).then(function () { + return requestStats(origin, graph.deps[0]); + }).then(function (stats) { + expect(stats.count).toBe(2); + expect(stats.headers["cache-control"]).toBe("no-cache"); + expect(stats.headers.pragma).toBe("no-cache"); + nsModule.setHttpCacheEnabled(true); + nsModule.invalidateModules([graph.entry].concat(graph.deps.map(function (dep) { + return origin + dep; + }))); + return import(graph.entry); + }).then(function () { + return requestCounts(origin, graph.deps); + }).then(function (counts) { + // Nothing the fallback fetched was stored: the walk requested + // every dependency again. + expect(counts).toEqual([3, 2, 3]); + done(); + }).catch(failWith(done)); + }); }); }); diff --git a/TestRunner/app/tests/httpCacheWorker.js b/TestRunner/app/tests/httpCacheWorker.js new file mode 100644 index 00000000..0c9c118b --- /dev/null +++ b/TestRunner/app/tests/httpCacheWorker.js @@ -0,0 +1,14 @@ +// Imports a URL, or flips the process-wide module HTTP cache switch, as the +// parent asks. +onmessage = function (msg) { + if (typeof msg.data.setEnabled === "boolean") { + require("ns:module").setHttpCacheEnabled(msg.data.setEnabled); + postMessage({ ok: true }); + return; + } + import(msg.data.url).then(function () { + postMessage({ ok: true }); + }).catch(function (error) { + postMessage({ ok: false, error: String((error && error.message) || error) }); + }); +}; diff --git a/TestRunnerTests/ModuleTestServer.swift b/TestRunnerTests/ModuleTestServer.swift index 39f13fc5..3d32357e 100644 --- a/TestRunnerTests/ModuleTestServer.swift +++ b/TestRunnerTests/ModuleTestServer.swift @@ -165,6 +165,7 @@ final class ModuleTestServer { "REQUEST_METHOD": head.method, "PATH_INFO": head.path, "QUERY_STRING": head.query, + "HTTP_HEADERS": head.headers, "swsgi.input": input, ] @@ -224,6 +225,8 @@ private struct ParsedRequestHead { let path: String let query: String let contentLength: Int + /// Header fields by lowercased name; the last one wins on repeats. + let headers: [String: String] init?(_ headerData: Data) { guard let text = String(data: headerData, encoding: .utf8) else { @@ -247,13 +250,19 @@ private struct ParsedRequestHead { query = "" } var length = 0 + var fields = [String: String]() for line in lines.dropFirst() { - let lowered = line.lowercased() - if lowered.hasPrefix("content-length:") { - length = Int(line.dropFirst("content-length:".count) - .trimmingCharacters(in: .whitespaces)) ?? 0 + guard let colon = line.firstIndex(of: ":") else { + continue + } + let name = line[line.startIndex...mjs` counts its evaluations per request + // target in globalThis.__nsCacheEvaluations. `cache` sets the + // Cache-Control: `immutable` (a year, immutable) or `no-cache` + // (the default). + if path.hasPrefix("/esm/cache/") { + let target = query.isEmpty ? path : "\(path)?\(query)" + let immutable = query.split(separator: "&").contains("cache=immutable") + let body = """ + const evaluations = globalThis.__nsCacheEvaluations || (globalThis.__nsCacheEvaluations = {}); + evaluations["\(jsStringLiteral(target))"] = (evaluations["\(jsStringLiteral(target))"] || 0) + 1; + export const target = "\(jsStringLiteral(target))"; + + """ + startResponse("200 OK", [ + ("Content-Type", "application/javascript; charset=utf-8"), + ("Cache-Control", immutable ? "max-age=31536000, immutable" : "no-cache"), + ]) + sendBody(body.data(using: .utf8) ?? Data()) + return + } + // ── Synchronous-fallback routes ── // `…/entry.mjs` statically imports `dep-a.mjs` and `dep-b.mjs`, // and `dep-a.mjs` imports `dep-a2.mjs`. `dep-a.mjs` and diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 4d37e435..ca49f71b 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -548,8 +548,10 @@ 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 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. | +| `invalidateModules(urls)` | Evicts the given URLs (canonicalized) from the module registry, so the next import of each requests it again. While the HTTP cache is on, that request goes through it, 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. | +| `setHttpCacheEnabled(enabled)` | Turns the loader's HTTP cache on or off for the whole process, workers included; see [Turning the cache off and clearing it](#turning-the-cache-off-and-clearing-it). Throws `TypeError` unless `enabled` is a boolean. | +| `clearHttpCache()` | Empties the loader's HTTP cache for every origin, for the whole process and for later launches. | | `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). | @@ -1193,8 +1195,47 @@ module scripts: the request carries no cache directives of its own, and the 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. +The request they cause is an ordinary one and, while the cache is on, is +answered from the HTTP cache whenever the server's headers allow it. + +The cache is kept per origin (scheme, host and port), is shared by every +isolate in the process, and serves every HTTP module fetch, the synchronous +fallback included. It is separate from the cache the app's own networking +uses, which the loader never touches. + +*Platform note (iOS):* the controls below are iOS behaviour for now; the +Android runtime has no module HTTP cache. + +#### Turning the cache off and clearing it + +The cache is **on** unless one of these turns it off: + +| control | effect | +|---|---| +| `setHttpCacheEnabled(false)` from `ns:module` | off until `setHttpCacheEnabled(true)` | +| launch argument `--nativescript-no-module-cache` | starts off | +| app config `"moduleHttpCache": false` (top level, next to `security`) | starts off | + +The launch argument and the app config are read once per process, before the +first module fetch, and `setHttpCacheEnabled` overrides them either way. They +apply to Debug and Release builds alike. + +While the cache is off nothing is read from it and nothing is written to it +(the Fetch `no-store` cache mode), and every request carries +`Cache-Control: no-cache` and `Pragma: no-cache`. The switch decides each +fetch when it is issued; a fetch already in flight finishes as it started. +Turning the cache back on reuses whatever it held before. + +These clear it: + +| control | clears | +|---|---| +| `clearHttpCache()` from `ns:module` | every origin | +| launch argument `--nativescript-clear-module-cache` | every origin, before the first fetch | + +A clear applies to the next fetch and to later launches, including when the +app is killed right after it, and works the same whether the cache is on or +off. ### App entries and bootstraps @@ -1365,13 +1406,20 @@ 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. -Module fetches use 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 reads, replaces or resizes the app's shared `NSURLCache`. Requests use -the default protocol cache policy. The synchronous fallback issues its request -on the same session and blocks for at most the request timeout plus five -seconds per attempt. +Module fetches use ephemeral `NSURLSession`s (no persistent cookies or +credentials). With the cache on, each origin has a session with an on-disk +`NSURLCache` of its own (8 MB memory, 256 MB disk) in +`Library/Caches/ns-module-http-cache/origins//`; with it +off, fetches use one session whose `URLCache` is `nil` and requests use +`NSURLRequestReloadIgnoringLocalCacheData`. The loader never reads, replaces +or resizes the app's shared `NSURLCache`. Requests otherwise use the default +protocol cache policy. A clear moves the origin's directory aside (into +`ns-module-http-cache/trash`, emptied in the background) and the next fetch +opens a new session on the next generation: `removeAllCachedResponses` is not +used because a process killed right after it still found the entries at its +next launch. The synchronous fallback issues its request through the same +sessions and blocks for at most the request timeout plus five seconds per +attempt. 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 diff --git a/types/ns-module.d.ts b/types/ns-module.d.ts index 02f7e7dc..f0a67408 100644 --- a/types/ns-module.d.ts +++ b/types/ns-module.d.ts @@ -64,9 +64,9 @@ declare module "ns:module" { importMap?: ImportMap; /** * 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. + * instead of being reused from the module registry. While the HTTP cache + * is on, the request still goes through it, so the server's caching + * headers decide whether it reaches the network. */ volatilePatterns?: string[]; canonicalization?: CanonicalizationConfig; @@ -86,8 +86,8 @@ declare module "ns:module" { /** * 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 + * next import of each requests it again. While the HTTP cache is on, that + * request goes through it: 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 @@ -101,6 +101,28 @@ declare module "ns:module" { */ export function getLoadedModuleUrls(): string[]; + /** + * Turns the loader's HTTP cache on or off for the whole process: every + * isolate, workers included. While it is off, module fetches neither read + * from nor write to the cache, and every request carries + * `Cache-Control: no-cache` and `Pragma: no-cache`. Fetches already in + * flight are unaffected. A DevTools frontend that disabled the cache through + * `Network.setCacheDisabled` keeps it off whatever this sets. + * + * Overrides the starting state set by the `--nativescript-no-module-cache` + * launch argument or the `moduleHttpCache` app config key. + * + * Throws `TypeError` if `enabled` is not a boolean. + */ + export function setHttpCacheEnabled(enabled: boolean): void; + + /** + * Empties the loader's HTTP cache for every origin, for the whole process. + * The next fetch of any module goes to the server, in this launch and in + * later ones. The app's own HTTP cache is not touched. + */ + export function clearHttpCache(): void; + /** * A `require` that resolves against the directory of `filenameOrURL` — a * trailing slash names the directory itself. Accepts an absolute path From c0c5b81053c4d893ff71b7ff9c9766067c1b6dc2 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:32:42 -0300 Subject: [PATCH 3/7] 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. --- NativeScript/runtime/HttpLoader.mm | 69 +++++++++++- TestRunner/app/tests/HttpEsmLoaderTests.js | 124 +++++++++++++++++++++ TestRunnerTests/TestRunnerTests.swift | 51 ++++++++- docs/ns-builtin-modules.md | 18 ++- 4 files changed, 255 insertions(+), 7 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index f867f92b..d406c9f6 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -812,6 +812,57 @@ void ClearModuleHttpCache() { } } +// Whether a Clear-Site-Data value, a comma-separated list of quoted strings, +// holds "cache" or "*". +static bool ClearSiteDataClearsCache(NSString* value) { + NSCharacterSet* whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet]; + for (NSString* item in [value componentsSeparatedByString:@","]) { + NSString* directive = [item stringByTrimmingCharactersInSet:whitespace]; + if ([directive isEqualToString:@"\"cache\""] || [directive isEqualToString:@"\"*\""]) { + return true; + } + } + return false; +} + +// Clear-Site-Data "cache" drops the cache of the response URL's origin. The +// partition the response was fetched through goes too, which is the same one +// unless a redirect crossed origins: the carrier itself is stored there, and +// left in place it would be replayed from the cache and clear again on every +// hit. Plain http: origins are honoured as well. +static void ApplyClearSiteData(NSURLResponse* response, const std::string& fetchingOrigin) { + if (![response isKindOfClass:[NSHTTPURLResponse class]]) { + return; + } + NSString* value = [(NSHTTPURLResponse*)response valueForHTTPHeaderField:@"Clear-Site-Data"]; + if (value == nil || !ClearSiteDataClearsCache(value)) { + return; + } + const std::string responseOrigin = HttpUrlOrigin(response.URL.absoluteString.UTF8String ?: ""); + + ModuleHttpCacheState& state = CacheState(); + std::lock_guard lock(state.mutex); + std::vector origins{responseOrigin}; + // Each origin once: a second pass would also trash the next-generation + // directory the first one reserved. + if (fetchingOrigin != responseOrigin) { + origins.push_back(fetchingOrigin); + } + for (const std::string& origin : origins) { + if (origin.empty()) { + continue; + } + if (state.partitions.count(origin) != 0) { + DropPartitionLocked(state, origin); + } else { + MoveToTrash(state, + [OriginsDirectory(state) URLByAppendingPathComponent:OriginDirectoryName(origin) + isDirectory:YES]); + } + } + PurgeTrashInBackground(state); +} + // Shared request builder for every module fetch. Caching follows the protocol // policy, so the server's response headers decide freshness. Returns an // autoreleased NSMutableURLRequest (nil for unparseable URLs). @@ -862,8 +913,9 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re // Every module request goes out through here, whichever path issued it: the // cache switch is read now, so it decides this request alone. `handler` runs -// exactly once, on the session's delegate queue. Returns the resumed task, -// autoreleased. +// exactly once, on the session's delegate queue, after the response's +// Clear-Site-Data has taken effect, so nothing the loader requests from then on +// can come from the cleared cache. Returns the resumed task, autoreleased. static NSURLSessionDataTask* StartModuleFetchTask(NSMutableURLRequest* request, void (^handler)(NSData*, NSURLResponse*, NSError*)) { @@ -883,9 +935,20 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; session = state.uncachedSession; } + void (^delivered)(NSData*, NSURLResponse*, NSError*) = + ^(NSData* data, NSURLResponse* response, NSError* error) { + @autoreleasepool { + try { + ApplyClearSiteData(response, origin); + } catch (...) { + Log(@"NativeScript: could not apply Clear-Site-Data from a module response"); + } + } + handler(data, response, error); + }; // Created and resumed under the lock: a cache dropped on another thread // invalidates its session, which then refuses new tasks. - NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:handler]; + NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:delivered]; [task resume]; return task; } diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index ac49ad7f..a3aa6dad 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -3266,6 +3266,130 @@ describe("HTTP module cache", function () { })); } + describe("Clear-Site-Data", function () { + function carrierTarget(key, directives) { + return "/esm/csd/carrier.mjs?k=" + key + "&directives=" + + encodeURIComponent(directives); + } + + // The same server under a second origin. + function otherOrigin(origin) { + return origin.replace("127.0.0.1", "localhost"); + } + + it("clears the response's origin once, before the response is delivered", + function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var key = uniqueKey("csd"); + var before = cacheTarget("csd-before", key, "immutable"); + var after = cacheTarget("csd-after", key, "immutable"); + var elsewhere = cacheTarget("csd-elsewhere", key, "immutable"); + var carrier = carrierTarget(key, "\"cookies\", \"cache\""); + var other = otherOrigin(origin); + Promise.all([import(origin + before), import(other + elsewhere)]).then(function () { + return import(origin + carrier); + }).then(function () { + return reimport(origin, before); + }).then(function () { + return import(origin + after); + }).then(function () { + return reimport(origin, after); + }).then(function () { + return reimport(other, elsewhere); + }).then(function () { + // The carrier was not kept: importing it again reaches the + // server, whose second response has no Clear-Site-Data, so + // nothing is cleared this time. + return reimport(origin, carrier); + }).then(function () { + return reimport(origin, after); + }).then(function () { + return requestCounts(origin, [before, after, elsewhere, carrier]); + }).then(function (counts) { + expect(counts).toEqual([2, 1, 1, 2]); + done(); + }).catch(failWith(done)); + }); + + it("clears on \"*\"", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var key = uniqueKey("csd-star"); + var cached = cacheTarget("csd-star", key, "immutable"); + import(origin + cached).then(function () { + return import(origin + carrierTarget(key, "\"*\"")); + }).then(function () { + return reimport(origin, cached); + }).then(function () { + return requestCount(origin, cached); + }).then(function (count) { + expect(count).toBe(2); + done(); + }).catch(failWith(done)); + }); + + it("ignores directives other than \"cache\" and \"*\"", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var key = uniqueKey("csd-storage"); + var cached = cacheTarget("csd-storage", key, "immutable"); + import(origin + cached).then(function () { + return import(origin + carrierTarget(key, "\"storage\", cache")); + }).then(function () { + return reimport(origin, cached); + }).then(function () { + return requestCount(origin, cached); + }).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(failWith(done)); + }); + + it("is applied to a response the synchronous fallback fetched", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var key = uniqueKey("csd-sync"); + var cached = cacheTarget("csd-sync", key, "immutable"); + import(origin + cached).then(function () { + // dep-b's synchronously fetched 200 carries the header. + return import(origin + "/esm/fallback/entry.mjs?k=" + key + + "&cache=immutable&csd=1"); + }).then(function () { + return reimport(origin, cached); + }).then(function () { + return requestCount(origin, cached); + }).then(function (count) { + expect(count).toBe(2); + done(); + }).catch(failWith(done)); + }); + + // The 304's header reaches the loader through the stored response + // NSURLSession delivers for the revalidation. + it("is applied when a 304 revalidation carries it", function (done) { + var origin = hostOrigin(); + if (skipWithoutHost(origin, done)) return; + var key = uniqueKey("csd-304"); + var cached = cacheTarget("csd-304", key, "immutable"); + var revalidate = "/esm/csd/revalidate.mjs?k=" + key; + import(origin + revalidate).then(function () { + return import(origin + cached); + }).then(function () { + return reimport(origin, revalidate); + }).then(function () { + return reimport(origin, cached); + }).then(function () { + return Promise.all([requestStats(origin, revalidate), requestCount(origin, cached)]); + }).then(function (results) { + expect(results[0].count).toBe(2); + expect(results[0].headers["if-none-match"]).toBe("\"v1\""); + expect(results[1]).toBe(2); + done(); + }).catch(failWith(done)); + }); + }); + describe("the synchronous fallback", function () { // The entry's dependencies fail in the graph walk (503) and are then // fetched by the resolver's synchronous fallback (200, immutable). diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 90149ce2..d7ed36f8 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -286,6 +286,46 @@ class TestRunnerTests: XCTestCase { return } + // ── Clear-Site-Data routes ── + // `/esm/csd/carrier.mjs` is cacheable for an hour and sends + // `Clear-Site-Data: ` on the first request of its + // target only, so a later request tells a network response + // (no header) from a cache replay of the first one. + // `/esm/csd/revalidate.mjs` answers a request carrying its + // ETag with a 304 that sends `Clear-Site-Data: "cache"`. + if path.hasPrefix("/esm/csd/") { + let target = query.isEmpty ? path : "\(path)?\(query)" + var directives = "" + for pair in query.split(separator: "&") where pair.hasPrefix("directives=") { + let raw = String(pair.dropFirst("directives=".count)) + directives = raw.removingPercentEncoding ?? raw + } + let javascript = ("Content-Type", "application/javascript; charset=utf-8") + if path == "/esm/csd/revalidate.mjs" { + if requestHeaders["if-none-match"] == "\"v1\"" { + startResponse("304 Not Modified", [ + ("ETag", "\"v1\""), + ("Cache-Control", "no-cache"), + ("Clear-Site-Data", "\"cache\""), + ]) + sendBody(Data()) + return + } + startResponse("200 OK", [ + javascript, ("ETag", "\"v1\""), ("Cache-Control", "no-cache"), + ]) + sendBody(Data("export const revalidated = true;\n".utf8)) + return + } + var headers = [javascript, ("Cache-Control", "max-age=3600")] + if self.requestCounts[target] == 1 && !directives.isEmpty { + headers.append(("Clear-Site-Data", directives)) + } + startResponse("200 OK", headers) + sendBody(Data("export const carrier = true;\n".utf8)) + return + } + // ── Synchronous-fallback routes ── // `…/entry.mjs` statically imports `dep-a.mjs` and `dep-b.mjs`, // and `dep-a.mjs` imports `dep-a2.mjs`. `dep-a.mjs` and @@ -293,7 +333,8 @@ class TestRunnerTests: XCTestCase { // with the module, so the graph walk's fetch fails and the // resolver's synchronous fallback fetches them. The walk never // sees `dep-a2.mjs`, so the fallback fetches it too, first time - // round. `cache` sets the 200's Cache-Control. + // round. `cache` sets the 200's Cache-Control; `csd=1` adds + // `Clear-Site-Data: "cache"` to `dep-b.mjs`'s 200. if path.hasPrefix("/esm/fallback/") { var cacheControl = "no-cache" for pair in query.split(separator: "&") where pair.hasPrefix("cache=") { @@ -326,10 +367,14 @@ class TestRunnerTests: XCTestCase { .replacingOccurrences(of: ".mjs", with: "") body = "export const \(id) = \"\(id)\";\n" } - startResponse("200 OK", [ + var headers = [ ("Content-Type", "application/javascript; charset=utf-8"), ("Cache-Control", cacheControl), - ]) + ] + if name == "dep-b.mjs" && query.split(separator: "&").contains("csd=1") { + headers.append(("Clear-Site-Data", "\"cache\"")) + } + startResponse("200 OK", headers) sendBody(body.data(using: .utf8) ?? Data()) return } diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index ca49f71b..966fc0ea 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1232,11 +1232,25 @@ These clear it: |---|---| | `clearHttpCache()` from `ns:module` | every origin | | launch argument `--nativescript-clear-module-cache` | every origin, before the first fetch | +| a module response with `Clear-Site-Data` listing `"cache"` or `"*"` | the origin of the response's URL | A clear applies to the next fetch and to later launches, including when the app is killed right after it, and works the same whether the cache is on or off. +`Clear-Site-Data` is honoured on every module response the loader receives, +from the graph walk and the synchronous fallback alike, and the cache is +cleared before that response is handed on, so nothing requested afterwards +comes from the old cache. Unlike browsers, which honour the header only from +secure origins, the loader honours it over plain `http:` too: dev servers +usually serve `http:` on the local network. The value is a comma-separated +list of quoted strings; directives other than `"cache"` and `"*"` are +ignored. The response that carries the header is never kept in the cache (if +it was stored, the cache it was stored in is the one cleared), so it clears +once per time it is actually fetched, not on every later import. A `304` that +carries the header counts too: on the iOS 26.3 simulator, a revalidation +answered by such a `304` cleared the origin's cache. + ### App entries and bootstraps An app's entry can be either CommonJS or an ES module, and the choice decides @@ -1417,7 +1431,9 @@ protocol cache policy. A clear moves the origin's directory aside (into `ns-module-http-cache/trash`, emptied in the background) and the next fetch opens a new session on the next generation: `removeAllCachedResponses` is not used because a process killed right after it still found the entries at its -next launch. The synchronous fallback issues its request through the same +next launch. `Clear-Site-Data` drops the partition of the response URL's +origin and, when a redirect crossed origins, also the partition the response +was fetched through, which is where the carrier was stored. The synchronous fallback issues its request through the same sessions and blocks for at most the request timeout plus five seconds per attempt. From 97437649252e24a4ee96e80732bed17fd893ebf1 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 10:33:52 -0300 Subject: [PATCH 4/7] 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. --- NativeScript/inspector/JsV8InspectorClient.mm | 55 +++++++++++++++++++ docs/ns-builtin-modules.md | 10 ++++ 2 files changed, 65 insertions(+) diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 82743339..43f8fce1 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -14,6 +14,7 @@ #include "Caches.h" #include "Helpers.h" +#include "HttpLoader.h" #include "InspectorServer.h" #include "JsV8InspectorClient.h" #include "NativeScriptException.h" @@ -213,6 +214,18 @@ bool GetInt32(const json& value, long long& out) { out = static_cast(number); return true; } + +// Network.setCacheDisabled's required boolean `cacheDisabled`, if present. +std::optional SetCacheDisabledParam(const json& message) { + if (!message.is_object() || !message.contains("params") || !message["params"].is_object()) { + return std::nullopt; + } + const json& params = message["params"]; + if (!params.contains("cacheDisabled") || !params["cacheDisabled"].is_boolean()) { + return std::nullopt; + } + return params["cacheDisabled"].get(); +} } // namespace #define NOTIFICATION(name) \ @@ -419,6 +432,9 @@ bool GetInt32(const json& value, long long& out) { } } + // Its Network.setCacheDisabled lasts only as long as the connection. + tns::SetModuleHttpCacheDisabledByInspector(connectionId, false); + // Free the process-global trace controller for other frontends. { std::lock_guard lock(this->tracingMutex_); @@ -498,6 +514,30 @@ bool GetInt32(const json& value, long long& out) { return; } + // The module HTTP cache is process-wide, so these take effect here, from + // any session and while any isolate is paused. A main-session message then + // goes on to the JS Network domain handler as usual, which answers it; + // DispatchFrontendMessage answers it when there is none. Worker sessions + // have no JS domain handlers, so they are answered here. + if (method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") { + const std::optional cacheDisabled = SetCacheDisabledParam(parsed); + const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value(); + if (method == "Network.clearBrowserCache") { + tns::ClearModuleHttpCache(); + } else if (valid) { + tns::SetModuleHttpCacheDisabledByInspector(connectionId, *cacheDisabled); + } + if (!sessionId.empty()) { + if (msgId >= 0) { + json reply = valid ? json{{"id", msgId}, {"result", json::object()}} + : json{{"id", msgId}, + {"error", {{"code", -32602}, {"message", "Invalid parameters"}}}}; + this->SendRawToConnection(connectionId, WithSessionId(reply, sessionId).dump()); + } + return; + } + } + // The Tracing domain never touches the isolate, so it is answered here // instead of on the main-thread message queue: flushing a large trace to the // frontend must not wait for (or block) JS. The dataCollected chunks are @@ -986,6 +1026,21 @@ bool GetInt32(const json& value, long long& out) { } } + // Applied in onFrontendMessageReceived. V8 does not know the Network domain + // and would answer method-not-found. + if (method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") { + if (!json_message.contains("id")) { + return; + } + const bool valid = + method == "Network.clearBrowserCache" || SetCacheDisabledParam(json_message).has_value(); + json reply = valid ? json{{"id", json_message["id"]}, {"result", json::object()}} + : json{{"id", json_message["id"]}, + {"error", {{"code", -32602}, {"message", "Invalid parameters"}}}}; + this->SendRawToConnection(connectionId, reply.dump()); + return; + } + // if no handler handled the message successfully, fall-through to the default V8 implementation sessions_->Dispatch(connectionId, method, message); diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 966fc0ea..91eede8e 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1215,6 +1215,7 @@ The cache is **on** unless one of these turns it off: | `setHttpCacheEnabled(false)` from `ns:module` | off until `setHttpCacheEnabled(true)` | | launch argument `--nativescript-no-module-cache` | starts off | | app config `"moduleHttpCache": false` (top level, next to `security`) | starts off | +| a DevTools frontend sends `Network.setCacheDisabled` with `cacheDisabled: true` | off until that frontend sends `cacheDisabled: false` or disconnects; with several frontends connected, off while any of them has it disabled, whatever `setHttpCacheEnabled` says | The launch argument and the app config are read once per process, before the first module fetch, and `setHttpCacheEnabled` overrides them either way. They @@ -1232,6 +1233,7 @@ These clear it: |---|---| | `clearHttpCache()` from `ns:module` | every origin | | launch argument `--nativescript-clear-module-cache` | every origin, before the first fetch | +| DevTools `Network.clearBrowserCache` | every origin | | a module response with `Clear-Site-Data` listing `"cache"` or `"*"` | the origin of the response's URL | A clear applies to the next fetch and to later launches, including when the @@ -1251,6 +1253,14 @@ once per time it is actually fetched, not on every later import. A `304` that carries the header counts too: on the iOS 26.3 simulator, a revalidation answered by such a `304` cleared the origin's cache. +The two DevTools commands take effect as soon as they arrive, also while the +app is paused in the debugger, and from a worker's session as well as the +main one. On the main session they then still reach a `Network` domain +handler the app registered (`@nativescript/core` registers one, and can clear +its own state there), and that handler's reply is the one the frontend gets; +without such a handler the runtime replies `{}`. A worker session's reply is +always the runtime's `{}`. + ### App entries and bootstraps An app's entry can be either CommonJS or an ES module, and the choice decides From c051f691c4a4558c3b3f6a90fc8b72c426cb94b7 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 11:07:57 -0300 Subject: [PATCH 5/7] 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. --- NativeScript/runtime/HttpLoader.mm | 40 +++++++++++++++++++++++++++++- docs/ns-builtin-modules.md | 33 ++++++++++++------------ 2 files changed, 56 insertions(+), 17 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index d406c9f6..84c043e3 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -539,7 +539,8 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // session finishes the tasks it has in flight, and anything those tasks store // lands in the moved directory or, should a write recreate the old path, in a // generation older than the one the origin uses next. An origin always opens -// its highest generation, and removes the others when it does. +// its highest generation, and removes the others when it does. At most +// kModuleCacheMaxOrigins origin directories outlive a launch. // // All of it is process-wide, guarded by one mutex: fetch threads, every // isolate's thread and the inspector's socket thread read and change it. @@ -547,6 +548,11 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { static constexpr NSUInteger kModuleCacheMemoryCapacity = 8 * 1024 * 1024; static constexpr NSUInteger kModuleCacheDiskCapacity = 256 * 1024 * 1024; +// Origins come and go with dev-server addresses (a new LAN IP or port is a new +// origin), so the partitions kept on disk need a bound: launch keeps this many +// of the most recently opened ones. +static constexpr NSUInteger kModuleCacheMaxOrigins = 8; + // Top-level app config key; `false` starts the process with the cache off. static constexpr const char* kModuleHttpCacheConfigKey = "moduleHttpCache"; @@ -648,6 +654,33 @@ static void PurgeTrashInBackground(ModuleHttpCacheState& state) { return [NSString stringWithUTF8String:name.c_str()]; } +// Keeps the kModuleCacheMaxOrigins origin directories opened most recently +// (PartitionLocked stamps each one's modification date) and trashes the rest; +// one whose date cannot be read counts as the oldest. Only safe before any +// partition is open. +static void PruneOriginsLocked(ModuleHttpCacheState& state) { + NSArray* origins = + [[NSFileManager defaultManager] contentsOfDirectoryAtURL:OriginsDirectory(state) + includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] + options:0 + error:nil]; + if (origins.count <= kModuleCacheMaxOrigins) { + return; + } + auto openedAt = ^NSDate*(NSURL* url) { + NSDate* date = nil; + [url getResourceValue:&date forKey:NSURLContentModificationDateKey error:nil]; + return date ?: [NSDate distantPast]; + }; + NSArray* newestFirst = + [origins sortedArrayUsingComparator:^NSComparisonResult(NSURL* a, NSURL* b) { + return [openedAt(b) compare:openedAt(a)]; + }]; + for (NSUInteger i = kModuleCacheMaxOrigins; i < newestFirst.count; i++) { + MoveToTrash(state, newestFirst[i]); + } +} + static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { if (state.initialized) { return; @@ -683,6 +716,7 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { } MoveToTrash(state, item); } + PruneOriginsLocked(state); PurgeTrashInBackground(state); NSURLSessionConfiguration* config = ModuleSessionConfiguration(nil); @@ -730,6 +764,10 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { NSURL* directory = [originDirectory URLByAppendingPathComponent:generationName isDirectory:YES]; [fm createDirectoryAtURL:directory withIntermediateDirectories:YES attributes:nil error:nil]; + // When it was last opened, which is what PruneOriginsLocked keeps by. + [fm setAttributes:@{NSFileModificationDate : [NSDate date]} + ofItemAtPath:originDirectory.path + error:nil]; NSURLCache* cache = [[NSURLCache alloc] initWithMemoryCapacity:kModuleCacheMemoryCapacity diskCapacity:kModuleCacheDiskCapacity directoryURL:directory]; diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 91eede8e..79fd37fe 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1203,9 +1203,6 @@ isolate in the process, and serves every HTTP module fetch, the synchronous fallback included. It is separate from the cache the app's own networking uses, which the loader never touches. -*Platform note (iOS):* the controls below are iOS behaviour for now; the -Android runtime has no module HTTP cache. - #### Turning the cache off and clearing it The cache is **on** unless one of these turns it off: @@ -1433,19 +1430,23 @@ driving it needs the rejection reason synchronously. Module fetches use ephemeral `NSURLSession`s (no persistent cookies or credentials). With the cache on, each origin has a session with an on-disk `NSURLCache` of its own (8 MB memory, 256 MB disk) in -`Library/Caches/ns-module-http-cache/origins//`; with it -off, fetches use one session whose `URLCache` is `nil` and requests use -`NSURLRequestReloadIgnoringLocalCacheData`. The loader never reads, replaces -or resizes the app's shared `NSURLCache`. Requests otherwise use the default -protocol cache policy. A clear moves the origin's directory aside (into -`ns-module-http-cache/trash`, emptied in the background) and the next fetch -opens a new session on the next generation: `removeAllCachedResponses` is not -used because a process killed right after it still found the entries at its -next launch. `Clear-Site-Data` drops the partition of the response URL's -origin and, when a redirect crossed origins, also the partition the response -was fetched through, which is where the carrier was stored. The synchronous fallback issues its request through the same -sessions and blocks for at most the request timeout plus five seconds per -attempt. +`Library/Caches/ns-module-http-cache/origins//`. Opening +an origin's cache stamps its directory's modification date, and each launch +keeps the 8 most recently opened origin directories and discards the rest +before the first fetch, since every new dev-server address or port is a new +origin. With the cache off, fetches use one session whose `URLCache` is `nil` +and requests use `NSURLRequestReloadIgnoringLocalCacheData`. The loader never +reads, replaces or resizes the app's shared `NSURLCache`. Requests otherwise +use the default protocol cache policy. A clear moves the origin's directory +aside (into `ns-module-http-cache/trash`, emptied in the background) and the +next fetch opens a new session on the next generation: +`removeAllCachedResponses` is not used because a process killed right after +it still found the entries at its next launch. `Clear-Site-Data` drops the +partition of the response URL's origin and, when a redirect crossed origins, +also the partition the response was fetched through, which is where the +carrier was stored. The synchronous fallback issues its request through the +same sessions and blocks for at most the request timeout plus five seconds +per attempt. 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 From 7c5df0c8e9118a6a40f7b1fbc3c24890743e6148 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 11:49:45 -0300 Subject: [PATCH 6/7] 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. --- NativeScript/inspector/JsV8InspectorClient.h | 3 +++ NativeScript/inspector/JsV8InspectorClient.mm | 12 ++++++++++-- docs/ns-builtin-modules.md | 6 ++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/NativeScript/inspector/JsV8InspectorClient.h b/NativeScript/inspector/JsV8InspectorClient.h index dd1c2dd0..a4a480d3 100644 --- a/NativeScript/inspector/JsV8InspectorClient.h +++ b/NativeScript/inspector/JsV8InspectorClient.h @@ -185,6 +185,9 @@ class JsV8InspectorClient : V8InspectorClient { void RouteToWorker(uint64_t connectionId, const std::string& sessionId, const std::string& method, long long msgId, const std::string& message); + // Whether RouteToWorker would deliver a message from this frontend to + // `sessionId` rather than answer "Session not found". + bool HasWorkerSession(uint64_t connectionId, const std::string& sessionId); // Announces every worker not yet announced to the frontend. Requires // workerTargetsMutex_. void AnnounceWorkerTargetsLocked(uint64_t connectionId, TargetState& state); diff --git a/NativeScript/inspector/JsV8InspectorClient.mm b/NativeScript/inspector/JsV8InspectorClient.mm index 43f8fce1..5d20447b 100644 --- a/NativeScript/inspector/JsV8InspectorClient.mm +++ b/NativeScript/inspector/JsV8InspectorClient.mm @@ -518,8 +518,11 @@ bool GetInt32(const json& value, long long& out) { // any session and while any isolate is paused. A main-session message then // goes on to the JS Network domain handler as usual, which answers it; // DispatchFrontendMessage answers it when there is none. Worker sessions - // have no JS domain handlers, so they are answered here. - if (method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") { + // have no JS domain handlers, so they are answered here. A sessionId that + // names no worker of this frontend changes nothing and is left to + // RouteToWorker's "Session not found". + if ((method == "Network.setCacheDisabled" || method == "Network.clearBrowserCache") && + (sessionId.empty() || this->HasWorkerSession(connectionId, sessionId))) { const std::optional cacheDisabled = SetCacheDisabledParam(parsed); const bool valid = method == "Network.clearBrowserCache" || cacheDisabled.has_value(); if (method == "Network.clearBrowserCache") { @@ -725,6 +728,11 @@ bool GetInt32(const json& value, long long& out) { } } +bool JsV8InspectorClient::HasWorkerSession(uint64_t connectionId, const std::string& sessionId) { + std::lock_guard lock(this->workerTargetsMutex_); + return this->targetStates_.count(connectionId) != 0 && this->workerTargets_.count(sessionId) != 0; +} + void JsV8InspectorClient::RouteToWorker(uint64_t connectionId, const std::string& sessionId, const std::string& method, long long msgId, const std::string& message) { diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index 79fd37fe..bf30d590 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1250,6 +1250,12 @@ once per time it is actually fetched, not on every later import. A `304` that carries the header counts too: on the iOS 26.3 simulator, a revalidation answered by such a `304` cleared the origin's cache. +Limitation: a module reached through a redirect from another origin is cached +with the origin the import requested, not the one that served it. A +`Clear-Site-Data` from the serving origin does not remove it; +`clearHttpCache()`, `--nativescript-clear-module-cache` and +`Network.clearBrowserCache` do. + The two DevTools commands take effect as soon as they arrive, also while the app is paused in the debugger, and from a worker's session as well as the main one. On the main session they then still reach a `Network` domain From ecf7487a3c25bd3ae124d910459216f29d3d67ed Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Wed, 2 Dec 2026 13:32:52 -0300 Subject: [PATCH 7/7] 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. --- NativeScript/runtime/HttpLoader.h | 5 +- NativeScript/runtime/HttpLoader.mm | 244 +++++++++++++++++------------ docs/ns-builtin-modules.md | 26 +-- 3 files changed, 158 insertions(+), 117 deletions(-) diff --git a/NativeScript/runtime/HttpLoader.h b/NativeScript/runtime/HttpLoader.h index 546110f6..666765e8 100644 --- a/NativeScript/runtime/HttpLoader.h +++ b/NativeScript/runtime/HttpLoader.h @@ -86,8 +86,9 @@ 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, for at most a few seconds past the request timeout per attempt: a -// response that has not arrived by then fails the fetch. Goes through the same -// session and HTTP cache as FetchModuleBodyAsync. Returns `result.ok`. +// response that has not arrived by then fails the fetch. Uses the same HTTP +// cache as FetchModuleBodyAsync, through sessions (and so connections) of its +// own. Returns `result.ok`. bool HttpFetchModule(const std::string& url, ModuleFetchResult& result); // Asynchronous single-URL module fetch — the I/O primitive behind the diff --git a/NativeScript/runtime/HttpLoader.mm b/NativeScript/runtime/HttpLoader.mm index 84c043e3..638fb03f 100644 --- a/NativeScript/runtime/HttpLoader.mm +++ b/NativeScript/runtime/HttpLoader.mm @@ -262,7 +262,7 @@ bool IsRemoteUrlAllowed(const std::string& url) { // concurrently off the JS thread before instantiation begins. // // Both issue their requests through StartModuleFetchTask, so they share one -// session and its HTTP cache, BuildModuleFetchRequest shapes every request, +// HTTP cache and its switch, BuildModuleFetchRequest shapes every request, // and ClassifyModuleResponse judges every response. Neither can drift into // its own idea of what a valid module response is. // @@ -522,11 +522,16 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // The module HTTP cache // // Module fetches use ephemeral sessions, so no cookies or credentials persist. -// While the cache is enabled each origin gets a session of its own with an -// on-disk NSURLCache in its own directory, so one origin's cache can be -// dropped without touching another's; the app's shared NSURLCache is never -// read, replaced or resized. While it is disabled every fetch goes through one -// session without a cache. +// While the cache is enabled each origin has an on-disk NSURLCache in its own +// directory, so one origin's cache can be dropped without touching another's; +// the app's shared NSURLCache is never read, replaced or resized. While it is +// disabled fetches go through sessions without a cache. +// +// The graph walk and the synchronous fallback each have sessions of their +// own, configured alike, so a blocking fallback fetch never waits for a +// connection held by the walk's fetches to the same host. An origin's two +// sessions share its one NSURLCache instance, so what either path stores the +// other reads. // // Every session's delegate queue is its own background queue, never the main // queue, so a thread blocked waiting on one of its tasks does not hold up the @@ -536,7 +541,7 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // origins/// one NSURLCache directory // trash/ deleted in the background // A cache is dropped by moving its directory into trash, which is atomic; its -// session finishes the tasks it has in flight, and anything those tasks store +// sessions finish the tasks they have in flight, and anything those tasks store // lands in the moved directory or, should a write recreate the old path, in a // generation older than the one the origin uses next. An origin always opens // its highest generation, and removes the others when it does. At most @@ -558,9 +563,23 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { namespace { +enum class ModuleFetchPath { kGraphWalk, kSynchronousFallback }; + +// One session per path; the fallback's is created on first use, since most +// processes never take the fallback. +struct ModuleSessions { + NSURLSession* graphWalk = nil; // retained + NSURLSession* synchronousFallback = nil; // retained + + NSURLSession*& For(ModuleFetchPath path) { + return path == ModuleFetchPath::kGraphWalk ? graphWalk : synchronousFallback; + } +}; + struct ModuleCachePartition { - NSURLSession* session = nil; // retained - NSURL* directory = nil; // retained + NSURLCache* cache = nil; // retained + ModuleSessions sessions; + NSURL* directory = nil; // retained uint64_t generation = 0; }; @@ -573,8 +592,8 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { // The generation each origin must open next, set when its cache is dropped // in this process. std::map reservedGenerations; - NSURLSession* uncachedSession = nil; // retained - NSURL* root = nil; // retained + ModuleSessions uncached; + NSURL* root = nil; // retained }; ModuleHttpCacheState& CacheState() { @@ -598,6 +617,25 @@ bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { return config; } +// The session `path` uses with `cache` (nil: uncached), created on first use. +static NSURLSession* SessionLocked(ModuleSessions& sessions, ModuleFetchPath path, + NSURLCache* cache) { + NSURLSession*& session = sessions.For(path); + if (session == nil) { + session = [[NSURLSession sessionWithConfiguration:ModuleSessionConfiguration(cache)] retain]; + } + return session; +} + +// The sessions finish what they have in flight without being used again. +static void RetireSessions(ModuleSessions& sessions) { + for (NSURLSession* session : {sessions.graphWalk, sessions.synchronousFallback}) { + [session finishTasksAndInvalidate]; + [session release]; + } + sessions = ModuleSessions(); +} + static NSURL* OriginsDirectory(ModuleHttpCacheState& state) { return [state.root URLByAppendingPathComponent:@"origins" isDirectory:YES]; } @@ -718,9 +756,6 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { } PruneOriginsLocked(state); PurgeTrashInBackground(state); - - NSURLSessionConfiguration* config = ModuleSessionConfiguration(nil); - state.uncachedSession = [[NSURLSession sessionWithConfiguration:config] retain]; } // The partition for `origin`, opened on first use in this process. Opening @@ -768,22 +803,18 @@ static void InitializeModuleHttpCacheLocked(ModuleHttpCacheState& state) { [fm setAttributes:@{NSFileModificationDate : [NSDate date]} ofItemAtPath:originDirectory.path error:nil]; - NSURLCache* cache = [[NSURLCache alloc] initWithMemoryCapacity:kModuleCacheMemoryCapacity - diskCapacity:kModuleCacheDiskCapacity - directoryURL:directory]; - NSURLSessionConfiguration* config = ModuleSessionConfiguration(cache); - [cache release]; - ModuleCachePartition& partition = state.partitions[origin]; - partition.session = [[NSURLSession sessionWithConfiguration:config] retain]; + partition.cache = [[NSURLCache alloc] initWithMemoryCapacity:kModuleCacheMemoryCapacity + diskCapacity:kModuleCacheDiskCapacity + directoryURL:directory]; partition.directory = [directory retain]; partition.generation = generation; return partition; } // Drops the cache of one open partition: its directory moves to trash, an -// empty directory for the next generation takes its place, and the session -// finishes what it has in flight without being used again. +// empty directory for the next generation takes its place, and both sessions +// are retired. static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& origin) { auto it = state.partitions.find(origin); if (it == state.partitions.end()) { @@ -803,8 +834,8 @@ static void DropPartitionLocked(ModuleHttpCacheState& state, const std::string& attributes:nil error:nil]; - [partition.session finishTasksAndInvalidate]; - [partition.session release]; + RetireSessions(partition.sessions); + [partition.cache release]; [partition.directory release]; } @@ -953,8 +984,10 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re // cache switch is read now, so it decides this request alone. `handler` runs // exactly once, on the session's delegate queue, after the response's // Clear-Site-Data has taken effect, so nothing the loader requests from then on -// can come from the cleared cache. Returns the resumed task, autoreleased. -static NSURLSessionDataTask* StartModuleFetchTask(NSMutableURLRequest* request, +// can come from the cleared cache. `path` picks which of the two paths' sessions +// carries it. Returns the resumed task, autoreleased. +static NSURLSessionDataTask* StartModuleFetchTask(ModuleFetchPath path, + NSMutableURLRequest* request, void (^handler)(NSData*, NSURLResponse*, NSError*)) { ModuleHttpCacheState& state = CacheState(); @@ -966,12 +999,13 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re enabled ? HttpUrlOrigin(request.URL.absoluteString.UTF8String ?: "") : std::string(); NSURLSession* session = nil; if (!origin.empty()) { - session = PartitionLocked(state, origin).session; + ModuleCachePartition& partition = PartitionLocked(state, origin); + session = SessionLocked(partition.sessions, path, partition.cache); } else { [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; [request setValue:@"no-cache" forHTTPHeaderField:@"Pragma"]; - session = state.uncachedSession; + session = SessionLocked(state.uncached, path, nil); } void (^delivered)(NSData*, NSURLResponse*, NSError*) = ^(NSData* data, NSURLResponse* response, NSError* error) { @@ -991,8 +1025,8 @@ static ModuleFetchOutcome ReadModuleFetchOutcome(NSData* data, NSURLResponse* re return task; } -// One blocking fetch attempt for the synchronous fallback, on the same session -// and cache as the async path. The wait is bounded: `waitExpired` reports a +// One blocking fetch attempt for the synchronous fallback, on the fallback's +// own session over the same cache as the async path. The wait is bounded: `waitExpired` reports a // task that had not completed when it ran out, which is then cancelled. static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, std::string& contentType, int& status, bool& waitExpired) { @@ -1016,8 +1050,9 @@ static bool PerformHttpFetchOnceSync(const std::string& url, std::string& out, const auto fetchStartUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - NSURLSessionDataTask* task = - StartModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { + NSURLSessionDataTask* task = StartModuleFetchTask( + ModuleFetchPath::kSynchronousFallback, request, + ^(NSData* data, NSURLResponse* response, NSError* error) { try { state->outcome = ReadModuleFetchOutcome(data, response, error); if (error != nil) { @@ -1128,78 +1163,81 @@ static void PerformModuleFetchAsyncAttempt( const std::string urlCopy = url; const uint64_t startUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - StartModuleFetchTask(request, ^(NSData* data, NSURLResponse* response, NSError* error) { - // NSURLSession invokes this block, so a C++ exception leaving it is - // an std::terminate rather than a failure anyone can report. Nothing - // here runs JS — the compile is posted to the isolate's own thread — - // so an escape could only come from an allocation failure, but the - // containment is structural on purpose: the graph load must hear - // back exactly once or it waits out its entire deadline. - bool retrying = false; - ModuleFetchResult result; - try { - ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); - int status = outcome.status; - std::string contentType = std::move(outcome.contentType); - std::string body = std::move(outcome.body); - - // Transport error → one retry while the enclosing load's budget - // can still fit the delay — the same single-retry policy the - // sync path applies, without blocking any thread. The retry's - // own request clamps to whatever remains when it fires. - const bool retryFitsDeadline = - fetchDeadline <= 0 || - fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; - if (error != nil && attempt == 0 && retryFitsDeadline) { - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", - urlCopy.c_str(), - (error.localizedDescription ?: @"").UTF8String); - dispatch_after(dispatch_time(DISPATCH_TIME_NOW, - (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), - dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ - PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, - completionHeap); - }); - // Set only once the retry is actually queued: it now owns the - // completion, and this attempt must not settle it too. - retrying = true; - } else { - ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, - result.failureReason.c_str()); - } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { - const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); - const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", urlCopy.c_str(), - (unsigned long)result.body.size(), (unsigned long long)ms); + StartModuleFetchTask( + ModuleFetchPath::kGraphWalk, request, + ^(NSData* data, NSURLResponse* response, NSError* error) { + // NSURLSession invokes this block, so a C++ exception leaving it is + // an std::terminate rather than a failure anyone can report. Nothing + // here runs JS — the compile is posted to the isolate's own thread — + // so an escape could only come from an allocation failure, but the + // containment is structural on purpose: the graph load must hear + // back exactly once or it waits out its entire deadline. + bool retrying = false; + ModuleFetchResult result; + try { + ModuleFetchOutcome outcome = ReadModuleFetchOutcome(data, response, error); + int status = outcome.status; + std::string contentType = std::move(outcome.contentType); + std::string body = std::move(outcome.body); + + // Transport error → one retry while the enclosing load's budget + // can still fit the delay — the same single-retry policy the + // sync path applies, without blocking any thread. The retry's + // own request clamps to whatever remains when it fires. + const bool retryFitsDeadline = + fetchDeadline <= 0 || + fetchDeadline - CFAbsoluteTimeGetCurrent() > kModuleFetchRetryDelaySeconds; + if (error != nil && attempt == 0 && retryFitsDeadline) { + TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error: %s", + urlCopy.c_str(), + (error.localizedDescription ?: @"").UTF8String); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, + (int64_t)(kModuleFetchRetryDelaySeconds * NSEC_PER_SEC)), + dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ + PerformModuleFetchAsyncAttempt(urlCopy, 1, fetchDeadline, + completionHeap); + }); + // Set only once the retry is actually queued: it now owns the + // completion, and this attempt must not settle it too. + retrying = true; + } else { + ClassifyModuleResponse(urlCopy, error == nil, status, contentType, body, result); + + if (!result.ok) { + TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] attempt=%d %s", attempt, + result.failureReason.c_str()); + } else if (tns::LogCategoryEnabled(tns::LogCategory::Fetch)) { + const uint64_t endUs = (uint64_t)(CFAbsoluteTimeGetCurrent() * 1000.0 * 1000.0); + const uint64_t ms = endUs > startUs ? (endUs - startUs) / 1000ull : 0ull; + TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%llu", + urlCopy.c_str(), (unsigned long)result.body.size(), + (unsigned long long)ms); + } + } + } catch (...) { + if (retrying) { + // The retry owns the completion and will settle it; nothing to + // report from here. + return; + } + result = ModuleFetchResult(); + result.failureReason = + "HTTP import failed: " + urlCopy + " (internal error handling the response)"; } - } - } catch (...) { - if (retrying) { - // The retry owns the completion and will settle it; nothing to - // report from here. - return; - } - result = ModuleFetchResult(); - result.failureReason = - "HTTP import failed: " + urlCopy + " (internal error handling the response)"; - } - if (retrying) { - return; - } - // Guarded for the same reason: the completion posts to the - // isolate's loop, and a throw on the way out would cross the - // ObjC boundary instead of failing the load. - try { - (*completionHeap)(std::move(result)); - } catch (...) { - Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); - } - delete completionHeap; - }); + if (retrying) { + return; + } + // Guarded for the same reason: the completion posts to the + // isolate's loop, and a throw on the way out would cross the + // ObjC boundary instead of failing the load. + try { + (*completionHeap)(std::move(result)); + } catch (...) { + Log(@"NativeScript: module fetch completion threw for %s", urlCopy.c_str()); + } + delete completionHeap; + }); } } diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index bf30d590..267c1eb8 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1434,25 +1434,27 @@ full deadline, throws on expiry, and does slice the runloop, because the tooling driving it needs the rejection reason synchronously. Module fetches use ephemeral `NSURLSession`s (no persistent cookies or -credentials). With the cache on, each origin has a session with an on-disk -`NSURLCache` of its own (8 MB memory, 256 MB disk) in -`Library/Caches/ns-module-http-cache/origins//`. Opening +credentials). With the cache on, each origin has an on-disk `NSURLCache` of +its own (8 MB memory, 256 MB disk) in +`Library/Caches/ns-module-http-cache/origins//`, shared by +two sessions configured alike: one for the graph walk and one, created on +first use, for the synchronous fallback, so a blocking fallback fetch never +waits for a connection held by the walk. Opening an origin's cache stamps its directory's modification date, and each launch keeps the 8 most recently opened origin directories and discards the rest before the first fetch, since every new dev-server address or port is a new -origin. With the cache off, fetches use one session whose `URLCache` is `nil` -and requests use `NSURLRequestReloadIgnoringLocalCacheData`. The loader never -reads, replaces or resizes the app's shared `NSURLCache`. Requests otherwise -use the default protocol cache policy. A clear moves the origin's directory -aside (into `ns-module-http-cache/trash`, emptied in the background) and the -next fetch opens a new session on the next generation: +origin. With the cache off, each path uses a session whose `URLCache` is +`nil`, and requests use `NSURLRequestReloadIgnoringLocalCacheData`. The +loader never reads, replaces or resizes the app's shared `NSURLCache`. +Requests otherwise use the default protocol cache policy. A clear moves the +origin's directory aside (into `ns-module-http-cache/trash`, emptied in the +background) and the next fetch opens new sessions on the next generation: `removeAllCachedResponses` is not used because a process killed right after it still found the entries at its next launch. `Clear-Site-Data` drops the partition of the response URL's origin and, when a redirect crossed origins, also the partition the response was fetched through, which is where the -carrier was stored. The synchronous fallback issues its request through the -same sessions and blocks for at most the request timeout plus five seconds -per attempt. +carrier was stored. The synchronous fallback blocks for at most the request +timeout plus five seconds per attempt. 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