Repository navigation
feat(runtime)!: load modules through the shared runtime-common core - #2179
Draft
edusperoni wants to merge 45 commits into
Draft
edusperoni wants to merge 45 commits into
edusperoni wants to merge 45 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.
Adopts units 6.4 and 6.5 of the shared loader core: - The module graph walk, file jobs, streamed compiles on the shared compile pool and the liveness token come from the core; Android's walk, pool, file jobs and streamed compile code are gone. - Static import and import() use the core's ResolveModuleCallback and ImportModuleDynamicallyCallback; JSON modules are the core's synthetic modules (strict JSON.parse), and import attributes are checked (debug builds warn; enforcement is off). - Every DestroyRuntime calls loader::Quiesce before the isolate leaves the runtime cache, replacing QuiesceModuleLoadsForIsolate. - EventLoop::PostV8Task and the platform adapter report a dropped task. - New up-calls: BuiltinModule (C++ exceptions become V8 exceptions) and FileModuleSourceWrap (no wrap); MainContext tolerates a runtime with no context yet.
- JSON modules reject text that is not strict JSON with a SyntaxError naming the module, keep __proto__ as an own property, and run nothing after the value, for files, a static import, and HTTP roots. - import() of large file modules and slow HTTP modules issued before and after a worker's close() or terminate() does not crash, and the main runtime still loads afterwards.
A top-level boolean in the app's package.json, false by default, mapped to LoaderConfig::enforceImportAttributes: true rejects an import whose attributes do not match the module with Node's TypeError instead of the debug-build warning.
Picks up: a static import of '' throws Cannot find module; the debug import-attribute warning is logged once per module whatever its query; a resolved import() root is not stat'ed a second time.
Core 6.6: InstallHostCallbacks, import.meta, the require(esm) facade and the ns:module binding in the core; import detects ES module syntax in a .js file and takes other extensions as CommonJS; code cache format 2; import() of a module being evaluated settles after its evaluation; and the cached import() trims.
…time-common 6.6 The core now installs the dynamic import and import.meta callbacks, builds the ns:module binding and the require(esm) facade; Android keeps only forcePlatformHttpTransport, added after the core's binding in debuggable builds. ModuleInternalCallbacks is gone. import() of a file that is not .mjs goes through the core's CompileFileModule: a .js file is detected as an ES module or CommonJS, and any other extension is CommonJS. platform::RequireFileForImport loads CommonJS through require()'s cache, as a script whatever the extension, with a .so taking the addon path. FileModuleSourceWrap is deleted. Code cache files are format 2 (a module format field at offset 32); the test helper reads that layout.
A top-level boolean in the app's package.json, false by default. True drops Android's file:// origin override, so files under the app root are reported as app:///<relative path> and import.meta.url, .filename and .dirname name the file's real path.
ES module and top-level-await .js files, CommonJS .js and .cjs sharing require()'s cache, throwing CommonJS, a self-import and an A->B->import(A) cycle settling after evaluation, import.meta fields, and the module format recorded in the code cache.
…common 7 Pins runtime-common at 0d6bea8. Module graph evaluation, LoadEsModule and require(esm) come from the core; ModuleInternal keeps the CommonJS loader and its require() options, now the core's ModuleEvaluationOptions. Runtime.run() calls a new runMainModule: an ES module entry runs through loader::RunMainEntry, a CommonJS one through require() and then loader::HoldBoot, both with no hand-off, so boot holds the thread, with timers running, until the entry settled and no graph walk is left, for up to 60 s. Every failure, termination included, is rethrown to Java as a NativeScriptException, in every build. HoldBootBackstop is gone, and runModule (@JavaScriptImplementation classes, tns-java-classes.js, inspector_modules) no longer holds the thread; an .mjs reached that way loads through a pumping LoadEsModule, so its class exists when the call returns. A worker's ES module entry goes through loader::RunEsModuleEntry, and the worker waits on the promise it returns. The 1 s entry window is gone: a local entry with a top-level await always comes back pending, and one that rejects reaches the worker's onerror as "Unhandled promise rejection: ...". The inspector's init() also swallows JsError and Terminated from inspector_modules.
import() and require() of one .mjs share one evaluation in either order; a pumping require() of a module whose top-level await is still running gets its settled exports; a require() of a module still evaluating up the stack throws ERR_REQUIRE_CYCLE_MODULE. Worker entry specs and fixtures describe a local entry that comes back pending instead of an in-place window.
The core's step 7 review fixes: one deadline covers a pumping load's walk and settle, and RunMainEntry's covers load and hold; the boot marks the entry's promise handled, so a boot rejection is reported once, by the throw; Quiesce ends a wait with "The module loader is shutting down"; kAsync loads and local worker entries throw Terminated on a terminating isolate. RunMainModule refuses a kHandedOff outcome: it passes no hand-off predicate, so a pending entry would have nowhere to report a failure.
Pins runtime-common at 212f22b. require() is the core's: the global require comes from loader::InstallCommonJs, ns:module's createRequire from the core's binding, and resolution, the require cache, module objects, JSON and require(esm) from ns/loader/CommonJs.h. A CommonJS file is compiled with CompileFileCommonJs, with no wrapper text, so MetadataNode no longer corrects line-1 columns for extend() names; the static binding generator's names are unchanged. `this` at a module's top level still holds __extends (commonJsThisHasExtends). Resolution follows the core: a package name walks node_modules first, then app/tns_modules and app/tns_modules/tns-core-modules. Errors are Node's: "Cannot find module '<spec>' (tried <path>)" with code MODULE_NOT_FOUND, and a compile error or a module's own throw arrives as thrown. Module.java loses its resolver: bootstrapApp and resolveEntryPath call ResolveMainEntry and ResolveEntry over JNI. Runtime.run() runs every main entry through RunMainEntry, and runModule and CommonJS worker entries through RunCommonJsEntry. A worker entry resolves through ResolveEntry: a bare name throws ERR_WORKER_PATH from the constructor, and a "./" name missing beside the caller is tried from the app root. inspector_modules is required from the app root. system_lib:// names and .so files load through platform::RequireNativeAddon (Node-API registration or NSMain, whose arguments keep module, exports, require, __filename, __dirname); a Node-API name that fails reads "Failed to initialize Node-API module". Removed: require-factory.js, the __nativeRequire and __requireOverride globals, and the Transitional.h up-calls. BREAKING CHANGE: the __nativeRequire and __requireOverride globals are removed. createRequire from ns:module replaces __nativeRequire.
A bare worker name throws ERR_WORKER_PATH from the constructor; a "./" name found in neither the caller's directory nor the app root reports the caller's attempt; one missing beside the caller runs from the app root. Two extend() calls on the first line of a CommonJS file get their prebuilt classes, named by the file's own columns.
Only the global require's base read it, and that is the app root now. initWorkerRuntime, initNativeScript, Runtime::Init, PrepareV8Runtime and WorkerWrapper no longer carry it, and DynamicConfiguration loses callingJsDir.
Runs Require/index.js "require directory with index.json and no package.json", which the core resolves now; the other specs the commit un-gates already ran on Android.
The Context names the data directory /data/user/<id>/<pkg>, and the app root is spelled under its canonical /data/data/<pkg>. Runtime.init passes that pair to LoaderConfig::appRootAliases, so a module reached through either spelling is one module.
…me-common 8c4e81d Pins runtime-common at 8c4e81d, the step 8 review round, and sets LoaderConfig::moduleRunScope: each CommonJS module's call, and each ES module evaluation root, runs inside CrashBreadcrumbs::ModuleScope and an instrumentation frame "LoadModule <name>". A native crash during a module's top-level code names that module in the breadcrumb store again. From the core: a .mjs worker or tool entry runs as an ES module, a JSON or native addon entry throws "Cannot run <path> as an entry: it is not a JavaScript module", a worker entry may be "~name", and the Node-API lookup runs once per bare name.
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
The Android runtime loads modules through NativeScript/runtime-common, the module-loader core it now shares with iOS (design:
docs/DESIGN.mdthere). The core is thetest-app/runtime/src/main/cpp/runtime-commonsubmodule, built throughadd_subdirectory. It is pinned at8c4e81d, which is on the core'smain. The iOS counterpart is NativeScript/ios#625.101 files change: +3113 / −10241.
Moved to the core
atob/btoanatives.RuntimeCommonPlatform.cppimplements the core's platform functions.tns::EventLoopimplements the core'sLoop.PumpUntil(Deadline, settled, PumpMode, idle)replaces both earlier pump functions.HttpLoader.cppkeeps only the OkHttp / HttpURLConnection transport.Context.getCodeCacheDir()/v8, which the system empties on upgrade. They are named, validated and written by the core.<source>.cache/.mcachefiles beside sources are deleted once per install.StaticConfiguration's old constructor leaves code caches off.import(), JSON modules and import attributes;import.meta, therequire(esm)facade and thens:modulebinding.ModuleInternalCallbacksis deleted.Runtime.run()boots the main entry through a new JNIrunMainModule. Boot is a pumping require of the entry, ES module or CommonJS: it holds the thread, with timers running, until the entry and everything it loaded have settled, for up to 60 s.NativeScriptExceptionin every build.HoldBootBackstopis gone.createRequireand Node-API /NSMainaddons.ScriptCompiler::CompileFunction, with no wrapper text. Top-levelthisstill holds__extends.Module.javaloses its resolver:bootstrapAppandresolveEntryPathcall the core over JNI.require-factory.jsis deleted.CrashBreadcrumbs::ModuleScopeand aLoadModule <name>instrumentation frame. ES modules had neither before.BREAKING CHANGE: the
__nativeRequireand__requireOverrideglobals are removed.createRequirefromns:modulereplaces__nativeRequire.@nativescript/viteis its only user and moves tocreateRequirefor 9.2.Changes JS can see
Loading and resolution
require()follows Node's order:node_modules, walking up to the app root;app/tns_modules;app/tns_modules/tns-core-modules.Cannot find module '<spec>' (tried <path>)with codeMODULE_NOT_FOUND.require()carry nofullMessage.package.jsonis read as strict JSON. Before,org.jsonaccepted comments, trailing commas, single quotes and unquoted keys.package.jsonmainstarting with/is a device path. Before, it resolved inside the package.importorrequire(), and through/data/user/0/<pkg>or/data/data/<pkg>.importof a.jsfile is detected as an ES module or CommonJS. Any other extension (.cjsincluded) goes throughrequire()and its cache.idis".", and it isrequire.main.JSON.parse."enforceImportAttributes": trueinpackage.jsonmakes them reject with aTypeError."appSchemeOrigins": truereports app files asapp:///<path>.file:URLs handed to the loader are parsed as URLs:#starts a fragment, and escapes are decoded;localhost, or%2F,%5Cor%00, names nothing;file:///app/andfile:///android_asset/app/both name the app root.blob:or builtin module has noimport.meta.dirname.system_lib://name or a.sofile loads through Node-API registration orNSMain. A Node-API module that fails reads "Failed to initialize Node-API module".Evaluation and boot
require()of a module whose top-level await is still running gets its settled exports.require()of an ES module still evaluating up the stack throwsERR_REQUIRE_CYCLE_MODULE.runModule:@JavaScriptImplementationclasses,tns-java-classes.jsandinspector_modulesno longer hold the thread.require()no longer returnsundefined.Workers
ERR_WORKER_PATHfrom the constructor;./and../resolve from the calling module, then from the app root;~/and~nameare app-root names.require: a worker's globalrequireis bound to the app root, as on iOS.onerror.HTTP loader
security.remoteModuleAllowlist, a redirect that ends outside the allowlist is refused.clearHttpCache()throws a plainErrorwith the message.Code cache
Unchanged on purpose: the synchronous HTTP fallback still has no total-wait bound. That needs a cancellable transport (design D7).
Merge order
589478f.Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
docs/DESIGN.md§9 records each step and its decisions)Does your pull request have unit tests?
Yes.
./gradlew -b runtests.gradle runtestsAndVerifyResults -Pabis=arm64-v8aran 2288 specs with 0 failures (8 skipped). The new specs cover:importandrequire();require()cycles;import()of CommonJS and.jsfiles;import()benchmark.Checked by hand on an emulator:
NSMainaddon probes;Debug, median of 12 cold starts, before and after the CommonJS core (
57a3f4917→d5185c27f):require()of a package nameNo Release suite was run; this repo has no Release test lane.
The core has host unit tests of its own (fake and ada URL parsers, ASan+UBSan, TSan) and an opt-in lane linked against V8.