Skip to content

Commit 41caa01

Browse files
authored
fix(runtime): bound HTTP module fetches by the graph walk's deadline (#2171)
### Description A pumped graph walk waits at most `kModuleEvaluateDeadlineSeconds` for its fetches. Each async attempt, though, carried a flat 15 s connect + 15 s read timeout and retried once unconditionally. A stalled edge could therefore keep fetching long after the wait had given up on it. - **One timeout policy.** `ModuleFetchTimeoutMs()` sets the connect and read timeouts of every attempt: **30 s in debug builds and 5 s in release builds**, the values iOS uses. That replaces 15 s / 15 s in both. Dev servers transform cold modules on demand. NativeScript/ios#552 reports toolchain responses of 5–9 s, which is why debug gets the longer budget. - **The deadline reaches every fetch.** The pumped walk takes its deadline before it starts and hands it to every fetch it issues (`AsyncGraphLoad::fetchDeadline`). Each async attempt: - clamps both timeouts to the time remaining; - retries only while the budget still fits the 120 ms retry delay; - fails with `HTTP import failed: <url> (module graph fetch deadline exceeded)` without issuing a request when it would start past the deadline, including when it was queued behind the concurrency cap. - A dynamic `import()` of an HTTP root passes no deadline and stays unbounded, since nothing waits on it. The synchronous fallback keeps its single retry. The docs now give the timeout values and the deadline rules in place of the old per-attempt-bounds caveat. #### Notes for review - **Release builds tighten from 15 s to 5 s per connect and per read.** This only affects release apps that set `security.allowRemoteModules`. A slow remote origin that answered within 15 s now fails at 5 s, as it does on iOS. - **The timeouts are still per-connect and per-read inactivity bounds, not totals.** A response that keeps dripping in can run past the deadline. The pumped wait gives up on it at the deadline regardless. - Transport timeouts were one of the cross-platform items listed in #2020. They now match iOS. ### Does your commit message include the wording below to reference a specific issue in this repo? No. It relates to #2020, a tracking issue that should stay open. ### Related Pull Requests Mirrors NativeScript/ios#552, including its timeout values and its slow-transform specs. The `/esm/slow/` and `/esm/request-stats.json` test-server routes it relies on came in earlier in this stack. Part of a stack of six; each PR targets the branch below it: 1. #2168 `fix/http-importer-specifiers`: specifier resolution from HTTP importers 2. #2169 `refactor/module-url-parse`: one URL parse for every http(s) entry point 3. #2170 `perf/http-module-streaming-compile`: compile large HTTP modules off the JS thread 4. #2171 `fix/http-module-fetch-budget`: bound fetches by the graph walk's deadline (**this PR**) 5. #2172 `perf/http-module-transport`: persistent connections, per-host-class caps, OkHttp transport 6. #2173 `feat/http-module-cache-controls`: HTTP module cache controls ### Does your pull request have [unit tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)? Yes. A new "fetch budget" group in `testEsmHttpLoader.js` uses `/esm/request-stats.json` to prove that each module was requested exactly once, with no retry and no synchronous-fallback round trip: - a 7 s module resolves on its first request; - a 7 s re-export chain resolves on one request per module; - a pumped `require()` through a local→HTTP boundary waits for a 7 s leaf. Full suite on the top of the stack (`./gradlew runtestsAndVerifyResults`): 2074 specs, 2068 passed, 0 failed, 6 skipped (the usual GC, native-module and environment skips), on an API 36 arm64 emulator with OkHttp in the test app, at `feat/http-module-cache-controls` 21f87a8. This stays a draft until the stack has been run against a real Vite dev session on Android, which has not happened yet. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * HTTP module graph loads now honor a shared time limit across fetching and retries, helping slow or stalled imports fail predictably. * Transport errors receive one brief retry when time remains; requests that can no longer fit within the deadline are skipped. * Dynamic imports and synchronous fallback fetches retain their existing per-attempt timeout behavior. * **Tests** * Added coverage for delayed HTTP modules, re-export chains, and modules loaded through `require()`. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 1fa2f60 commit 41caa01

8 files changed

