From 566d45048cb7990d8ec2d937789aa68c499748db Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 01:56:20 -0300 Subject: [PATCH 1/3] perf(runtime): load large file modules off the JS thread ES module files of 32 KiB or more are read and compiled on the stream-compile pool: a streamed compile when no fresh code cache exists, otherwise (from 256 KiB) the cache is consumed there. The isolate thread only finalizes. import() of a file graph that reaches such a file now settles asynchronously; boot, Worker entries and require() still wait for the whole graph, sleeping until a background load lands instead of spinning the runloop, so no timers, promise jobs or other walks' evaluation run inside a synchronous load. Code caches are no longer created right after compiling: creation is queued and run in one-per-pass idle slices after loading goes quiet (or when the app moves to the background), and the file is written off-thread. The development flavor, which never consumes a cache, no longer creates or writes one. --- NativeScript/runtime/ModuleInternal.h | 42 +- NativeScript/runtime/ModuleInternal.mm | 263 +++-- .../runtime/ModuleInternalCallbacks.mm | 943 ++++++++++++++---- TestRunner/app/tests/FileModuleLoadTests.js | 463 +++++++++ .../app/tests/fileModuleImportWorker.js | 11 + TestRunner/app/tests/index.js | 3 + 6 files changed, 1487 insertions(+), 238 deletions(-) create mode 100644 TestRunner/app/tests/FileModuleLoadTests.js create mode 100644 TestRunner/app/tests/fileModuleImportWorker.js diff --git a/NativeScript/runtime/ModuleInternal.h b/NativeScript/runtime/ModuleInternal.h index f2e1df83..b2b81cf5 100644 --- a/NativeScript/runtime/ModuleInternal.h +++ b/NativeScript/runtime/ModuleInternal.h @@ -102,6 +102,35 @@ class ModuleInternal { const std::string& path, std::string* rejectionReason); + // A code-cache blob is either a script blob or a module blob, and V8 rejects + // the wrong kind outright. One file compiled both ways — require('./x.js') + // and import './x.js' — would otherwise share a blob and each load would + // reject and overwrite the other's, so the two kinds get their own suffix + // and the cache actually hits. + enum class ScriptCacheKind { kClassicScript, kEsModule }; + // The blob for `path` when one was written for the file's modification time + // `sourceModifiedTime`, otherwise empty. Stats only; never reads the blob. + // Always empty in the development flavor, which never consumes a cache. + static std::string FreshScriptCachePath(const std::string& path, + ScriptCacheKind kind, + time_t sourceModifiedTime); + // Queues creation of the code cache for a script compiled from `path` as + // it was at `sourceModifiedTime`. Creation needs the isolate's thread and + // costs a fifth of a cold compile, so it runs later in short slices once + // loading goes quiet (or when the app moves to the background); the file is + // written off-thread, and skipped if the source changed since it was read. + // A no-op in the development flavor. Isolate thread only. + static void QueueScriptCache(v8::Isolate* isolate, + v8::Local script, + const std::string& path, + time_t sourceModifiedTime); + static void QueueScriptCache(v8::Isolate* isolate, + v8::Local script, + const std::string& path, + time_t sourceModifiedTime); + // Where the code cache for `path` (with its kind's suffix) lives. + static std::string GetCacheFileName(const std::string& path); + private: static void RequireCallback(const v8::FunctionCallbackInfo& info); static void CreateRequireCallback( @@ -137,19 +166,8 @@ class ModuleInternal { const std::string& moduleName); std::string ResolvePathFromPackageJson(const std::string& packageJson, bool& error); - // A code-cache blob is either a script blob or a module blob, and V8 rejects - // the wrong kind outright. One file compiled both ways — require('./x.js') - // and import './x.js' — would otherwise share a blob and each load would - // reject and overwrite the other's, so the two kinds get their own suffix - // and the cache actually hits. - enum class ScriptCacheKind { kClassicScript, kEsModule }; static v8::ScriptCompiler::CachedData* LoadScriptCache( - const std::string& path, ScriptCacheKind kind); - static void SaveScriptCache(const v8::Local script, - const std::string& path); - static void SaveScriptCache(const v8::ScriptCompiler::CachedData* cache, - const std::string& path, ScriptCacheKind kind); - static std::string GetCacheFileName(const std::string& path); + const std::string& path, ScriptCacheKind kind, time_t sourceModifiedTime); v8::MaybeLocal RunScriptString(v8::Isolate* isolate, v8::Local context, const std::string script); diff --git a/NativeScript/runtime/ModuleInternal.mm b/NativeScript/runtime/ModuleInternal.mm index 65da6312..b7fbb2e9 100644 --- a/NativeScript/runtime/ModuleInternal.mm +++ b/NativeScript/runtime/ModuleInternal.mm @@ -5,9 +5,11 @@ #include #include #include +#include #include #include "BuiltinLoader.h" #include "Caches.h" +#include "EventLoop.h" #include "Helpers.h" #include "HttpLoader.h" #include "ModuleInternalCallbacks.h" // for ResolveModuleCallback @@ -967,7 +969,8 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio // wrap & cache lookup Local sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath); - auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kClassicScript); + auto* cacheData = + ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kClassicScript, st.st_mtime); // note: is_module=false here Local urlString; @@ -1002,8 +1005,10 @@ ScriptOrigin origin(urlString, throw NativeScriptException(isolate, tc, "Cannot compile script " + canonicalPath); } - if (cacheData == nullptr) { - ModuleInternal::SaveScriptCache(script, canonicalPath); + // A rejected blob is stale; leaving it would cost a full compile per launch. + if (cacheData == nullptr || source.GetCachedData()->rejected) { + ModuleInternal::QueueScriptCache(isolate, script->GetUnboundScript(), canonicalPath, + st.st_mtime); } return script; @@ -1021,7 +1026,8 @@ ScriptOrigin origin(urlString, const std::string url = ReportedModuleUrl(canonicalPath + query); Local sourceText = ModuleInternal::WrapModuleContent(isolate, canonicalPath); - auto* cacheData = ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kEsModule); + auto* cacheData = + ModuleInternal::LoadScriptCache(canonicalPath, ScriptCacheKind::kEsModule, st.st_mtime); Local urlString; if (!v8::String::NewFromUtf8(isolate, url.c_str(), NewStringType::kNormal).ToLocal(&urlString)) { @@ -1042,10 +1048,9 @@ ScriptOrigin origin(urlString, 0, 0, false, -1, Local(), false, false, return MaybeLocal(); } - if (cacheData == nullptr) { - Local unbound = module->GetUnboundModuleScript(); - auto* generatedCache = ScriptCompiler::CreateCodeCache(unbound); - ModuleInternal::SaveScriptCache(generatedCache, canonicalPath, ScriptCacheKind::kEsModule); + if (cacheData == nullptr || source.GetCachedData()->rejected) { + ModuleInternal::QueueScriptCache(isolate, module->GetUnboundModuleScript(), canonicalPath, + st.st_mtime); } return maybeMod; @@ -1561,7 +1566,8 @@ throw NativeScriptException("Module evaluation interrupted by isolate terminatio // edges, and without this they hit the resolver cold and fetch serially, // one blocking request at a time. The walk compiles and registers the // whole closure up front, so instantiation resolves as pure lookup. A - // graph with no HTTP edges settles inside the call and pays no wait. + // graph of small local files settles inside the call; large ones load in + // the background while this waits, running no timers or other JS. // // The deadline is the FETCH bound, independent of the evaluation policy's // settle window: a strict require refuses an async EVALUATION, not an @@ -1916,84 +1922,227 @@ throw NativeScriptException( // installed cache keeps working; module blobs take a name of their own. static const char* ScriptCacheSuffix(bool isModule) { return isModule ? ".mcache" : ".cache"; } -ScriptCompiler::CachedData* ModuleInternal::LoadScriptCache(const std::string& path, - ScriptCacheKind kind) { - std::string canonicalPath = NormalizePath(path); +std::string ModuleInternal::FreshScriptCachePath(const std::string& path, ScriptCacheKind kind, + time_t sourceModifiedTime) { if (RuntimeConfig.IsDebug) { - return nullptr; + return std::string(); } - - long length = 0; std::string cachePath = ModuleInternal::GetCacheFileName( - canonicalPath + ScriptCacheSuffix(kind == ScriptCacheKind::kEsModule)); - + NormalizePath(path) + ScriptCacheSuffix(kind == ScriptCacheKind::kEsModule)); + // A blob is published stamped with its source's modification time, so a + // differing time means the source changed after the blob was written. struct stat result; - if (stat(cachePath.c_str(), &result) == 0) { - auto cacheLastModifiedTime = result.st_mtime; - if (stat(canonicalPath.c_str(), &result) == 0) { - auto jsLastModifiedTime = result.st_mtime; - if (jsLastModifiedTime != cacheLastModifiedTime) { - // files have different dates, ignore the cache file (this is enforced by the - // SaveScriptCache function) - return nullptr; - } - } + if (stat(cachePath.c_str(), &result) != 0 || result.st_mtime != sourceModifiedTime) { + return std::string(); } + return cachePath; +} +ScriptCompiler::CachedData* ModuleInternal::LoadScriptCache(const std::string& path, + ScriptCacheKind kind, + time_t sourceModifiedTime) { + const std::string cachePath = FreshScriptCachePath(path, kind, sourceModifiedTime); + if (cachePath.empty()) { + return nullptr; + } + long length = 0; uint8_t* data = tns::ReadBinary(cachePath, length); if (!data) { return nullptr; } - return new ScriptCompiler::CachedData(data, (int)length, ScriptCompiler::CachedData::BufferOwned); } -// A blob is published carrying its source file's modification time; that is -// the freshness check LoadScriptCache applies, so the two must land together. -static void WriteScriptCache(const std::string& cachePath, const std::string& sourcePath, - const uint8_t* data, long length) { - time_t sourceModifiedTime = -1; - struct stat result; - if (stat(sourcePath.c_str(), &result) == 0) { - sourceModifiedTime = result.st_mtime; - } - tns::WriteBinary(cachePath, data, length, sourceModifiedTime); +namespace { + +struct PendingScriptCache { + // Exactly one of the two is set. + Global module; + Global script; + std::string sourcePath; + std::string cachePath; + time_t sourceModifiedTime = 0; +}; + +// Per-isolate queue of code caches waiting to be created. Isolate thread only. +struct ScriptCacheQueue { + ~ScriptCacheQueue() { + if (backgroundObserver != nil) { + [[NSNotificationCenter defaultCenter] removeObserver:backgroundObserver]; + } + } + std::deque pending; + CFAbsoluteTime lastQueuedAt = 0; + // A slice is posted to the event loop; at most one is outstanding. + bool sliceScheduled = false; + id backgroundObserver = nil; +}; + +// Quiet period after the last queued cache before creation starts, so a burst +// of loads (boot, a lazy route) finishes before any cache work competes with it. +constexpr double kScriptCacheQuietSeconds = 0.5; +// Gap between two creations, so each one is a short block of its own and the +// loop runs whatever else is due in between. +constexpr double kScriptCacheSliceGapMs = 16; + +dispatch_queue_t ScriptCacheWriteQueue() { + static dispatch_queue_t queue = dispatch_queue_create( + "org.nativescript.script-cache-write", + dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)); + return queue; } -void ModuleInternal::SaveScriptCache(const ScriptCompiler::CachedData* cache, - const std::string& path, ScriptCacheKind kind) { - // CreateCodeCache yields nullptr for a script V8 declines to serialize. +// Creates one cache and hands the bytes to the write queue. Isolate thread. +void CreateAndWriteScriptCache(Isolate* isolate, PendingScriptCache& entry) { + HandleScope handleScope(isolate); + ScriptCompiler::CachedData* cache = nullptr; + if (!entry.module.IsEmpty()) { + cache = ScriptCompiler::CreateCodeCache(entry.module.Get(isolate)); + } else if (!entry.script.IsEmpty()) { + cache = ScriptCompiler::CreateCodeCache(entry.script.Get(isolate)); + } + entry.module.Reset(); + entry.script.Reset(); + // Null for a script V8 declines to serialize. if (cache == nullptr) { return; } + // CreateCodeCache hands back a buffer allocated with new[]; the write + // queue takes it over. + const uint8_t* data = cache->data; + const int length = cache->length; + cache->buffer_policy = ScriptCompiler::CachedData::BufferNotOwned; + delete cache; - std::string canonicalPath = NormalizePath(path); - std::string cachePath = ModuleInternal::GetCacheFileName( - canonicalPath + ScriptCacheSuffix(kind == ScriptCacheKind::kEsModule)); + std::string sourcePath = entry.sourcePath; + std::string cachePath = entry.cachePath; + const time_t sourceModifiedTime = entry.sourceModifiedTime; + dispatch_async(ScriptCacheWriteQueue(), ^{ + // The blob describes the source as it was read; one written for a source + // that changed since would be stamped as matching the new file. + struct stat st; + if (stat(sourcePath.c_str(), &st) == 0 && st.st_mtime == sourceModifiedTime) { + tns::WriteBinary(cachePath, data, length, sourceModifiedTime); + } + delete[] data; + }); +} - WriteScriptCache(cachePath, canonicalPath, cache->data, cache->length); - delete cache; +void ScheduleScriptCacheSlice(Isolate* isolate, double delayMs); + +// One event-loop slice: creates a single cache once loading has been quiet +// for kScriptCacheQuietSeconds, then schedules the next. +void RunScriptCacheSlice(Isolate* isolate) { + auto* queue = Caches::StateFor(isolate); + if (queue == nullptr) { + return; + } + queue->sliceScheduled = false; + if (queue->pending.empty()) { + return; + } + const double quietLeft = + kScriptCacheQuietSeconds - (CFAbsoluteTimeGetCurrent() - queue->lastQueuedAt); + if (quietLeft > 0) { + ScheduleScriptCacheSlice(isolate, quietLeft * 1000.0); + return; + } + PendingScriptCache entry = std::move(queue->pending.front()); + queue->pending.pop_front(); + CreateAndWriteScriptCache(isolate, entry); + if (!queue->pending.empty()) { + ScheduleScriptCacheSlice(isolate, kScriptCacheSliceGapMs); + } +} + +void ScheduleScriptCacheSlice(Isolate* isolate, double delayMs) { + auto* queue = Caches::StateFor(isolate); + Runtime* runtime = Runtime::GetRuntime(isolate); + if (queue == nullptr || queue->sliceScheduled || runtime == nullptr || + runtime->GetEventLoop() == nullptr) { + return; + } + queue->sliceScheduled = runtime->GetEventLoop()->PostInternalDelayed( + [isolate]() { RunScriptCacheSlice(isolate); }, delayMs); +} + +// Creates every queued cache now. Used when the app moves to the background, +// where the slices may never get to run. +void FlushScriptCaches(Isolate* isolate) { + auto* queue = Caches::StateFor(isolate); + if (queue == nullptr) { + return; + } + while (!queue->pending.empty()) { + PendingScriptCache entry = std::move(queue->pending.front()); + queue->pending.pop_front(); + CreateAndWriteScriptCache(isolate, entry); + } } -void ModuleInternal::SaveScriptCache(const Local