diff --git a/docs/ns-builtin-modules.md b/docs/ns-builtin-modules.md index e0d8dc8e2..42320c8fc 100644 --- a/docs/ns-builtin-modules.md +++ b/docs/ns-builtin-modules.md @@ -1178,13 +1178,23 @@ deadline is a single constant, `kModuleEvaluateDeadlineSeconds` = 60 seconds (`ModuleInternal.h`), shared by the HTTP entry's settle window, the pumped graph walk, and — doubled, at 120 seconds — the boot backstop. The waits are *designed* to nest — transport timeouts within the module deadline within the -boot backstop — but the transport numbers are per-attempt bounds (connect) and -per-read inactivity bounds (read), not totals: a retried fetch or a slowly -dripping response can legally spend longer than one connect+read sum, and the -deadline above it is what actually cuts the wait off. The local entry's short -yield is deliberately *not* derived from that constant: it is an independent -one-second literal in `BootEntryEvaluationOptions`, with `return-pending` -behavior. An HTTP entry instead gets the full deadline and throws on expiry, +boot backstop. Each fetch attempt gets a connect timeout and a read timeout +of 30 seconds in debug builds and 5 seconds in release builds +(`ModuleFetchTimeoutMs` in `HttpLoader.cpp`, the same values as iOS), and a +transport error is retried once after 120 ms. A +pumped graph walk passes its own deadline down to every fetch it issues: an +attempt clamps both timeouts to the time remaining, the retry is skipped when +the remaining budget cannot fit its delay, and an attempt that would start +after the deadline — including one still queued behind the concurrency cap — +fails as `HTTP import failed: (module graph fetch deadline exceeded)` +without issuing a request. A dynamic `import()` of an HTTP root nothing pumps +for passes no deadline, and the synchronous fallback fetch keeps the plain +per-attempt timeouts. The timeouts are still per-connect and per-read +inactivity bounds, not totals, so a response that keeps dripping in can run +past the deadline; the pumped wait gives up on it at the deadline regardless. +The local entry's short yield is deliberately *not* derived from that +constant: it is an independent one-second literal in +`BootEntryEvaluationOptions`, with `return-pending` behavior. An HTTP entry instead gets the full deadline and throws on expiry, because the tooling driving it needs the rejection reason synchronously. The backstop itself is `HoldBootBackstop` in `Runtime.cpp`, called from both `Runtime::RunModule` overloads; it pumps the isolate's event loop in place diff --git a/test-app/app/src/main/assets/app/esm/mixed/slow-entry.mjs b/test-app/app/src/main/assets/app/esm/mixed/slow-entry.mjs new file mode 100644 index 000000000..a17c8df59 --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/mixed/slow-entry.mjs @@ -0,0 +1,7 @@ +// Entry of a local->local->http graph whose HTTP leaf answers only after a +// multi-second transform delay (ModuleTestServer /esm/slow/req-leaf.mjs). +// Exercises the pumped graph walk's fetch budget through require(): the leaf +// must arrive within the walk's deadline on its first request. +import { leaf as leafValue } from "./slow-mid.mjs"; + +export const leaf = leafValue; diff --git a/test-app/app/src/main/assets/app/esm/mixed/slow-mid.mjs b/test-app/app/src/main/assets/app/esm/mixed/slow-mid.mjs new file mode 100644 index 000000000..71448c55f --- /dev/null +++ b/test-app/app/src/main/assets/app/esm/mixed/slow-mid.mjs @@ -0,0 +1,4 @@ +// Named re-export through the local->HTTP boundary: "ns-slow-leaf" is a bare +// specifier the spec's import map points at a delayed ModuleTestServer URL, +// so this file needs no baked-in origin. +export { value as leaf } from "ns-slow-leaf"; diff --git a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js index 5b9540c5e..6fc323042 100644 --- a/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js +++ b/test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js @@ -829,6 +829,82 @@ describe("HTTP ESM Loader", function () { }); }); + // Dev servers transform cold modules on demand, and responses have + // been measured at 5-9 s. A 7 s module must land inside the transport + // timeout (30 s per attempt in debug builds) on its first request: a + // timeout would show as a second request, from the retry or from the + // synchronous fallback. + describe("fetch budget", function () { + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + require("ns:module").configureLoader({ importMap: { imports: {} } }); + }); + + function statsCount(target) { + return import(origin + "/esm/request-stats.json?target=" + + encodeURIComponent(target) + "&n=" + (++requestStatsQueries)) + .then(function (stats) { + return stats.default.count; + }); + } + + it("resolves a slow HTTP module on its first request", function (done) { + var target = "/esm/slow/leaf.mjs?k=direct&delayMs=7000"; + import(origin + target).then(function (mod) { + expect(mod.value).toBe(42); + return statsCount(target); + }).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("resolves a slow HTTP re-export chain on one request per module", function (done) { + // The walk discovers the child only once the parent's 7 s + // response lands. + var parentTarget = "/esm/slow/parent.mjs?k=chain&delayMs=7000"; + var childTarget = "/esm/slow/child.mjs?from=chain"; + import(origin + parentTarget).then(function (mod) { + expect(mod.value).toBe(42); + expect(mod.parent).toBe("chain"); + return Promise.all([statsCount(parentTarget), statsCount(childTarget)]); + }).then(function (counts) { + expect(counts).toEqual([1, 1]); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + + it("waits for a slow HTTP leaf during a pumped require()", function (done) { + var leafTarget = "/esm/slow/req-leaf.mjs?k=req&delayMs=7000"; + var nsModule = require("ns:module"); + nsModule.configureLoader({ + importMap: { + imports: { "ns-slow-leaf": origin + leafTarget }, + }, + }); + // Blocks the JS thread for the walk's 7 s fetch; the re-export + // at slow-mid.mjs keeps the leaf inside the pumped graph. + var req = nsModule.createRequire(appRoot + "/anything.js"); + var mod = req("./esm/mixed/slow-entry.mjs"); + expect(mod.leaf).toBe(42); + statsCount(leafTarget).then(function (count) { + expect(count).toBe(1); + done(); + }).catch(function (error) { + reportRejection(error, done); + }); + }); + }); + describe("worker teardown", function () { var originalTimeout; beforeEach(function () { diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index c97f57417..176df7c3c 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -345,8 +345,18 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std:: } static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey, - std::string& out, std::string& contentType, int& status, - bool& bustApplied); + int timeoutMs, std::string& out, std::string& contentType, + int& status, bool& bustApplied); + +// Each module-fetch attempt's connect timeout and read timeout, for both +// transports, matching iOS. Debug builds talk to dev servers that transform +// cold modules on demand (measured at 5-9 s); release builds fetch remote +// modules that should fail fast. +static int ModuleFetchTimeoutMs() { + return IsDebuggable() ? 30000 : 5000; +} + +static constexpr std::chrono::milliseconds kModuleFetchRetryDelay{120}; static std::string ApplyCacheBustNonce(const std::string& url, const std::string& canonicalKey, bool* outBustRequested) { @@ -595,16 +605,17 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, std::string contentType; int status = 0; bool bustApplied = false; - bool transportOk = - PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, bustApplied); + const int timeoutMs = ModuleFetchTimeoutMs(); + bool transportOk = PerformHttpFetchOnceSync(url, canonicalKey, timeoutMs, body, contentType, + status, bustApplied); if (!transportOk) { // One retry, and only for a transport error: an HTTP status is an // answer, not a failure to communicate, so asking again would just // repeat it. TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str()); - usleep(120 * 1000); - transportOk = - PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, bustApplied); + std::this_thread::sleep_for(kModuleFetchRetryDelay); + transportOk = PerformHttpFetchOnceSync(url, canonicalKey, timeoutMs, body, contentType, + status, bustApplied); } ClassifyModuleResponse(url, transportOk, status, contentType, body, result); @@ -645,13 +656,14 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // tells a status-bearing answer (an empty 404) apart from a transport failure, // and past the InputStream close. The wrappers stay on the setup calls, whose // failures have no per-stage verdict and are caught below. +// `timeoutMs` must be positive: HttpURLConnection reads 0 as no timeout. static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey, - std::string& out, std::string& contentType, int& status, - bool& bustApplied) { + int timeoutMs, std::string& out, std::string& contentType, + int& status, bool& bustApplied) { out.clear(); contentType.clear(); status = 0; - TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s", url.c_str()); + TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s timeoutMs=%d", url.c_str(), timeoutMs); const std::string fetchUrl = ApplyCacheBustNonce(url, canonicalKey, &bustApplied); @@ -718,8 +730,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& jmethodID setUseCaches = env.GetMethodID(clsConn, "setUseCaches", "(Z)V"); jmethodID setReqProp = env.GetMethodID(clsConn, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); - env.CallVoidMethod(conn, setConnectTimeout, 15000); - env.CallVoidMethod(conn, setReadTimeout, 15000); + env.CallVoidMethod(conn, setConnectTimeout, timeoutMs); + env.CallVoidMethod(conn, setReadTimeout, timeoutMs); if (setDoInput) { env.CallVoidMethod(conn, setDoInput, JNI_TRUE); } @@ -895,9 +907,27 @@ namespace { struct ModuleFetchJob { std::string url; std::string canonicalKey; + ModuleFetchDeadline deadline; std::function completion; }; +// The timeout for an attempt starting now, or nullopt when `deadline` has +// already passed. +std::optional AttemptTimeoutMs(const ModuleFetchDeadline& deadline) { + const int policyMs = ModuleFetchTimeoutMs(); + if (!deadline) return policyMs; + const auto now = std::chrono::steady_clock::now(); + if (now >= *deadline) return std::nullopt; + // Rounded up: a sub-millisecond remainder must not become 0, which + // HttpURLConnection reads as no timeout at all. + const auto remainingMs = std::chrono::ceil(*deadline - now).count(); + return remainingMs < policyMs ? static_cast(remainingMs) : policyMs; +} + +bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) { + return !deadline || *deadline - std::chrono::steady_clock::now() > kModuleFetchRetryDelay; +} + // See the cap's rationale in HttpLoader.h. 16 matches iOS's // HTTPMaximumConnectionsPerHost. constexpr size_t kMaxConcurrentModuleFetches = 16; @@ -921,22 +951,36 @@ void RunModuleFetchJob(const ModuleFetchJob& job) { int status = 0; const auto start = std::chrono::steady_clock::now(); bool bustApplied = false; - bool transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, body, contentType, - status, bustApplied); - if (!transportOk) { + bool transportOk = false; + std::optional timeoutMs = AttemptTimeoutMs(job.deadline); + if (timeoutMs) { + transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs, body, + contentType, status, bustApplied); // Transport error → one retry, the same single-retry policy the - // sync path applies. - TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error", - job.url.c_str()); - usleep(120 * 1000); - transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, body, contentType, - status, bustApplied); + // sync path applies, while the deadline can still fit the delay. + if (!transportOk && !RetryFitsDeadline(job.deadline)) { + TNS_DEBUG(Esm, "[http-loader][fetch-async] no budget left to retry %s", + job.url.c_str()); + } else if (!transportOk) { + TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error", + job.url.c_str()); + std::this_thread::sleep_for(kModuleFetchRetryDelay); + timeoutMs = AttemptTimeoutMs(job.deadline); + if (timeoutMs) { + transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs, + body, contentType, status, bustApplied); + } + } } - ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result); - - if (result.ok && bustApplied) { - ClearCacheBustForUrl(job.canonicalKey); + if (timeoutMs) { + ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result); + if (result.ok && bustApplied) { + ClearCacheBustForUrl(job.canonicalKey); + } + } else { + result.failureReason = + "HTTP import failed: " + job.url + " (module graph fetch deadline exceeded)"; } if (!result.ok) { @@ -1018,6 +1062,7 @@ void ModuleFetchThreadMain(ModuleFetchJob job) { } // namespace void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKey, + ModuleFetchDeadline fetchDeadline, std::function completion) { // Security gate: single point of enforcement, same as HttpFetchModule. if (!IsRemoteUrlAllowed(url)) { @@ -1030,7 +1075,7 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe return; } - ModuleFetchJob job{url, canonicalKey, std::move(completion)}; + ModuleFetchJob job{url, canonicalKey, fetchDeadline, std::move(completion)}; { std::lock_guard lock(g_fetchQueueMutex); if (g_fetchThreadCount >= kMaxConcurrentModuleFetches) { diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index 4b6c0f542..2a549d012 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -92,6 +93,10 @@ struct ModuleFetchResult { bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, ModuleFetchResult& result); +// An absolute bound on an async module fetch, retries included; nullopt = +// unbounded. +using ModuleFetchDeadline = std::optional; + // Asynchronous single-URL module fetch — the I/O primitive behind the // module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h). // Same response policy as HttpFetchModule, minus the JS-thread block: @@ -99,6 +104,13 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // - a JNI HttpURLConnection GET on a background thread with the same // request shape as the sync path (cache-bust nonce, zero-cache headers) // and one retry on transport error. +// `fetchDeadline` is the enclosing graph load's fetch budget: each attempt +// clamps its connect and read timeouts to the time remaining, the +// transport-error retry is skipped once the budget cannot fit it, and an +// attempt that would start with no budget left fails instead. Time spent +// queued behind the concurrency cap counts against it. The timeouts bound one +// connect and each read, not the whole response, so a body that keeps +// trickling in can still finish past the deadline. // `completion(result)` is invoked exactly once, on an arbitrary thread — // callers must hop to their JS thread before touching V8. // `canonicalKey` as for HttpFetchModule: computed on the calling isolate's @@ -112,7 +124,7 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey, // fetch thread as one frees — the CALLER never blocks, so this stays safe to // call from the JS thread. void FetchModuleBodyAsync( - const std::string& url, const std::string& canonicalKey, + const std::string& url, const std::string& canonicalKey, ModuleFetchDeadline fetchDeadline, std::function completion); // Mark a set of canonical registry keys so that the NEXT network fetch of diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index a7b585768..00b1ffd66 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -1644,6 +1644,7 @@ struct AsyncGraphLoad { size_t fetchedCount = 0; size_t compiledCount = 0; uint64_t startUs = 0; + ModuleFetchDeadline fetchDeadline; std::atomic dead{false}; // set by isolate teardown (any thread) std::function context)> @@ -2258,7 +2259,8 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, std::shared_ptr ticket = BeginStreamedCompile(isolate, *moduleState); // The canonical key is computed here, on the isolate's thread; the fetch // carries it so background threads never touch per-isolate vocabulary. - FetchModuleBodyAsync(url, key, [loadRef, url, ticket](ModuleFetchResult result) { + const ModuleFetchDeadline deadline = load->fetchDeadline; + FetchModuleBodyAsync(url, key, deadline, [loadRef, url, ticket](ModuleFetchResult result) { // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 // foreground task — delivery is a property of the isolate, not of the // thread that started the fetch, and the pumped walk's @@ -2309,7 +2311,7 @@ static ModuleResolution ResolutionForRoot(const std::string& root) { void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, - const std::string& root, + const std::string& root, ModuleFetchDeadline fetchDeadline, std::function context)> onComplete) { @@ -2321,6 +2323,7 @@ void StartModuleGraphLoad( ? CanonicalizeNormalizedHttpUrlKey(rootResolution.url) : CanonicalizeRegistryKey(root); load->startUs = MonotonicUs(); + load->fetchDeadline = fetchDeadline; load->onComplete = std::move(onComplete); AsyncGraphLoad::g_asyncGraphLoadsInFlightCounter().fetch_add( @@ -2342,8 +2345,14 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, const std::string& root, double timeoutSeconds) { if (timeoutSeconds <= 0.0) timeoutSeconds = kModuleEvaluateDeadlineSeconds; + // Taken before the walk starts: local modules compile inline inside + // StartModuleGraphLoad, and that time spends the same budget. + const auto deadline = + std::chrono::steady_clock::now() + + std::chrono::duration_cast( + std::chrono::duration(timeoutSeconds)); auto done = std::make_shared(false); - StartModuleGraphLoad(isolate, context, root, + StartModuleGraphLoad(isolate, context, root, deadline, [done](bool /*ok*/, const std::string& /*errorMessage*/, v8::Local) { *done = true; }); @@ -2356,7 +2365,9 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; if (!*done && eventLoop != nullptr) { - if (eventLoop->PumpUntil(timeoutSeconds, [&]() { return *done; }, + const double remainingSeconds = + std::chrono::duration(deadline - std::chrono::steady_clock::now()).count(); + if (eventLoop->PumpUntil(remainingSeconds, [&]() { return *done; }, /*drainLooperWork=*/true) == EventLoop::PumpResult::kTerminated) { // terminating isolate or stopped loop: nothing can complete the walk, @@ -3734,7 +3745,7 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( httpDynamicWaiters[key].emplace_back(isolate, resolver); const std::string requestUrl = normalizedSpec; StartModuleGraphLoad( - isolate, context, requestUrl, + isolate, context, requestUrl, /*fetchDeadline=*/std::nullopt, [key, requestUrl, isolate](bool ok, const std::string& errorMessage, v8::Local completionContext) { v8::Isolate* iso = isolate; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 91b777a50..5a10ed9d9 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -162,6 +162,10 @@ v8::MaybeLocal LoadHttpModuleForUrl( // Compilation runs no user code, so pre-compiling the closure cannot change // evaluation order: V8 still evaluates in spec order from the root. // +// `fetchDeadline` bounds every HTTP fetch the walk issues, retries included +// (see FetchModuleBodyAsync). Callers that pump for the load pass their own +// wait deadline; callers that only queue work pass nullopt. +// // `onComplete(ok, errorMessage, context)` runs exactly once on the isolate's // JS thread with the isolate entered and `context` (the context captured at // start) already scoped. `ok` is false only when an HTTP ROOT fetch/compile @@ -177,17 +181,17 @@ v8::MaybeLocal LoadHttpModuleForUrl( // captured v8 handle would be destroyed off-thread. void StartModuleGraphLoad( v8::Isolate* isolate, v8::Local context, - const std::string& root, + const std::string& root, ModuleFetchDeadline fetchDeadline, std::function context)> onComplete); // Synchronous wrapper for callers that need the graph ready before // continuing: starts the walk, then pumps the isolate's event loop in place -// (EventLoop::PumpUntil) until it settles or `timeoutSeconds` elapses. A -// graph with no http(s) edges completes entirely inside StartModuleGraphLoad, -// so this returns without entering the pump at all — a disk-only load pays -// no pump slice. +// (EventLoop::PumpUntil) until it settles or `timeoutSeconds` elapses; the +// same deadline bounds the walk's fetches. A graph with no http(s) edges +// completes entirely inside StartModuleGraphLoad, so this returns without +// entering the pump at all — a disk-only load pays no pump slice. // Returns true when the walk completed (regardless of root success — the // caller's own load path reports root failures). bool RunModuleGraphLoadPumped(v8::Isolate* isolate,