Lines changed: 213 additions & 44 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,13 +1178,23 @@ deadline is a single constant, `kModuleEvaluateDeadlineSeconds` = 60 seconds
11781178
(`ModuleInternal.h`), shared by the HTTP entry's settle window, the pumped
11791179
graph walk, and — doubled, at 120 seconds — the boot backstop. The waits are
11801180
*designed* to nest — transport timeouts within the module deadline within the
1181-
boot backstop — but the transport numbers are per-attempt bounds (connect) and
1182-
per-read inactivity bounds (read), not totals: a retried fetch or a slowly
1183-
dripping response can legally spend longer than one connect+read sum, and the
1184-
deadline above it is what actually cuts the wait off. The local entry's short
1185-
yield is deliberately *not* derived from that constant: it is an independent
1186-
one-second literal in `BootEntryEvaluationOptions`, with `return-pending`
1187-
behavior. An HTTP entry instead gets the full deadline and throws on expiry,
1181+
boot backstop. Each fetch attempt gets a connect timeout and a read timeout
1182+
of 30 seconds in debug builds and 5 seconds in release builds
1183+
(`ModuleFetchTimeoutMs` in `HttpLoader.cpp`, the same values as iOS), and a
1184+
transport error is retried once after 120 ms. A
1185+
pumped graph walk passes its own deadline down to every fetch it issues: an
1186+
attempt clamps both timeouts to the time remaining, the retry is skipped when
1187+
the remaining budget cannot fit its delay, and an attempt that would start
1188+
after the deadline — including one still queued behind the concurrency cap —
1189+
fails as `HTTP import failed: <url> (module graph fetch deadline exceeded)`
1190+
without issuing a request. A dynamic `import()` of an HTTP root nothing pumps
1191+
for passes no deadline, and the synchronous fallback fetch keeps the plain
1192+
per-attempt timeouts. The timeouts are still per-connect and per-read
1193+
inactivity bounds, not totals, so a response that keeps dripping in can run
1194+
past the deadline; the pumped wait gives up on it at the deadline regardless.
1195+
The local entry's short yield is deliberately *not* derived from that
1196+
constant: it is an independent one-second literal in
1197+
`BootEntryEvaluationOptions`, with `return-pending` behavior. An HTTP entry instead gets the full deadline and throws on expiry,
11881198
because the tooling driving it needs the rejection reason synchronously. The
11891199
backstop itself is `HoldBootBackstop` in `Runtime.cpp`, called from both
11901200
`Runtime::RunModule` overloads; it pumps the isolate's event loop in place
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// Entry of a local->local->http graph whose HTTP leaf answers only after a
2+
// multi-second transform delay (ModuleTestServer /esm/slow/req-leaf.mjs).
3+
// Exercises the pumped graph walk's fetch budget through require(): the leaf
4+
// must arrive within the walk's deadline on its first request.
5+
import { leaf as leafValue } from "./slow-mid.mjs";
6+
7+
export const leaf = leafValue;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// Named re-export through the local->HTTP boundary: "ns-slow-leaf" is a bare
2+
// specifier the spec's import map points at a delayed ModuleTestServer URL,
3+
// so this file needs no baked-in origin.
4+
export { value as leaf } from "ns-slow-leaf";

‎test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -829,6 +829,82 @@ describe("HTTP ESM Loader", function () {
829829
});
830830
});
831831

