Repository navigation
feat(runtime): base64 and the HTTP module loader from runtime-common - #2179
Draft
edusperoni wants to merge 24 commits into
Draft
edusperoni wants to merge 24 commits into
edusperoni wants to merge 24 commits into
Conversation
…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.
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.
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
…ions 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.
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.
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.
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.
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.
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.
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.
…red 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 <path>" / "Cannot find module <path>" 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.
Once per install, a background thread deletes <source>.cache and <source>.mcache files whose .js/.mjs source sits beside them, and their write temporaries, under files/app. A marker in the files directory records that it ran.
Picks up the fix that measures the code cache quiet period in milliseconds; without it the main isolate created no caches until the app went to the background.
Every worker in the batch publishes the same caches through the one writer thread, so a cache file can exist while a later write of it is still in its temporary.
The core now names modules itself (ModuleIdentity), reading URLs through platform::ParseUrl, which this runtime backs with its own ada. The loader config keeps today's spellings: origins of app files are file:// plus the absolute path, written verbatim, and import.meta.url is the origin. file:///app/ and file:///android_asset/app/ name the app root.
import.meta.url, import.meta.dirname and stack frames spell a file as file:// plus its absolute path, not percent-encoded: a space, a non-ASCII character, a '%' sequence and a '#' in a file name, a query, and a file outside the app root.
Registry keys, script origins, import.meta and the paths read back from origins now come from runtime-common's ModuleIdentity. The runtime's own NormalizePath and the moved ModuleUrl helpers are gone. Origins and import.meta.url keep today's verbatim spelling. What changes for JS: - An http(s), blob: or builtin module has no import.meta.dirname. - A file: URL handed to the loader as a key (invalidateModules, a graph root) is parsed by the URL parser: '#' starts a fragment, escapes are decoded, and a host other than localhost, %2F, %5C or %00 names nothing. - file:///app/ and file:///android_asset/app/ keys name the app root, so invalidating a module through either spelling hits. - A query in a specifier the URL parser rejects stays part of the key. The import() referrer and inspector URLs are origins the runtime wrote, so they are read back verbatim.
Brings units 6.2 (per-isolate loader config, the closing flag and the module registry) and 6.3 (loader vocabulary, import maps and the specifier resolver). The runtime does not build against it until the commits that follow adopt the new API.
platform::LoaderSnapshot() replaces platform::Loader(). The main runtime installs that snapshot with loader::InstallLoader before its first compile; a worker installs the configuration its parent was installed with, captured on the parent's thread. Isolate-thread readers use LoaderConfigFor(isolate), the inspector keeps the snapshot it was created with, and CodeCacheEntryFor takes the config. platform::ParseModuleUrl and BlobStoreUrl now live in ModuleUrl.cpp, from the core's ada reference implementation.
…solver The module registry, its module -> key index, the require(esm) facades, the loader vocabulary (import map, volatile patterns, canonicalization) and specifier resolution now come from runtime-common: - every registration goes through loader::SetRegisteredModule, with the file it was read from for a file module; - static resolution, import() and the graph walk resolve through loader::ResolveModuleSpecifier and report with UnresolvedModuleMessage; - configureLoader parses with loader::ParseImportMap and installs through InstallImportMap, SetVolatilePatterns and SetCanonicalizationConfig; - a worker copies its parent's vocabulary with Capture/InstallLoaderVocabulary; - teardown calls loader::Quiesce first, after which the runtime's own loader state is no longer handed out except to drain it. RemoveModuleFromRegistry and InvalidateModules stay as thin wrappers that also drop in-flight file loads and settle the dynamic imports waiting on a key. The runtime's own resolver, import-map parser and vocabulary are deleted.
- app:/// names the app root, from a file or an http(s) importer;
- a file: URL is percent-decoded, accepts a localhost host and refuses any
other host or an encoded '/';
- an import-map target may be a builtin, and an index-like key ("404") is
accepted;
- a specifier left empty once its query is cut resolves to nothing;
- a root-absolute path is used as written only when it is under the app root
by whole segments, after '..' is folded;
- files named with '#' or '%' invalidate through their own import.meta.url,
and a directory named with '?' resolves its relative imports.
The step6-review fixes on top of 3bcf603.
BlobStoreUrl follows the core's reference again: only text the URL parser would read as a blob: scheme reaches the parse.
- "~/", bare and prefixed root-absolute specifiers drop a ".." at the app root; a relative specifier can still leave it; - a relative import from a blob: module resolves to nothing; - app:x.mjs is refused, app://localhost/ names the app root, and FILE: and file:/ spellings resolve; - a written U+0000 is refused from every importer kind, and %00 in a file: URL names no file; - an import-map scope key without a trailing '/' matches only that URL. The scope-normalization spec keyed a scope on a partial path segment; it now keys it on the importer's exact URL.
JniBench rows for import() of a cached module through each specifier form, and for linking a fresh module whose 20 static imports are cached.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
First consumer of NativeScript/runtime-common, the shared iOS/Android loader core (design:
docs/DESIGN.mdthere). Draft, so it can be tested with vite and other dev servers before review.Moved to the core
Base64 (
ns/Base64.h,ns/Base64Binding.h): the codec and the atob/btoa natives. The core is thetest-app/runtime/src/main/cpp/runtime-commonsubmodule, built throughadd_subdirectory.HTTP module loader (
ns/http/): the remote-module gate and allowlist, classification, canonicalization, timeouts, the single transport-error retry, deadline clamping, the fetch threads capped per host class (moved from here), the cache switch with its inspector holders, and Clear-Site-Data.HttpLoader.cppkeeps only the OkHttp / HttpURLConnection transport. That transport now takes its headers from the core and reports the final URL and the raw Clear-Site-Data values.tns::aliases keep the call sites unchanged.Foundation and event loop (core
ebb7b87):RuntimeCommonPlatform.cppimplements the core's platform functions, including a coreIsolateStateBagper runtime.tns::EventLoopimplements the core'sLoop:PumpUntil(Deadline, settled, PumpMode, idle)replacesPumpUntil(double, …)andPumpNestableV8TasksUntil. The V8-flag parsing for stream-compile threads moves to the core. Catch boundaries also catch the core'sJsErrorandTerminated.User-visible changes
security.remoteModuleAllowlist, a module whose redirect ends outside the allowlist is refused. Before, the gate only checked the requested URL.require()return the namespace;require()interrupted before V8 starts unwinding throws instead of returningundefined;TerminateExecution, so a pump stops even before V8 notices.clearHttpCache()throws a plainErrorwith the message. It no longer carries the Java throwable.Unchanged on purpose: the synchronous fallback still has no total-wait bound. That needs a cancellable transport (design D7).
Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
Does your pull request have unit tests?
The suite passes:
./gradlew -b runtests.gradle runtestsAndVerifyResults -Pabis=arm64-v8aran 2210 tests with 0 failures. The core has host unit tests of its own, including the gate and the redirect check withisDebug=false, which the debuggable test app never exercises.