diff --git a/NativeScript/runtime/ModuleInternalCallbacks.mm b/NativeScript/runtime/ModuleInternalCallbacks.mm index 3c69dd28b..5b99a1e69 100644 --- a/NativeScript/runtime/ModuleInternalCallbacks.mm +++ b/NativeScript/runtime/ModuleInternalCallbacks.mm @@ -2,19 +2,29 @@ #include "ModuleInternalCallbacks.h" #import #include +#include +#include #include #include #include #include +#include +#include #include #include +#include +#include +#include #include #include #include #include +#include +#include #include #include "Caches.h" #include "EventLoop.h" +#include "ExternalMemory.h" #include "Helpers.h" // for tns::Exists #include "HttpLoader.h" #include "ModuleInternal.h" // for CompileFileEsModule / EvaluateModuleGraph @@ -86,6 +96,7 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { // QuiesceModuleLoadsForIsolate so in-flight walks can't touch a disposed // isolate. static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate); +static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate); static v8::MaybeLocal CompileJsonTextAsEsModule(v8::Isolate* isolate, v8::Local context, const std::string& jsonText, @@ -102,6 +113,131 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { v8::Global facade; }; +// ── Off-thread compile of large HTTP module bodies ─────────────────────────── +// +// ScriptStreamingTask::Run() works on the isolate's heap from another thread +// (it opens a LocalIsolate), so the isolate must outlive every Run() and a +// task that has run must be destroyed before the isolate is disposed. Hence: +// - StreamedModuleCompile (StreamedSource + task) is owned by the isolate's +// ModuleLoaderState and created, finalized and destroyed on the isolate +// thread only; +// - background threads hold a StreamTicket, which never owns V8 state; +// - StreamCompileGate counts Run() calls in flight; teardown closes it and +// waits for zero before the event loop stops and the state is destroyed. + +// Hands the fetched body to the stream. GetMoreData blocks until it is fed or +// cancelled; V8 takes ownership of the chunk and delete[]s it. +class StreamFeed { + public: + void Feed(std::unique_ptr chunk, size_t length) { + std::lock_guard lock(mutex_); + chunk_ = std::move(chunk); + length_ = length; + ready_ = true; + cv_.notify_all(); + } + + void Cancel() { + std::lock_guard lock(mutex_); + ready_ = true; + cv_.notify_all(); + } + + size_t Take(const uint8_t** src) { + std::unique_lock lock(mutex_); + cv_.wait(lock, [this] { return ready_; }); + if (chunk_ == nullptr) { + return 0; + } + *src = chunk_.release(); + return length_; + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + std::unique_ptr chunk_; + size_t length_ = 0; + bool ready_ = false; +}; + +class FeedSourceStream : public v8::ScriptCompiler::ExternalSourceStream { + public: + explicit FeedSourceStream(std::shared_ptr feed) : feed_(std::move(feed)) {} + size_t GetMoreData(const uint8_t** src) override { return feed_->Take(src); } + + private: + std::shared_ptr feed_; +}; + +class StreamCompileGate { + public: + // False once closed: no Run() may start after teardown began. + bool TryEnter() { + std::lock_guard lock(mutex_); + if (closed_) { + return false; + } + inFlight_++; + return true; + } + + void Leave() { + std::lock_guard lock(mutex_); + if (--inFlight_ == 0) { + cv_.notify_all(); + } + } + + // Isolate thread. A Run() that needs a GC parks until the isolate thread + // performs it (CollectionBarrier::AwaitCollectionBackground), and the + // waiting thread is not parked itself, so a plain wait could deadlock: + // `serviceGcRequests` runs between short waits to let that GC happen. + void CloseAndDrain(const std::function& serviceGcRequests) { + std::unique_lock lock(mutex_); + closed_ = true; + while (inFlight_ > 0) { + if (cv_.wait_for(lock, std::chrono::milliseconds(2), [this] { return inFlight_ == 0; })) { + break; + } + lock.unlock(); + serviceGcRequests(); + lock.lock(); + } + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + int inFlight_ = 0; + bool closed_ = false; +}; + +// The background threads' view of one streamed compile. `task` is owned by +// the isolate-side StreamedModuleCompile and may be used only between a +// successful gate->TryEnter() and the matching Leave(). `ran` and `ascii` are +// written before the completion task is posted and read after it runs. +struct StreamTicket { + uint64_t id = 0; + std::shared_ptr gate; + std::shared_ptr feed; + v8::ScriptCompiler::ScriptStreamingTask* task = nullptr; + bool ran = false; + bool ascii = false; +}; + +struct StreamedModuleCompile { + ~StreamedModuleCompile() { + if (feed != nullptr) { + feed->Cancel(); + } + } + std::shared_ptr feed; + // Declared before `task`, which points into it. + std::unique_ptr source; + std::unique_ptr task; +}; + // All module-loader state owned by one isolate. v8::Global handles are bound // to the isolate that created them, so each isolate (main + every Worker) // keeps its own set. Lives in a Caches state slot (Caches::StateFor), so it is @@ -151,6 +287,12 @@ static inline bool StartsWith(const std::string& s, const char* prefix) { // Holds the facade target across that facade's InstantiateModule and nothing // else — the facade's resolve callback is the only reader. v8::Global pendingFacadeTarget; + + // Streamed compiles issued and not yet finalized or discarded, by ticket id. + // QuiesceModuleLoadsForIsolate drains the gate before any of these die. + std::shared_ptr streamGate = std::make_shared(); + std::unordered_map> streamedCompiles; + uint64_t nextStreamedCompileId = 1; }; // This isolate's loader state, or null once teardown has begun — callers must @@ -450,9 +592,15 @@ void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey // which nothing downstream can reconstruct. A caller that cannot let it // propagate must consume it through its own TryCatch and route the text into // its own failure channel — never drop it. -static v8::MaybeLocal CompileModuleForResolveRegisterOnly( - v8::Isolate* isolate, v8::Local context, const std::string& code, - const std::string& urlStr) { +// +// `compile` produces the module for `origin`; it is not called when the key is +// already registered. +using ModuleCompileStep = std::function(const v8::ScriptOrigin& origin)>; + +static v8::MaybeLocal CompileAndRegisterModule(v8::Isolate* isolate, + v8::Local context, + const std::string& urlStr, + const ModuleCompileStep& compile) { v8::EscapableHandleScope hs(isolate); auto* moduleState = ModuleLoaderStateFor(isolate); if (moduleState == nullptr) { @@ -476,20 +624,16 @@ void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey } } - // Length-aware conversion: module source may contain embedded NUL bytes, - // which the char* overload would truncate. - v8::Local sourceText = tns::ToV8String(isolate, code); v8::Local urlV8; if (!v8::String::NewFromUtf8(isolate, urlStr.c_str(), v8::NewStringType::kNormal) .ToLocal(&urlV8)) { return v8::MaybeLocal(); } v8::ScriptOrigin origin(urlV8, 0, 0, false, -1, v8::Local(), false, false, true); - v8::ScriptCompiler::Source src(sourceText, origin); v8::Local mod; { v8::TryCatch tcCompile(isolate); - if (!v8::ScriptCompiler::CompileModule(isolate, &src).ToLocal(&mod)) { + if (!compile(origin).ToLocal(&mod)) { TNS_DEBUG(Esm, "[http-esm][compile][fail] %s %s", urlStr.c_str(), DescribeCaughtError(isolate, context, tcCompile).c_str()); tcCompile.ReThrow(); @@ -500,6 +644,64 @@ void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey return hs.Escape(mod); } +static v8::MaybeLocal CompileModuleForResolveRegisterOnly( + v8::Isolate* isolate, v8::Local context, const std::string& code, + const std::string& urlStr) { + return CompileAndRegisterModule( + isolate, context, urlStr, [isolate, &code](const v8::ScriptOrigin& origin) { + // Length-aware conversion: module source may contain embedded NUL + // bytes, which the char* overload would truncate. + v8::ScriptCompiler::Source src(tns::ToV8String(isolate, code), origin); + return v8::ScriptCompiler::CompileModule(isolate, &src); + }); +} + +// A module body the isolate keeps as an external one-byte string. Valid only +// for pure-ASCII bodies: a one-byte string is Latin-1, which matches the +// UTF-8 bytes the streamed compile parsed only below 0x80. The bytes live +// outside the V8 heap, so they are charged as external memory for as long as +// the string holds them. +class OwnedAsciiSource : public v8::String::ExternalOneByteStringResource { + public: + OwnedAsciiSource(std::string body, v8::Isolate* isolate, int gateId) + : body_(std::move(body)), charge_(isolate, gateId) {} + const char* data() const override { return body_.data(); } + size_t length() const override { return body_.size(); } + // Isolate thread, while the string is reachable: it can run a collection. + void Charge() { charge_.Set(body_.size()); } + + private: + std::string body_; + ExternalMemoryCharge charge_; +}; + +// Finalizes a streamed compile whose ScriptStreamingTask::Run() has returned. +// `body` must be the exact bytes the stream was fed. +static v8::MaybeLocal CompileStreamedModuleRegisterOnly(v8::Isolate* isolate, + v8::Local context, + StreamedModuleCompile& streamed, + std::string body, bool ascii, + const std::string& urlStr) { + return CompileAndRegisterModule( + isolate, context, urlStr, + [isolate, context, &streamed, &body, ascii](const v8::ScriptOrigin& origin) { + v8::Local sourceText; + if (ascii) { + auto* resource = + new OwnedAsciiSource(std::move(body), isolate, Caches::Get(isolate)->getGateId()); + if (!v8::String::NewExternalOneByte(isolate, resource).ToLocal(&sourceText)) { + delete resource; + return v8::MaybeLocal(); + } + resource->Charge(); + } else { + sourceText = tns::ToV8String(isolate, body); + } + return v8::ScriptCompiler::CompileModule(context, streamed.source.get(), sourceText, + origin); + }); +} + // ──────────────────────────────────────────────────────────────────────────── // Per-isolate module registries: map absolute file paths / canonical URLs → // compiled v8::Module handles, keyed by the owning v8::Isolate*. @@ -535,9 +737,13 @@ void IndexModuleForIsolate(v8::Isolate* isolate, const std::string& canonicalKey // Neutralize any in-flight async graph loads for `isolate`: their fetch // completions check the dead flag before touching V8, and their context -// Globals are Reset here, while the isolate is still alive. The rest of the -// loader state is destroyed with the isolate's Caches. -void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate) { KillAsyncGraphLoadsForIsolate(isolate); } +// Globals are Reset here, while the isolate is still alive. Background compiles +// are waited out for the same reason. The rest of the loader state is +// destroyed with the isolate's Caches. +void QuiesceModuleLoadsForIsolate(v8::Isolate* isolate) { + KillAsyncGraphLoadsForIsolate(isolate); + DrainStreamedCompilesForIsolate(isolate); +} // ──────────────────────────────────────────────────────────────────────────── // Import map: bare specifier → resolved URL (populated by ns:module configureLoader) @@ -984,17 +1190,20 @@ void SetCanonicalizationConfig(CanonicalizationConfig config) { // EnqueueUrl(root) // → FetchModuleBodyAsync (NSURLSession on a // background queue — see HttpLoader.mm) +// → JavaScript bodies of kStreamingCompileThresholdBytes or more: parse + +// bytecode generation on a StreamCompilePool thread (V8 streaming) // → hop to the isolate's JS thread (ExecuteOnRunLoop on the runtime loop) -// → CompileModuleForResolveRegisterOnly (registers under the canonical -// URL key — the exact entry ResolveModuleCallback will look up) +// → CompileModuleForResolveRegisterOnly, or the streamed compile's +// finalization (registers under the canonical URL key — the exact +// entry ResolveModuleCallback will look up) // → GetModuleRequests() → ResolveSpecifierToPath → EnqueueUrl(…) // → when pendingFetches drains, onComplete fires on the JS thread. // // Thread discipline: `visited`, `pendingFetches`, `failed`, `completed` are // touched ONLY on the isolate's JS thread (every fetch completion hops there -// first). Only raw I/O runs off-thread. The one crossing signal is `dead`, -// an atomic set by isolate teardown so in-flight completions become no-ops -// instead of touching a disposed isolate. +// first). Off-thread work is the I/O and ScriptStreamingTask::Run(). The one +// crossing signal is `dead`, an atomic set by isolate teardown so in-flight +// completions become no-ops instead of touching a disposed isolate. // // Failure semantics are deliberately unchanged from the synchronous loader: // only a ROOT fetch/compile failure fails the walk (mirroring today's @@ -1063,6 +1272,199 @@ void RegisterAsyncGraphLoad(v8::Isolate* isolate, const std::shared_ptr job) { + { + std::lock_guard lock(mutex_); + if (jobs_.size() >= idle_ && threads_ < maxThreads_ && StartThreadLocked()) { + threads_++; + } + if (threads_ == 0) { + return false; + } + jobs_.push_back(std::move(job)); + } + cv_.notify_one(); + return true; + } + + private: + static constexpr size_t kStackBytes = 2 * 1024 * 1024; + + StreamCompilePool() { + const unsigned cpus = std::thread::hardware_concurrency(); + maxThreads_ = std::clamp(cpus > 1 ? cpus - 1 : 1u, 1u, 4u); + } + + bool StartThreadLocked() { + pthread_attr_t attr; + if (pthread_attr_init(&attr) != 0) { + return false; + } + pthread_attr_setstacksize(&attr, kStackBytes); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INITIATED, 0); + pthread_t thread; + const bool started = pthread_create(&thread, &attr, &ThreadMain, this) == 0; + pthread_attr_destroy(&attr); + return started; + } + + static void* ThreadMain(void* arg) { + pthread_setname_np("org.nativescript.esm.stream-compile"); + auto* pool = static_cast(arg); + for (;;) { + std::function job; + { + std::unique_lock lock(pool->mutex_); + pool->idle_++; + pool->cv_.wait(lock, [pool] { return !pool->jobs_.empty(); }); + pool->idle_--; + job = std::move(pool->jobs_.front()); + pool->jobs_.pop_front(); + } + @autoreleasepool { + job(); + } + } + return nullptr; + } + + std::mutex mutex_; + std::condition_variable cv_; + std::deque> jobs_; + size_t idle_ = 0; + unsigned threads_ = 0; + unsigned maxThreads_ = 1; +}; + +// Isolate thread, at fetch issue. Null when V8 declines to stream; otherwise +// the compile is parked in the loader state, its stream empty until the +// transport feeds it. +std::shared_ptr BeginStreamedCompile(v8::Isolate* isolate, ModuleLoaderState& state) { + auto compile = std::make_unique(); + compile->feed = std::make_shared(); + compile->source = std::make_unique( + std::make_unique(compile->feed), v8::ScriptCompiler::StreamedSource::UTF8); + // Streaming follows --lazy-streaming, not --lazy, so the --no-lazy that + // Runtime sets outside debug has to be passed explicitly. + const auto options = RuntimeConfig.IsDebug ? v8::ScriptCompiler::kNoCompileOptions + : v8::ScriptCompiler::kEagerCompile; + compile->task.reset(v8::ScriptCompiler::StartStreaming(isolate, compile->source.get(), + v8::ScriptType::kModule, options)); + if (compile->task == nullptr) { + return nullptr; + } + auto ticket = std::make_shared(); + ticket->id = state.nextStreamedCompileId++; + ticket->gate = state.streamGate; + ticket->feed = compile->feed; + ticket->task = compile->task.get(); + state.streamedCompiles.emplace(ticket->id, std::move(compile)); + return ticket; +} + +// The issuing isolate's compile for `ticket`, now owned by the caller. +// Isolate thread only. +std::unique_ptr TakeStreamedCompile(v8::Isolate* isolate, + const StreamTicket* ticket) { + auto* state = ticket != nullptr ? ModuleLoaderStateFor(isolate) : nullptr; + if (state == nullptr) { + return nullptr; + } + auto it = state->streamedCompiles.find(ticket->id); + if (it == state->streamedCompiles.end()) { + return nullptr; + } + std::unique_ptr compile = std::move(it->second); + state->streamedCompiles.erase(it); + return compile; +} + +bool IsAscii(const std::string& bytes) { + const unsigned char* p = reinterpret_cast(bytes.data()); + const size_t n = bytes.size(); + size_t i = 0; + for (; i + sizeof(uint64_t) <= n; i += sizeof(uint64_t)) { + uint64_t word; + memcpy(&word, p + i, sizeof(word)); + if (word & 0x8080808080808080ull) { + return false; + } + } + for (; i < n; i++) { + if (p[i] & 0x80) { + return false; + } + } + return true; +} + +// Transport thread. Feeds `result` to the ticket's stream and runs the compile +// on the StreamCompilePool, which calls `postCompletion` once Run() has +// returned. Returns false, without running anything, when the body is not to +// be streamed; the caller then posts the completion itself. +bool DispatchStreamedCompile(const std::shared_ptr& load, + const std::shared_ptr& ticket, + const std::shared_ptr& result, + std::function postCompletion) { + if (!result->ok || result->kind != ModuleResponseKind::kJavaScript || + result->body.size() < kStreamingCompileThresholdBytes) { + return false; + } + // The stream skips a leading UTF-8 BOM that the full source string would + // keep, which would shift every position the finalized script reports. + if (StartsWith(result->body, "\xEF\xBB\xBF")) { + return false; + } + if (!ticket->gate->TryEnter()) { + return false; + } + if (load->dead.load(std::memory_order_acquire)) { + ticket->gate->Leave(); + return false; + } + const bool posted = StreamCompilePool::Shared().Post([load, ticket, result, postCompletion]() { + if (!load->dead.load(std::memory_order_acquire)) { + const std::string& body = result->body; + std::unique_ptr chunk(new uint8_t[body.size()]); + memcpy(chunk.get(), body.data(), body.size()); + ticket->ascii = IsAscii(body); + ticket->feed->Feed(std::move(chunk), body.size()); + ticket->task->Run(); + ticket->ran = true; + // Posted before Leave(): teardown stops the event loop only after the + // gate drains, so this post cannot be dropped off the isolate thread. + postCompletion(); + } + ticket->gate->Leave(); + }); + if (!posted) { + ticket->gate->Leave(); + return false; + } + return true; +} } // namespace bool HasPendingAsyncModuleGraphWork() { @@ -1090,6 +1492,26 @@ static void KillAsyncGraphLoadsForIsolate(v8::Isolate* isolate) { state->asyncGraphLoads.clear(); } +// Isolate-teardown hook, after KillAsyncGraphLoadsForIsolate and before the +// event loop stops: closes the streaming gate, waits out every Run() in flight +// and destroys the compiles that will never be finalized, all while the +// isolate is alive and locked. A Run() parked on a GC request is released by +// running the loop's nestable v8 tasks, where V8 posted the request. +static void DrainStreamedCompilesForIsolate(v8::Isolate* isolate) { + auto* state = Caches::ExistingStateFor(isolate); + if (state == nullptr) { + return; + } + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + state->streamGate->CloseAndDrain([&loop]() { + if (loop != nullptr) { + loop->RunNestableV8Tasks(); + } + }); + state->streamedCompiles.clear(); +} + // ── The shared resolution seam ─────────────────────────────────────────────── // // One module specifier resolved to something the loader can act on. Both @@ -1466,7 +1888,9 @@ static void AsyncGraphMaybeComplete(const std::shared_ptr& load, // it enters the isolate the same way other cross-thread callbacks do. static void AsyncGraphOnFetchCompleted(const std::shared_ptr& load, const std::string& url, - const std::shared_ptr& fetched) { + const std::shared_ptr& fetched, + const std::shared_ptr& ticket) { + // Dead loads leave their streamed compile to DrainStreamedCompilesForIsolate. if (load->dead.load(std::memory_order_acquire)) { return; } @@ -1479,6 +1903,8 @@ static void AsyncGraphOnFetchCompleted(const std::shared_ptr& lo v8::Locker locker(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); + std::unique_ptr streamed = TakeStreamedCompile(isolate, ticket.get()); + const bool streamedRan = streamed != nullptr && ticket->ran; v8::Local context = load->context.Get(isolate); if (context.IsEmpty()) { return; @@ -1529,8 +1955,15 @@ static void AsyncGraphOnFetchCompleted(const std::shared_ptr& lo // compile exception must be consumed here rather than left pending; // its text goes into the load's own failure channel instead. v8::TryCatch tcCompile(isolate); - compiled = - CompileModuleForResolveRegisterOnly(isolate, context, fetched->body, key).ToLocal(&mod); + if (streamedRan) { + compiled = CompileStreamedModuleRegisterOnly(isolate, context, *streamed, + std::move(fetched->body), ticket->ascii, key) + .ToLocal(&mod); + streamed.reset(); + } else { + compiled = CompileModuleForResolveRegisterOnly(isolate, context, fetched->body, key) + .ToLocal(&mod); + } if (!compiled) { compileError = DescribeCaughtError(isolate, context, tcCompile); } @@ -1651,32 +2084,42 @@ static void AsyncGraphEnqueue(const std::shared_ptr& load, load->pendingFetches++; std::shared_ptr loadRef = load; const std::string url = target; + 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, load->fetchDeadline, [loadRef, url](ModuleFetchResult result) { - // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 - // foreground task — thread-independent delivery, so an import() issued - // from a background thread still lands on the isolate's own event loop, - // and the boot pump's RunNestableV8Tasks can drain it with JS frames on - // the stack. If the isolate died in between, drop everything — the - // context Global was already Reset by the teardown hook, which runs - // before the event loop shuts down, so a post dropped on this thread - // destroys only inert state. - if (loadRef->dead.load(std::memory_order_acquire)) { - return; - } - auto* platform = NativeScriptPlatform::Instance(); - std::shared_ptr loop = - platform != nullptr ? platform->LookupEventLoop(loadRef->isolate) : nullptr; - if (loop == nullptr) { - return; - } - auto resultPtr = std::make_shared(std::move(result)); - loop->PostV8Task(std::make_unique([loadRef, url, resultPtr]() { - AsyncGraphOnFetchCompleted(loadRef, url, resultPtr); - }), - /*nestable=*/true, /*delaySeconds=*/0); - }); + FetchModuleBodyAsync( + url, key, load->fetchDeadline, [loadRef, url, ticket](ModuleFetchResult result) { + // Arbitrary thread. Hop to the isolate's home thread as a nestable v8 + // foreground task — thread-independent delivery, so an import() issued + // from a background thread still lands on the isolate's own event loop, + // and the boot pump's RunNestableV8Tasks can drain it with JS frames on + // the stack. If the isolate died in between, drop everything — the + // context Global was already Reset by the teardown hook, which runs + // before the event loop shuts down, so a post dropped on this thread + // destroys only inert state. + if (loadRef->dead.load(std::memory_order_acquire)) { + return; + } + auto* platform = NativeScriptPlatform::Instance(); + std::shared_ptr loop = + platform != nullptr ? platform->LookupEventLoop(loadRef->isolate) : nullptr; + if (loop == nullptr) { + return; + } + auto resultPtr = std::make_shared(std::move(result)); + auto postCompletion = [loop, loadRef, url, resultPtr, ticket]() { + loop->PostV8Task( + std::make_unique([loadRef, url, resultPtr, ticket]() { + AsyncGraphOnFetchCompleted(loadRef, url, resultPtr, ticket); + }), + /*nestable=*/true, /*delaySeconds=*/0); + }; + if (ticket != nullptr && + DispatchStreamedCompile(loadRef, ticket, resultPtr, postCompletion)) { + return; + } + postCompletion(); + }); } // Classify a walk root. The root arrives already resolved — an absolute URL diff --git a/TestRunner/app/tests/HttpEsmLoaderTests.js b/TestRunner/app/tests/HttpEsmLoaderTests.js index 91e6aab4e..d09d702ac 100644 --- a/TestRunner/app/tests/HttpEsmLoaderTests.js +++ b/TestRunner/app/tests/HttpEsmLoaderTests.js @@ -421,6 +421,294 @@ describe("HTTP ESM Loader", function() { }); }); + // Bodies of 32 KiB or more compile off the JS thread. Every module + // here comes from ModuleTestServer's /esm/big.mjs generator, has its + // own `k` (modules evaluate once per process) and asserts `bytes` so + // it is above that threshold by construction. + describe("large modules", function () { + var STREAMING_THRESHOLD = 32 * 1024; + var LINES = 1500; + var originalTimeout; + beforeEach(function () { + originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; + jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000; + }); + afterEach(function () { + jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; + }); + + function bigQuery(k, lines, extra) { + return "k=" + k + "&lines=" + lines + (extra || ""); + } + + function bigUrl(origin, k, lines, extra) { + return origin + "/esm/big.mjs?" + bigQuery(k, lines, extra); + } + + function expectWholeBody(mod, k, lines) { + var total = 0; + for (var i = 0; i < lines; i++) { + total += (i * 3 + i) % 1000; + } + expect(mod.id).toBe(k); + expect(mod.count).toBe(lines); + expect(mod.total).toBe(total); + expect(mod.bytes).toBeGreaterThan(STREAMING_THRESHOLD); + expect(globalThis.__nsBigModuleEvaluations[k]).toBe(1); + } + + function rejectionOf(url) { + return import(url).then(function () { + return "resolved"; + }, function (error) { + return formatError(error); + }); + } + + // The rejection names the module and the error position; strip the + // URL so a small and a large module's texts compare equal. + function withoutUrl(message, url) { + return message.split(url).join(""); + } + + function failWith(done) { + return function (error) { + expect("rejected: " + formatError(error)).toBe("resolved"); + done(); + }; + } + + it("evaluates one loaded with import()", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + import(bigUrl(origin, "big-dynamic", LINES)).then(function (mod) { + expectWholeBody(mod, "big-dynamic", LINES); + done(); + }).catch(failWith(done)); + }); + + it("evaluates one reached through a static import", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var child = encodeURIComponent(bigQuery("big-static", LINES)); + import(origin + "/esm/big-parent.mjs?k=big-static-parent&child=" + child) + .then(function (mod) { + expect(mod.parent).toBe("big-static-parent"); + expectWholeBody(mod.child, "big-static", LINES); + done(); + }).catch(failWith(done)); + }); + + it("evaluates one reached during a pumped require()", function () { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + return; + } + var nsModule = require("ns:module"); + nsModule.configureLoader({ + importMap: { + imports: { "ns-big-leaf": bigUrl(origin, "big-require", LINES) }, + }, + }); + try { + var req = nsModule.createRequire(__dirname + "/anything.js"); + var mod = req("./esm/mixed/big-entry.mjs"); + expectWholeBody(mod.leaf, "big-require", LINES); + } finally { + nsModule.configureLoader({ importMap: { imports: {} } }); + } + }); + + it("evaluates non-ASCII string literals to the right values", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + import(bigUrl(origin, "big-unicode", LINES, "&unicode=1")).then(function (mod) { + expectWholeBody(mod, "big-unicode", LINES); + var joinedLength = 0; + for (var i = 0; i < LINES; i++) { + joinedLength += ("café 日本語 😀 " + i).length; + } + expect(mod.first).toBe("café 日本語 😀 0"); + expect(mod.last).toBe("café 日本語 😀 " + (LINES - 1)); + expect(mod.joinedLength).toBe(joinedLength); + done(); + }).catch(failWith(done)); + }); + + it("rejects a syntax error with the text a small module produces", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var smallUrl = bigUrl(origin, "small-syntax", 0, "&error=1"); + var largeUrl = bigUrl(origin, "big-syntax", LINES, "&error=1"); + Promise.all([rejectionOf(smallUrl), rejectionOf(largeUrl)]).then(function (texts) { + var position = /\(line (\d+):(\d+)\)/; + var small = withoutUrl(texts[0], smallUrl); + var large = withoutUrl(texts[1], largeUrl); + expect(small).toContain("SyntaxError"); + // The error sits on the line after the filler declarations. + expect(small.match(position)[1]).toBe("3"); + expect(large.match(position)[1]).toBe(String(LINES + 3)); + expect(large.replace(position, "")).toBe(small.replace(position, "")); + expect(large.match(position)[2]).toBe(small.match(position)[2]); + done(); + }).catch(failWith(done)); + }); + + it("rejects pathologically deep nesting like a small module does", function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + // 20 KB of brackets: below the threshold on its own, above it + // with the filler declarations. + var smallUrl = bigUrl(origin, "small-deep", 0, "&nest=10000"); + var largeUrl = bigUrl(origin, "big-deep", 600, "&nest=10000"); + Promise.all([rejectionOf(smallUrl), rejectionOf(largeUrl)]).then(function (texts) { + var position = /\s*\(line \d+:\d+\)/; + var small = withoutUrl(texts[0], smallUrl).replace(position, ""); + var large = withoutUrl(texts[1], largeUrl).replace(position, ""); + expect(small).toContain("Maximum call stack size exceeded"); + expect(large).toBe(small); + done(); + }).catch(failWith(done)); + }); + + it("resolves one module for concurrent imports from several call sites", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var query = bigQuery("big-shared", LINES); + var url = origin + "/esm/big.mjs?" + query; + var parent = origin + "/esm/big-parent.mjs?child=" + encodeURIComponent(query) + + "&k="; + Promise.all([ + import(url), + import(parent + "big-shared-a"), + import(url), + import(parent + "big-shared-b"), + ]).then(function (mods) { + expectWholeBody(mods[0], "big-shared", LINES); + expect(mods[2]).toBe(mods[0]); + expect(mods[1].child).toBe(mods[0]); + expect(mods[3].child).toBe(mods[0]); + done(); + }).catch(failWith(done)); + }); + + it("survives workers terminated while their large modules compile", + function (done) { + var origin = getHostOrigin(); + if (!origin) { + pending("REPORT_BASEURL not set; skipping host HTTP tests"); + done(); + return; + } + var MODULE_LINES = 40000; + // The sweep terminates worker n at n * STEP of a calibrated + // import's duration, from 0 to slightly past its end. The + // background compile occupies only part of that duration, and + // where it starts depends on the machine, so the points cover + // all of it. + var STEPS = 23; + var STEP = 0.05; + + function importOnMain() { + import(bigUrl(origin, "big-after-workers", LINES)).then(function (mod) { + expectWholeBody(mod, "big-after-workers", LINES); + done(); + }).catch(failWith(done)); + } + + // Calls onFetching when the worker's import is issued and + // onSettled when it settles, each at most once; a worker + // that errors counts as settled. + function startWorker(k, onFetching, onSettled) { + var worker = new Worker("./httpImportSettleWorker.js"); + var fetching = false; + var settled = false; + function settle() { + if (!settled) { + settled = true; + onSettled(worker); + } + } + worker.onmessage = function (msg) { + if (msg.data === "fetching" && !fetching) { + fetching = true; + onFetching(worker); + } else if (msg.data === "settled") { + settle(); + } + }; + worker.onerror = function (error) { + fail("worker " + k + " errored: " + formatError(error)); + settle(); + }; + worker.postMessage(bigUrl(origin, k, MODULE_LINES)); + } + + // One worker at a time, so each compile has the pool to itself + // as the calibration import did. A worker moves the sweep on + // at its termination point or when it settles, whichever + // comes first; a terminated worker never settles. + function sweep(durationMs, step) { + if (step === STEPS) { + importOnMain(); + return; + } + var ended = false; + function next(worker) { + if (ended) { + return; + } + ended = true; + worker.terminate(); + sweep(durationMs, step + 1); + } + startWorker("big-worker-" + step, function (worker) { + setTimeout(function () { + next(worker); + }, durationMs * step * STEP); + }, next); + } + + var fetchingAt = 0; + startWorker("big-worker-calibration", function () { + fetchingAt = Date.now(); + }, function (worker) { + worker.terminate(); + if (fetchingAt === 0) { + importOnMain(); + return; + } + sweep(Date.now() - fetchingAt, 0); + }); + }, 60000); + }); + // The import map is process-wide, so every spec here installs its own // and restores the empty map afterwards. // Each present configureLoader section replaces its state wholesale, so diff --git a/TestRunner/app/tests/esm/mixed/big-entry.mjs b/TestRunner/app/tests/esm/mixed/big-entry.mjs new file mode 100644 index 000000000..5d046e292 --- /dev/null +++ b/TestRunner/app/tests/esm/mixed/big-entry.mjs @@ -0,0 +1,4 @@ +// Local root whose only edge is "ns-big-leaf", a bare specifier the spec's +// import map points at a generated ModuleTestServer module above the +// streaming-compile threshold. +export * as leaf from "ns-big-leaf"; diff --git a/TestRunner/app/tests/httpImportSettleWorker.js b/TestRunner/app/tests/httpImportSettleWorker.js new file mode 100644 index 000000000..02072141f --- /dev/null +++ b/TestRunner/app/tests/httpImportSettleWorker.js @@ -0,0 +1,10 @@ +// Starts an HTTP dynamic import, reports "fetching" as soon as it is issued +// and "settled" once it resolves or rejects. A terminated worker never sends +// "settled". +onmessage = function (msg) { + function settled() { + postMessage("settled"); + } + import(msg.data).then(settled, settled); + postMessage("fetching"); +}; diff --git a/TestRunnerTests/TestRunnerTests.swift b/TestRunnerTests/TestRunnerTests.swift index 24593e0c6..2cfb2430a 100644 --- a/TestRunnerTests/TestRunnerTests.swift +++ b/TestRunnerTests/TestRunnerTests.swift @@ -190,6 +190,72 @@ class TestRunnerTests: XCTestCase { return } + // ── Generated modules of a requested size ────────── + // /esm/big.mjs: `lines` real declarations whose evaluation + // folds into `total`, so a value depends on the whole body. + // k module id (also the evaluation counter's key) + // unicode 1 adds non-ASCII string literals (strs/first/last) + // error 1 ends the body with a syntax error at line lines+3 + // nest appends an array literal nested `nest` deep + // delayMs answers after a delay + // /esm/big-parent.mjs?k=…&child= + // statically imports that big.mjs and re-exports it as `child`. + if path == "/esm/big.mjs" || path == "/esm/big-parent.mjs" { + var params = [String: String]() + for pair in query.split(separator: "&") { + let kv = pair.split(separator: "=", maxSplits: 1) + let value = kv.count > 1 ? String(kv[1]) : "" + params[String(kv[0])] = value.removingPercentEncoding ?? value + } + let key = String((params["k"] ?? "x").filter { $0.isLetter || $0.isNumber || $0 == "-" }) + let delayMs = Int(params["delayMs"] ?? "") ?? 0 + var body = "" + if path == "/esm/big-parent.mjs" { + let child = (params["child"] ?? "").replacingOccurrences(of: "\"", with: "") + body = "export * as child from \"./big.mjs?\(child)\";\n" + + "export const parent = \"\(key)\";\n" + } else { + let lines = Int(params["lines"] ?? "") ?? 0 + let unicode = params["unicode"] == "1" + body.reserveCapacity(lines * 96 + 256) + body += "let acc = 0;\nconst strs = [];\n" + for i in 0.. 0 { + body += "export const deep = " + String(repeating: "[", count: depth) + + String(repeating: "]", count: depth) + ";\n" + } + if params["error"] == "1" { + body += "export const broken = ;\n" + } + body += """ + const evaluations = globalThis.__nsBigModuleEvaluations || (globalThis.__nsBigModuleEvaluations = {}); + evaluations["\(key)"] = (evaluations["\(key)"] || 0) + 1; + export const id = "\(key)"; + export const count = \(lines); + export const total = acc; + export const first = strs[0]; + export const last = strs[strs.length - 1]; + export const joinedLength = strs.join("").length; + + """ + body += "export const bytes = \(body.utf8.count);\n" + } + let data = body.data(using: .utf8) ?? Data() + DispatchQueue.global(qos: .utility).asyncAfter( + deadline: .now() + Double(delayMs) / 1000.0 + ) { + startResponse("200 OK", [("Content-Type", "application/javascript; charset=utf-8")]) + sendBody(data) + } + return + } + if path == "/esm/timeout.mjs" { // Delay the response without blocking request handling. // The loader still hits its client-side timeout when