832+
// Dev servers transform cold modules on demand, and responses have
833+
// been measured at 5-9 s. A 7 s module must land inside the transport
834+
// timeout (30 s per attempt in debug builds) on its first request: a
835+
// timeout would show as a second request, from the retry or from the
836+
// synchronous fallback.
837+
describe("fetch budget", function () {
838+
var originalTimeout;
839+
beforeEach(function () {
840+
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
841+
jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
842+
});
843+
afterEach(function () {
844+
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
845+
require("ns:module").configureLoader({ importMap: { imports: {} } });
846+
});
847+
848+
function statsCount(target) {
849+
return import(origin + "/esm/request-stats.json?target=" +
850+
encodeURIComponent(target) + "&n=" + (++requestStatsQueries))
851+
.then(function (stats) {
852+
return stats.default.count;
853+
});
854+
}
855+
856+
it("resolves a slow HTTP module on its first request", function (done) {
857+
var target = "/esm/slow/leaf.mjs?k=direct&delayMs=7000";
858+
import(origin + target).then(function (mod) {
859+
expect(mod.value).toBe(42);
860+
return statsCount(target);
861+
}).then(function (count) {
862+
expect(count).toBe(1);
863+
done();
864+
}).catch(function (error) {
865+
reportRejection(error, done);
866+
});
867+
});
868+
869+
it("resolves a slow HTTP re-export chain on one request per module", function (done) {
870+
// The walk discovers the child only once the parent's 7 s
871+
// response lands.
872+
var parentTarget = "/esm/slow/parent.mjs?k=chain&delayMs=7000";
873+
var childTarget = "/esm/slow/child.mjs?from=chain";
874+
import(origin + parentTarget).then(function (mod) {
875+
expect(mod.value).toBe(42);
876+
expect(mod.parent).toBe("chain");
877+
return Promise.all([statsCount(parentTarget), statsCount(childTarget)]);
878+
}).then(function (counts) {
879+
expect(counts).toEqual([1, 1]);
880+
done();
881+
}).catch(function (error) {
882+
reportRejection(error, done);
883+
});
884+
});
885+
886+
it("waits for a slow HTTP leaf during a pumped require()", function (done) {
887+
var leafTarget = "/esm/slow/req-leaf.mjs?k=req&delayMs=7000";
888+
var nsModule = require("ns:module");
889+
nsModule.configureLoader({
890+
importMap: {
891+
imports: { "ns-slow-leaf": origin + leafTarget },
892+
},
893+
});
894+
// Blocks the JS thread for the walk's 7 s fetch; the re-export
895+
// at slow-mid.mjs keeps the leaf inside the pumped graph.
896+
var req = nsModule.createRequire(appRoot + "/anything.js");
897+
var mod = req("./esm/mixed/slow-entry.mjs");
898+
expect(mod.leaf).toBe(42);
899+
statsCount(leafTarget).then(function (count) {
900+
expect(count).toBe(1);
901+
done();
902+
}).catch(function (error) {
903+
reportRejection(error, done);
904+
});
905+
});
906+
});
907+
832908
describe("worker teardown", function () {
833909
var originalTimeout;
834910
beforeEach(function () {

‎test-app/runtime/src/main/cpp/HttpLoader.cpp‎

Lines changed: 71 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -345,8 +345,18 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std::
345345
}
346346

347347
static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey,
348-
std::string& out, std::string& contentType, int& status,
349-
bool& bustApplied);
348+
int timeoutMs, std::string& out, std::string& contentType,
349+
int& status, bool& bustApplied);
350+
351+
// Each module-fetch attempt's connect timeout and read timeout, for both
352+
// transports, matching iOS. Debug builds talk to dev servers that transform
353+
// cold modules on demand (measured at 5-9 s); release builds fetch remote
354+
// modules that should fail fast.
355+
static int ModuleFetchTimeoutMs() {
356+
return IsDebuggable() ? 30000 : 5000;
357+
}
358+
359+
static constexpr std::chrono::milliseconds kModuleFetchRetryDelay{120};
350360

351361
static std::string ApplyCacheBustNonce(const std::string& url, const std::string& canonicalKey,
352362
bool* outBustRequested) {
@@ -595,16 +605,17 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey,
595605
std::string contentType;
596606
int status = 0;
597607
bool bustApplied = false;
598-
bool transportOk =
599-
PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, bustApplied);
608+
const int timeoutMs = ModuleFetchTimeoutMs();
609+
bool transportOk = PerformHttpFetchOnceSync(url, canonicalKey, timeoutMs, body, contentType,
610+
status, bustApplied);
600611
if (!transportOk) {
601612
// One retry, and only for a transport error: an HTTP status is an
602613
// answer, not a failure to communicate, so asking again would just
603614
// repeat it.
604615
TNS_DEBUG(Esm, "[http-loader] retrying %s after initial fetch error", url.c_str());
605-
usleep(120 * 1000);
606-
transportOk =
607-
PerformHttpFetchOnceSync(url, canonicalKey, body, contentType, status, bustApplied);
616+
std::this_thread::sleep_for(kModuleFetchRetryDelay);
617+
transportOk = PerformHttpFetchOnceSync(url, canonicalKey, timeoutMs, body, contentType,
618+
status, bustApplied);
608619
}
609620

610621
ClassifyModuleResponse(url, transportOk, status, contentType, body, result);
@@ -645,13 +656,14 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey,
645656
// tells a status-bearing answer (an empty 404) apart from a transport failure,
646657
// and past the InputStream close. The wrappers stay on the setup calls, whose
647658
// failures have no per-stage verdict and are caught below.
659+
// `timeoutMs` must be positive: HttpURLConnection reads 0 as no timeout.
648660
static bool PerformHttpFetchOnceSync(const std::string& url, const std::string& canonicalKey,
649-
std::string& out, std::string& contentType, int& status,
650-
bool& bustApplied) {
661+
int timeoutMs, std::string& out, std::string& contentType,
662+
int& status, bool& bustApplied) {
651663
out.clear();
652664
contentType.clear();
653665
status = 0;
654-
TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s", url.c_str());
666+
TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s timeoutMs=%d", url.c_str(), timeoutMs);
655667

656668
const std::string fetchUrl = ApplyCacheBustNonce(url, canonicalKey, &bustApplied);
657669

@@ -718,8 +730,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, const std::string&
718730
jmethodID setUseCaches = env.GetMethodID(clsConn, "setUseCaches", "(Z)V");
719731
jmethodID setReqProp =
720732
env.GetMethodID(clsConn, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
721-
env.CallVoidMethod(conn, setConnectTimeout, 15000);
722-
env.CallVoidMethod(conn, setReadTimeout, 15000);
733+
env.CallVoidMethod(conn, setConnectTimeout, timeoutMs);
734+
env.CallVoidMethod(conn, setReadTimeout, timeoutMs);
723735
if (setDoInput) {
724736
env.CallVoidMethod(conn, setDoInput, JNI_TRUE);
725737
}
@@ -895,9 +907,27 @@ namespace {
895907
struct ModuleFetchJob {
896908
std::string url;
897909
std::string canonicalKey;
910+
ModuleFetchDeadline deadline;
898911
std::function<void(ModuleFetchResult)> completion;
899912
};
900913

914+
// The timeout for an attempt starting now, or nullopt when `deadline` has
915+
// already passed.
916+
std::optional<int> AttemptTimeoutMs(const ModuleFetchDeadline& deadline) {
917+
const int policyMs = ModuleFetchTimeoutMs();
918+
if (!deadline) return policyMs;
919+
const auto now = std::chrono::steady_clock::now();
920+
if (now >= *deadline) return std::nullopt;
921+
// Rounded up: a sub-millisecond remainder must not become 0, which
922+
// HttpURLConnection reads as no timeout at all.
923+
const auto remainingMs = std::chrono::ceil<std::chrono::milliseconds>(*deadline - now).count();
924+
return remainingMs < policyMs ? static_cast<int>(remainingMs) : policyMs;
925+
}
926+
927+
bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) {
928+
return !deadline || *deadline - std::chrono::steady_clock::now() > kModuleFetchRetryDelay;
929+
}
930+
901931
// See the cap's rationale in HttpLoader.h. 16 matches iOS's
902932
// HTTPMaximumConnectionsPerHost.
903933
constexpr size_t kMaxConcurrentModuleFetches = 16;
@@ -921,22 +951,36 @@ void RunModuleFetchJob(const ModuleFetchJob& job) {
921951
int status = 0;
922952
const auto start = std::chrono::steady_clock::now();
923953
bool bustApplied = false;
924-
bool transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, body, contentType,
925-
status, bustApplied);
926-
if (!transportOk) {
954+
bool transportOk = false;
955+
std::optional<int> timeoutMs = AttemptTimeoutMs(job.deadline);
956+
if (timeoutMs) {
957+
transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs, body,
958+
contentType, status, bustApplied);
927959
// Transport error → one retry, the same single-retry policy the
928-
// sync path applies.
929-
TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error",
930-
job.url.c_str());
931-
usleep(120 * 1000);
932-
transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, body, contentType,
933-
status, bustApplied);
960+
// sync path applies, while the deadline can still fit the delay.
961+
if (!transportOk && !RetryFitsDeadline(job.deadline)) {
962+
TNS_DEBUG(Esm, "[http-loader][fetch-async] no budget left to retry %s",
963+
job.url.c_str());
964+
} else if (!transportOk) {
965+
TNS_DEBUG(Esm, "[http-loader][fetch-async] retrying %s after transport error",
966+
job.url.c_str());
967+
std::this_thread::sleep_for(kModuleFetchRetryDelay);
968+
timeoutMs = AttemptTimeoutMs(job.deadline);
969+
if (timeoutMs) {
970+
transportOk = PerformHttpFetchOnceSync(job.url, job.canonicalKey, *timeoutMs,
971+
body, contentType, status, bustApplied);
972+
}
973+
}
934974
}
935975

936-
ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result);
937-
938-
if (result.ok && bustApplied) {
939-
ClearCacheBustForUrl(job.canonicalKey);
976+
if (timeoutMs) {
977+
ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result);
978+
if (result.ok && bustApplied) {
979+
ClearCacheBustForUrl(job.canonicalKey);
980+
}
981+
} else {
982+
result.failureReason =
983+
"HTTP import failed: " + job.url + " (module graph fetch deadline exceeded)";
940984
}
941985

