From 0cd5c7fafcd1effb5b2b9c3c9a95b973f6df58be Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Fri, 4 Dec 2026 16:21:01 -0300 Subject: [PATCH 01/45] build(runtime): take the base64 codec from the shared runtime-common core The new test-app/runtime/src/main/cpp/runtime-common submodule pins the NativeScript/runtime-common repository, the C++ shared with the iOS runtime. CMakeLists adds it with add_subdirectory once CMAKE_CXX_FLAGS is final, so the core compiles with the runtime's V8 configuration defines, and links its static library into libNativeScript.so. The core resets its include path, so it sees only its own headers and V8's. The atob/btoa natives and the forgiving-base64 codec now come from there; Base64.cpp keeps the builtin wiring. --- .gitmodules | 3 + test-app/runtime/CMakeLists.txt | 7 + test-app/runtime/src/main/cpp/Base64.cpp | 164 +------------------ test-app/runtime/src/main/cpp/runtime-common | 1 + 4 files changed, 14 insertions(+), 161 deletions(-) create mode 160000 test-app/runtime/src/main/cpp/runtime-common diff --git a/.gitmodules b/.gitmodules index 7913129bb..82c79cfdf 100644 --- a/.gitmodules +++ b/.gitmodules @@ -8,3 +8,6 @@ path = test-app/build-tools/android-dts-generator url = https://github.com/NativeScript/android-dts-generator.git branch = main +[submodule "test-app/runtime/src/main/cpp/runtime-common"] + path = test-app/runtime/src/main/cpp/runtime-common + url = https://github.com/NativeScript/runtime-common.git diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index a17a37bef..b5ee41777 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -191,6 +191,12 @@ else () set(NAPI_TEST_SOURCES) endif () +# Code shared with the iOS runtime (NativeScript/runtime-common). Added after +# CMAKE_CXX_FLAGS is final: the library compiles with these flags, which carry +# the V8 configuration defines it must agree with. +set(NS_V8_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/src/main/cpp/include) +add_subdirectory(src/main/cpp/runtime-common) + # Command info: https://cmake.org/cmake/help/v3.4/command/add_library.html # Creates(shared static) and names a library given relative sources # Gradle automatically packages shared libraries with your APK. @@ -337,6 +343,7 @@ MESSAGE(STATUS "# CMAKE_C_FLAGS: " ${CMAKE_C_FLAGS}) MESSAGE(STATUS "# CMAKE_CXX_FLAGS: " ${CMAKE_CXX_FLAGS}) # Command info: https://cmake.org/cmake/help/v3.4/command/target_link_libraries.html +target_link_libraries(NativeScript ns_runtime_common) target_link_libraries(NativeScript ${PROJECT_SOURCE_DIR}/src/main/libs/${ANDROID_ABI}/libzip.a) # libv8_monolith.a carries the NDK libc++ it was compiled against, and libc++ is # only ABI-compatible with itself, so v8-buildscripts has to build V8 with the diff --git a/test-app/runtime/src/main/cpp/Base64.cpp b/test-app/runtime/src/main/cpp/Base64.cpp index 76a192e59..0587fea0d 100644 --- a/test-app/runtime/src/main/cpp/Base64.cpp +++ b/test-app/runtime/src/main/cpp/Base64.cpp @@ -1,9 +1,8 @@ #include "Base64.h" -#include - #include "BuiltinLoader.h" #include "Util.h" +#include "ns/Base64Binding.h" using namespace v8; @@ -11,168 +10,11 @@ namespace tns { namespace { -constexpr char kAlphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -// 6-bit value per ASCII byte; 0xFF marks everything outside the alphabet. -constexpr uint8_t kInvalid = 0xFF; - -uint8_t SixBits(uint8_t c) { - if (c >= 'A' && c <= 'Z') { - return static_cast(c - 'A'); - } - if (c >= 'a' && c <= 'z') { - return static_cast(c - 'a' + 26); - } - if (c >= '0' && c <= '9') { - return static_cast(c - '0' + 52); - } - if (c == '+') { - return 62; - } - if (c == '/') { - return 63; - } - return kInvalid; -} - -bool IsAsciiWhitespace(uint8_t c) { - return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '; -} - -// The string's code units as bytes. Fails when any unit is above U+00FF, -// which neither op can represent. -bool GetLatin1Bytes(Isolate* isolate, Local value, - std::vector* out) { - if (!value->IsString()) { - return false; - } - Local str = value.As(); - if (!str->ContainsOnlyOneByte()) { - return false; - } - const int length = str->Length(); - out->resize(static_cast(length)); - if (length > 0) { - str->WriteOneByteV2(isolate, 0, static_cast(length), out->data()); - } - return true; -} - -// btoa: base64-encode the input's code units. -void BtoaCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector input; - if (!GetLatin1Bytes(isolate, info[0], &input)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve((input.size() + 2) / 3 * 4); - size_t i = 0; - for (; i + 3 <= input.size(); i += 3) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8) | - input[i + 2]; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back(kAlphabet[group & 0x3F]); - } - const size_t remaining = input.size() - i; - if (remaining == 1) { - const uint32_t group = static_cast(input[i]) << 16; - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back('='); - out.push_back('='); - } else if (remaining == 2) { - const uint32_t group = (static_cast(input[i]) << 16) | - (static_cast(input[i + 1]) << 8); - out.push_back(kAlphabet[(group >> 18) & 0x3F]); - out.push_back(kAlphabet[(group >> 12) & 0x3F]); - out.push_back(kAlphabet[(group >> 6) & 0x3F]); - out.push_back('='); - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - -// atob: forgiving-base64 decode -// (https://infra.spec.whatwg.org/#forgiving-base64-decode). -void AtobCallback(const FunctionCallbackInfo& info) { - Isolate* isolate = info.GetIsolate(); - std::vector raw; - if (!GetLatin1Bytes(isolate, info[0], &raw)) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector data; - data.reserve(raw.size()); - for (uint8_t c : raw) { - if (!IsAsciiWhitespace(c)) { - data.push_back(c); - } - } - - if (data.size() % 4 == 0) { - size_t strip = 0; - while (strip < 2 && !data.empty() && data.back() == '=') { - data.pop_back(); - strip++; - } - } - if (data.size() % 4 == 1) { - info.GetReturnValue().SetNull(); - return; - } - - std::vector out; - out.reserve(data.size() / 4 * 3 + 2); - uint32_t accumulator = 0; - uint32_t bits = 0; - for (uint8_t c : data) { - const uint8_t value = SixBits(c); - if (value == kInvalid) { - info.GetReturnValue().SetNull(); - return; - } - accumulator = (accumulator << 6) | value; - bits += 6; - if (bits >= 8) { - bits -= 8; - out.push_back(static_cast((accumulator >> bits) & 0xFF)); - } - } - - if (out.empty()) { - info.GetReturnValue().Set(v8::String::Empty(isolate)); - return; - } - Local result; - if (v8::String::NewFromOneByte(isolate, out.data(), NewStringType::kNormal, - static_cast(out.size())) - .ToLocal(&result)) { - info.GetReturnValue().Set(result); - } -} - MaybeLocal CreateBinding(Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - tns::SetMethodNoSideEffect(context, binding, "btoa", BtoaCallback); - tns::SetMethodNoSideEffect(context, binding, "atob", AtobCallback); + tns::SetMethodNoSideEffect(context, binding, "btoa", nativescript::common::base64::Btoa); + tns::SetMethodNoSideEffect(context, binding, "atob", nativescript::common::base64::Atob); return binding; } diff --git a/test-app/runtime/src/main/cpp/runtime-common b/test-app/runtime/src/main/cpp/runtime-common new file mode 160000 index 000000000..49dd52bc9 --- /dev/null +++ b/test-app/runtime/src/main/cpp/runtime-common @@ -0,0 +1 @@ +Subproject commit 49dd52bc926997bcaa15eebc08ae9c7815feac02 From 1624660e8b8a843f365bedda0ed06d79f143fa12 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 01:02:53 -0300 Subject: [PATCH 02/45] feat(runtime): run the HTTP module loader on runtime-common The gate, classification, retry and deadline policy, the fetch threads, the cache switch and Clear-Site-Data come from the shared core (ns/http); HttpLoader keeps the OkHttp / HttpURLConnection transport and the per-isolate canonicalization vocabulary. User-visible changes: - Clear-Site-Data clears the response origin and the fetching origin (after a cross-origin redirect), never the whole cache; - in release builds with a remote module allowlist, a redirect that ends outside it is refused; - a failed clearHttpCache() throws a plain Error with the message. --- test-app/runtime/CMakeLists.txt | 1 + test-app/runtime/src/main/cpp/HttpLoader.cpp | 1147 +++++------------ test-app/runtime/src/main/cpp/HttpLoader.h | 227 +--- .../src/main/cpp/JsV8InspectorClient.cpp | 30 +- .../src/main/cpp/JsV8InspectorClient.h | 16 +- .../src/main/cpp/ModuleInternalCallbacks.cpp | 18 +- test-app/runtime/src/main/cpp/ModuleUrl.cpp | 8 + test-app/runtime/src/main/cpp/ModuleUrl.h | 5 + .../src/main/cpp/RuntimeCommonPlatform.cpp | 45 + test-app/runtime/src/main/cpp/runtime-common | 2 +- .../main/java/com/tns/ModuleHttpCache.java | 76 +- .../java/com/tns/OkHttpModuleFetcher.java | 132 +- 12 files changed, 550 insertions(+), 1157 deletions(-) create mode 100644 test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp diff --git a/test-app/runtime/CMakeLists.txt b/test-app/runtime/CMakeLists.txt index b5ee41777..82e3a5f11 100644 --- a/test-app/runtime/CMakeLists.txt +++ b/test-app/runtime/CMakeLists.txt @@ -284,6 +284,7 @@ add_library( src/main/cpp/URLSearchParamsImpl.cpp src/main/cpp/URLPatternImpl.cpp src/main/cpp/HttpLoader.cpp + src/main/cpp/RuntimeCommonPlatform.cpp src/main/cpp/TraceLog.cpp # Node-API: vendored upstream implementation plus the embedder half diff --git a/test-app/runtime/src/main/cpp/HttpLoader.cpp b/test-app/runtime/src/main/cpp/HttpLoader.cpp index a0433ced8..308a0280e 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.cpp +++ b/test-app/runtime/src/main/cpp/HttpLoader.cpp @@ -1,16 +1,10 @@ #include "HttpLoader.h" -#include - #include #include -#include -#include -#include -#include #include +#include #include -#include #include #include @@ -24,151 +18,29 @@ #include "NativeScriptException.h" #include "Runtime.h" #include "TraceLog.h" +#include "ns/http/ModuleTransport.h" namespace tns { -static inline bool StartsWith(const std::string& s, const char* prefix) { - size_t n = strlen(prefix); - return s.size() >= n && s.compare(0, n, prefix) == 0; -} - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate - -static std::once_flag s_securityConfigInitFlag; -static bool s_allowRemoteModules = false; -static RemoteModuleAllowlist s_remoteModuleAllowlist; -static bool s_isDebuggable = false; - -static bool RemoteUrlMatchesAllowlistEntry(const std::string& url, const std::string& entry) { - if (entry.empty()) return false; - if (url.size() < entry.size()) return false; - if (url.compare(0, entry.size(), entry) != 0) return false; - if (url.size() == entry.size()) return true; - if (entry.back() == '/') return true; - const char next = url[entry.size()]; - return next == '/' || next == '?' || next == '#'; -} - -static std::string NormalizeRemoteModuleAllowlistEntry(const std::string& entry) { - const std::string url = NormalizeHttpModuleUrl(entry); - return url.empty() ? entry : url; -} - -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( - const std::optional>>& items) { - RemoteModuleAllowlist allowlist; - if (!items.has_value() || items->empty()) { - return allowlist; - } - allowlist.inForce = true; - for (const std::optional& item : *items) { - if (item.has_value() && !item->empty()) { - allowlist.entries.push_back(NormalizeRemoteModuleAllowlistEntry(*item)); - } - } - return allowlist; -} - -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist) { - if (!allowlist.inForce) { - return true; - } - for (const std::string& entry : allowlist.entries) { - if (RemoteUrlMatchesAllowlistEntry(url, entry)) { - return true; - } - } - return false; -} +namespace http = nativescript::common::http; -static void InitializeSecurityConfig() { - std::call_once(s_securityConfigInitFlag, []() { - // Remote modules are enabled only after the allowlist was read in - // full: a failure part way keeps them disabled rather than enabling - // them with a list cut short. +bool IsDebuggable() { + static std::once_flag once; + static bool debuggable = false; + std::call_once(once, [] { + JEnv env; try { - JEnv env; jclass runtimeClass = env.FindClass("com/tns/Runtime"); - if (runtimeClass == nullptr) { - return; - } - - jmethodID isDebuggableMid = env.GetStaticMethodID(runtimeClass, "isDebuggable", "()Z"); - if (isDebuggableMid != nullptr) { - s_isDebuggable = env.CallStaticBooleanMethod(runtimeClass, isDebuggableMid) == - JNI_TRUE; - } - - if (s_isDebuggable) { - s_allowRemoteModules = true; - return; - } - - bool allowRemoteModules = false; - jmethodID allowRemoteMid = - env.GetStaticMethodID(runtimeClass, "isRemoteModulesAllowed", "()Z"); - if (allowRemoteMid != nullptr) { - allowRemoteModules = - env.CallStaticBooleanMethod(runtimeClass, allowRemoteMid) == JNI_TRUE; - } - - // Null when the list is not in force; a null element stands for an - // item that is not a string. - std::optional>> items; - jmethodID getAllowlistMid = env.GetStaticMethodID( - runtimeClass, "getRemoteModuleAllowlist", "()[Ljava/lang/String;"); - if (getAllowlistMid == nullptr) { - return; - } - jobjectArray allowlistArray = static_cast( - env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); - if (allowlistArray != nullptr) { - items.emplace(); - jsize len = env.GetArrayLength(allowlistArray); - for (jsize i = 0; i < len; i++) { - jstring jstr = - static_cast(env.GetObjectArrayElement(allowlistArray, i)); - items->push_back(ToExactUtf8(env, jstr)); - if (jstr != nullptr) { - env.DeleteLocalRef(jstr); - } - } - env.DeleteLocalRef(allowlistArray); + if (runtimeClass != nullptr) { + jmethodID mid = env.GetStaticMethodID(runtimeClass, "isDebuggable", "()Z"); + debuggable = env.CallStaticBooleanMethod(runtimeClass, mid) == JNI_TRUE; } - - s_remoteModuleAllowlist = RemoteModuleAllowlistFromConfig(items); - s_allowRemoteModules = allowRemoteModules; } catch (...) { - // Keep defaults (remote modules disabled) + // Not debuggable. } + static_cast(env)->ExceptionClear(); }); -} - -bool IsDebuggable() { - InitializeSecurityConfig(); - return s_isDebuggable; -} - -bool IsRemoteModulesAllowed() { - if (IsDebuggable()) { - return true; - } - InitializeSecurityConfig(); - return s_allowRemoteModules; -} - -bool IsRemoteUrlAllowed(const std::string& url) { - if (IsDebuggable()) { - return true; - } - - InitializeSecurityConfig(); - if (!s_allowRemoteModules) { - return false; - } - - return RemoteUrlAllowedByAllowlist(url, s_remoteModuleAllowlist); + return debuggable; } // ───────────────────────────────────────────────────────────── @@ -180,97 +52,20 @@ std::string CanonicalizeHttpUrlKey(const std::string& url) { } std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl) { - size_t hashPos = normalizedUrl.find('#'); - std::string noHash = - (hashPos == std::string::npos) ? normalizedUrl : normalizedUrl.substr(0, hashPos); - - size_t schemePos = noHash.find("://"); - if (schemePos == std::string::npos) { - size_t q = noHash.find('?'); - return (q == std::string::npos) ? noHash : noHash.substr(0, q); - } - size_t pathStart = noHash.find('/', schemePos + 3); - if (pathStart == std::string::npos) { - return noHash; - } - size_t qPos = noHash.find('?', pathStart); - std::string originAndPath = (qPos == std::string::npos) ? noHash : noHash.substr(0, qPos); - std::string query = (qPos == std::string::npos) ? std::string() : noHash.substr(qPos + 1); - - // This key is the module registry/cache key. For general-purpose HTTP - // module loading the query can be part of a module's identity (auth, - // content versioning, routing), so query normalization applies only to the - // endpoints the client names, through the vocabulary it supplies. - // - // `preserveQueryFor` is checked BEFORE the dev-endpoint prefix test, so it - // covers endpoints nested under a dev prefix: for some endpoints the query - // IS the identity, and stripping it would collapse every refetch onto the - // boot-time key. - // - // Until a client supplies that vocabulary, canonicalization is purely - // mechanical: the fragment is gone and the query stays. Which params are - // cache-busters and which paths are dev endpoints is knowledge only the - // client has; guessing would silently collapse two distinct modules onto - // one registry key. - const CanonicalizationConfig* canon = CanonicalizationConfigForCurrentIsolate(); - if (canon == nullptr) { - return noHash; - } - { - std::string pathOnly = originAndPath.substr(pathStart); - for (const auto& p : canon->preserveQueryPrefixes) { - if (!p.empty() && pathOnly.find(p) != std::string::npos) { - return noHash; - } - } - bool isDevEndpoint = false; - for (const auto& p : canon->devPathPrefixes) { - if (!p.empty() && StartsWith(pathOnly, p.c_str())) { - isDevEndpoint = true; - break; - } - } - if (!isDevEndpoint) { - return noHash; - } - } - - if (query.empty()) return originAndPath; - - std::vector kept; - size_t start = 0; - while (start <= query.size()) { - size_t amp = query.find('&', start); - std::string pair = - (amp == std::string::npos) ? query.substr(start) : query.substr(start, amp - start); - if (!pair.empty()) { - size_t eq = pair.find('='); - std::string name = (eq == std::string::npos) ? pair : pair.substr(0, eq); - const bool drop = std::find(canon->stripParams.begin(), canon->stripParams.end(), - name) != canon->stripParams.end(); - if (!drop) kept.push_back(pair); - } - if (amp == std::string::npos) break; - start = amp + 1; - } - if (kept.empty()) return originAndPath; - std::sort(kept.begin(), kept.end()); - std::string rebuilt = originAndPath + "?"; - for (size_t i = 0; i < kept.size(); i++) { - if (i > 0) rebuilt += "&"; - rebuilt += kept[i]; - } - return rebuilt; + return http::CanonicalizeNormalizedHttpUrlKey(normalizedUrl, + CanonicalizationConfigForCurrentIsolate()); } // ───────────────────────────────────────────────────────────── -// JNI fetch diagnostics + request builder +// The transport: one attempt over OkHttp or HttpURLConnection + +namespace { // Describes and clears a pending Java exception. The introspection calls go // through the raw JNIEnv: JEnv's wrappers turn a pending Java exception into a // thrown NativeScriptException, which here would replace the exception being // described with the failure to describe it. -static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std::string& outMessage) { +bool DrainPendingJniException(JEnv& env, std::string& outClassName, std::string& outMessage) { outClassName.clear(); outMessage.clear(); JNIEnv* raw = env; @@ -304,74 +99,6 @@ static bool DrainPendingJniException(JEnv& env, std::string& outClassName, std:: return true; } -static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool useCache, - std::string& out, std::string& contentType, int& status); - -// ── The HTTP module cache switch ───────────────────────────── - -static std::once_flag s_moduleHttpCacheInitFlag; -static std::atomic s_moduleHttpCacheSetting{true}; -static std::atomic s_moduleHttpCacheInspectorDisables{0}; - -// The app config's and launch options' answer, read once. Every writer of the -// setting runs this first, so a later first read cannot overwrite a setter. -static void InitializeModuleHttpCacheSetting() { - std::call_once(s_moduleHttpCacheInitFlag, []() { - try { - JEnv env; - jclass cls = env.FindClass("com/tns/ModuleHttpCache"); - if (cls == nullptr) { - env.ExceptionClear(); - return; - } - jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); - if (mid == nullptr) { - env.ExceptionClear(); - return; - } - s_moduleHttpCacheSetting.store(env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE); - } catch (...) { - // Enabled. - } - }); -} - -bool ModuleHttpCacheEnabled() { - InitializeModuleHttpCacheSetting(); - return s_moduleHttpCacheSetting.load() && s_moduleHttpCacheInspectorDisables.load() == 0; -} - -void SetModuleHttpCacheEnabled(bool enabled) { - InitializeModuleHttpCacheSetting(); - s_moduleHttpCacheSetting.store(enabled); -} - -void AddModuleHttpCacheInspectorDisable(int delta) { - InitializeModuleHttpCacheSetting(); - s_moduleHttpCacheInspectorDisables.fetch_add(delta); -} - -void ClearModuleHttpCache() { - JEnv env; - jclass cls = env.FindClass("com/tns/ModuleHttpCache"); - if (cls == nullptr) { - // Takes the ClassNotFoundException FindClass left pending. - throw NativeScriptException(env); - } - jmethodID mid = env.GetStaticMethodID(cls, "clear", "()V"); - env.CallStaticVoidMethod(cls, mid); -} - -// 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}; - // A blocking network call on the JS thread is exactly what StrictMode is meant // to flag, so the fetch relaxes the thread policy — but the policy belongs to // the app, not to this request: whatever runs next on this thread must get its @@ -448,189 +175,54 @@ struct StrictModeScope { } }; -// ── The module response policy ─────────────────────────────── -// -// Module scripts are strict about MIME: the HTML spec's "fetch a single module -// script" fails the fetch outright for anything that is not a JavaScript or -// JSON MIME type, where a classic script would sniff and run it anyway. That -// strictness is the whole point — an SPA dev server answering an unknown path -// with `200 text/html` should say so, not hand HTML to the parser and produce -// `Unexpected token '<'` from somewhere deep in the graph. -// -// Both transports classify here, so the synchronous fallback and the async -// walk cannot disagree about what a response means. - -// "text/javascript; charset=utf-8" → "text/javascript": parameters stripped, -// trimmed, lowercased. -static std::string MimeEssence(const std::string& contentType) { - size_t semi = contentType.find(';'); - std::string essence = - semi == std::string::npos ? contentType : contentType.substr(0, semi); - size_t begin = essence.find_first_not_of(" \t"); - if (begin == std::string::npos) { - return ""; +// Alternating header names and values, in order; null, with nothing pending, +// when the array could not be built. +jobjectArray NewHeaderArray(JEnv& env, const std::vector& headers) { + JNIEnv* raw = env; + jclass clsString = env.FindClass("java/lang/String"); + if (clsString == nullptr) { + raw->ExceptionClear(); + return nullptr; } - size_t end = essence.find_last_not_of(" \t"); - essence = essence.substr(begin, end - begin + 1); - for (char& c : essence) { - c = (char)tolower((unsigned char)c); + jobjectArray array = + raw->NewObjectArray(static_cast(headers.size() * 2), clsString, nullptr); + if (array == nullptr) { + raw->ExceptionClear(); + return nullptr; } - return essence; -} - -// The HTML spec's JavaScript MIME type essence list, verbatim. -static bool IsJavaScriptMimeEssence(const std::string& essence) { - static const char* const kJavaScriptEssences[] = {"application/ecmascript", - "application/javascript", - "application/x-ecmascript", - "application/x-javascript", - "text/ecmascript", - "text/javascript", - "text/javascript1.0", - "text/javascript1.1", - "text/javascript1.2", - "text/javascript1.3", - "text/javascript1.4", - "text/javascript1.5", - "text/jscript", - "text/livescript", - "text/x-ecmascript", - "text/x-javascript"}; - for (const char* candidate : kJavaScriptEssences) { - if (essence == candidate) { - return true; + jsize index = 0; + for (const http::RequestHeader& header : headers) { + for (const std::string* text : {&header.name, &header.value}) { + jstring jText = raw->NewStringUTF(text->c_str()); + if (jText == nullptr) { + raw->ExceptionClear(); + return nullptr; + } + raw->SetObjectArrayElement(array, index++, jText); + raw->DeleteLocalRef(jText); } } - return false; -} - -// A JSON MIME type is application/json, text/json, or any `+json` subtype. -static bool IsJsonMimeEssence(const std::string& essence) { - if (essence == "application/json" || essence == "text/json") { - return true; - } - const std::string suffix = "+json"; - return essence.size() > suffix.size() && - essence.compare(essence.size() - suffix.size(), suffix.size(), suffix) == 0; + return array; } -// `transportOk` means a response arrived at all; everything else about it — -// status, MIME, emptiness — is policy decided here. `body` is moved into the -// result on success. -static void ClassifyModuleResponse(const std::string& url, bool transportOk, int status, - const std::string& contentType, std::string& body, - ModuleFetchResult& result) { - result.status = status; - result.contentType = contentType; - - if (!transportOk) { - result.failureReason = "HTTP import failed: " + url + " (network error)"; - return; - } - if (status == 204 || status == 205) { - // "No content" carries no module, which the web treats as a network - // error for a module script rather than as an empty module. - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + - ", no content)"; - return; - } - if (status < 200 || status >= 300) { - result.failureReason = - "HTTP import failed: " + url + " (status=" + std::to_string(status) + ")"; - return; +// The strings of a Java String[], null elements skipped. +std::vector StringArrayValues(JNIEnv* raw, jobjectArray array) { + std::vector values; + if (array == nullptr) { + return values; } - - const std::string essence = MimeEssence(contentType); - if (essence.empty()) { - result.failureReason = - "Expected a JavaScript module but '" + url + "' responded with no MIME type"; - return; - } - - if (IsJsonMimeEssence(essence)) { - if (body.empty()) { - result.failureReason = - "Expected a JSON module but '" + url + "' responded with an empty body"; - return; + const jsize length = raw->GetArrayLength(array); + for (jsize i = 0; i < length; i++) { + auto value = static_cast(raw->GetObjectArrayElement(array, i)); + if (value != nullptr) { + values.push_back(ArgConverter::jstringToString(value)); + raw->DeleteLocalRef(value); } - result.kind = ModuleResponseKind::kJson; - } else if (IsJavaScriptMimeEssence(essence)) { - result.kind = ModuleResponseKind::kJavaScript; - // An empty 2xx JavaScript body is a valid module: type-only TypeScript - // modules transform to zero runtime code and dev servers serve them as - // empty 200s. Failing here would kill the whole graph with a misleading - // "status=200". - if (body.empty()) { - body = "export {};\n"; - TNS_DEBUG(Esm, "[http-loader] empty 2xx body for %s — serving canonical empty module", - url.c_str()); - } - } else { - result.failureReason = "Expected a JavaScript module but '" + url + - "' responded with MIME type '" + essence + "'"; - return; } - - result.ok = true; - result.body = std::move(body); + return values; } -bool HttpFetchModule(const std::string& url, ModuleFetchResult& result) { - result = ModuleFetchResult(); - - // Security gate: the single point of enforcement for all HTTP module - // loading, checked before any network turn. - if (!IsRemoteUrlAllowed(url)) { - result.status = 403; - result.failureReason = - "HTTP import blocked: remote module loading is not allowed for " + url; - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - return false; - } - - const bool urlLogEnabled = LogCategoryEnabled(LogCategory::Fetch); - const auto netStart = urlLogEnabled ? std::chrono::steady_clock::now() - : std::chrono::steady_clock::time_point{}; - - std::string body; - std::string contentType; - int status = 0; - const int timeoutMs = ModuleFetchTimeoutMs(); - const bool useCache = ModuleHttpCacheEnabled(); - bool transportOk = - PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); - 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()); - std::this_thread::sleep_for(kModuleFetchRetryDelay); - transportOk = PerformHttpFetchOnceSync(url, timeoutMs, useCache, body, contentType, status); - } - - ClassifyModuleResponse(url, transportOk, status, contentType, body, result); - - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-sync][reject] %s", result.failureReason.c_str()); - return false; - } - - TNS_DEBUG(Esm, "[http-loader] fetched status=%d content-type=%s bytes=%llu", result.status, - result.contentType.empty() ? "" : result.contentType.c_str(), - (unsigned long long)result.body.size()); - if (urlLogEnabled) { - const auto netMs = std::chrono::duration_cast( - std::chrono::steady_clock::now() - netStart) - .count(); - TNS_DEBUG(Fetch, "[http-loader][fetch][network] %s bytes=%lu ms=%lld", url.c_str(), - (unsigned long)result.body.size(), (long long)netMs); - } - - return true; -} - -// ── OkHttp transport (see ActiveModuleTransportName) ───────── +// ── OkHttp ────────────────────────────────────────────────── struct OkHttpBridge { jclass fetcher = nullptr; @@ -638,14 +230,16 @@ struct OkHttpBridge { jfieldID status = nullptr; jfieldID contentType = nullptr; jfieldID body = nullptr; + jfieldID finalUrl = nullptr; + jfieldID clearSiteData = nullptr; }; -static std::atomic s_forcePlatformTransport{false}; -static std::atomic s_okHttpIncompatible{false}; +std::atomic s_forcePlatformTransport{false}; +std::atomic s_okHttpIncompatible{false}; // Null when the app does not ship OkHttp. isAvailable() is the first call into // the bridge: nothing else there may run without okhttp3. -static const OkHttpBridge* OkHttpBridgeIfAvailable() { +const OkHttpBridge* OkHttpBridgeIfAvailable() { static std::once_flag once; static OkHttpBridge bridge; static bool available = false; @@ -670,13 +264,19 @@ static const OkHttpBridge* OkHttpBridgeIfAvailable() { return; } bridge.fetch = raw->GetStaticMethodID( - fetcher, "fetch", "(Ljava/lang/String;IIIZ)Lcom/tns/OkHttpModuleFetcher$Result;"); + fetcher, "fetch", + "(Ljava/lang/String;[Ljava/lang/String;IIZ)Lcom/tns/OkHttpModuleFetcher$Result;"); bridge.status = bridge.fetch ? raw->GetFieldID(result, "status", "I") : nullptr; bridge.contentType = bridge.status ? raw->GetFieldID(result, "contentType", "Ljava/lang/String;") : nullptr; bridge.body = bridge.contentType ? raw->GetFieldID(result, "body", "[B") : nullptr; - if (!bridge.body) { + bridge.finalUrl = + bridge.body ? raw->GetFieldID(result, "finalUrl", "Ljava/lang/String;") : nullptr; + bridge.clearSiteData = bridge.finalUrl ? raw->GetFieldID(result, "clearSiteData", + "[Ljava/lang/String;") + : nullptr; + if (!bridge.clearSiteData) { raw->ExceptionClear(); return; } @@ -689,7 +289,7 @@ static const OkHttpBridge* OkHttpBridgeIfAvailable() { return available ? &bridge : nullptr; } -static const OkHttpBridge* ActiveOkHttpBridge() { +const OkHttpBridge* ActiveOkHttpBridge() { if (s_forcePlatformTransport.load(std::memory_order_relaxed) || s_okHttpIncompatible.load(std::memory_order_relaxed)) { return nullptr; @@ -697,14 +297,6 @@ static const OkHttpBridge* ActiveOkHttpBridge() { return OkHttpBridgeIfAvailable(); } -const char* ActiveModuleTransportName() { - return ActiveOkHttpBridge() != nullptr ? "okhttp" : "platform"; -} - -void SetForcePlatformModuleTransport(bool force) { - s_forcePlatformTransport.store(force, std::memory_order_relaxed); -} - // The OkHttp counterpart of the HttpURLConnection exchange in // PerformHttpFetchOnceSync, with the same contract: false for a transport // failure, true once a status arrived. A failed body read only fails the @@ -712,25 +304,28 @@ void SetForcePlatformModuleTransport(bool force) { // Empty when the app's OkHttp turned out to lack a call the bridge makes; the // caller then fetches through HttpURLConnection. template -static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, - const std::string& url, int timeoutMs, - bool useCache, std::string& out, std::string& contentType, - int& status, OnFailure recordStageFailure) { +std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bridge, + const http::AttemptRequest& request, + http::AttemptOutcome& outcome, + OnFailure recordStageFailure) { JNIEnv* raw = env; // The pool keeps at least as many idle connections as the most fetches // that can run at once, so a burst's connections all survive to be reused. const size_t maxIdle = std::max(ModuleFetchConcurrency(ModuleFetchHostClass::kLoopback), ModuleFetchConcurrency(ModuleFetchHostClass::kRemote)); - jstring jUrl = raw->NewStringUTF(url.c_str()); + jstring jUrl = raw->NewStringUTF(request.url.c_str()); if (jUrl == nullptr) { raw->ExceptionClear(); return false; } - jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, - static_cast(timeoutMs), - static_cast(ModuleFetchTimeoutMs()), + jobjectArray jHeaders = NewHeaderArray(env, request.headers); + if (jHeaders == nullptr) { + return false; + } + jobject result = raw->CallStaticObjectMethod(bridge.fetcher, bridge.fetch, jUrl, jHeaders, + static_cast(request.timeout.count()), static_cast(maxIdle), - useCache ? JNI_TRUE : JNI_FALSE); + request.useCache ? JNI_TRUE : JNI_FALSE); { std::string excClass, excMsg; if (DrainPendingJniException(env, excClass, excMsg)) { @@ -743,26 +338,35 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri return std::nullopt; } - status = raw->GetIntField(result, bridge.status); + outcome.status = raw->GetIntField(result, bridge.status); auto jct = static_cast(raw->GetObjectField(result, bridge.contentType)); if (jct != nullptr) { - contentType = ArgConverter::jstringToString(jct); + outcome.contentType = ArgConverter::jstringToString(jct); } + auto jFinalUrl = static_cast(raw->GetObjectField(result, bridge.finalUrl)); + if (jFinalUrl != nullptr) { + outcome.finalUrl = ArgConverter::jstringToString(jFinalUrl); + } + outcome.clearSiteData = StringArrayValues( + raw, static_cast(raw->GetObjectField(result, bridge.clearSiteData))); auto bytes = static_cast(raw->GetObjectField(result, bridge.body)); if (bytes == nullptr) { recordStageFailure("read-body", "", "the response body could not be read"); - return !(status >= 200 && status < 300); + return !(outcome.status >= 200 && outcome.status < 300); } const jsize len = raw->GetArrayLength(bytes); - out.resize(static_cast(len)); + outcome.body.resize(static_cast(len)); if (len > 0) { - raw->GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&out[0])); + raw->GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&outcome.body[0])); } return true; } -// Runs on whichever thread drives the fetch — the JS thread for the sync path, -// a detached background thread for the async one. +// ── One attempt ───────────────────────────────────────────── + +// Runs on whichever thread the core runs the attempt on — the JS thread for +// the synchronous fallback, a core fetch thread for the graph walk. True when +// the attempt arrived (AttemptOutcome::arrived). // // The network calls below go through the raw JNIEnv rather than JEnv's // wrappers: a wrapper converts a pending Java exception into a thrown @@ -770,18 +374,18 @@ static std::optional PerformOkHttpFetch(JEnv& env, const OkHttpBridge& bri // 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, int timeoutMs, bool useCache, - std::string& out, std::string& contentType, int& status) { - out.clear(); - contentType.clear(); - status = 0; +// `request.timeout` must be positive: HttpURLConnection reads 0 as no timeout. +bool PerformHttpFetchOnceSync(const http::AttemptRequest& request, http::AttemptOutcome& outcome) { + const std::string& url = request.url; + const int timeoutMs = static_cast(request.timeout.count()); TNS_DEBUG(Esm, "[http-esm][fetch][enter] url=%s timeoutMs=%d", url.c_str(), timeoutMs); - auto recordStageFailure = [&url](const char* stage, const std::string& excClass, - const std::string& excMsg) { + auto recordStageFailure = [&url, &outcome](const char* stage, const std::string& excClass, + const std::string& excMsg) { TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=%s url=%s class=%s msg=%s", stage, url.c_str(), excClass.c_str(), excMsg.c_str()); + outcome.errorDescription = std::string("stage=") + stage + " class=" + excClass + + " msg=" + excMsg; }; JEnv env; @@ -809,9 +413,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool StrictModeScope strictMode(env); if (const OkHttpBridge* okhttp = ActiveOkHttpBridge()) { - if (std::optional fetched = PerformOkHttpFetch( - env, *okhttp, url, timeoutMs, useCache, out, contentType, status, - recordStageFailure)) { + if (std::optional fetched = + PerformOkHttpFetch(env, *okhttp, request, outcome, recordStageFailure)) { return *fetched; } } @@ -847,8 +450,8 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool jmethodID setReadTimeout = env.GetMethodID(clsConn, "setReadTimeout", "(I)V"); jmethodID setDoInput = env.GetMethodID(clsConn, "setDoInput", "(Z)V"); jmethodID setUseCaches = env.GetMethodID(clsConn, "setUseCaches", "(Z)V"); - jmethodID setReqProp = - env.GetMethodID(clsConn, "setRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); + jmethodID addReqProp = + env.GetMethodID(clsConn, "addRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V"); env.CallVoidMethod(conn, setConnectTimeout, timeoutMs); env.CallVoidMethod(conn, setReadTimeout, timeoutMs); if (setDoInput) { @@ -859,18 +462,12 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool if (setUseCaches) { env.CallVoidMethod(conn, setUseCaches, JNI_FALSE); } - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Accept"), - env.NewStringUTF("application/javascript, text/javascript, */*;q=0.1")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Accept-Encoding"), - env.NewStringUTF("identity")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("User-Agent"), - env.NewStringUTF("NativeScript-HTTP-ESM")); - // This transport has no cache, but a proxy on the way may. - if (!useCache) { - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Cache-Control"), - env.NewStringUTF("no-cache")); - env.CallVoidMethod(conn, setReqProp, env.NewStringUTF("Pragma"), - env.NewStringUTF("no-cache")); + for (const http::RequestHeader& header : request.headers) { + jstring jName = env.NewStringUTF(header.name.c_str()); + jstring jValue = env.NewStringUTF(header.value.c_str()); + env.CallVoidMethod(conn, addReqProp, jName, jValue); + env.DeleteLocalRef(jName); + env.DeleteLocalRef(jValue); } jclass clsHttp = env.FindClass("java/net/HttpURLConnection"); @@ -880,6 +477,7 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool jmethodID getErrorStream = isHttp ? env.GetMethodID(clsHttp, "getErrorStream", "()Ljava/io/InputStream;") : nullptr; + int& status = outcome.status; // Once a status line has been read the server has answered, and every // body-side failure below stops being a transport error: an empty 404 // is an answer, and reporting it as "network error" would both hide @@ -971,27 +569,48 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool env.CallVoidMethod(baos, baosClose); if (bytes) { jsize len = env.GetArrayLength(bytes); - out.resize(static_cast(len)); + outcome.body.resize(static_cast(len)); if (len > 0) { - env.GetByteArrayRegion(bytes, 0, len, reinterpret_cast(&out[0])); + env.GetByteArrayRegion(bytes, 0, len, + reinterpret_cast(&outcome.body[0])); } } else { readFailed = true; } } } - // Clear-Site-Data, now that the stream is closed, and whether or not - // the body arrived whole, as on the OkHttp transport. A failure here - // costs only the clear, never the module. + // The final URL and Clear-Site-Data, whether or not the body arrived + // whole, as on the OkHttp transport. A failure here costs only those, + // never the module. if (isHttp) { + // getURL() is the URL the redirects ended at. + jmethodID getURL = raw->GetMethodID(clsConn, "getURL", "()Ljava/net/URL;"); + jobject finalUrl = getURL ? raw->CallObjectMethod(conn, getURL) : nullptr; + raw->ExceptionClear(); + jmethodID urlToString = + finalUrl ? raw->GetMethodID(clsURL, "toString", "()Ljava/lang/String;") : nullptr; + auto jFinalUrl = urlToString + ? static_cast(raw->CallObjectMethod(finalUrl, urlToString)) + : nullptr; + raw->ExceptionClear(); + if (jFinalUrl != nullptr) { + outcome.finalUrl = ArgConverter::jstringToString(jFinalUrl); + } + jclass clsCache = env.FindClass("com/tns/ModuleHttpCache"); - jmethodID onResponse = - clsCache ? raw->GetStaticMethodID(clsCache, "onPlatformResponse", - "(Ljava/net/HttpURLConnection;)V") + jmethodID clearSiteDataValues = + clsCache ? raw->GetStaticMethodID(clsCache, "clearSiteDataValues", + "(Ljava/net/HttpURLConnection;)[Ljava/lang/String;") : nullptr; - if (onResponse) { - raw->CallStaticVoidMethod(clsCache, onResponse, conn); + auto values = clearSiteDataValues + ? static_cast( + raw->CallStaticObjectMethod(clsCache, clearSiteDataValues, conn)) + : nullptr; + if (raw->ExceptionCheck()) { + raw->ExceptionClear(); + values = nullptr; } + outcome.clearSiteData = StringArrayValues(raw, values); raw->ExceptionClear(); } @@ -1006,14 +625,12 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool env.GetMethodID(clsConn, "getContentType", "()Ljava/lang/String;"); jstring jct = static_cast(env.CallObjectMethod(conn, getContentType)); if (jct) { - contentType = ArgConverter::jstringToString(jct); + outcome.contentType = ArgConverter::jstringToString(jct); } if (status == 0) status = 200; // Pure transport: true means a response arrived. Whether that response - // is a usable module — status, MIME, emptiness — is - // ClassifyModuleResponse's call, so both fetch paths answer it the - // same way. + // is a usable module — status, MIME, emptiness — is the core's call. return true; } catch (NativeScriptException& nse) { std::string what = nse.what() ? nse.what() : ""; @@ -1022,342 +639,226 @@ static bool PerformHttpFetchOnceSync(const std::string& url, int timeoutMs, bool } TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=native-script-exception url=%s msg=%s", url.c_str(), what.c_str()); + outcome.errorDescription = "stage=native-script-exception msg=" + what; return false; } catch (std::exception& ex) { std::string what = ex.what() ? ex.what() : ""; TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=std-exception url=%s msg=%s", url.c_str(), what.c_str()); + outcome.errorDescription = "stage=std-exception msg=" + what; return false; } catch (...) { TNS_DEBUG(Esm, "[http-esm][fetch][exception] stage=unknown-cpp-exception url=%s", url.c_str()); + outcome.errorDescription = "stage=unknown-cpp-exception"; return false; } } -// ── Fetch concurrency ──────────────────────────────────────── - -// The defaults per host class (see ModuleFetchHostClass). adbd's reverse -// listener has a backlog of 4, so a burst of new connections overflows it, and -// each overflow costs the client a 1 s SYN retry. Remote hosts are -// bound by their round trip, so more fetches in flight load faster. -static constexpr size_t kLoopbackModuleFetchConcurrency = 6; -static constexpr size_t kRemoteModuleFetchConcurrency = 32; - -static std::once_flag s_fetchConcurrencyInitFlag; -// 0 = not configured. -static size_t s_configuredLoopbackConcurrency = 0; -static size_t s_configuredRemoteConcurrency = 0; - -static void InitializeFetchConcurrencyConfig() { - std::call_once(s_fetchConcurrencyInitFlag, []() { - try { - JEnv env; - jclass runtimeClass = env.FindClass("com/tns/Runtime"); - if (runtimeClass == nullptr) { - return; - } - jmethodID getter = - env.GetStaticMethodID(runtimeClass, "getModuleFetchConcurrency", "()[I"); - if (getter == nullptr) { - return; - } - jintArray values = - static_cast(env.CallStaticObjectMethod(runtimeClass, getter)); - if (values == nullptr) { - return; - } - if (env.GetArrayLength(values) == 2) { - jint pair[2] = {0, 0}; - env.GetIntArrayRegion(values, 0, 2, pair); - s_configuredLoopbackConcurrency = pair[0] > 0 ? static_cast(pair[0]) : 0; - s_configuredRemoteConcurrency = pair[1] > 0 ? static_cast(pair[1]) : 0; - } - env.DeleteLocalRef(values); - } catch (...) { - // Keep the defaults. +// ModuleHttpCache., with `origin` as its argument when not null. A +// Java failure comes back as the reader-facing message the runtime gives a +// Java exception. +http::CacheOpResult CallModuleHttpCache(const char* method, const std::string* origin) { + try { + JEnv env; + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { + // Takes the ClassNotFoundException FindClass left pending. + throw NativeScriptException(env); + } + if (origin == nullptr) { + jmethodID mid = env.GetStaticMethodID(cls, method, "()V"); + env.CallStaticVoidMethod(cls, mid); + } else { + // Clear-Site-Data, applied on the thread that fetched: for the + // synchronous fallback that is the JS thread, and the cache's disk + // work is no more the app's StrictMode business than the fetch was. + StrictModeScope strictMode(env); + jmethodID mid = env.GetStaticMethodID(cls, method, "(Ljava/lang/String;)V"); + jstring jOrigin = env.NewStringUTF(origin->c_str()); + // Deleted on both paths: a JNI exception leaves the ref valid. + struct DeleteRef { + JNIEnv* jni; + jobject ref; + ~DeleteRef() { + if (ref != nullptr) jni->DeleteLocalRef(ref); + } + } deleteOrigin{env, jOrigin}; + env.CallStaticVoidMethod(cls, mid, jOrigin); } - }); + return {}; + } catch (NativeScriptException& e) { + return {false, e.GetErrorMessage()}; + } catch (const std::exception& e) { + return {false, e.what()}; + } } -static std::string LowercaseHostOf(const std::string& url) { - const size_t schemeEnd = url.find("://"); - if (schemeEnd == std::string::npos) return ""; - const size_t start = schemeEnd + 3; - const size_t end = url.find_first_of("/?#", start); - std::string authority = - url.substr(start, end == std::string::npos ? std::string::npos : end - start); - const size_t at = authority.rfind('@'); - if (at != std::string::npos) authority.erase(0, at + 1); - std::string host; - if (!authority.empty() && authority[0] == '[') { - const size_t close = authority.find(']'); - host = close == std::string::npos ? authority : authority.substr(0, close + 1); - } else { - host = authority.substr(0, authority.find(':')); +class AndroidModuleTransport final : public http::ModuleTransport { +public: + // "okhttp" when the app ships OkHttp (com.tns.OkHttpModuleFetcher: a + // dedicated client with an on-disk HTTP cache under + // /ns-module-http-cache) and it has not been forced off or + // found incompatible, otherwise "platform" (HttpURLConnection, uncached). + const char* Name() const override { + return ActiveOkHttpBridge() != nullptr ? "okhttp" : "platform"; } - for (char& c : host) { - c = static_cast(tolower(static_cast(c))); + + // Neither HTTP stack makes a blocking request wait for a connection + // another request holds, so FetchPath needs no separate connections. + // `waitBound` is not honoured: neither stack can abandon an attempt in + // flight. + http::AttemptOutcome FetchBlocking(const http::AttemptRequest& request) override { + http::AttemptOutcome outcome; + outcome.arrived = PerformHttpFetchOnceSync(request, outcome); + return outcome; } - return host; -} -ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url) { - const std::string host = LowercaseHostOf(url); - // 10.0.2.2 and 10.0.3.2 are the development machine as seen from the - // Android emulator and Genymotion. - if (host == "127.0.0.1" || host == "[::1]" || host == "localhost" || host == "10.0.2.2" || - host == "10.0.3.2") { - return ModuleFetchHostClass::kLoopback; + http::CacheOpResult ClearAll() override { + return CallModuleHttpCache("clear", nullptr); } - return ModuleFetchHostClass::kRemote; -} -const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass) { - return hostClass == ModuleFetchHostClass::kLoopback ? "loopback" : "remote"; -} + http::CacheOpResult ClearOrigin(const std::string& origin) override { + return CallModuleHttpCache("clearOrigin", &origin); + } -size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass) { - InitializeFetchConcurrencyConfig(); - if (hostClass == ModuleFetchHostClass::kLoopback) { - return s_configuredLoopbackConcurrency > 0 ? s_configuredLoopbackConcurrency - : kLoopbackModuleFetchConcurrency; + // The JVM attach is paid once per fetch thread rather than once per + // module. + void OnFetchThreadStart() override { + JavaVM* jvm = Runtime::GetJVM(); + if (jvm == nullptr) { + return; + } + JNIEnv* raw = nullptr; + if (jvm->GetEnv(reinterpret_cast(&raw), JNI_VERSION_1_6) != JNI_OK && + jvm->AttachCurrentThread(&raw, nullptr) == JNI_OK) { + s_attachedForFetches = true; + } } - return s_configuredRemoteConcurrency > 0 ? s_configuredRemoteConcurrency - : kRemoteModuleFetchConcurrency; -} -// ── Bounded async fetch ────────────────────────────────────── -// -// One module fetch, with everything the fetch thread needs; nothing here -// touches V8 or an isolate. -namespace { + void OnFetchThreadExit() override { + if (!s_attachedForFetches) { + return; + } + s_attachedForFetches = false; + if (JavaVM* jvm = Runtime::GetJVM()) { + jvm->DetachCurrentThread(); + } + } -struct ModuleFetchJob { - std::string url; - ModuleFetchHostClass hostClass; - ModuleFetchDeadline deadline; - // The cache switch as it was when the fetch was issued. - bool useCache; - std::function completion; +private: + static thread_local bool s_attachedForFetches; }; -// 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; -} +thread_local bool AndroidModuleTransport::s_attachedForFetches = false; -bool RetryFitsDeadline(const ModuleFetchDeadline& deadline) { - return !deadline || *deadline - std::chrono::steady_clock::now() > kModuleFetchRetryDelay; -} +// ── Platform config ───────────────────────────────────────── -// One queue and thread count per ModuleFetchHostClass, all under one mutex. -struct ModuleFetchLane { - std::deque queue; - size_t threadCount = 0; -}; +// Runs `read`, then clears whatever Java exception it left pending. A failure +// keeps the defaults `read` had not overwritten yet. +template +void ReadJavaConfig(Read read) { + JEnv env; + try { + read(env); + } catch (...) { + } + static_cast(env)->ExceptionClear(); +} -std::mutex g_fetchQueueMutex; -ModuleFetchLane g_fetchLanes[2]; +} // namespace -ModuleFetchLane& LaneFor(ModuleFetchHostClass hostClass) { - return g_fetchLanes[hostClass == ModuleFetchHostClass::kLoopback ? 0 : 1]; +void SetForcePlatformModuleTransport(bool force) { + s_forcePlatformTransport.store(force, std::memory_order_relaxed); } -void RunModuleFetchJob(const ModuleFetchJob& job) { - // Nothing may escape this function: it runs at the top of a detached - // thread, where an unwinding exception is std::terminate for the whole - // process — and a throw past the caller's loop would also strand the - // queue bookkeeping. The fetch phase converts an escaped exception into a - // transport-error result so the completion still runs exactly once; the - // completion itself gets a log-only guard, since by then delivery has - // either happened or cannot be retried. - ModuleFetchResult result; - try { - std::string body; - std::string contentType; - int status = 0; - const auto start = std::chrono::steady_clock::now(); - bool transportOk = false; - std::optional timeoutMs = AttemptTimeoutMs(job.deadline); - if (timeoutMs) { - transportOk = PerformHttpFetchOnceSync(job.url, *timeoutMs, job.useCache, body, - contentType, status); - // Transport error → one retry, the same single-retry policy the - // 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, *timeoutMs, job.useCache, - body, contentType, status); - } - } - } - - if (timeoutMs) { - ClassifyModuleResponse(job.url, transportOk, status, contentType, body, result); - } else { - result.failureReason = - "HTTP import failed: " + job.url + " (module graph fetch deadline exceeded)"; - } +} // namespace tns - if (!result.ok) { - TNS_DEBUG(Esm, "[http-loader][fetch-async][reject] %s", result.failureReason.c_str()); - } else if (LogCategoryEnabled(LogCategory::Fetch)) { - const auto ms = std::chrono::duration_cast( - std::chrono::steady_clock::now() - start) - .count(); - TNS_DEBUG(Fetch, "[http-loader][fetch][async] %s bytes=%lu ms=%lld", job.url.c_str(), - (unsigned long)result.body.size(), (long long)ms); - } - } catch (NativeScriptException& e) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] native exception fetching %s: %s", - job.url.c_str(), e.what()); - } catch (const std::exception& e) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] c++ exception fetching %s: %s", - job.url.c_str(), e.what()); - } catch (...) { - result = ModuleFetchResult{}; - result.failureReason = "HTTP import failed: " + job.url + " (network error)"; - DEBUG_WRITE_FORCE("[http-loader][fetch-async] unknown exception fetching %s", - job.url.c_str()); - } +namespace nativescript::common::platform { - try { - job.completion(std::move(result)); - } catch (const std::exception& e) { - DEBUG_WRITE_FORCE("[http-loader][fetch-async] completion threw for %s: %s", - job.url.c_str(), e.what()); - } catch (...) { - DEBUG_WRITE_FORCE("[http-loader][fetch-async] completion threw for %s", job.url.c_str()); - } -} +// Called once, from whichever thread reaches the loader first: the JS thread, +// a worker, a core fetch thread or the inspector's socket thread. JEnv +// attaches a thread that is not attached yet. +http::HttpLoaderConfig ReadHttpLoaderConfig() { + using tns::JEnv; + http::HttpLoaderConfig config; + config.isDebug = tns::IsDebuggable(); -// A fetch thread serves its own job and then drains the queue, so the JVM -// attach is paid once per thread rather than once per module and the cap -// bounds threads, not just sockets. Exiting checks the queue and decrements -// the count in ONE critical section: a producer that queues therefore always -// observes — and is observed by — a thread that has not yet exited, so a -// queued job cannot be stranded behind a thread on its way out. -void ModuleFetchThreadMain(ModuleFetchJob job) { - JavaVM* jvm = Runtime::GetJVM(); - bool attachedHere = false; - if (jvm != nullptr) { - JNIEnv* raw = nullptr; - if (jvm->GetEnv(reinterpret_cast(&raw), JNI_VERSION_1_6) != JNI_OK) { - if (jvm->AttachCurrentThread(&raw, nullptr) == JNI_OK) { - attachedHere = true; + // Debuggable apps load remote modules regardless of the security config. + if (!config.isDebug) { + tns::ReadJavaConfig([&config](JEnv& env) { + jclass runtimeClass = env.FindClass("com/tns/Runtime"); + if (runtimeClass == nullptr) { + return; } - } - } - struct DetachIfAttached { - JavaVM* jvm; - bool attached; - ~DetachIfAttached() { - if (attached && jvm != nullptr) { - jvm->DetachCurrentThread(); + jmethodID allowRemoteMid = + env.GetStaticMethodID(runtimeClass, "isRemoteModulesAllowed", "()Z"); + const bool allowRemoteModules = + env.CallStaticBooleanMethod(runtimeClass, allowRemoteMid) == JNI_TRUE; + + // Null when the list is not in force; a null element stands for an + // item that is not a string. + std::optional>> items; + jmethodID getAllowlistMid = env.GetStaticMethodID( + runtimeClass, "getRemoteModuleAllowlist", "()[Ljava/lang/String;"); + jobjectArray allowlistArray = static_cast( + env.CallStaticObjectMethod(runtimeClass, getAllowlistMid)); + if (allowlistArray != nullptr) { + items.emplace(); + jsize len = env.GetArrayLength(allowlistArray); + for (jsize i = 0; i < len; i++) { + jstring jstr = + static_cast(env.GetObjectArrayElement(allowlistArray, i)); + items->push_back(tns::ToExactUtf8(env, jstr)); + if (jstr != nullptr) { + env.DeleteLocalRef(jstr); + } + } + env.DeleteLocalRef(allowlistArray); } - } - } detachGuard{jvm, attachedHere}; - ModuleFetchLane& lane = LaneFor(job.hostClass); - for (;;) { - RunModuleFetchJob(job); + // Remote modules are enabled only after the allowlist was read in + // full: a failure part way keeps them disabled rather than enabling + // them with a list cut short. + config.remoteModuleAllowlist = std::move(items); + config.allowRemoteModules = allowRemoteModules; + }); + } - std::lock_guard lock(g_fetchQueueMutex); - if (lane.queue.empty()) { - lane.threadCount--; + tns::ReadJavaConfig([&config](JEnv& env) { + jclass cls = env.FindClass("com/tns/ModuleHttpCache"); + if (cls == nullptr) { return; } - job = std::move(lane.queue.front()); - lane.queue.pop_front(); - } -} - -} // namespace - -void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline fetchDeadline, - std::function completion) { - // Security gate: single point of enforcement, same as HttpFetchModule. - if (!IsRemoteUrlAllowed(url)) { - TNS_DEBUG(Esm, "[http-esm][security][blocked] %s", url.c_str()); - ModuleFetchResult blocked; - blocked.status = 403; - blocked.failureReason = - "HTTP import blocked: remote module loading is not allowed for " + url; - completion(std::move(blocked)); - return; - } + jmethodID mid = env.GetStaticMethodID(cls, "isEnabledAtStartup", "()Z"); + config.moduleHttpCacheAtStartup = env.CallStaticBooleanMethod(cls, mid) == JNI_TRUE; + }); - const ModuleFetchHostClass hostClass = ModuleFetchHostClassOf(url); - // Outside the lock: the first call reads the app config over JNI. - const size_t cap = ModuleFetchConcurrency(hostClass); - ModuleFetchLane& lane = LaneFor(hostClass); - ModuleFetchJob job{url, hostClass, fetchDeadline, ModuleHttpCacheEnabled(), - std::move(completion)}; - { - std::lock_guard lock(g_fetchQueueMutex); - if (lane.threadCount >= cap) { - lane.queue.push_back(std::move(job)); + tns::ReadJavaConfig([&config](JEnv& env) { + jclass runtimeClass = env.FindClass("com/tns/Runtime"); + if (runtimeClass == nullptr) { return; } - lane.threadCount++; - } - - // Copied, not moved: a throwing std::thread constructor leaves its - // decay-copies in an unspecified state, and the failure path below still - // has to deliver this job's completion. - try { - std::thread(ModuleFetchThreadMain, job).detach(); - return; - } catch (...) { - } - - // A counted slot with no thread behind it: anything queued against it has - // nothing left to drain it if this was the last one, so those jobs are - // failed here rather than left waiting on a thread that will never exist. - std::deque orphaned; - { - std::lock_guard lock(g_fetchQueueMutex); - lane.threadCount--; - if (lane.threadCount == 0) { - orphaned.swap(lane.queue); + jmethodID getter = env.GetStaticMethodID(runtimeClass, "getModuleFetchConcurrency", "()[I"); + jintArray values = static_cast(env.CallStaticObjectMethod(runtimeClass, getter)); + if (values == nullptr) { + return; } - } + if (env.GetArrayLength(values) == 2) { + jint pair[2] = {0, 0}; + env.GetIntArrayRegion(values, 0, 2, pair); + config.fetchConcurrency[0] = pair[0] > 0 ? static_cast(pair[0]) : 0; + config.fetchConcurrency[1] = pair[1] > 0 ? static_cast(pair[1]) : 0; + } + env.DeleteLocalRef(values); + }); - // The completion contract is exactly-once, and the caller's bookkeeping - // (pendingFetches) is already incremented — a swallowed spawn failure - // wedges the graph walk short of settling forever. - auto failSpawn = [](const ModuleFetchJob& failedJob) { - ModuleFetchResult failed; - failed.failureReason = "Could not fetch " + failedJob.url + - ": the runtime could not start a fetch thread"; - TNS_DEBUG(Esm, "[http-loader][fetch-async][spawn-fail] %s", failedJob.url.c_str()); - failedJob.completion(std::move(failed)); - }; + return config; +} - failSpawn(job); - for (const ModuleFetchJob& orphan : orphaned) { - failSpawn(orphan); - } +http::ModuleTransport& HttpTransport() { + static auto* transport = new tns::AndroidModuleTransport(); + return *transport; } -} // namespace tns +} // namespace nativescript::common::platform diff --git a/test-app/runtime/src/main/cpp/HttpLoader.h b/test-app/runtime/src/main/cpp/HttpLoader.h index efe45c266..c2f06b0e4 100644 --- a/test-app/runtime/src/main/cpp/HttpLoader.h +++ b/test-app/runtime/src/main/cpp/HttpLoader.h @@ -1,210 +1,55 @@ #pragma once -#include -#include -#include #include -#include -namespace tns { - -// HttpLoader: the native half of the NativeScript HTTP module-loader -// contract. -// -// The runtime deliberately exposes *mechanism* only: -// - the synchronous HTTP text fetch backing the HTTP ESM loader's -// fallback path (V8's ResolveModuleCallback is synchronous — still -// true as of 14.9.207.39 — so the fallback must be native), -// - the async background-thread fetch behind the phase-1 module-graph -// walk (StartModuleGraphLoad), which is how module bodies -// normally arrive, -// - the remote-module security gate, seeded once from nativescript.config -// at boot and never exposed on ns:runtime getConfig/setConfig. +#include "ns/http/ModuleFetch.h" -// ───────────────────────────────────────────────────────────── -// HTTP loader helpers (used by dev/HMR and general-purpose HTTP module loading) -// -// The canonical-key *mechanism* (fragment strip, cache-buster param drop, -// param sort) must be native because it keys the module registry inside V8's -// synchronous resolve walk. The *vocabulary* — which query params are pure -// cache busters, which path prefixes identify dev endpoints whose queries may -// be normalized, and which paths must keep their query verbatim because the -// query IS the identity — is server/framework policy, supplied by the dev -// client via ns:module `configureLoader({ canonicalization: {...} })`. It is -// per-isolate loader vocabulary — installed through SetCanonicalizationConfig -// in ModuleInternalCallbacks.h — so CanonicalizeHttpUrlKey runs on the -// isolate's own thread only. The transport never canonicalizes. -// -// When unconfigured, canonicalization is purely mechanical (fragment strip). -struct CanonicalizationConfig { - std::vector stripParams; // query param names to drop - std::vector devPathPrefixes; // StartsWith → normalize query - std::vector preserveQueryPrefixes; // contains → keep query -}; +namespace tns { -// Normalize an HTTP(S) URL into a stable module registry/cache key. -// - Anything that is not HTTP(S) comes back unchanged; an http(s) URL is -// first spelled by NormalizeHttpModuleUrl. -// - The fragment is always stripped. -// - The query survives unless the isolate's canonicalization vocabulary says -// otherwise: a path matching `preserveQueryFor` keeps its query verbatim; -// a path under a `forPathPrefixes` prefix drops every `stripParams` name and -// sorts what remains, for stability. Unconfigured, every query is kept. -// Module identity IS the (canonical) URL — the dev server serves every -// module under exactly one URL and never varies it for freshness. +// The HTTP module loader's policy and orchestration (gate, allowlist, request +// headers, timeouts, retry, fetch threads, classification, the cache switch, +// Clear-Site-Data) live in the shared core, ns/http/ModuleFetch.h. This +// runtime supplies the transport (OkHttp when the app ships it, otherwise +// HttpURLConnection), the platform config read, and the per-isolate +// canonicalization vocabulary. + +using nativescript::common::http::CacheOpResult; +using nativescript::common::http::CanonicalizationConfig; +using nativescript::common::http::ClearModuleHttpCache; +using nativescript::common::http::FetchModuleBodyAsync; +using nativescript::common::http::HttpFetchModule; +using nativescript::common::http::IsRemoteModulesAllowed; +using nativescript::common::http::IsRemoteUrlAllowed; +using nativescript::common::http::ModuleFetchConcurrency; +using nativescript::common::http::ModuleFetchDeadline; +using nativescript::common::http::ModuleFetchHostClass; +using nativescript::common::http::ModuleFetchHostClassName; +using nativescript::common::http::ModuleFetchHostClassOf; +using nativescript::common::http::ModuleFetchResult; +using nativescript::common::http::ModuleHttpCacheEnabled; +using nativescript::common::http::ModuleResponseKind; +using nativescript::common::http::RemoteModuleAllowlist; +using nativescript::common::http::RemoteModuleAllowlistFromConfig; +using nativescript::common::http::RemoteUrlAllowedByAllowlist; +using nativescript::common::http::SetModuleHttpCacheDisabledBy; +using nativescript::common::http::SetModuleHttpCacheEnabled; + +// The module registry key of an HTTP(S) URL: anything that is not HTTP(S) +// comes back unchanged; an http(s) URL is spelled by NormalizeHttpModuleUrl, +// then canonicalized with the calling isolate's vocabulary (ns:module +// `configureLoader({ canonicalization })`, see SetCanonicalizationConfig in +// ModuleInternalCallbacks.h). Isolate thread only. std::string CanonicalizeHttpUrlKey(const std::string& url); // CanonicalizeHttpUrlKey for a URL already spelled by NormalizeHttpModuleUrl. std::string CanonicalizeNormalizedHttpUrlKey(const std::string& normalizedUrl); -// What a module response turned out to be. Decided once, by the shared -// classifier, for whichever transport produced the response. -enum class ModuleResponseKind { - kJavaScript, - kJson, -}; - -// The outcome of fetching one module over HTTP. Both transports produce this -// same verdict, so the synchronous fallback and the async graph walk cannot -// drift apart on what counts as a usable module. -struct ModuleFetchResult { - bool ok = false; - int status = 0; - ModuleResponseKind kind = ModuleResponseKind::kJavaScript; - // Normalized: an empty 2xx JavaScript body becomes the canonical empty - // module. Meaningful only when `ok`. - std::string body; - std::string contentType; // as received, parameters included - // Reader-facing explanation, non-empty exactly when `!ok`. This is the text - // that reaches the importer's rejection, so it names the URL and the cause. - std::string failureReason; -}; - -// Synchronous module fetch with one retry on transport error — the fallback -// path for anything the module-graph walk missed. Blocks the calling thread. -// Returns `result.ok`. -bool HttpFetchModule(const std::string& url, 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: -// - security gate (IsRemoteUrlAllowed) checked up front, -// - a GET on a background thread through the active transport (see -// ActiveModuleTransportName) with the same request shape as the sync -// path, over persistent connections, 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. -// -// Concurrency is capped per host class (ModuleFetchConcurrency), process-wide -// rather than per host as NSURLSession does on iOS: the fetch threads are a -// process resource, and a dev session's modules all come from one origin. Over -// the cap the request is queued and picked up by a fetch thread of its class -// as one frees — the CALLER never blocks, so this stays safe to call from the -// JS thread. -void FetchModuleBodyAsync( - const std::string& url, ModuleFetchDeadline fetchDeadline, - std::function completion); - -// The transport both fetch paths use: "okhttp" when the app ships OkHttp -// (com.tns.OkHttpModuleFetcher: a dedicated client with an on-disk HTTP cache -// under /ns-module-http-cache), otherwise "platform" -// (HttpURLConnection, uncached). Request headers, timeouts, redirects, the -// security gate and response classification are the same on both. -const char* ActiveModuleTransportName(); - // Debug builds only (ns:module forcePlatformHttpTransport): fetch through the // platform transport even when OkHttp is available, so that fallback stays // testable in an app that ships OkHttp. void SetForcePlatformModuleTransport(bool force); -// The HTTP module cache switch, process-wide: every isolate and both fetch -// paths. A fetch reads it once, when it is issued. Off, a fetch neither reads -// nor writes the cache and sends `Cache-Control: no-cache` and -// `Pragma: no-cache`, on either transport. -// -// Enabled = the setting (app config `moduleHttpCache`, the -// nativescript-no-module-cache launch option, then ns:module -// setHttpCacheEnabled) AND no inspector client has the cache disabled. -bool ModuleHttpCacheEnabled(); -void SetModuleHttpCacheEnabled(bool enabled); -// +1 when an inspector client disables the cache, -1 when it re-enables it or -// disconnects. -void AddModuleHttpCacheInspectorDisable(int delta); - -// Wipes the module cache (ModuleHttpCache.clear()), durably, before returning. -// Throws NativeScriptException when Java reports a failure. -void ClearModuleHttpCache(); - -// Which concurrency cap a module URL's fetches share. -// kLoopback: the host is 127.0.0.1, [::1] or localhost. On a device that -// is almost always `adb reverse`, whose listener overflows under a burst -// of connects; every overflow costs the client a ~1 s SYN retry. -// kRemote: any other host, where a fetch is bound by its round trip and -// more connections in flight hide more of it. -enum class ModuleFetchHostClass { kLoopback, kRemote }; - -ModuleFetchHostClass ModuleFetchHostClassOf(const std::string& url); - -const char* ModuleFetchHostClassName(ModuleFetchHostClass hostClass); - -// How many fetches of `hostClass` run at once: `android.moduleFetchConcurrency` -// from the app config when set (validated by AppConfig.java), otherwise the -// built-in default for the class. Read from the config once per process. -size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass); - -// ───────────────────────────────────────────────────────────── -// Remote-module security gate -// -// Seeded once from nativescript.config / package.json (`security.allowRemoteModules`, -// `security.remoteModuleAllowlist`) the first time a fetch is gated. Debug -// apps always allow. These values are not readable or writable through -// ns:runtime getConfig/setConfig — only nativescript.config at boot. - -// In debug mode (Runtime.isDebuggable()): always returns true. -// Otherwise returns the boot-time `security.allowRemoteModules` value. -bool IsRemoteModulesAllowed(); - -// Whether `url` may be fetched as a remote ES module. Debug apps always -// allow. Production requires allowRemoteModules, then RemoteUrlAllowedByAllowlist. -bool IsRemoteUrlAllowed(const std::string& url); - -// The allowlist IsRemoteUrlAllowed applies once remote modules are enabled. -struct RemoteModuleAllowlist { - // False only when `security.remoteModuleAllowlist` is absent, not an - // array, or an empty array: then every URL is allowed. - bool inForce = false; - // The usable items, each spelled the way the loader spells the URLs it - // fetches (NormalizeHttpModuleUrl) so path-scoped entries compare against - // resolved paths, or kept verbatim when it is not an http(s) URL. An item - // that is not a string, is empty or has no exact UTF-8 form is not here: - // it matches nothing but still keeps the list in force. - std::vector entries; -}; - -// The allowlist for the `security.remoteModuleAllowlist` config value: nullopt -// when it is absent or not an array, otherwise its items in order, each -// nullopt when it is not a string or has no exact UTF-8 form. -RemoteModuleAllowlist RemoteModuleAllowlistFromConfig( - const std::optional>>& items); - -// Whether `url` (as fetched) passes `allowlist`: always when it is not in -// force, otherwise when one entry matches it by prefix with the match ending -// at a URL-component boundary. -bool RemoteUrlAllowedByAllowlist(const std::string& url, const RemoteModuleAllowlist& allowlist); - -// Mirrors com.tns.Runtime.isDebuggable(), cached once via the security -// config init. Fail-safe false until initialized. +// com.tns.Runtime.isDebuggable(), read once. False when it cannot be read. bool IsDebuggable(); } // namespace tns diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp index b9cd119b5..8c4bc9f27 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.cpp @@ -835,16 +835,13 @@ bool JsV8InspectorClient::handleMessageOnSocketThread(const std::string& message } std::optional JsV8InspectorClient::ClearModuleHttpCacheFromInspector() { - std::string failure = "Could not clear the HTTP module cache"; - try { - ClearModuleHttpCache(); + const CacheOpResult cleared = ClearModuleHttpCache(); + if (cleared.ok) { return std::nullopt; - } catch (NativeScriptException& e) { - const std::string detail = e.GetErrorMessage(); - if (!detail.empty()) { - failure += ": " + detail; - } - } catch (...) { + } + std::string failure = "Could not clear the HTTP module cache"; + if (!cleared.error.empty()) { + failure += ": " + cleared.error; } DEBUG_WRITE_FORCE("Network.clearBrowserCache: %s", failure.c_str()); return failure; @@ -854,21 +851,26 @@ void JsV8InspectorClient::SetCacheDisabledBy(jobject socket, bool cacheDisabled) if (socket == nullptr) { return; } + // Unique per process, as the core's holder set is. + static std::atomic nextCacheHolderId{1}; JEnv env; std::lock_guard lock(connectionMutex_); auto holder = std::find_if(cacheDisabledBy_.begin(), cacheDisabledBy_.end(), - [&](jobject held) { return env.isSameObject(held, socket); }); + [&](const CacheHolder& held) { + return env.isSameObject(held.socket, socket); + }); const bool holds = holder != cacheDisabledBy_.end(); if (cacheDisabled == holds) { return; } if (cacheDisabled) { - cacheDisabledBy_.push_back(env.NewGlobalRef(socket)); - AddModuleHttpCacheInspectorDisable(1); + const uint64_t id = nextCacheHolderId.fetch_add(1, std::memory_order_relaxed); + cacheDisabledBy_.push_back({env.NewGlobalRef(socket), id}); + SetModuleHttpCacheDisabledBy(id, true); } else { - env.DeleteGlobalRef(*holder); + SetModuleHttpCacheDisabledBy(holder->id, false); + env.DeleteGlobalRef(holder->socket); cacheDisabledBy_.erase(holder); - AddModuleHttpCacheInspectorDisable(-1); } } diff --git a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h index d091ea437..5a5128cbc 100644 --- a/test-app/runtime/src/main/cpp/JsV8InspectorClient.h +++ b/test-app/runtime/src/main/cpp/JsV8InspectorClient.h @@ -174,12 +174,16 @@ class JsV8InspectorClient : V8InspectorClient, v8_inspector::V8Inspector::Channe // memory location with the bitfields above, which the main thread // writes. std::atomic isConnected_; - // Global refs to the websockets whose frontend has the HTTP module cache - // disabled, each holding one AddModuleHttpCacheInspectorDisable count - // until it re-enables it or its socket closes. A replaced frontend's - // socket can outlive connection_, so this is not tied to it. Guarded by - // connectionMutex_. - std::vector cacheDisabledBy_; + // The websockets whose frontend has the HTTP module cache disabled, + // each a global ref and the holder id it disables the cache under + // (SetModuleHttpCacheDisabledBy) until it re-enables it or its socket + // closes. A replaced frontend's socket can outlive connection_, so this + // is not tied to it. Guarded by connectionMutex_. + struct CacheHolder { + jobject socket; + uint64_t id; + }; + std::vector cacheDisabledBy_; // {N} specific helpers diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 8e517b5e2..332a64f15 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -5054,7 +5054,7 @@ void HttpFetchDiagnosticsCallback(const v8::FunctionCallbackInfo& inf ModuleFetchHostClassOf(ArgConverter::ToString(isolate, info[0])); v8::Local result = v8::Object::New(isolate); if (!result->CreateDataProperty(context, ToV8String(isolate, "transport"), - ToV8String(isolate, ActiveModuleTransportName())) + ToV8String(isolate, nativescript::common::platform::HttpTransport().Name())) .FromMaybe(false) || !result->CreateDataProperty(context, ToV8String(isolate, "hostClass"), ToV8String(isolate, ModuleFetchHostClassName(hostClass))) @@ -5091,16 +5091,12 @@ void SetHttpCacheEnabledCallback(const v8::FunctionCallbackInfo& info } void ClearHttpCacheCallback(const v8::FunctionCallbackInfo& info) { - try { - ClearModuleHttpCache(); - } catch (NativeScriptException& e) { - e.ReThrowToV8(); - } catch (std::exception& e) { - NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); - nsEx.ReThrowToV8(); - } catch (...) { - NativeScriptException nsEx(std::string("Error: c++ exception!")); - nsEx.ReThrowToV8(); + const CacheOpResult cleared = ClearModuleHttpCache(); + if (!cleared.ok) { + v8::Isolate* isolate = info.GetIsolate(); + isolate->ThrowException(v8::Exception::Error(ToV8String( + isolate, cleared.error.empty() ? "Could not clear the HTTP module cache" + : cleared.error))); } } diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.cpp b/test-app/runtime/src/main/cpp/ModuleUrl.cpp index 31395f916..0a98251b3 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.cpp +++ b/test-app/runtime/src/main/cpp/ModuleUrl.cpp @@ -52,6 +52,14 @@ bool IsHttpRegistryKey(const std::string& key) { return key.compare(schemeEnd, 3, "://") == 0; } +std::string HttpUrlOrigin(const std::string& url) { + auto parsed = ada::parse(url, nullptr); + if (!parsed || !HasHttpScheme(*parsed)) { + return std::string(); + } + return parsed->get_origin(); +} + ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base) { ModuleUrl result; ada::result url; diff --git a/test-app/runtime/src/main/cpp/ModuleUrl.h b/test-app/runtime/src/main/cpp/ModuleUrl.h index a68388a5a..064db8882 100644 --- a/test-app/runtime/src/main/cpp/ModuleUrl.h +++ b/test-app/runtime/src/main/cpp/ModuleUrl.h @@ -34,6 +34,11 @@ ModuleUrl ParseModuleUrl(const std::string& input, const std::string& base); // not an http(s) URL. std::string NormalizeHttpModuleUrl(const std::string& input); +// The WHATWG origin (`scheme://host[:port]`, default port omitted, host +// lowercased) of an absolute http(s) URL; empty for anything else. Never part +// of a module's identity, which keeps the authority as written. +std::string HttpUrlOrigin(const std::string& url); + // The key the blob URL store is looked up by for `input`, per the File API's // blob URL resolution: the URL serialized without its fragment, a query kept. // Empty when `input` is not an absolute blob: URL. diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp new file mode 100644 index 000000000..70340f0bd --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp @@ -0,0 +1,45 @@ +// The platform functions of the shared core (ns/Platform.h). The HTTP loader's +// (ReadHttpLoaderConfig, HttpTransport) are in HttpLoader.cpp, next to the +// transport. + +#include +#include + +#include "ModuleUrl.h" +#include "NativeScriptAssert.h" +#include "TraceLog.h" +#include "ns/Platform.h" + +namespace nativescript::common::platform { + +namespace { + +tns::LogCategory ToLogCategory(TraceCategory category) { + return category == TraceCategory::kFetch ? tns::LogCategory::Fetch : tns::LogCategory::Esm; +} + +} // namespace + +void Log(std::string_view message) { + const std::string line(message); + DEBUG_WRITE_FORCE("%s", line.c_str()); +} + +bool TraceEnabled(TraceCategory category) { + return tns::LogCategoryEnabled(ToLogCategory(category)); +} + +void Trace(TraceCategory category, std::string_view message) { + const std::string line(message); + tns::EmitDebugLog(ToLogCategory(category), "%s", line.c_str()); +} + +std::string NormalizeHttpModuleUrl(const std::string& input) { + return tns::NormalizeHttpModuleUrl(input); +} + +std::string HttpUrlOrigin(const std::string& url) { + return tns::HttpUrlOrigin(url); +} + +} // namespace nativescript::common::platform diff --git a/test-app/runtime/src/main/cpp/runtime-common b/test-app/runtime/src/main/cpp/runtime-common index 49dd52bc9..3ebf3bc80 160000 --- a/test-app/runtime/src/main/cpp/runtime-common +++ b/test-app/runtime/src/main/cpp/runtime-common @@ -1 +1 @@ -Subproject commit 49dd52bc926997bcaa15eebc08ae9c7815feac02 +Subproject commit 3ebf3bc8078fd5372bf172d84750d876fa9d3bae diff --git a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java index 24e895265..faec25761 100644 --- a/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java +++ b/test-app/runtime/src/main/java/com/tns/ModuleHttpCache.java @@ -6,14 +6,15 @@ import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; +import java.util.ArrayList; import java.util.List; import java.util.Map; /** * The HTTP module loader's cache controls on the Java side: the startup state - * (app config + launch options), wiping the cache, and the Clear-Site-Data - * response header. The live on/off switch is native (HttpLoader.cpp), which - * reads {@link #isEnabledAtStartup()} once. + * (app config + launch options) and clearing the cache. The live on/off switch + * and Clear-Site-Data are native; the loader reads {@link #isEnabledAtStartup()} + * once. * * Only the OkHttp transport has a cache. Wipes still clear the on-disk * directory when OkHttp is absent or its client was never created, since an @@ -88,7 +89,7 @@ private static boolean consumeLaunchOption(String appName, String option) { /** Wipes the whole module cache. Durable once this returns. */ static void clear() throws IOException { synchronized (LOCK) { - if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(null)) { + if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache()) { return; } File dir = Runtime.getModuleHttpCacheDir(); @@ -99,69 +100,30 @@ static void clear() throws IOException { } /** - * Clears what the cache holds for {@code url}'s origin, or the whole cache - * when there is no open cache to pick one origin's entries from. + * Removes what the open cache holds for {@code origin} (a WHATWG origin such + * as {@code https://example.com:8443}). Durable once this returns. Without an + * open cache there is nothing to remove. */ - static void clearOrigin(String url) throws IOException { + static void clearOrigin(String origin) throws IOException { synchronized (LOCK) { - if (OkHttpModuleFetcher.isAvailable() && OkHttpModuleFetcher.clearClientCache(url)) { - return; + if (OkHttpModuleFetcher.isAvailable()) { + OkHttpModuleFetcher.clearClientCacheOrigin(origin); } - clear(); - } - } - - /** - * Honours Clear-Site-Data on a module response. Call once the response body - * was read and closed: the cache commits an entry when its body closes, and - * the carrier's own entry must not survive, or every hit on it would clear - * the cache again. - */ - static void onClearSiteData(List headerValues, String responseUrl) { - if (!clearSiteDataClearsCache(headerValues)) { - return; - } - try { - clearOrigin(responseUrl); - } catch (IOException | RuntimeException e) { - Log.w("JS", "HTTP modules: could not honour Clear-Site-Data from " + responseUrl + ": " + e); } } - /** {@link #onClearSiteData} for the platform transport. */ - static void onPlatformResponse(HttpURLConnection connection) { + /** Every Clear-Site-Data value of the platform transport's response, unparsed. */ + static String[] clearSiteDataValues(HttpURLConnection connection) { + List values = new ArrayList<>(); Map> fields = connection.getHeaderFields(); - if (fields == null) { - return; - } - for (Map.Entry> field : fields.entrySet()) { - if ("Clear-Site-Data".equalsIgnoreCase(field.getKey())) { - onClearSiteData(field.getValue(), connection.getURL().toString()); - } - } - } - - /** - * Whether Clear-Site-Data header lines name the {@code "cache"} or - * {@code "*"} type. Types are quoted strings; an unquoted one is ignored, - * as browsers do. - */ - static boolean clearSiteDataClearsCache(List values) { - if (values == null) { - return false; - } - for (String value : values) { - if (value == null) { - continue; - } - for (String type : value.split(",")) { - String trimmed = type.trim(); - if (trimmed.equals("\"cache\"") || trimmed.equals("\"*\"")) { - return true; + if (fields != null) { + for (Map.Entry> field : fields.entrySet()) { + if ("Clear-Site-Data".equalsIgnoreCase(field.getKey()) && field.getValue() != null) { + values.addAll(field.getValue()); } } } - return false; + return values.toArray(new String[0]); } private static void deleteContents(File dir) throws IOException { diff --git a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java index 5d14665e1..db990fe3e 100644 --- a/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java +++ b/test-app/runtime/src/main/java/com/tns/OkHttpModuleFetcher.java @@ -6,7 +6,7 @@ /** * The HTTP module loader's transport when the app ships OkHttp (okhttp3), driven - * synchronously from HttpLoader's fetch threads over JNI. + * synchronously over JNI by the native transport in HttpLoader.cpp. * * okhttp3 is compileOnly: {@link #isAvailable()} must answer true before * anything else here runs. Outside the private nested Client class no field or @@ -19,16 +19,24 @@ private OkHttpModuleFetcher() { private static final long CACHE_MAX_BYTES = 256L * 1024 * 1024; - /** Read by HttpLoader through JNI. {@code body} is null when reading the body failed. */ + /** + * Read by HttpLoader through JNI. {@code body} is null when reading the body + * failed. {@code clearSiteData} holds every Clear-Site-Data value of the final + * response, unparsed. + */ static final class Result { final int status; final String contentType; final byte[] body; + final String finalUrl; + final String[] clearSiteData; - Result(int status, String contentType, byte[] body) { + Result(int status, String contentType, byte[] body, String finalUrl, String[] clearSiteData) { this.status = status; this.contentType = contentType; this.body = body; + this.finalUrl = finalUrl; + this.clearSiteData = clearSiteData; } } @@ -51,18 +59,18 @@ static boolean isAvailable() { } /** - * One GET of {@code url}, following redirects within the same protocol. - * {@code timeoutMs} bounds the connect and each read; {@code defaultTimeoutMs} - * and {@code maxIdleConnections} configure the shared client on the first call - * only. {@code useCache} false neither reads nor writes the cache and asks - * every cache on the way for a fresh response. Null, without throwing, when - * this OkHttp version is missing a call used here; {@link #isAvailable()} is - * false from then on. + * One GET of {@code url}, following redirects within the same protocol, with + * {@code headers} (alternating names and values) added in order. + * {@code timeoutMs} bounds the connect and each read; the shared client is + * configured with the first call's {@code timeoutMs} and + * {@code maxIdleConnections}. {@code useCache} false neither reads nor writes + * the cache. Null, without throwing, when this OkHttp version is missing a + * call used here; {@link #isAvailable()} is false from then on. */ - static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections, + static Result fetch(String url, String[] headers, int timeoutMs, int maxIdleConnections, boolean useCache) throws IOException { try { - return Client.fetch(url, timeoutMs, defaultTimeoutMs, maxIdleConnections, useCache); + return Client.fetch(url, headers, timeoutMs, maxIdleConnections, useCache); } catch (LinkageError e) { available = false; android.util.Log.w("JS", "HTTP modules: the app's OkHttp is incompatible; using HttpURLConnection instead: " + e); @@ -71,21 +79,32 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle } /** - * Empties the client's cache, or only its entries with the same scheme, host - * and port as {@code sameOriginAs} when that is not null. False when there is - * no client yet, no cache to clear through it, or {@code sameOriginAs} is not - * an HTTP URL; the caller then deletes the files itself. Call under + * Empties the client's cache. False when there is no client yet or no cache + * to clear through it; the caller then deletes the files itself. Call under * {@link ModuleHttpCache#LOCK}. */ - static boolean clearClientCache(String sameOriginAs) throws IOException { + static boolean clearClientCache() throws IOException { try { - return Client.clearCache(sameOriginAs); + return Client.clearCache(); } catch (LinkageError e) { available = false; return false; } } + /** + * Removes the client's cache entries whose URL has the scheme, host and port + * of {@code origin}. Nothing to do when there is no client yet or it has no + * cache. Call under {@link ModuleHttpCache#LOCK}. + */ + static void clearClientCacheOrigin(String origin) throws IOException { + try { + Client.clearCacheOrigin(origin); + } catch (LinkageError e) { + available = false; + } + } + private static final class Client { // An okhttp3.OkHttpClient, typed Object to keep okhttp3 out of member // signatures. Never an app-configured client: its interceptors, cache @@ -130,42 +149,48 @@ private static void create(int timeoutMs, int maxIdleConnections) { client = built; } - static boolean clearCache(String sameOriginAs) throws IOException { + private static okhttp3.Cache openCache() { Object created = client; - okhttp3.Cache cache = created != null ? ((okhttp3.OkHttpClient) created).cache() : null; + return created != null ? ((okhttp3.OkHttpClient) created).cache() : null; + } + + static boolean clearCache() throws IOException { + okhttp3.Cache cache = openCache(); if (cache == null) { return false; } + // Removing an entry deletes its files at once, so the wipe outlives + // a process kill; the flush also persists the journal's record of it. + cache.evictAll(); + cache.flush(); + return true; + } + + static void clearCacheOrigin(String origin) throws IOException { + okhttp3.Cache cache = openCache(); + if (cache == null) { + return; + } // Cache keys are HttpUrl strings, which can hold characters // java.net.URI rejects, such as a raw | in the query. - okhttp3.HttpUrl origin = null; - if (sameOriginAs != null) { - origin = okhttp3.HttpUrl.parse(sameOriginAs); - if (origin == null) { - return false; - } + okhttp3.HttpUrl originUrl = okhttp3.HttpUrl.parse(origin); + if (originUrl == null) { + throw new IOException("not an HTTP origin: " + origin); } - // Removing an entry deletes its files at once, so the wipe outlives - // a process kill; the flush also persists the journal's record of it. - if (origin == null) { - cache.evictAll(); - } else { - for (java.util.Iterator urls = cache.urls(); urls.hasNext(); ) { - okhttp3.HttpUrl entry = okhttp3.HttpUrl.parse(urls.next()); - if (entry != null && entry.port() == origin.port() - && entry.scheme().equals(origin.scheme()) - && entry.host().equals(origin.host())) { - urls.remove(); - } + for (java.util.Iterator urls = cache.urls(); urls.hasNext(); ) { + okhttp3.HttpUrl entry = okhttp3.HttpUrl.parse(urls.next()); + if (entry != null && entry.port() == originUrl.port() + && entry.scheme().equals(originUrl.scheme()) + && entry.host().equals(originUrl.host())) { + urls.remove(); } } cache.flush(); - return true; } - static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdleConnections, + static Result fetch(String url, String[] headers, int timeoutMs, int maxIdleConnections, boolean useCache) throws IOException { - okhttp3.OkHttpClient http = base(defaultTimeoutMs, maxIdleConnections, useCache); + okhttp3.OkHttpClient http = base(timeoutMs, maxIdleConnections, useCache); if (timeoutMs != clientTimeoutMs) { // Shares the pool, and the cache if any, with the base client. http = http.newBuilder() @@ -173,17 +198,13 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle .readTimeout(timeoutMs, TimeUnit.MILLISECONDS) .build(); } - okhttp3.Request.Builder request = new okhttp3.Request.Builder() - .url(url) - .header("Accept", "application/javascript, text/javascript, */*;q=0.1") - // Also turns off OkHttp's transparent gzip. - .header("Accept-Encoding", "identity") - .header("User-Agent", "NativeScript-HTTP-ESM"); - if (!useCache) { - request.header("Cache-Control", "no-cache").header("Pragma", "no-cache"); + // An Accept-Encoding among the headers also turns off OkHttp's + // transparent gzip. + okhttp3.Request.Builder request = new okhttp3.Request.Builder().url(url); + for (int i = 0; i + 1 < headers.length; i += 2) { + request.addHeader(headers[i], headers[i + 1]); } okhttp3.Response response = http.newCall(request.build()).execute(); - Result result; try { byte[] body; okhttp3.ResponseBody responseBody = response.body(); @@ -196,13 +217,16 @@ static Result fetch(String url, int timeoutMs, int defaultTimeoutMs, int maxIdle body = null; } } - result = new Result(response.code(), response.header("Content-Type"), body); + // Unredirected, the URL stays as requested: HttpUrl respells it + // (lowercase host, no default port), and the loader checks the + // final URL against its own spelling. + String finalUrl = response.priorResponse() == null + ? url : response.request().url().toString(); + return new Result(response.code(), response.header("Content-Type"), body, finalUrl, + response.headers("Clear-Site-Data").toArray(new String[0])); } finally { response.close(); } - ModuleHttpCache.onClearSiteData(response.headers("Clear-Site-Data"), - response.request().url().toString()); - return result; } } } From 21083473395a9f36b519b836ca041560d879af79 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:02:17 -0300 Subject: [PATCH 03/45] build: pin runtime-common foundation and implement its platform functions Pins the core at e1c85ea (foundation headers and the Loop interface) and implements the platform functions it declares: Loader() (filled once from Runtime::Init on the main runtime's thread), ApplyThreadPriority, RunJob, IsRuntimeAlive, MainContext and StateBag, a core IsolateStateBag owned by the Runtime and closed right after RuntimeState at the end of teardown. TraceCategory::kRegistry maps to the registry log category. The stream-compile flags now come from the core's V8FlagsDisableLazyCompile and BackgroundCompileStackBytes; the private copies are gone. Every catch ladder the loader reaches learns JsError (rethrown to V8, or reported to Java by message where no isolate scope is open) and Terminated (nothing to report), ahead of its generic clauses. --- test-app/runtime/src/main/cpp/EventLoop.cpp | 11 ++ .../runtime/src/main/cpp/ModuleInternal.cpp | 9 ++ .../src/main/cpp/ModuleInternalCallbacks.cpp | 127 +++++++----------- test-app/runtime/src/main/cpp/Runtime.cpp | 6 + test-app/runtime/src/main/cpp/Runtime.h | 11 ++ .../src/main/cpp/RuntimeCommonPlatform.cpp | 78 ++++++++++- .../src/main/cpp/RuntimeCommonPlatform.h | 16 +++ .../runtime/src/main/cpp/WorkerWrapper.cpp | 12 ++ .../runtime/src/main/cpp/com_tns_Runtime.cpp | 10 ++ test-app/runtime/src/main/cpp/runtime-common | 2 +- 10 files changed, 197 insertions(+), 85 deletions(-) create mode 100644 test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h diff --git a/test-app/runtime/src/main/cpp/EventLoop.cpp b/test-app/runtime/src/main/cpp/EventLoop.cpp index df6a28c43..794a9fdaa 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.cpp +++ b/test-app/runtime/src/main/cpp/EventLoop.cpp @@ -17,6 +17,7 @@ #include "JniLocalRef.h" #include "NativeScriptAssert.h" #include "NativeScriptException.h" +#include "ns/JsError.h" using namespace v8; @@ -46,6 +47,10 @@ void RunGuarded(F&& body) { body(); } catch (tns::NativeScriptException& ex) { ex.ReThrowToJava(); + } catch (nativescript::common::JsError& ex) { + // No isolate scope is open here to build its JS value in. + tns::NativeScriptException(ex.message()).ReThrowToJava(); + } catch (nativescript::common::Terminated&) { } catch (std::exception& ex) { DEBUG_WRITE_FORCE("Error: c++ exception in event loop task: %s", ex.what()); } catch (...) { @@ -614,6 +619,9 @@ void EventLoop::GuardEntryRun(const std::function& body) { // what() may read a JNI local ref that cannot outlive this dispatch, // so only its text is carried DeferJavaThrow(std::make_shared(std::string(ex.what()))); + } catch (nativescript::common::JsError& ex) { + DeferJavaThrow(std::make_shared(ex.message())); + } catch (nativescript::common::Terminated&) { } catch (std::exception& ex) { DEBUG_WRITE_FORCE("Error: c++ exception in event loop task: %s", ex.what()); } catch (...) { @@ -946,6 +954,9 @@ extern "C" JNIEXPORT void JNICALL Java_com_tns_EventLoopHandler_nativeRunTask( loop->ReportDeferredJavaError(); } catch (tns::NativeScriptException& e) { e.ReThrowToJava(); + } catch (nativescript::common::JsError& e) { + tns::NativeScriptException(e.message()).ReThrowToJava(); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { std::string msg = std::string("Error: c++ exception: ") + e.what(); tns::NativeScriptException nsEx(msg); diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 5ec3645f6..e1d595751 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -26,6 +26,7 @@ #include "Runtime.h" #include "RuntimeState.h" #include "TraceLog.h" +#include "ns/JsError.h" #include #include #include @@ -455,6 +456,10 @@ void ModuleInternal::DispatchRequire(const v8::FunctionCallbackInfo& thiz->RequireCallbackImpl(args, honorEvaluationOptions); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { + // The isolate is going away; there is nothing for JS to observe. } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; @@ -631,6 +636,10 @@ void ModuleInternal::LoadWorker(Local context, const string& path) { Load(context, path); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { + // A terminating worker reports nothing to its onerror. } if (tc.HasCaught()) { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 332a64f15..07837d58d 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -42,6 +42,8 @@ #include "RuntimeState.h" #include "TraceLog.h" #include "robin_hood.h" +#include "ns/JsError.h" +#include "ns/V8Flags.h" using namespace v8; using namespace std; @@ -1904,78 +1906,6 @@ class StreamCompilePool { unsigned maxThreads_ = 1; }; -// `flags` split the way V8's SetFlagsFromString splits them: on whitespace, -// with nothing after a bare "--". V8 has no public flag getter. -std::vector V8FlagArgs(const std::string& flags) { - static constexpr const char* kSpace = " \t\n\v\f\r"; - std::vector args; - size_t pos = 0; - while (pos < flags.size()) { - const size_t start = flags.find_first_not_of(kSpace, pos); - if (start == std::string::npos) break; - size_t end = flags.find_first_of(kSpace, start); - if (end == std::string::npos) end = flags.size(); - pos = end; - std::string arg = flags.substr(start, end - start); - if (arg == "--") break; - args.push_back(std::move(arg)); - } - return args; -} - -// Whether `flags` turn lazy compilation off, read the way V8 reads a bool -// flag: an optional second dash, a "no"/"no-" negation, `_` and `-` alike, the -// last occurrence winning. -bool FlagsDisableLazyCompile(const std::string& flags) { - bool lazy = true; - for (std::string arg : V8FlagArgs(flags)) { - if (arg.size() < 2 || arg[0] != '-') continue; - std::replace(arg.begin(), arg.end(), '_', '-'); - size_t name = arg[1] == '-' ? 2 : 1; - bool negated = false; - if (arg.compare(name, 2, "no") == 0) { - name += 2; - if (name < arg.size() && arg[name] == '-') name++; - negated = true; - } - if (arg.compare(name, std::string::npos, "lazy") == 0 || - arg.compare(name, 5, "lazy=") == 0) { - lazy = !negated; - } - } - return !lazy; -} - -// The --stack-size (in KB) that `flags` set, read the way V8 reads an int -// flag: an optional second dash, `_` and `-` alike, the value after '=' or as -// the next argument, the last occurrence winning. 0 when none is set. -size_t FlagsStackSizeKb(const std::string& flags) { - const std::vector args = V8FlagArgs(flags); - size_t kb = 0; - for (size_t i = 0; i < args.size(); i++) { - std::string arg = args[i]; - if (arg.size() < 2 || arg[0] != '-') continue; - std::replace(arg.begin(), arg.end(), '_', '-'); - const size_t name = arg[1] == '-' ? 2 : 1; - std::string value; - if (arg.compare(name, std::string::npos, "stack-size") == 0) { - if (i + 1 >= args.size()) break; - value = args[++i]; - } else if (arg.compare(name, 11, "stack-size=") == 0) { - value = arg.substr(name + 11); - } else { - continue; - } - char* end = nullptr; - errno = 0; - const long long parsed = std::strtoll(value.c_str(), &end, 10); - if (errno == 0 && end != value.c_str() && *end == '\0' && parsed > 0) { - kb = static_cast(parsed); - } - } - return kb; -} - // Isolate's Locker, 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. @@ -2087,16 +2017,8 @@ bool DispatchStreamedCompile(const std::shared_ptr& load, } // namespace void NoteAppliedV8Flags(const std::string& flags) { - g_eagerStreamedCompiles = FlagsDisableLazyCompile(flags); - // Room for the frames above Run() and the guard page, as the 2 MB floor - // leaves for V8's default --stack-size. - constexpr size_t kHeadroomBytes = 1024 * 1024; - constexpr size_t kMinStackBytes = 2 * 1024 * 1024; - const size_t stackKb = FlagsStackSizeKb(flags); - const size_t maxKb = (SIZE_MAX - kHeadroomBytes) / 1024; - g_streamCompileStackBytes = - stackKb == 0 ? kMinStackBytes - : std::max(kMinStackBytes, std::min(stackKb, maxKb) * 1024 + kHeadroomBytes); + g_eagerStreamedCompiles = nativescript::common::V8FlagsDisableLazyCompile(flags); + g_streamCompileStackBytes = nativescript::common::BackgroundCompileStackBytes(flags); } bool HasPendingAsyncModuleGraphWork() { @@ -2403,6 +2325,12 @@ static void AsyncGraphCompileLocalModule( TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", path.c_str(), ex.GetErrorMessage().c_str()); return; + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[graph][local-compile-fail] %s %s (left to the resolver)", + path.c_str(), ex.what()); + return; + } catch (nativescript::common::Terminated&) { + return; } if (!compiled) { TNS_DEBUG(Esm, "[graph][local-compile-fail] %s (left to the resolver)", @@ -3577,6 +3505,13 @@ static v8::MaybeLocal LoadResolvedModule( resolution.specifier.c_str(), absPath.c_str()); ex.ReThrowToV8(); return v8::MaybeLocal(); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[resolver] failed to compile '%s' -> '%s'", + resolution.specifier.c_str(), absPath.c_str()); + ex.ThrowToV8(isolate); + return v8::MaybeLocal(); + } catch (nativescript::common::Terminated&) { + return v8::MaybeLocal(); } } @@ -3916,6 +3851,14 @@ static void SettleDynamicImport(v8::Isolate* isolate, v8::Local con isolate, "Native error during dynamic import")); nativeTc.Reset(); resolver->Reject(context, error).FromMaybe(false); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[dyn-import] native failed %s", normalizedSpec.c_str()); + v8::Local error = ex.ToV8(isolate); + if (!error.IsEmpty()) { + resolver->Reject(context, error).FromMaybe(false); + } + } catch (nativescript::common::Terminated&) { + // A terminating isolate cannot settle the promise; it is never observed. } } @@ -4678,6 +4621,14 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( isolate, "Native error during dynamic import")); nativeTc.Reset(); resolver->Reject(context, error).FromMaybe(false); + } catch (nativescript::common::JsError& ex) { + TNS_DEBUG(Esm, "[dyn-import] native failed %s", normalizedSpec.c_str()); + v8::Local error = ex.ToV8(isolate); + if (!error.IsEmpty()) { + resolver->Reject(context, error).FromMaybe(false); + } + } catch (nativescript::common::Terminated&) { + // A terminating isolate cannot settle the promise; it is never observed. } return scope.Escape(resolver->GetPromise()); @@ -4951,6 +4902,9 @@ void ConfigureLoaderCallback(const v8::FunctionCallbackInfo& info) { } } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -5006,6 +4960,9 @@ void InvalidateModulesCallback(const v8::FunctionCallbackInfo& info) tns::InvalidateModules(isolate, ctx, urls); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -5031,6 +4988,9 @@ void GetLoadedModuleUrlsCallback(const v8::FunctionCallbackInfo& info info.GetReturnValue().Set(result); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(isolate); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -5135,6 +5095,9 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local info.GetReturnValue().Set(ToV8String(iso, key)); } catch (NativeScriptException& e) { e.ReThrowToV8(); + } catch (nativescript::common::JsError& e) { + e.ThrowToV8(iso); + } catch (nativescript::common::Terminated&) { } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index ce708f91a..817f01680 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -37,6 +37,7 @@ #include "NativeScriptAssert.h" #include "NativeScriptException.h" #include "NativeScriptPlatform.h" +#include "RuntimeCommonPlatform.h" #include "RuntimeState.h" #include "napi/NapiEnv.h" #include "Performance.h" @@ -147,6 +148,7 @@ Runtime::Runtime(JNIEnv* env, jobject runtime, int id) m_runtime = env->NewGlobalRef(runtime); m_objectManager = new ObjectManager(m_runtime); m_state = std::make_unique(); + m_stateBag = std::make_unique(); RuntimeGates::Open(id, this); { std::lock_guard lock(s_runtimeCacheMutex); @@ -233,6 +235,7 @@ void Runtime::Init(JNIEnv* env, jstring filesPath, jstring nativeLibDir, Constants::APP_ROOT_FOLDER_PATH = filesRoot + "/app/"; Constants::V8_STARTUP_FLAGS = options.v8Flags; Constants::V8_CACHE_COMPILED_CODE = options.codeCache; + InitLoaderConfig(filesRoot + "/app"); m_discardUncaughtJsExceptions = options.discardUncaughtJsExceptions; // AppConfig validates and warns about unknown values; anything that is not // "throw" behaves as the default. @@ -1371,6 +1374,9 @@ void Runtime::DestroyRuntime() { if (m_state != nullptr) { m_state->Clear(); } + if (m_stateBag != nullptr) { + m_stateBag->Close(); + } // New pins are refused from here on; the isolate is disposed only once the // threads already pinned have let go. diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 32aa95b2e..502953998 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -14,6 +14,7 @@ #include "Timers.h" #include "EventLoop.h" #include "AdmissionGate.h" +#include "ns/IsolateStateBag.h" #include #include #include @@ -183,6 +184,14 @@ class Runtime { return m_state.get(); } + /* + * The shared core's per-isolate state (ns/IsolateState.h). Closed in + * DestroyRuntime after RuntimeState, while the isolate is still alive. + */ + nativescript::common::IsolateStateBag* GetStateBag() const { + return m_stateBag.get(); + } + bool IsMainThread() const { return m_isMainThread; } @@ -421,6 +430,8 @@ class Runtime { std::unique_ptr m_state; + std::unique_ptr m_stateBag; + napi_env m_napiEnv = nullptr; v8::Global m_globalEventTarget; diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp index 70340f0bd..eae5aac34 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp @@ -1,21 +1,67 @@ -// The platform functions of the shared core (ns/Platform.h). The HTTP loader's +// The platform functions of the shared core (ns/Platform.h and the other +// headers that declare a `platform` namespace). The HTTP loader's // (ReadHttpLoaderConfig, HttpTransport) are in HttpLoader.cpp, next to the // transport. +#include "RuntimeCommonPlatform.h" + +#include + +#include #include #include +#include +#include "Constants.h" +#include "HttpLoader.h" #include "ModuleUrl.h" #include "NativeScriptAssert.h" +#include "Runtime.h" #include "TraceLog.h" +#include "ns/IsolateState.h" +#include "ns/LoaderConfig.h" #include "ns/Platform.h" +#include "ns/RuntimeAccess.h" +#include "ns/Thread.h" + +namespace { + +nativescript::common::LoaderConfig g_loaderConfig; + +} // namespace + +namespace tns { + +void InitLoaderConfig(std::string appRoot) { + static std::once_flag once; + std::call_once(once, [&appRoot] { + nativescript::common::LoaderConfig config; + config.appRoot = std::move(appRoot); + config.isDebug = IsDebuggable(); + config.codeCacheEnabled = Constants::V8_CACHE_COMPILED_CODE && !config.isDebug; + // Caches are written next to their source file, so there is no cache + // directory to name. + config.v8Flags = Constants::V8_STARTUP_FLAGS; + g_loaderConfig = std::move(config); + }); +} + +} // namespace tns namespace nativescript::common::platform { namespace { tns::LogCategory ToLogCategory(TraceCategory category) { - return category == TraceCategory::kFetch ? tns::LogCategory::Fetch : tns::LogCategory::Esm; + switch (category) { + case TraceCategory::kEsm: + return tns::LogCategory::Esm; + case TraceCategory::kFetch: + return tns::LogCategory::Fetch; + case TraceCategory::kRegistry: + return tns::LogCategory::Registry; + } + return tns::LogCategory::Esm; } } // namespace @@ -42,4 +88,32 @@ std::string HttpUrlOrigin(const std::string& url) { return tns::HttpUrlOrigin(url); } +const LoaderConfig& Loader() { + return g_loaderConfig; +} + +void ApplyThreadPriority(ThreadPriority priority) { + if (priority == ThreadPriority::kUtility) { + // On Linux PRIO_PROCESS with who == 0 names the calling thread only. + setpriority(PRIO_PROCESS, 0, 10); + } +} + +void RunJob(const std::function& job) { + job(); +} + +bool IsRuntimeAlive(v8::Isolate* isolate) { + return tns::Runtime::TryGetRuntime(isolate) != nullptr; +} + +v8::Local MainContext(v8::Isolate* isolate) { + return tns::Runtime::TryGetRuntime(isolate)->GetContext(); +} + +IsolateStateBag* StateBag(v8::Isolate* isolate) { + tns::Runtime* runtime = tns::Runtime::TryGetRuntime(isolate); + return runtime != nullptr ? runtime->GetStateBag() : nullptr; +} + } // namespace nativescript::common::platform diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h new file mode 100644 index 000000000..649806584 --- /dev/null +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h @@ -0,0 +1,16 @@ +#ifndef RUNTIME_COMMON_PLATFORM_H_ +#define RUNTIME_COMMON_PLATFORM_H_ + +#include + +namespace tns { + +// Fills what nativescript::common::platform::Loader() returns. Only the first +// call takes effect: it must come from the main runtime's thread before its +// isolate exists, because it reads the debug flag over JNI and the core reads +// the config from threads that cannot attach to the JVM. +void InitLoaderConfig(std::string appRoot); + +} // namespace tns + +#endif // RUNTIME_COMMON_PLATFORM_H_ diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index bd8f871be..2ea2de458 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -21,6 +21,7 @@ #include "NativeScriptPlatform.h" #include "Runtime.h" #include "WorkerEvents.h" +#include "ns/JsError.h" #include @@ -698,6 +699,17 @@ void WorkerWrapper::BackgroundLooper(std::shared_ptr self) { if (!isTerminating_) { PassUncaughtExceptionFromWorkerToParent(ex.GetErrorMessage(), workerPath_, "", 0); } + } catch (nativescript::common::JsError& ex) { + if (jniEnv->ExceptionCheck()) { + jniEnv->ExceptionClear(); + } + if (!isTerminating_) { + PassUncaughtExceptionFromWorkerToParent(ex.message(), workerPath_, "", 0); + } + } catch (nativescript::common::Terminated&) { + if (jniEnv->ExceptionCheck()) { + jniEnv->ExceptionClear(); + } } catch (std::exception& ex) { DEBUG_WRITE_FORCE("Worker(id=%d) error: c++ exception: %s", workerId_, ex.what()); } catch (...) { diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 7e013259b..3c06c4264 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -11,6 +11,7 @@ #include "ModuleUrl.h" #include "ModuleInternal.h" #include "EventLoop.h" +#include "ns/JsError.h" #include #include #include @@ -232,6 +233,15 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_runModule(JNIEnv* _env, jobject o runtime->RunModule(_env, obj, scriptFile); } catch (NativeScriptException& e) { e.ReThrowToJava(); + } catch (nativescript::common::JsError& e) { + v8::Local error = e.ToV8(isolate); + if (error.IsEmpty()) { + NativeScriptException(e.message()).ReThrowToJava(); + } else { + NativeScriptException(isolate, error, e.message()).ReThrowToJava(); + } + } catch (nativescript::common::Terminated&) { + // A terminated boot has no outcome to report. } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; diff --git a/test-app/runtime/src/main/cpp/runtime-common b/test-app/runtime/src/main/cpp/runtime-common index 3ebf3bc80..e1c85ea28 160000 --- a/test-app/runtime/src/main/cpp/runtime-common +++ b/test-app/runtime/src/main/cpp/runtime-common @@ -1 +1 @@ -Subproject commit 3ebf3bc8078fd5372bf172d84750d876fa9d3bae +Subproject commit e1c85ea2801fff4611dc158b40eb1029c877044c From 89b9580453d9bff81a0ec7abff7f6c2a92e3f201 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:05:02 -0300 Subject: [PATCH 04/45] feat(runtime): pump through Loop::PumpUntil tns::EventLoop implements nativescript::common::Loop. PumpUntil takes a monotonic Deadline and a PumpMode, replacing both PumpUntil(seconds, settled, drainLooperWork) and PumpNestableV8TasksUntil: kPlatformWork is the looper-equivalent drain, kV8Tasks the nestable-tasks-plus-checkpoint drain, kNestableOnly the quiet drain with microtasks suppressed. A null idle in kNestableOnly falls back to WaitForInternalWork. The head check follows the interface: a stopped loop counts as termination and is now checked before settled, not after it. PostInternal and PostInternalDelayed report a dropped post. LoopFor resolves through the platform's loop registry. A worker's loop is marked termination-requested before TerminateExecution, both in Terminate() and in the near-heap-limit callback. The boot backstop polls the entry without stringifying its rejection reason inside the pump, and reads the reason once the pump returns. --- test-app/runtime/src/main/cpp/EventLoop.cpp | 105 ++++++++---------- test-app/runtime/src/main/cpp/EventLoop.h | 89 +++++++-------- .../runtime/src/main/cpp/ModuleInternal.cpp | 7 +- .../src/main/cpp/ModuleInternalCallbacks.cpp | 27 ++--- .../src/main/cpp/ModuleInternalCallbacks.h | 7 +- test-app/runtime/src/main/cpp/Runtime.cpp | 17 ++- .../src/main/cpp/RuntimeCommonPlatform.cpp | 7 ++ .../runtime/src/main/cpp/WorkerWrapper.cpp | 13 ++- 8 files changed, 131 insertions(+), 141 deletions(-) diff --git a/test-app/runtime/src/main/cpp/EventLoop.cpp b/test-app/runtime/src/main/cpp/EventLoop.cpp index 794a9fdaa..2a2ce2652 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.cpp +++ b/test-app/runtime/src/main/cpp/EventLoop.cpp @@ -271,20 +271,22 @@ void EventLoop::PostOrderedLocked(Entry entry, double delayMs) { } } -void EventLoop::PostInternal(std::function fn) { +bool EventLoop::PostInternal(std::function fn) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, 0); + return true; } -void EventLoop::PostInternalDelayed(std::function fn, double delayMs) { +bool EventLoop::PostInternalDelayed(std::function fn, double delayMs) { std::lock_guard lock(mutex_); if (stopped_) { - return; + return false; } PostInternalLocked(Entry{nullptr, std::move(fn), true, false, 0}, delayMs); + return true; } void EventLoop::PostInternalBare(std::function fn) { @@ -743,37 +745,54 @@ int EventLoop::RunDueOrderedEntries() { return ran; } -EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, - const std::function& settled, - bool drainLooperWork) { +nativescript::common::PumpResult EventLoop::PumpUntil( + const nativescript::common::Deadline& deadline, const std::function& settled, + nativescript::common::PumpMode mode, const std::function& idle) { + using nativescript::common::PumpMode; + using nativescript::common::PumpResult; // home thread only: the drains below take ordered/timer slots and eventfd // units that the looper's own dispatch owns on that thread NS_DCHECK(looper_ == nullptr || ALooper_forThread() == looper_); PumpScope pumpScope; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::duration(deadlineSeconds); + const bool platformWork = mode == PumpMode::kPlatformWork; for (;;) { - // Both probes: IsExecutionTerminating is true only while JS frames - // unwind with the termination exception active, so a pump parked with - // nothing queued would never observe TerminateExecution through it. - // Termination outranks settlement: consuming a settled result means - // running more JS, which a terminating isolate must not do. - if (terminationRequested_.load(std::memory_order_acquire) || - isolate_->IsExecutionTerminating()) { + // IsExecutionTerminating is true only while JS frames unwind with the + // termination exception active, so a pump parked with nothing queued + // would never observe TerminateExecution through it; the flag covers + // that. A stopped loop drops every post, so nothing can settle + // anymore. Termination outranks settlement: consuming a settled + // result means running more JS, which a terminating isolate must not + // do. + if (TerminationRequested() || isolate_->IsExecutionTerminating() || IsStopped()) { return PumpResult::kTerminated; } if (settled()) { return PumpResult::kSettled; } - if (IsStopped()) { - // a stopped loop drops every post, so nothing can settle anymore - return PumpResult::kTerminated; - } - if (std::chrono::steady_clock::now() >= deadline) { + if (nativescript::common::DeadlinePassed(deadline)) { return PumpResult::kDeadline; } - RunDueInternalWork(drainLooperWork ? DrainFilter::kPumpDeliverable - : DrainFilter::kNestableV8); + if (mode == PumpMode::kNestableOnly) { + { + v8::Locker locker(isolate_); + v8::Isolate::Scope isolateScope(isolate_); + v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); + RunDueInternalWork(DrainFilter::kNestableV8); + } + if (settled()) { + // back through the loop head, where termination outranks the + // settlement this drain produced + continue; + } + if (idle != nullptr) { + idle(kQuietPumpPollMs); + } else { + WaitForInternalWork(kQuietPumpPollMs); + } + continue; + } + RunDueInternalWork(platformWork ? DrainFilter::kPumpDeliverable + : DrainFilter::kNestableV8); { // work may enqueue microtasks without entering JS; scopes are // re-entrant, so callers already holding them pay nothing @@ -783,54 +802,18 @@ EventLoop::PumpResult EventLoop::PumpUntil(double deadlineSeconds, isolate_->PerformMicrotaskCheckpoint(); } int ranLooperWork = 0; - if (drainLooperWork) { + if (platformWork) { ranLooperWork = RunDueOrderedEntries(); if (pumpDrainHook_ != nullptr) { ranLooperWork += pumpDrainHook_(); } } if (settled()) { - // back through the loop head, where termination outranks the - // settlement this drain produced continue; } if (ranLooperWork == 0) { - WaitForInternalWork(10, /*pumpDeliverable=*/drainLooperWork); - } - } -} - -EventLoop::PumpResult EventLoop::PumpNestableV8TasksUntil( - double deadlineSeconds, const std::function& settled, - const std::function& idle) { - NS_DCHECK(looper_ == nullptr || ALooper_forThread() == looper_); - PumpScope pumpScope; - const auto deadline = std::chrono::steady_clock::now() + - std::chrono::duration(deadlineSeconds); - for (;;) { - if (terminationRequested_.load(std::memory_order_acquire) || - isolate_->IsExecutionTerminating()) { - return PumpResult::kTerminated; - } - if (settled()) { - return PumpResult::kSettled; - } - if (IsStopped()) { - return PumpResult::kTerminated; - } - if (std::chrono::steady_clock::now() >= deadline) { - return PumpResult::kDeadline; - } - { - v8::Locker locker(isolate_); - v8::Isolate::Scope isolateScope(isolate_); - v8::Isolate::SuppressMicrotaskExecutionScope noMicrotasks(isolate_); - RunDueInternalWork(DrainFilter::kNestableV8); - } - if (settled()) { - continue; + WaitForInternalWork(10, /*pumpDeliverable=*/platformWork); } - idle(kQuietPumpPollMs); } } diff --git a/test-app/runtime/src/main/cpp/EventLoop.h b/test-app/runtime/src/main/cpp/EventLoop.h index 8beecffe6..c0b9a6f14 100644 --- a/test-app/runtime/src/main/cpp/EventLoop.h +++ b/test-app/runtime/src/main/cpp/EventLoop.h @@ -14,6 +14,8 @@ #include #include "v8.h" #include "v8-platform.h" +#include "ns/Deadline.h" +#include "ns/Loop.h" namespace tns { @@ -76,11 +78,11 @@ class OrderedTaskSource { * sibling, possibly on this loop), so Shutdown moves the lanes out and lets * them die after the unlock. */ -class EventLoop { +class EventLoop : public nativescript::common::Loop { public: explicit EventLoop(v8::Isolate* isolate) : isolate_(isolate) {} - ~EventLoop(); + ~EventLoop() override; /** * Attaches both lanes to the calling thread (Java handler on the thread's @@ -157,8 +159,8 @@ class EventLoop { void SetTimerSource(OrderedTaskSource* source); // internal lane: runs on the home thread as soon as the looper polls - void PostInternal(std::function fn); - void PostInternalDelayed(std::function fn, double delayMs); + bool PostInternal(std::function fn) override; + bool PostInternalDelayed(std::function fn, double delayMs) override; /** * Internal-lane post whose fn does its OWN isolate ceremony: RunEntry @@ -174,13 +176,13 @@ class EventLoop { * Posts a v8 foreground task into the internal lane. Called by the * platform's per-isolate v8::TaskRunner adapter, from any thread. */ - void PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds); + void PostV8Task(std::unique_ptr task, bool nestable, double delaySeconds) override; /** * True once Shutdown ran. A stopped loop found in the platform registry * for a (reused) isolate pointer is stale and must be replaced. */ - bool IsStopped(); + bool IsStopped() override; /** * Runs the internal-lane v8 tasks that are due and nestable, bounded to @@ -189,7 +191,7 @@ class EventLoop { * non-nestable tasks and plain function posts stay queued and run from * their own wakeups after the loop unwinds. */ - void RunNestableV8Tasks(); + void RunNestableV8Tasks() override; /** * True while this loop's home thread is inside one of the loop's ALooper @@ -204,16 +206,20 @@ class EventLoop { /** * Marks this loop's isolate as termination-requested. Callable from any - * thread. Pumps consult it alongside Isolate::IsExecutionTerminating, - * which per its contract is true only while JS frames are unwinding with - * the termination exception active - a pump parked with nothing queued - * never runs JS, so TerminateExecution alone cannot end it before the - * deadline. + * thread, and called before the isolate's TerminateExecution. Pumps + * consult it alongside Isolate::IsExecutionTerminating, which per its + * contract is true only while JS frames are unwinding with the + * termination exception active - a pump parked with nothing queued never + * runs JS, so TerminateExecution alone cannot end it before the deadline. */ void NoteTerminationRequested() { terminationRequested_.store(true, std::memory_order_release); } + bool TerminationRequested() const override { + return terminationRequested_.load(std::memory_order_acquire); + } + /** * Blocks the calling thread until this loop's internal lane has work (the * eventfd or timerfd is readable) or `timeoutMs` elapses, whichever comes @@ -240,52 +246,37 @@ class EventLoop { */ int RunDueOrderedEntries(); - enum class PumpResult { kSettled, kDeadline, kTerminated }; - /** - * Drives this loop in place on the home thread until `settled()` returns - * true or `deadlineSeconds` elapses, idling in WaitForInternalWork - * between slices. The one pump primitive behind module evaluation, the - * graph walk, and the boot backstop; `settled` may throw and the - * exception propagates. Returns kTerminated when the isolate is - * terminating or the loop has been shut down. - * - * `drainLooperWork` picks what a pump iteration runs, mirroring the iOS - * pump's pumpRunLoop split: - * - false: nestable v8 tasks and a microtask checkpoint only, exactly - * like the inspector pause loops (iOS's default pump body). - * - true (the looper-equivalent drain, standing in for iOS's runloop - * slice): additionally runs due ordered-lane work (JS timers included) - * and plain internal-lane posts (worker->parent messages, Node-API - * completions), plus the registered pump drain hook. Non-nestable v8 - * tasks stay queued in both modes (the v8 nestability contract: JS - * frames are on the stack throughout), and so do bare posts - their - * fns lock a DIFFERENT isolate, and running one under a caller - * holding this isolate's Locker nests Lockers across isolates. + * Loop::PumpUntil. What each mode runs per slice: + * - kNestableOnly: nestable v8 tasks with microtasks suppressed, then + * `idle(kQuietPumpPollMs)` (WaitForInternalWork when `idle` is null). + * No timer, plain post, worker message or promise job runs inside it. + * V8 asks for the GC a background compile is blocked on with a + * nestable PostTask, which only the next slice runs - hence the bound + * on `idle`. + * - kV8Tasks: nestable v8 tasks and a microtask checkpoint, exactly like + * the inspector pause loops; idles in WaitForInternalWork. + * - kPlatformWork: additionally due ordered-lane work (JS timers + * included), plain internal-lane posts (worker->parent messages, + * Node-API completions) and the registered pump drain hook. + * Non-nestable v8 tasks stay queued in every mode (the v8 nestability + * contract: JS frames are on the stack throughout), and so do bare posts + * - their fns lock a DIFFERENT isolate, and running one under a caller + * holding this isolate's Locker nests Lockers across isolates. */ - PumpResult PumpUntil(double deadlineSeconds, const std::function& settled, - bool drainLooperWork); + nativescript::common::PumpResult PumpUntil( + const nativescript::common::Deadline& deadline, const std::function& settled, + nativescript::common::PumpMode mode, + const std::function& idle = nullptr) override; - /** - * A quieter PumpUntil for waits whose completions all arrive as nestable - * v8 tasks: each iteration runs only those, with microtasks suppressed, - * then calls `idle(kQuietPumpPollMs)` instead of waiting on the looper's - * fds. No timer, plain post, worker message or promise job runs inside - * it. `idle` must return within that bound even when nothing signals it: - * V8 asks for the GC a background compile is blocked on with a nestable - * PostTask, which only the next iteration runs. - */ static constexpr int kQuietPumpPollMs = 2; - PumpResult PumpNestableV8TasksUntil(double deadlineSeconds, - const std::function& settled, - const std::function& idle); /** * True on the thread BindToCurrentThread ran on. Any thread may ask: with * multithreaded JavaScript, JS also runs on threads that only hold the * isolate's Locker, and those must not wait on work this loop delivers. */ - bool IsOnHomeThread() const; + bool IsOnHomeThread() const override; /** * True while the calling thread is inside PumpUntil. Callback code that @@ -439,7 +430,7 @@ class EventLoop { Lane internal_; Lane ordered_; std::atomic claimCells_[kClaimCells] = {}; - // Set by NoteTerminationRequested (any thread), read by PumpUntil. + // Set by NoteTerminationRequested (any thread), read by the pumps. std::atomic_bool terminationRequested_{false}; // Depth, not a flag: an fd callback can dispatch JS that lands back in // another callback through a nested drain. Home thread only, like the fd diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index e1d595751..cec35d1aa 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -1363,8 +1363,11 @@ MaybeLocal tns::EvaluateModuleGraph(Isolate* isolate, Local co }; if (!probe() && eventLoop != nullptr) { - if (eventLoop->PumpUntil(options.deadlineSeconds, probe, options.pumpRunLoop) == - EventLoop::PumpResult::kTerminated) { + if (eventLoop->PumpUntil(nativescript::common::DeadlineAfterSeconds(options.deadlineSeconds), + probe, + options.pumpRunLoop ? nativescript::common::PumpMode::kPlatformWork + : nativescript::common::PumpMode::kV8Tasks) == + nativescript::common::PumpResult::kTerminated) { // terminating isolate (worker.terminate) or a stopped loop: no // outcome to report, and no timeout to mislabel it with return MaybeLocal(); diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 07837d58d..8b14e0e55 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -2882,10 +2882,8 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, 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)); + const nativescript::common::Deadline deadline = + nativescript::common::DeadlineAfterSeconds(timeoutSeconds); auto done = std::make_shared(false); SyncModuleLoadScope syncLoad(isolate); const std::shared_ptr load = @@ -2909,31 +2907,30 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; while (!*done && eventLoop != nullptr) { - const double remainingSeconds = - std::chrono::duration(deadline - std::chrono::steady_clock::now()).count(); - EventLoop::PumpResult result; + nativescript::common::PumpResult result; if (load->pendingHttpFetches > 0 || fileJobSignal == nullptr) { result = eventLoop->PumpUntil( - remainingSeconds, [&]() { return *done || load->pendingHttpFetches == 0; }, - /*drainLooperWork=*/true); + deadline, [&]() { return *done || load->pendingHttpFetches == 0; }, + nativescript::common::PumpMode::kPlatformWork); } else { // Taken before each drain, so a completion posted while the pump drains // ends the next wait at once. uint64_t seen = fileJobSignal->Generation(); - result = eventLoop->PumpNestableV8TasksUntil( - remainingSeconds, [&]() { return *done || load->pendingHttpFetches > 0; }, - [&fileJobSignal, &seen](int timeoutMs) { - fileJobSignal->WaitForChange(seen, std::chrono::milliseconds(timeoutMs)); + result = eventLoop->PumpUntil( + deadline, [&]() { return *done || load->pendingHttpFetches > 0; }, + nativescript::common::PumpMode::kNestableOnly, + [&fileJobSignal, &seen](int waitMs) { + fileJobSignal->WaitForChange(seen, std::chrono::milliseconds(waitMs)); seen = fileJobSignal->Generation(); }); } - if (result == EventLoop::PumpResult::kTerminated) { + if (result == nativescript::common::PumpResult::kTerminated) { // terminating isolate or stopped loop: nothing can complete the walk, // and the sync takeover below must not start a blocking fetch TNS_DEBUG(Esm, "[graph][pumped][terminated] root=%s", root.c_str()); return *done; } - if (result == EventLoop::PumpResult::kDeadline) { + if (result == nativescript::common::PumpResult::kDeadline) { break; } } diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index 26cc3fe09..c64d1eebc 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -205,10 +205,9 @@ class SyncModuleLoadScope { // Synchronous wrapper for callers that need the graph ready before // continuing: starts the walk, then pumps the isolate's event loop in place // until it settles or `timeoutSeconds` elapses; the same deadline bounds the -// walk's fetches. With an http(s) fetch outstanding the pump is -// EventLoop::PumpUntil's looper-equivalent drain; while only background file -// loads are outstanding it is PumpNestableV8TasksUntil, which runs no timers or -// other JS. A graph of small local files completes entirely inside +// walk's fetches. With an http(s) fetch outstanding the pump runs +// PumpMode::kPlatformWork; while only background file loads are outstanding +// it runs kNestableOnly, which runs no timers or other JS. A graph of small local files completes entirely inside // StartModuleGraphLoad, so this returns without entering a pump at all. // Returns true when the walk completed (regardless of root success — the // caller's own load path reports root failures). diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 817f01680..d695597a9 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -374,12 +374,14 @@ static void HoldBootBackstop(v8::Isolate* isolate, const std::string& entryPath) // iOS pumps its runloop, and Java Handler messages cannot dispatch while // this frame holds the launching thread — so an entry parked on a JS // timer or a worker reply settles here. - const EventLoop::PumpResult result = eventLoop->PumpUntil( - deadlineSeconds, + const nativescript::common::PumpResult result = eventLoop->PumpUntil( + nativescript::common::DeadlineAfterSeconds(deadlineSeconds), [&]() { if (entryPending) { - EntryEvaluationState state = ModuleInternal::PollEntryEvaluation( - isolate, entryPath, &entryRejectionReason); + // No reason here: stringifying it can run JS, which a pump's + // predicate must not. + EntryEvaluationState state = + ModuleInternal::PollEntryEvaluation(isolate, entryPath, nullptr); // Once it settles, stop probing for good. entryPending = state == EntryEvaluationState::kPending; entryRejected = state == EntryEvaluationState::kRejected; @@ -387,12 +389,15 @@ static void HoldBootBackstop(v8::Isolate* isolate, const std::string& entryPath) return entryRejected || (!entryPending && !tns::HasPendingAsyncModuleGraphWork()); }, - /*drainLooperWork=*/true); - if (result == EventLoop::PumpResult::kTerminated && !entryRejected) { + nativescript::common::PumpMode::kPlatformWork); + if (result == nativescript::common::PumpResult::kTerminated && !entryRejected) { // terminating isolate or stopped loop: no outcome to report, and no // timeout to mislabel it with return; } + if (entryRejected) { + ModuleInternal::PollEntryEvaluation(isolate, entryPath, &entryRejectionReason); + } } // Evict before throwing: the entry would otherwise stay registered at diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp index eae5aac34..0a78a610d 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp @@ -16,10 +16,12 @@ #include "HttpLoader.h" #include "ModuleUrl.h" #include "NativeScriptAssert.h" +#include "NativeScriptPlatform.h" #include "Runtime.h" #include "TraceLog.h" #include "ns/IsolateState.h" #include "ns/LoaderConfig.h" +#include "ns/Loop.h" #include "ns/Platform.h" #include "ns/RuntimeAccess.h" #include "ns/Thread.h" @@ -103,6 +105,11 @@ void RunJob(const std::function& job) { job(); } +std::shared_ptr LoopFor(v8::Isolate* isolate) { + tns::NativeScriptPlatform* nsPlatform = tns::NativeScriptPlatform::Instance(); + return nsPlatform != nullptr ? nsPlatform->LookupEventLoop(isolate) : nullptr; +} + bool IsRuntimeAlive(v8::Isolate* isolate) { return tns::Runtime::TryGetRuntime(isolate) != nullptr; } diff --git a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp index 2ea2de458..349c08718 100644 --- a/test-app/runtime/src/main/cpp/WorkerWrapper.cpp +++ b/test-app/runtime/src/main/cpp/WorkerWrapper.cpp @@ -251,15 +251,16 @@ void WorkerWrapper::Terminate() { std::lock_guard lock(workerIsolateMutex_); Isolate* isolate = workerIsolate_.load(); if (isolate != nullptr) { - // Legal from any thread: interrupts any JS currently running on the - // worker (e.g. a busy loop, including one that follows close()). - isolate->TerminateExecution(); // A pump parked with nothing queued runs no JS, so the interrupt - // above never materializes for it - the loop's own flag ends it. + // below never materializes for it - the loop's own flag ends it. + // Set first, so whatever observes the interrupt also sees the flag. auto loop = NativeScriptPlatform::Instance()->LookupEventLoop(isolate); if (loop != nullptr) { loop->NoteTerminationRequested(); } + // Legal from any thread: interrupts any JS currently running on the + // worker (e.g. a busy loop, including one that follows close()). + isolate->TerminateExecution(); } } @@ -303,6 +304,10 @@ size_t WorkerWrapper::OnNearHeapLimit(void* data, size_t currentHeapLimit, // before that. The isolate being collected is the one to interrupt. Isolate* isolate = Isolate::GetCurrent(); if (isolate != nullptr) { + auto loop = NativeScriptPlatform::Instance()->LookupEventLoop(isolate); + if (loop != nullptr) { + loop->NoteTerminationRequested(); + } isolate->TerminateExecution(); } worker->Terminate(); From 2a2d7350fe586ca0364b8ca6099c7ce4e07c9507 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:08:27 -0300 Subject: [PATCH 05/45] fix(runtime): termination always ends a module load with a throw Termination outranks settlement, and the termination path throws nativescript::common::Terminated, which carries no V8 value; each boundary decides what it means. - The top-level-await probe only records the outcome; a rejection is thrown after the pump returns kSettled, so a termination in the same slice outranks it. On kTerminated EvaluateModuleGraph evicts a still-pending module and throws instead of returning empty, so LoadESModule never hands back the namespace of an interrupted graph. - RunModuleGraphLoadPumped returns false on kTerminated, even when the walk finished in the same slice. - LoadESModule checks the loop's termination flag and a stopped loop as well as V8's IsExecutionTerminating after each walk, and throws rather than returning empty. - The entry Load throws when LoadESModule produces no namespace. --- .../runtime/src/main/cpp/ModuleInternal.cpp | 62 ++++++++++++++----- .../src/main/cpp/ModuleInternalCallbacks.cpp | 6 +- .../src/main/cpp/ModuleInternalCallbacks.h | 3 +- 3 files changed, 52 insertions(+), 19 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index cec35d1aa..f6e57f217 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -607,7 +607,11 @@ void ModuleInternal::Load(Local context, const string& path) { } // The entry runs before this thread's event loop does, so its graph can // only make progress from the pump inside LoadESModule. - LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); + Local moduleNamespace = + LoadESModule(isolate, path, BootEntryEvaluationOptions(isHttpModule)); + if (moduleNamespace.IsEmpty()) { + throw NativeScriptException("ES module load returned no namespace for entry " + path); + } if (isHttpModule) { TNS_DEBUG(Esm, "run-module http-esm ok %s", NormalizeHttpModuleUrl(path).c_str()); } @@ -1229,6 +1233,25 @@ namespace { "loop cannot be pumped re-entrantly. Call it from a task context, or use import()."); } +// Whether the isolate must not load anything more: V8 is unwinding a +// termination, one was requested of the isolate's loop (V8 reports it only +// once JS runs again), or the loop has stopped and can deliver nothing. +bool LoadInterruptedByTermination(Isolate* isolate) { + if (isolate->IsExecutionTerminating()) { + return true; + } + Runtime* runtime = Runtime::TryGetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + return loop != nullptr && (loop->TerminationRequested() || loop->IsStopped()); +} + +// No V8 error can be built on a terminating isolate; each boundary decides +// what the interruption means. +[[noreturn]] void ThrowLoadTerminated(const std::string& canonicalPath, const char* phase) { + LogEsmPhase(canonicalPath, phase, "terminated"); + throw nativescript::common::Terminated(); +} + // Evicts the module and surfaces the rejection reason. Always throws, in every // build — the reason has to reach the boundary handler that reports it. [[noreturn]] void ThrowModuleEvaluationRejection(Isolate* isolate, Local promise, @@ -1343,9 +1366,11 @@ MaybeLocal tns::EvaluateModuleGraph(Isolate* isolate, Local co std::shared_ptr eventLoop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; bool settled = false; + bool rejected = false; // Probed before the first pump iteration: a synchronous graph's evaluation // promise is already settled when Evaluate() returns, so it never pays for - // a pump slice. + // a pump slice. It only records the outcome: a rejection is thrown once the + // pump has returned, so a termination in the same slice outranks it. const auto probe = [&]() { if (promiseTc.HasCaught()) { return true; @@ -1355,10 +1380,7 @@ MaybeLocal tns::EvaluateModuleGraph(Isolate* isolate, Local co return false; } settled = true; - if (state == Promise::kRejected) { - ThrowModuleEvaluationRejection(isolate, promise, promiseTc, canonicalPath); - } - LogEsmPhase(canonicalPath, "evaluate", "promise-resolved"); + rejected = state == Promise::kRejected; return true; }; @@ -1368,12 +1390,22 @@ MaybeLocal tns::EvaluateModuleGraph(Isolate* isolate, Local co options.pumpRunLoop ? nativescript::common::PumpMode::kPlatformWork : nativescript::common::PumpMode::kV8Tasks) == nativescript::common::PumpResult::kTerminated) { - // terminating isolate (worker.terminate) or a stopped loop: no - // outcome to report, and no timeout to mislabel it with - return MaybeLocal(); + // Only a still-pending promise leaves a half-evaluated module in + // the registry; one that settled is complete and stays. + if (promise->State() == Promise::kPending) { + RemoveModuleFromRegistry(isolate, canonicalPath); + } + ThrowLoadTerminated(canonicalPath, "evaluate"); } } + if (rejected) { + ThrowModuleEvaluationRejection(isolate, promise, promiseTc, canonicalPath); + } + if (settled) { + LogEsmPhase(canonicalPath, "evaluate", "promise-resolved"); + } + if (!settled && promise->State() == Promise::kPending) { LogEsmPhase(canonicalPath, "evaluate", "promise-timeout"); if (options.timeoutBehavior == ModuleEvaluationOptions::TimeoutBehavior::kThrow) { @@ -1488,10 +1520,10 @@ Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& p if (isHttpModule) { logPhase("compile", "delegate-http"); RunModuleGraphLoadPumped(isolate, context, requestPath, kModuleEvaluateDeadlineSeconds); - if (isolate->IsExecutionTerminating()) { - // no outcome to report, and the sync loader below must not start - // a blocking fetch on a terminating isolate - return Local(); + if (LoadInterruptedByTermination(isolate)) { + // the sync loader below must not start a blocking fetch on a + // terminating isolate + ThrowLoadTerminated(canonicalPath, "load"); } // The loader throws the classifier's reason (status, MIME or // transport); catch it so it lands in the message instead of staying @@ -1566,10 +1598,10 @@ Local ModuleInternal::LoadESModule(Isolate* isolate, const std::string& p // no timers or other JS. RunModuleGraphLoadPumped(isolate, context, canonicalPath, kModuleEvaluateDeadlineSeconds); - if (isolate->IsExecutionTerminating()) { + if (LoadInterruptedByTermination(isolate)) { // a background job may not have registered the root yet, and // the inline fallback must not compile on a terminating isolate - return Local(); + ThrowLoadTerminated(canonicalPath, "load"); } auto walkedIt = registry.find(canonicalPath); if (walkedIt != registry.end()) { diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index 8b14e0e55..d3c183508 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -2925,10 +2925,10 @@ bool RunModuleGraphLoadPumped(v8::Isolate* isolate, }); } if (result == nativescript::common::PumpResult::kTerminated) { - // terminating isolate or stopped loop: nothing can complete the walk, - // and the sync takeover below must not start a blocking fetch + // terminating isolate or stopped loop: a walk that finished in the + // same slice still counts as interrupted TNS_DEBUG(Esm, "[graph][pumped][terminated] root=%s", root.c_str()); - return *done; + return false; } if (result == nativescript::common::PumpResult::kDeadline) { break; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h index c64d1eebc..9b7e868bd 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.h @@ -210,7 +210,8 @@ class SyncModuleLoadScope { // it runs kNestableOnly, which runs no timers or other JS. A graph of small local files completes entirely inside // StartModuleGraphLoad, so this returns without entering a pump at all. // Returns true when the walk completed (regardless of root success — the -// caller's own load path reports root failures). +// caller's own load path reports root failures); false when it timed out or +// the isolate is terminating, which the caller tells apart. bool RunModuleGraphLoadPumped(v8::Isolate* isolate, v8::Local context, const std::string& root, double timeoutSeconds); From 31b4eaabf107f1b2be368602179b23e3bb86fdef Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:15:45 -0300 Subject: [PATCH 06/45] build: pin runtime-common at ebb7b87 Takes Terminated::ThrowToV8, -fno-rtti on the core target and the defined meaning of a null idle in kNestableOnly, which the Android pump already implements as a short WaitForInternalWork. --- test-app/runtime/src/main/cpp/runtime-common | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test-app/runtime/src/main/cpp/runtime-common b/test-app/runtime/src/main/cpp/runtime-common index e1c85ea28..ebb7b87b9 160000 --- a/test-app/runtime/src/main/cpp/runtime-common +++ b/test-app/runtime/src/main/cpp/runtime-common @@ -1 +1 @@ -Subproject commit e1c85ea2801fff4611dc158b40eb1029c877044c +Subproject commit ebb7b87b9452320b8b9bfaea97142d7d4f6b95a8 From 2f63376a80c423df7b0611bb0b1994fd3d171d24 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 02:15:45 -0300 Subject: [PATCH 07/45] fix(runtime): V8 callbacks throw on Terminated instead of returning Termination is requested before V8 starts unwinding, so JS can still be running when a load is interrupted. A V8 callback that swallowed Terminated let an interrupted require() return undefined and the caller carry on. require(), the ns:module callbacks and the resolver now call Terminated::ThrowToV8, and import() rejects with that error; once V8 is terminating it throws nothing. Non-JS boundaries (Java, the worker entry and bootstrap, the event-loop guards, the boot backstop) are unchanged. --- .../runtime/src/main/cpp/ModuleInternal.cpp | 4 +-- .../src/main/cpp/ModuleInternalCallbacks.cpp | 35 ++++++++++++++----- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index f6e57f217..65b422141 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -458,8 +458,8 @@ void ModuleInternal::DispatchRequire(const v8::FunctionCallbackInfo& e.ReThrowToV8(); } catch (nativescript::common::JsError& e) { e.ThrowToV8(isolate); - } catch (nativescript::common::Terminated&) { - // The isolate is going away; there is nothing for JS to observe. + } catch (nativescript::common::Terminated& e) { + e.ThrowToV8(isolate); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; diff --git a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp index d3c183508..89a4d71ca 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternalCallbacks.cpp @@ -3507,7 +3507,8 @@ static v8::MaybeLocal LoadResolvedModule( resolution.specifier.c_str(), absPath.c_str()); ex.ThrowToV8(isolate); return v8::MaybeLocal(); - } catch (nativescript::common::Terminated&) { + } catch (nativescript::common::Terminated& ex) { + ex.ThrowToV8(isolate); return v8::MaybeLocal(); } } @@ -3854,8 +3855,14 @@ static void SettleDynamicImport(v8::Isolate* isolate, v8::Local con if (!error.IsEmpty()) { resolver->Reject(context, error).FromMaybe(false); } - } catch (nativescript::common::Terminated&) { - // A terminating isolate cannot settle the promise; it is never observed. + } catch (nativescript::common::Terminated& ex) { + v8::TryCatch terminatedTc(isolate); + ex.ThrowToV8(isolate); + if (terminatedTc.HasCaught()) { + v8::Local error = terminatedTc.Exception(); + terminatedTc.Reset(); + resolver->Reject(context, error).FromMaybe(false); + } } } @@ -4624,8 +4631,14 @@ v8::MaybeLocal ImportModuleDynamicallyCallback( if (!error.IsEmpty()) { resolver->Reject(context, error).FromMaybe(false); } - } catch (nativescript::common::Terminated&) { - // A terminating isolate cannot settle the promise; it is never observed. + } catch (nativescript::common::Terminated& ex) { + v8::TryCatch terminatedTc(isolate); + ex.ThrowToV8(isolate); + if (terminatedTc.HasCaught()) { + v8::Local error = terminatedTc.Exception(); + terminatedTc.Reset(); + resolver->Reject(context, error).FromMaybe(false); + } } return scope.Escape(resolver->GetPromise()); @@ -4901,7 +4914,8 @@ void ConfigureLoaderCallback(const v8::FunctionCallbackInfo& info) { e.ReThrowToV8(); } catch (nativescript::common::JsError& e) { e.ThrowToV8(isolate); - } catch (nativescript::common::Terminated&) { + } catch (nativescript::common::Terminated& e) { + e.ThrowToV8(isolate); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -4959,7 +4973,8 @@ void InvalidateModulesCallback(const v8::FunctionCallbackInfo& info) e.ReThrowToV8(); } catch (nativescript::common::JsError& e) { e.ThrowToV8(isolate); - } catch (nativescript::common::Terminated&) { + } catch (nativescript::common::Terminated& e) { + e.ThrowToV8(isolate); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -4987,7 +5002,8 @@ void GetLoadedModuleUrlsCallback(const v8::FunctionCallbackInfo& info e.ReThrowToV8(); } catch (nativescript::common::JsError& e) { e.ThrowToV8(isolate); - } catch (nativescript::common::Terminated&) { + } catch (nativescript::common::Terminated& e) { + e.ThrowToV8(isolate); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); nsEx.ReThrowToV8(); @@ -5094,7 +5110,8 @@ bool BuildNsModuleBinding(v8::Local context, v8::Local e.ReThrowToV8(); } catch (nativescript::common::JsError& e) { e.ThrowToV8(iso); - } catch (nativescript::common::Terminated&) { + } catch (nativescript::common::Terminated& e) { + e.ThrowToV8(iso); } catch (std::exception& e) { NativeScriptException nsEx(std::string("Error: c++ exception: ") + e.what() + "\n"); From b6fd4b1e58a927f2a9794456f5820c64261c0168 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 10:39:41 -0300 Subject: [PATCH 08/45] build: pin runtime-common at 95d96cc and implement its app-file seam platform::Stat reports the on-disk mtime, with nanoseconds, as the freshness token. platform::ReadFile is all-or-nothing: a file that reads short or grows past its fstat size fails. The debug-only LiveSync lock moves from each Runtime into ReadFile as one process-wide lock; Runtime::Lock/Unlock and Runtime::ReadFileText now go through it. --- test-app/runtime/src/main/cpp/Runtime.cpp | 26 +++--- test-app/runtime/src/main/cpp/Runtime.h | 4 - .../src/main/cpp/RuntimeCommonPlatform.cpp | 86 +++++++++++++++++++ .../src/main/cpp/RuntimeCommonPlatform.h | 6 ++ test-app/runtime/src/main/cpp/runtime-common | 2 +- 5 files changed, 105 insertions(+), 19 deletions(-) diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index d695597a9..0daed0a3b 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -38,6 +38,7 @@ #include "NativeScriptException.h" #include "NativeScriptPlatform.h" #include "RuntimeCommonPlatform.h" +#include "ns/AppFiles.h" #include "RuntimeState.h" #include "napi/NapiEnv.h" #include "Performance.h" @@ -313,29 +314,26 @@ Runtime::~Runtime() { } std::string Runtime::ReadFileText(const std::string& filePath) { -#ifdef APPLICATION_IN_DEBUG - std::lock_guard lock(m_fileWriteMutex); -#endif - return File::ReadText(filePath); + bool ok; + return ReadFileText(filePath, ok); } std::string Runtime::ReadFileText(const std::string& filePath, bool& ok) { -#ifdef APPLICATION_IN_DEBUG - std::lock_guard lock(m_fileWriteMutex); -#endif - return File::ReadText(filePath, ok); + std::string content; + ok = nativescript::common::platform::ReadFile(filePath, content); + if (!ok) { + DEBUG_WRITE_FORCE("Cannot read %s", filePath.c_str()); + return std::string(); + } + return content; } void Runtime::Lock() { -#ifdef APPLICATION_IN_DEBUG - m_fileWriteMutex.lock(); -#endif + LockAppFilesForLiveSync(); } void Runtime::Unlock() { -#ifdef APPLICATION_IN_DEBUG - m_fileWriteMutex.unlock(); -#endif + UnlockAppFilesForLiveSync(); } // The boot backstop: hold the launching thread until boot has actually diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index 502953998..b8b65f191 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -535,10 +535,6 @@ class Runtime { // calling its thread-local initialization hook. static constinit thread_local CurrentRuntime s_current; static thread_local PendingIsolateSetup s_pendingIsolateSetup; - -#ifdef APPLICATION_IN_DEBUG - std::mutex m_fileWriteMutex; -#endif }; inline v8::Isolate* Runtime::GetIsolate() const { diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp index 0a78a610d..7abe75d3a 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp @@ -5,9 +5,15 @@ #include "RuntimeCommonPlatform.h" +#include #include +#include +#include +#include +#include #include +#include #include #include #include @@ -19,6 +25,7 @@ #include "NativeScriptPlatform.h" #include "Runtime.h" #include "TraceLog.h" +#include "ns/AppFiles.h" #include "ns/IsolateState.h" #include "ns/LoaderConfig.h" #include "ns/Loop.h" @@ -30,6 +37,39 @@ namespace { nativescript::common::LoaderConfig g_loaderConfig; +#ifdef APPLICATION_IN_DEBUG +// Never destroyed: pool and worker threads may read files during exit. +std::mutex& LiveSyncMutex() { + static auto* mutex = new std::mutex(); + return *mutex; +} +#endif + +// Reads exactly `size` bytes, then requires end of file: a file that shrank or +// grew since its size was taken would otherwise read as a mix of versions. +bool ReadExactly(int fd, size_t size, std::string& out) { + out.resize(size); + size_t done = 0; + while (done < size) { + const ssize_t got = read(fd, out.data() + done, size - done); + if (got < 0 && errno == EINTR) { + continue; + } + if (got <= 0) { + return false; + } + done += static_cast(got); + } + char extra; + for (;;) { + const ssize_t got = read(fd, &extra, 1); + if (got < 0 && errno == EINTR) { + continue; + } + return got == 0; + } +} + } // namespace namespace tns { @@ -48,6 +88,18 @@ void InitLoaderConfig(std::string appRoot) { }); } +void LockAppFilesForLiveSync() { +#ifdef APPLICATION_IN_DEBUG + LiveSyncMutex().lock(); +#endif +} + +void UnlockAppFilesForLiveSync() { +#ifdef APPLICATION_IN_DEBUG + LiveSyncMutex().unlock(); +#endif +} + } // namespace tns namespace nativescript::common::platform { @@ -94,6 +146,40 @@ const LoaderConfig& Loader() { return g_loaderConfig; } +std::optional Stat(std::string_view logicalPath) { + const std::string path(logicalPath); + struct stat st; + if (stat(path.c_str(), &st) != 0) { + return std::nullopt; + } + FileInfo info; + info.isFile = S_ISREG(st.st_mode); + if (info.isFile) { + info.size = static_cast(st.st_size); + char token[48]; + std::snprintf(token, sizeof(token), "%lld.%09ld", static_cast(st.st_mtim.tv_sec), + static_cast(st.st_mtim.tv_nsec)); + info.freshnessToken = token; + } + return info; +} + +bool ReadFile(std::string_view logicalPath, std::string& out) { +#ifdef APPLICATION_IN_DEBUG + std::lock_guard lock(LiveSyncMutex()); +#endif + const std::string path(logicalPath); + const int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return false; + } + struct stat st; + const bool ok = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) && + ReadExactly(fd, static_cast(st.st_size), out); + close(fd); + return ok; +} + void ApplyThreadPriority(ThreadPriority priority) { if (priority == ThreadPriority::kUtility) { // On Linux PRIO_PROCESS with who == 0 names the calling thread only. diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h index 649806584..5ba1e31d3 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h @@ -11,6 +11,12 @@ namespace tns { // the config from threads that cannot attach to the JVM. void InitLoaderConfig(std::string appRoot); +// Held by LiveSync while it rewrites app files; platform::ReadFile waits for +// it, so a read never sees a half-written file. One lock for the process, +// because every runtime reads the same files. No-ops outside debug builds. +void LockAppFilesForLiveSync(); +void UnlockAppFilesForLiveSync(); + } // namespace tns #endif // RUNTIME_COMMON_PLATFORM_H_ diff --git a/test-app/runtime/src/main/cpp/runtime-common b/test-app/runtime/src/main/cpp/runtime-common index ebb7b87b9..95d96cc7c 160000 --- a/test-app/runtime/src/main/cpp/runtime-common +++ b/test-app/runtime/src/main/cpp/runtime-common @@ -1 +1 @@ -Subproject commit ebb7b87b9452320b8b9bfaea97142d7d4f6b95a8 +Subproject commit 95d96cc7c1ceb192b0bff01cb1468ce8a49f4126 From 32ab7ec20d7526fbf925da42b1cb9a008a151187 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 10:40:18 -0300 Subject: [PATCH 09/45] feat(runtime): give the code cache a directory of its own The app's Context.getCodeCacheDir() reaches native init through StaticConfiguration, and the runtime keeps its V8 caches in its "v8" subdirectory as LoaderConfig.codeCacheDir. The system empties that directory when the app or the platform is upgraded. StaticConfiguration keeps its old constructor, which leaves code caches off. --- test-app/app/src/main/java/com/tns/RuntimeHelper.java | 2 +- test-app/runtime/src/main/cpp/Runtime.cpp | 2 +- test-app/runtime/src/main/cpp/Runtime.h | 2 ++ .../runtime/src/main/cpp/RuntimeCommonPlatform.cpp | 7 +++---- test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h | 2 +- test-app/runtime/src/main/cpp/com_tns_Runtime.cpp | 3 ++- test-app/runtime/src/main/java/com/tns/Runtime.java | 10 ++++++---- .../src/main/java/com/tns/StaticConfiguration.java | 10 ++++++++++ 8 files changed, 26 insertions(+), 12 deletions(-) diff --git a/test-app/app/src/main/java/com/tns/RuntimeHelper.java b/test-app/app/src/main/java/com/tns/RuntimeHelper.java index 695d9ee4d..114126022 100644 --- a/test-app/app/src/main/java/com/tns/RuntimeHelper.java +++ b/test-app/app/src/main/java/com/tns/RuntimeHelper.java @@ -160,7 +160,7 @@ public static Runtime initRuntime(Context context) { boolean isDebuggable = Util.isDebuggableApp(context); StaticConfiguration config = new StaticConfiguration(logger, appName, nativeLibDir, rootDir, - appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable); + appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable, context.getCodeCacheDir()); runtime = Runtime.initializeRuntimeWithConfiguration(config); if (isDebuggable) { diff --git a/test-app/runtime/src/main/cpp/Runtime.cpp b/test-app/runtime/src/main/cpp/Runtime.cpp index 0daed0a3b..a75c09c92 100644 --- a/test-app/runtime/src/main/cpp/Runtime.cpp +++ b/test-app/runtime/src/main/cpp/Runtime.cpp @@ -236,7 +236,7 @@ void Runtime::Init(JNIEnv* env, jstring filesPath, jstring nativeLibDir, Constants::APP_ROOT_FOLDER_PATH = filesRoot + "/app/"; Constants::V8_STARTUP_FLAGS = options.v8Flags; Constants::V8_CACHE_COMPILED_CODE = options.codeCache; - InitLoaderConfig(filesRoot + "/app"); + InitLoaderConfig(filesRoot + "/app", options.codeCacheDir); m_discardUncaughtJsExceptions = options.discardUncaughtJsExceptions; // AppConfig validates and warns about unknown values; anything that is not // "throw" behaves as the default. diff --git a/test-app/runtime/src/main/cpp/Runtime.h b/test-app/runtime/src/main/cpp/Runtime.h index b8b65f191..249508cae 100644 --- a/test-app/runtime/src/main/cpp/Runtime.h +++ b/test-app/runtime/src/main/cpp/Runtime.h @@ -158,6 +158,8 @@ class Runtime { struct StartupOptions { std::string v8Flags; bool codeCache; + // Absolute; empty leaves code caches off. + std::string codeCacheDir; std::string profilerOutputDir; bool discardUncaughtJsExceptions; std::string uncaughtErrorPolicy; diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp index 7abe75d3a..23855a33e 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.cpp @@ -74,15 +74,14 @@ bool ReadExactly(int fd, size_t size, std::string& out) { namespace tns { -void InitLoaderConfig(std::string appRoot) { +void InitLoaderConfig(std::string appRoot, std::string codeCacheDir) { static std::once_flag once; - std::call_once(once, [&appRoot] { + std::call_once(once, [&appRoot, &codeCacheDir] { nativescript::common::LoaderConfig config; config.appRoot = std::move(appRoot); config.isDebug = IsDebuggable(); config.codeCacheEnabled = Constants::V8_CACHE_COMPILED_CODE && !config.isDebug; - // Caches are written next to their source file, so there is no cache - // directory to name. + config.codeCacheDir = std::move(codeCacheDir); config.v8Flags = Constants::V8_STARTUP_FLAGS; g_loaderConfig = std::move(config); }); diff --git a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h index 5ba1e31d3..dc064cc4a 100644 --- a/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h +++ b/test-app/runtime/src/main/cpp/RuntimeCommonPlatform.h @@ -9,7 +9,7 @@ namespace tns { // call takes effect: it must come from the main runtime's thread before its // isolate exists, because it reads the debug flag over JNI and the core reads // the config from threads that cannot attach to the JVM. -void InitLoaderConfig(std::string appRoot); +void InitLoaderConfig(std::string appRoot, std::string codeCacheDir); // Held by LiveSync while it rewrites app files; platform::ReadFile waits for // it, so a read never sees a half-written file. One lock for the process, diff --git a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp index 3c06c4264..e4c28d33f 100644 --- a/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp +++ b/test-app/runtime/src/main/cpp/com_tns_Runtime.cpp @@ -114,12 +114,13 @@ extern "C" JNIEXPORT void Java_com_tns_Runtime_setManualInstrumentationModeLegac setManualInstrumentationModeFast_impl(_env, clazz, mode); } -extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jobject obj, jint runtimeId, jstring filesPath, jstring nativeLibDir, jboolean verboseLoggingEnabled, jboolean isDebuggable, jstring packageName, jstring v8Flags, jboolean codeCache, jstring profilerOutputDir, jboolean discardUncaughtJsExceptions, jstring uncaughtErrorPolicy, jstring wrapperLifetimeMode, jstring wrapperLifetimeScope, jboolean multithreadedJavascript, jstring callingDir, jint maxLogcatObjectSize, jboolean forceLog) { +extern "C" JNIEXPORT void Java_com_tns_Runtime_initNativeScript(JNIEnv* _env, jobject obj, jint runtimeId, jstring filesPath, jstring nativeLibDir, jboolean verboseLoggingEnabled, jboolean isDebuggable, jstring packageName, jstring v8Flags, jboolean codeCache, jstring codeCacheDir, jstring profilerOutputDir, jboolean discardUncaughtJsExceptions, jstring uncaughtErrorPolicy, jstring wrapperLifetimeMode, jstring wrapperLifetimeScope, jboolean multithreadedJavascript, jstring callingDir, jint maxLogcatObjectSize, jboolean forceLog) { JEnv::EntryScope envScope(_env); try { Runtime::StartupOptions options{ ArgConverter::jstringToString(v8Flags), codeCache == JNI_TRUE, + ArgConverter::jstringToString(codeCacheDir), ArgConverter::jstringToString(profilerOutputDir), discardUncaughtJsExceptions == JNI_TRUE, ArgConverter::jstringToString(uncaughtErrorPolicy), diff --git a/test-app/runtime/src/main/java/com/tns/Runtime.java b/test-app/runtime/src/main/java/com/tns/Runtime.java index 39d45c97f..00c114c1f 100644 --- a/test-app/runtime/src/main/java/com/tns/Runtime.java +++ b/test-app/runtime/src/main/java/com/tns/Runtime.java @@ -38,7 +38,7 @@ public class Runtime { private native void initNativeScript(int runtimeId, String filesPath, String nativeLibDir, boolean verboseLoggingEnabled, boolean isDebuggable, String packageName, - String v8Flags, boolean codeCache, String profilerOutputDir, boolean discardUncaughtJsExceptions, String uncaughtErrorPolicy, + String v8Flags, boolean codeCache, String codeCacheDir, String profilerOutputDir, boolean discardUncaughtJsExceptions, String uncaughtErrorPolicy, String wrapperLifetimeMode, String wrapperLifetimeScope, boolean multithreadedJavascript, String callingDir, int maxLogcatObjectSize, boolean forceLog); @@ -849,10 +849,10 @@ boolean isInitializedImpl() { } public void init() { - init(config.logger, config.appName, config.nativeLibDir, config.rootDir, config.appDir, config.classLoader, config.dexDir, config.dexThumb, config.appConfig, dynamicConfig.callingJsDir, config.isDebuggable); + init(config.logger, config.appName, config.nativeLibDir, config.rootDir, config.appDir, config.codeCacheDir, config.classLoader, config.dexDir, config.dexThumb, config.appConfig, dynamicConfig.callingJsDir, config.isDebuggable); } - private void init(Logger logger, String appName, String nativeLibDir, File rootDir, File appDir, ClassLoader classLoader, File dexDir, String dexThumb, AppConfig appConfig, String callingJsDir, boolean isDebuggable) throws RuntimeException { + private void init(Logger logger, String appName, String nativeLibDir, File rootDir, File appDir, File codeCacheDir, ClassLoader classLoader, File dexDir, String dexThumb, AppConfig appConfig, String callingJsDir, boolean isDebuggable) throws RuntimeException { if (initialized) { throw new RuntimeException("NativeScriptApplication already initialized"); } @@ -881,7 +881,9 @@ private void init(Logger logger, String appName, String nativeLibDir, File rootD } initNativeScript(getRuntimeId(), Module.getApplicationFilesPath(), nativeLibDir, logger.isEnabled(), isDebuggable, appName, - appConfig.getV8Flags(), appConfig.getCodeCache(), appConfig.getProfilerOutputDir(), + appConfig.getV8Flags(), appConfig.getCodeCache(), + codeCacheDir != null ? new File(codeCacheDir, "v8").getAbsolutePath() : "", + appConfig.getProfilerOutputDir(), appConfig.getDiscardUncaughtJsExceptions(), appConfig.getUncaughtErrorPolicy(), appConfig.getWrapperLifetimeMode(), appConfig.getWrapperLifetimeScope(), multithreadedJavascript, callingJsDir, appConfig.getMaxLogcatObjectSize(), forceConsoleLog); diff --git a/test-app/runtime/src/main/java/com/tns/StaticConfiguration.java b/test-app/runtime/src/main/java/com/tns/StaticConfiguration.java index 29072bd8d..2ccb95f98 100644 --- a/test-app/runtime/src/main/java/com/tns/StaticConfiguration.java +++ b/test-app/runtime/src/main/java/com/tns/StaticConfiguration.java @@ -13,10 +13,19 @@ public class StaticConfiguration { public final String dexThumb; public final AppConfig appConfig; public final boolean isDebuggable; + // Context.getCodeCacheDir(); null leaves V8 code caches off. + public final File codeCacheDir; public StaticConfiguration(Logger logger, String appName, String nativeLibDir, File rootDir, File appDir, ClassLoader classLoader, File dexDir, String dexThumb, AppConfig appConfig, boolean isDebuggable) { + this(logger, appName, nativeLibDir, rootDir, appDir, classLoader, dexDir, dexThumb, appConfig, isDebuggable, null); + } + + public StaticConfiguration(Logger logger, + String appName, String nativeLibDir, File rootDir, File appDir, ClassLoader classLoader, + File dexDir, String dexThumb, AppConfig appConfig, boolean isDebuggable, + File codeCacheDir) { this.logger = logger; this.appName = appName; this.nativeLibDir = nativeLibDir; @@ -27,5 +36,6 @@ public StaticConfiguration(Logger logger, this.dexThumb = dexThumb; this.appConfig = appConfig; this.isDebuggable = isDebuggable; + this.codeCacheDir = codeCacheDir; } } From 88d3a22ee04868bdead53b53f53723c0aaa58af5 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Sat, 5 Dec 2026 10:49:51 -0300 Subject: [PATCH 10/45] feat(runtime): compile app files and keep code caches through the shared core Classic scripts and ES modules compile through loader::CompileFileClassicScript and CompileFileEsModule with the same script origins and CommonJS wrapper as before. Caches live under LoaderConfig.codeCacheDir, named and validated by the core (a header with the key, source size and freshness token), and are created by the core's per-isolate queue and writer thread. The off-thread file-module job decides with CodeCacheEntryFor/HasFreshCodeCache at dispatch, reads with platform::ReadFile and re-checks SourceUnchanged on the pool, and queues creation at finalize. flushScriptCachesNative calls NotifyAppBackgrounded. Behaviour changes: - A classic script that exists but cannot be read (or vanishes before the read) throws "Cannot read module " / "Cannot find module " instead of loading as an empty module. - A file that reads short fails instead of compiling the truncated text. The Android ScriptCache queue, writer, cache naming and File::ReadText/WriteBinary are gone. The cache specs read the core's file layout through tests/codeCacheFiles.js. --- .../main/assets/app/tests/codeCacheFiles.js | 140 +++++++ .../assets/app/tests/requireExceptionTests.js | 24 ++ .../assets/app/tests/testFileModuleLoad.js | 74 ++-- .../app/tests/testWorkerConcurrentStartup.js | 25 +- test-app/runtime/src/main/cpp/File.cpp | 87 +---- test-app/runtime/src/main/cpp/File.h | 14 - .../runtime/src/main/cpp/ModuleInternal.cpp | 364 +----------------- .../runtime/src/main/cpp/ModuleInternal.h | 59 +-- .../src/main/cpp/ModuleInternalCallbacks.cpp | 72 ++-- test-app/runtime/src/main/cpp/Runtime.cpp | 1 - test-app/runtime/src/main/cpp/Runtime.h | 1 - .../runtime/src/main/cpp/com_tns_Runtime.cpp | 8 +- 12 files changed, 255 insertions(+), 614 deletions(-) create mode 100644 test-app/app/src/main/assets/app/tests/codeCacheFiles.js diff --git a/test-app/app/src/main/assets/app/tests/codeCacheFiles.js b/test-app/app/src/main/assets/app/tests/codeCacheFiles.js new file mode 100644 index 000000000..34a6462e5 --- /dev/null +++ b/test-app/app/src/main/assets/app/tests/codeCacheFiles.js @@ -0,0 +1,140 @@ +// The runtime's on-disk code caches, as the shared core lays them out: +// /v8/<16 hex digits of the FNV-1a 64 hash of the key>, then +// ".mcache" for an ES module or ".cache" for a classic script. The key is the +// source's path relative to the app root, or its absolute path outside it. +// A file is a header (magic "NSCC", version, kind, key length, source size, +// freshness token length, payload length, key, token), then V8's payload. +var context = com.tns.NativeScriptApplication.getInstance(); +var dir = String(new java.io.File(context.getCodeCacheDir(), "v8").getAbsolutePath()); +var appRoot = String(context.getFilesDir().getCanonicalPath()) + "/app"; + +var FNV_OFFSET = BigInt("0xcbf29ce484222325"); +var FNV_PRIME = BigInt("0x100000001b3"); +var MASK_64 = (BigInt(1) << BigInt(64)) - BigInt(1); + +function fnv1a64(text) { + var bytes = unescape(encodeURIComponent(text)); + var hash = FNV_OFFSET; + for (var i = 0; i < bytes.length; i++) { + hash = ((hash ^ BigInt(bytes.charCodeAt(i))) * FNV_PRIME) & MASK_64; + } + var hex = hash.toString(16); + while (hex.length < 16) { + hex = "0" + hex; + } + return hex; +} + +function keyFor(path) { + return path.indexOf(appRoot + "/") === 0 ? path.substring(appRoot.length + 1) : path; +} + +// `kind` is "module" or "script". +function fileFor(path, kind) { + return dir + "/" + fnv1a64(keyFor(path)) + (kind === "script" ? ".cache" : ".mcache"); +} + +// What platform::Stat reports as the source's freshness token: its mtime with +// nanoseconds. +function sourceToken(path) { + var mtime = android.system.Os.stat(path).st_mtim; + var nanos = String(mtime.tv_nsec); + while (nanos.length < 9) { + nanos = "0" + nanos; + } + return String(mtime.tv_sec) + "." + nanos; +} + +function readBytes(file) { + var f = new java.io.File(file); + return f.exists() ? java.nio.file.Files.readAllBytes(f.toPath()) : null; +} + +// The cache file's header, or null when there is no file or it is not a cache. +function readHeader(file) { + var bytes = readBytes(file); + if (bytes === null || bytes.length < 32) { + return null; + } + var u8 = function (i) { + return bytes[i] & 0xff; + }; + var u32 = function (i) { + return (u8(i) | (u8(i + 1) << 8) | (u8(i + 2) << 16) | (u8(i + 3) << 24)) >>> 0; + }; + var text = function (start, length) { + var out = ""; + for (var i = start; i < start + length; i++) { + out += String.fromCharCode(u8(i)); + } + return decodeURIComponent(escape(out)); + }; + if (text(0, 4) !== "NSCC") { + return null; + } + var keyLength = u32(12); + var tokenLength = u32(24); + var payloadStart = 32 + keyLength + tokenLength; + var zeroPayload = true; + for (var i = payloadStart; i < bytes.length && zeroPayload; i++) { + zeroPayload = bytes[i] === 0; + } + return { + key: text(32, keyLength), + sourceSize: u32(16) + u32(20) * 4294967296, + token: text(32 + keyLength, tokenLength), + payloadStart: payloadStart, + payloadLength: u32(28), + fileLength: bytes.length, + zeroPayload: zeroPayload + }; +} + +// Whether `file` is a cache for the source at `path` as it is now. +function isFresh(file, path) { + var header = readHeader(file); + return header !== null && header.key === keyFor(path) && + header.sourceSize === new java.io.File(path).length() && + header.token === sourceToken(path) && + header.fileLength === header.payloadStart + header.payloadLength; +} + +// Overwrites the payload with zeros and keeps the header, so the cache still +// reads as fresh and V8 rejects it. +function zeroPayload(file) { + var header = readHeader(file); + var bytes = readBytes(file); + for (var i = header.payloadStart; i < bytes.length; i++) { + bytes[i] = 0; + } + var out = new java.io.FileOutputStream(file); + try { + out.write(bytes); + } finally { + out.close(); + } +} + +// Names in the cache directory that start with `file`'s name and a dot: the +// writer's temporaries. +function temporariesOf(file) { + var name = file.substring(file.lastIndexOf("/") + 1) + "."; + var names = new java.io.File(dir).list(); + var found = []; + for (var i = 0; names && i < names.length; i++) { + if (String(names[i]).indexOf(name) === 0) { + found.push(String(names[i])); + } + } + return found; +} + +module.exports = { + dir: dir, + fileFor: fileFor, + sourceToken: sourceToken, + readHeader: readHeader, + isFresh: isFresh, + zeroPayload: zeroPayload, + temporariesOf: temporariesOf +}; diff --git a/test-app/app/src/main/assets/app/tests/requireExceptionTests.js b/test-app/app/src/main/assets/app/tests/requireExceptionTests.js index 5b28cbd8e..9b55983f3 100644 --- a/test-app/app/src/main/assets/app/tests/requireExceptionTests.js +++ b/test-app/app/src/main/assets/app/tests/requireExceptionTests.js @@ -161,4 +161,28 @@ describe("Tests require exceptions ", function () { expect(exceptionCaught).toBe(false); }); + + it("throws when a script that exists cannot be read", function () { + var name = "unreadable-" + Date.now() + ".js"; + var path = __dirname + "/" + name; + var file = new java.io.File(path); + var writer = new java.io.FileWriter(file); + try { + writer.write("module.exports = { loaded: true };"); + } finally { + writer.close(); + } + file.setReadable(false, false); + var message; + try { + require(path); + message = "loaded"; + } catch (e) { + message = String(e.message || e); + } finally { + file.delete(); + } + expect(message).toContain("Cannot read module "); + expect(message).toContain(name); + }); }); \ No newline at end of file diff --git a/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js index 73b43bd89..41915d85c 100644 --- a/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js +++ b/test-app/app/src/main/assets/app/tests/testFileModuleLoad.js @@ -18,6 +18,7 @@ describe("Large file modules", function () { // Debuggable builds are the development flavor: no code caches. var isDebugBuild = typeof require("ns:module").canonicalizeHttpUrlKey === "function"; var origin = "http://127.0.0.1:" + com.tns.tests.ModuleTestServer.ensureStarted(); + var codeCaches = require("./codeCacheFiles"); var originalTimeout; function writeModule(name, body) { @@ -100,21 +101,13 @@ describe("Large file modules", function () { return name + String((error && error.message) || error); } - function modifiedSeconds(path) { - var file = new java.io.File(path); - return file.exists() ? Math.floor(file.lastModified() / 1000) : -1; - } - - // Resolves once a code cache stamped with `path`'s current modification - // time exists, the one the runtime treats as fresh. + // Resolves once a code cache for `path` as it is now exists, the one the + // runtime treats as fresh. function freshCodeCache(path) { var deadline = Date.now() + 5000; return new Promise(function (resolve, reject) { (function poll() { - var source = modifiedSeconds(path); - if (codeCacheEntries(path).some(function (entry) { - return modifiedSeconds(entry) === source; - })) { + if (codeCaches.isFresh(codeCacheFile(path), path)) { resolve(); } else if (Date.now() > deadline) { reject(new Error("no fresh code cache for " + path)); @@ -165,9 +158,9 @@ describe("Large file modules", function () { }); } - // `path`'s module code cache, which the runtime keeps beside the source. - function codeCacheEntries(path) { - return new java.io.File(path + ".mcache").exists() ? [path + ".mcache"] : []; + // `path`'s module code cache. + function codeCacheFile(path) { + return codeCaches.fileFor(path, "module"); } beforeAll(function () { @@ -558,22 +551,23 @@ describe("Large file modules", function () { var firstSource; import(spec + "?v=1").then(function (mod) { expectWholeBody(mod, "file-edited-1", CONSUME_LINES); - firstSource = modifiedSeconds(module.path); + firstSource = codeCaches.sourceToken(module.path); return isDebugBuild ? undefined : freshCodeCache(module.path); }).then(function () { var edited = bigModule("file-edited-2", CONSUME_LINES + 7).body; expect(edited.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); writeModule("edited", edited); - // Freshness is compared in whole seconds, so an edit within the - // first source's second would leave the old cache looking fresh. - if (modifiedSeconds(module.path) === firstSource) { - new java.io.File(module.path).setLastModified((firstSource + 2) * 1000); + // On a file system with coarse timestamps the edit could keep the + // first source's mtime, and with it the old cache's freshness token. + if (codeCaches.sourceToken(module.path) === firstSource) { + var source = new java.io.File(module.path); + source.setLastModified(source.lastModified() + 2000); } if (!isDebugBuild) { - var stale = codeCacheEntries(module.path); - expect(stale.length).toBe(1); - expect(modifiedSeconds(stale[0])).toBe(firstSource); - expect(modifiedSeconds(module.path)).not.toBe(firstSource); + var stale = codeCaches.readHeader(codeCacheFile(module.path)); + expect(stale !== null).toBe(true); + expect(stale && stale.token).toBe(firstSource); + expect(codeCaches.sourceToken(module.path)).not.toBe(firstSource); } return import(spec + "?v=2"); }).then(function (mod) { @@ -593,12 +587,10 @@ describe("Large file modules", function () { expectWholeBody(mod, "file-cache-probe", LINES); var deadline = Date.now() + 5000; function poll() { - var entries = codeCacheEntries(module.path); - if (entries.length > 0 || Date.now() > deadline) { - expect(entries.length).toBe(isDebugBuild ? 0 : 1); - for (var i = 0; i < entries.length; i++) { - new java.io.File(entries[i]).delete(); - } + var cache = new java.io.File(codeCacheFile(module.path)); + if (cache.exists() || Date.now() > deadline) { + expect(cache.exists()).toBe(!isDebugBuild); + cache.delete(); done(); return; } @@ -616,31 +608,25 @@ describe("Large file modules", function () { } var module = writeBig("corrupt-cache", "file-corrupt-cache", CONSUME_LINES); expect(module.body.length).toBeGreaterThan(CACHE_CONSUME_THRESHOLD); - var cachePath = module.path + ".mcache"; - var garbage = "not a code cache"; + var cachePath = codeCacheFile(module.path); import(module.spec + "?v=1").then(function (mod) { expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES); return freshCodeCache(module.path); }).then(function () { - var cacheFile = new java.io.File(cachePath); - var stamp = cacheFile.lastModified(); - var out = new java.io.FileOutputStream(cacheFile); - try { - out.write(new java.lang.String(garbage).getBytes("UTF-8")); - } finally { - out.close(); - } - cacheFile.setLastModified(stamp); - // Still looks fresh, so the next load consumes it. - expect(modifiedSeconds(cachePath)).toBe(modifiedSeconds(module.path)); + // The header still matches, so the next load hands the zeroed + // payload to V8, which rejects it. + codeCaches.zeroPayload(cachePath); + expect(codeCaches.isFresh(cachePath, module.path)).toBe(true); + expect(codeCaches.readHeader(cachePath).zeroPayload).toBe(true); return import(module.spec + "?v=2"); }).then(function (mod) { expectWholeBody(mod, "file-corrupt-cache", CONSUME_LINES, 2); var deadline = Date.now() + 5000; return new Promise(function (resolve, reject) { (function poll() { - if (new java.io.File(cachePath).length() > garbage.length && - modifiedSeconds(cachePath) === modifiedSeconds(module.path)) { + var header = codeCaches.readHeader(cachePath); + if (header !== null && !header.zeroPayload && + codeCaches.isFresh(cachePath, module.path)) { resolve(); } else if (Date.now() > deadline) { reject(new Error("the corrupt cache was not rewritten")); diff --git a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js index 4a321aac5..9b914d2b7 100644 --- a/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js +++ b/test-app/app/src/main/assets/app/tests/testWorkerConcurrentStartup.js @@ -14,8 +14,12 @@ describe("Script code caches with workers starting together", function () { expected[name] = require("./concurrentStartup/" + name).value; }); + var codeCaches = require("./codeCacheFiles"); + var sourcePath = function (name) { + return fixtureDir + "/" + name + ".js"; + }; var cacheFile = function (name) { - return new java.io.File(fixtureDir, name + ".js.cache"); + return new java.io.File(codeCaches.fileFor(sourcePath(name), "script")); }; var dropCaches = function () { @@ -99,7 +103,7 @@ describe("Script code caches with workers starting together", function () { expectValues(await runBatch()); }, 120000); - it("publishes caches stamped with their source's mtime and leaves no temporaries", async function () { + it("publishes caches for their source's current mtime and leaves no temporaries", async function () { if (!cachesEnabled) { pending("code caches are off: debuggable build or no \"codeCache\": true"); } @@ -114,21 +118,12 @@ describe("Script code caches with workers starting together", function () { }); } + var leftovers = []; moduleNames.forEach(function (name) { - var cache = cacheFile(name); - var source = new java.io.File(fixtureDir, name + ".js"); - expect(name + ": " + cache.exists()).toBe(name + ": true"); - expect(Math.floor(cache.lastModified() / 1000)) - .toBe(Math.floor(source.lastModified() / 1000)); + var cache = String(cacheFile(name).getAbsolutePath()); + expect(name + ": " + codeCaches.isFresh(cache, sourcePath(name))).toBe(name + ": true"); + leftovers = leftovers.concat(codeCaches.temporariesOf(cache)); }); - - var names = new java.io.File(fixtureDir).list(); - var leftovers = []; - for (var i = 0; i < names.length; i++) { - if (String(names[i]).indexOf(".cache.") !== -1) { - leftovers.push(String(names[i])); - } - } expect(leftovers).toEqual([]); }, 60000); }); diff --git a/test-app/runtime/src/main/cpp/File.cpp b/test-app/runtime/src/main/cpp/File.cpp index da5c6b737..9f3d59d59 100644 --- a/test-app/runtime/src/main/cpp/File.cpp +++ b/test-app/runtime/src/main/cpp/File.cpp @@ -20,47 +20,6 @@ using namespace std; namespace tns { -string File::ReadText(const string& filePath) { - bool ok; - return ReadText(filePath, ok); -} - -string File::ReadText(const string& filePath, bool& ok) { - ok = false; - - FILE* file = fopen(filePath.c_str(), READ_BINARY); - if (file == nullptr) { - // A path that never existed, or one deleted between a caller's stat and - // this open. Callers surface their own error; reading on regardless - // aborts the process on a null FILE*. - DEBUG_WRITE_FORCE("File::ReadText: cannot open %s", filePath.c_str()); - return string(); - } - - fseek(file, 0, SEEK_END); - auto size = ftell(file); - if (size < 0) { - DEBUG_WRITE_FORCE("File::ReadText: cannot size %s", filePath.c_str()); - fclose(file); - return string(); - } - rewind(file); - - // Read straight into the string that is returned: main and worker runtimes - // read modules concurrently from their own threads, so there is no scratch - // buffer to share, and the caller needs a string either way. - string content(static_cast(size), '\0'); - auto bytesRead = fread(content.data(), 1, static_cast(size), file); - fclose(file); - - // A short read is a truncated file, not a failure to open; `size` is only - // what the directory entry claimed. - content.resize(bytesRead); - - ok = true; - return content; -} - void* File::ReadBinary(const string& filePath, int& length) { length = 0; @@ -77,9 +36,8 @@ void* File::ReadBinary(const string& filePath, int& length) { } rewind(file); - // A file truncated after the size was taken reads short. Callers hand the - // buffer to consumers that trust its length (V8 does not checksum code - // caches in release builds), so it is all of the file or nothing. + // A file truncated after the size was taken reads short; callers get all + // of the file or nothing. uint8_t* data = new uint8_t[size]; auto bytesRead = fread(data, sizeof(uint8_t), size, file); fclose(file); @@ -92,46 +50,5 @@ void* File::ReadBinary(const string& filePath, int& length) { return data; } -bool File::WriteBinary(const string& filePath, const void* data, int length, time_t modificationTime) { - // Exclusive creation in the target's directory, so concurrent writers of - // the same path never share a temporary and rename stays on one file system. - string tempPath(filePath); - tempPath.append(".ns-XXXXXX"); - int fd = mkstemp(tempPath.data()); - if (fd < 0) { - return false; - } - - bool ok = length >= 0; - auto cursor = static_cast(data); - size_t remaining = ok ? static_cast(length) : 0; - while (ok && remaining > 0) { - ssize_t written = write(fd, cursor, remaining); - if (written < 0) { - ok = errno == EINTR; - continue; - } - cursor += written; - remaining -= static_cast(written); - } - - if (ok && modificationTime >= 0) { - struct timespec times[2]; - times[0].tv_sec = 0; - times[0].tv_nsec = UTIME_NOW; - times[1].tv_sec = modificationTime; - times[1].tv_nsec = 0; - ok = futimens(fd, times) == 0; - } - - ok = (close(fd) == 0) && ok; - ok = ok && rename(tempPath.c_str(), filePath.c_str()) == 0; - if (!ok) { - unlink(tempPath.c_str()); - } - - return ok; -} - const char* File::READ_BINARY = "rb"; } diff --git a/test-app/runtime/src/main/cpp/File.h b/test-app/runtime/src/main/cpp/File.h index 6e3f4a0bd..f045079f3 100644 --- a/test-app/runtime/src/main/cpp/File.h +++ b/test-app/runtime/src/main/cpp/File.h @@ -8,25 +8,11 @@ #ifndef JNI_FILE_H_ #define JNI_FILE_H_ -#include #include namespace tns { class File { public: - static std::string ReadText(const std::string& filePath); - /* - * `ok` distinguishes a file that could not be opened from one that is - * genuinely empty — the plain overload renders both as "". - */ - static std::string ReadText(const std::string& filePath, bool& ok); - /* - * Replaces the file atomically: readers of `filePath` see the previous - * file or the complete new one, never a partial write. A non-negative - * `modificationTime` becomes the file's mtime before it is published. - */ - static bool WriteBinary(const std::string& filePath, const void* inData, int length, - time_t modificationTime = -1); /* * The whole file in a buffer the caller frees with delete[], or * nullptr (length 0) when it cannot be read in full. diff --git a/test-app/runtime/src/main/cpp/ModuleInternal.cpp b/test-app/runtime/src/main/cpp/ModuleInternal.cpp index 65b422141..48c4122b2 100644 --- a/test-app/runtime/src/main/cpp/ModuleInternal.cpp +++ b/test-app/runtime/src/main/cpp/ModuleInternal.cpp @@ -7,7 +7,6 @@ #include "ModuleInternal.h" #include "ModuleInternalCallbacks.h" #include "BuiltinLoader.h" -#include "File.h" #include "HttpLoader.h" #include "ModuleUrl.h" #include "JniLocalRef.h" @@ -24,25 +23,17 @@ #include "CallbackHandlers.h" #include "ManualInstrumentation.h" #include "Runtime.h" -#include "RuntimeState.h" #include "TraceLog.h" #include "ns/JsError.h" +#include "ns/loader/FileCompile.h" #include #include #include -#include -#include #include #include -#include #include -#include #include -#include #include -#include -#include -#include using namespace v8; using namespace std; @@ -996,44 +987,18 @@ Local ModuleInternal::LoadModule(Isolate* isolate, const string& moduleP Local