Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions docs/ns-builtin-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <url> (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
Expand Down
7 changes: 7 additions & 0 deletions test-app/app/src/main/assets/app/esm/mixed/slow-entry.mjs
Original file line number Diff line number Diff line change
@@ -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;
4 changes: 4 additions & 0 deletions test-app/app/src/main/assets/app/esm/mixed/slow-mid.mjs
Original file line number Diff line number Diff line change
@@ -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";
76 changes: 76 additions & 0 deletions test-app/app/src/main/assets/app/tests/testEsmHttpLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () {
Expand Down
97 changes: 71 additions & 26 deletions test-app/runtime/src/main/cpp/HttpLoader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -895,9 +907,27 @@ namespace {
struct ModuleFetchJob {
std::string url;
std::string canonicalKey;
ModuleFetchDeadline deadline;
std::function<void(ModuleFetchResult)> completion;
};

// The timeout for an attempt starting now, or nullopt when `deadline` has
// already passed.
std::optional<int> 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<std::chrono::milliseconds>(*deadline - now).count();
return remainingMs < policyMs ? static_cast<int>(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;
Expand All @@ -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<int> 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) {
Expand Down Expand Up @@ -1018,6 +1062,7 @@ void ModuleFetchThreadMain(ModuleFetchJob job) {
} // namespace

void FetchModuleBodyAsync(const std::string& url, const std::string& canonicalKey,
ModuleFetchDeadline fetchDeadline,
std::function<void(ModuleFetchResult result)> completion) {
// Security gate: single point of enforcement, same as HttpFetchModule.
if (!IsRemoteUrlAllowed(url)) {
Expand All @@ -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<std::mutex> lock(g_fetchQueueMutex);
if (g_fetchThreadCount >= kMaxConcurrentModuleFetches) {
Expand Down
14 changes: 13 additions & 1 deletion test-app/runtime/src/main/cpp/HttpLoader.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <chrono>
#include <functional>
#include <optional>
#include <string>
Expand Down Expand Up @@ -92,13 +93,24 @@ 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<std::chrono::steady_clock::time_point>;

// Asynchronous single-URL module fetch — the I/O primitive behind the
// module-graph walk (see StartModuleGraphLoad in ModuleInternalCallbacks.h).
// Same response policy as HttpFetchModule, minus the JS-thread block:
// - security gate (IsRemoteUrlAllowed) checked up front,
// - 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
Expand All @@ -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<void(ModuleFetchResult result)> completion);

// Mark a set of canonical registry keys so that the NEXT network fetch of
Expand Down
Loading