942986
if (!result.ok) {
@@ -1018,6 +1062,7 @@ void ModuleFetchThreadMain(ModuleFetchJob job) {
10181062
} // namespace
10191063

10201064
void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKey,
1065+
ModuleFetchDeadline fetchDeadline,
10211066
std::function<void(ModuleFetchResult result)> completion) {
10221067
// Security gate: single point of enforcement, same as HttpFetchModule.
10231068
if (!IsRemoteUrlAllowed(url)) {
@@ -1030,7 +1075,7 @@ void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKe
10301075
return;
10311076
}
10321077

1033-
ModuleFetchJob job{url, canonicalKey, std::move(completion)};
1078+
ModuleFetchJob job{url, canonicalKey, fetchDeadline, std::move(completion)};
10341079
{
10351080
std::lock_guard<std::mutex> lock(g_fetchQueueMutex);
10361081
if (g_fetchThreadCount >= kMaxConcurrentModuleFetches) {

‎test-app/runtime/src/main/cpp/HttpLoader.h‎

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

3+
#include <chrono>
34
#include <functional>
45
#include <optional>
56
#include <string>
@@ -92,13 +93,24 @@ struct ModuleFetchResult {
9293
bool HttpFetchModule(const std::string& url, const std::string& canonicalKey,
9394
ModuleFetchResult& result);
9495

96+
// An absolute bound on an async module fetch, retries included; nullopt =
97+
// unbounded.
98+
using ModuleFetchDeadline = std::optional<std::chrono::steady_clock::time_point>;
99+
95100
// Asynchronous single-URL module fetch — the I/O primitive behind the
96101
// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h).
97102
// Same response policy as HttpFetchModule, minus the JS-thread block:
98103
// - security gate (IsRemoteUrlAllowed) checked up front,
99104
// - a JNI HttpURLConnection GET on a background thread with the same
100105
// request shape as the sync path (cache-bust nonce, zero-cache headers)
101106
// and one retry on transport error.
107+
// `fetchDeadline` is the enclosing graph load's fetch budget: each attempt
108+
// clamps its connect and read timeouts to the time remaining, the
109+
// transport-error retry is skipped once the budget cannot fit it, and an
110+
// attempt that would start with no budget left fails instead. Time spent
111+
// queued behind the concurrency cap counts against it. The timeouts bound one
112+
// connect and each read, not the whole response, so a body that keeps
113+
// trickling in can still finish past the deadline.
102114
// `completion(result)` is invoked exactly once, on an arbitrary thread —
103115
// callers must hop to their JS thread before touching V8.
104116
// `canonicalKey` as for HttpFetchModule: computed on the calling isolate's
@@ -112,7 +124,7 @@ bool HttpFetchModule(const std::string& url, const std::string& canonicalKey,
112124
// fetch thread as one frees — the CALLER never blocks, so this stays safe to
113125
// call from the JS thread.
114126
void FetchModuleBodyAsync(
115-
const std::string& url, const std::string& canonicalKey,
127+
const std::string& url, const std::string& canonicalKey, ModuleFetchDeadline fetchDeadline,
116128
std::function<void(ModuleFetchResult result)> completion);
117129

118130
// Mark a set of canonical registry keys so that the NEXT network fetch of

0 commit comments

Comments
 (0)