Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 24 additions & 6 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ set_property(DIRECTORY PROPERTY INCLUDE_DIRECTORIES "")

set(NS_RUNTIME_COMMON_V8_FREE_SOURCES
src/Base64.cpp
src/Trace.cpp
src/http/Canonicalize.cpp
src/http/HostClass.cpp
src/http/ModuleFetch.cpp
src/http/ModuleResponse.cpp
src/http/RemoteModuleAllowlist.cpp
)

set(NS_RUNTIME_COMMON_V8_SOURCES
Expand Down Expand Up @@ -61,16 +67,28 @@ else ()
endif ()

target_include_directories(ns_runtime_common PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_include_directories(ns_runtime_common PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_compile_features(ns_runtime_common PRIVATE cxx_std_20)
set_target_properties(ns_runtime_common PROPERTIES CXX_EXTENSIONS OFF)
target_compile_options(ns_runtime_common PRIVATE ${NS_RUNTIME_COMMON_WARNINGS})

if (NS_RUNTIME_COMMON_HOST_TESTS)
enable_testing()
add_executable(ns_runtime_common_tests tests/Base64Test.cpp)
target_link_libraries(ns_runtime_common_tests PRIVATE ns_runtime_common)
target_compile_features(ns_runtime_common_tests PRIVATE cxx_std_20)
set_target_properties(ns_runtime_common_tests PROPERTIES CXX_EXTENSIONS OFF)
target_compile_options(ns_runtime_common_tests PRIVATE ${NS_RUNTIME_COMMON_WARNINGS})
add_test(NAME ns_runtime_common_tests COMMAND ns_runtime_common_tests)
find_package(Threads REQUIRED)
# The core resolves its platform functions (ns/Platform.h) at the final
# link; tests/FakePlatform.cpp stands in for a runtime's.
set(NS_RUNTIME_COMMON_TESTS
Base64Test
HttpFetchTest
HttpPolicyTest
)
foreach (test ${NS_RUNTIME_COMMON_TESTS})
add_executable(${test} tests/${test}.cpp tests/FakePlatform.cpp)
target_link_libraries(${test} PRIVATE ns_runtime_common Threads::Threads)
target_include_directories(${test} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src)
target_compile_features(${test} PRIVATE cxx_std_20)
set_target_properties(${test} PROPERTIES CXX_EXTENSIONS OFF)
target_compile_options(${test} PRIVATE ${NS_RUNTIME_COMMON_WARNINGS})
add_test(NAME ${test} COMMAND ${test})
endforeach ()
endif ()
92 changes: 56 additions & 36 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
# A shared module-loader core for the iOS and Android runtimes

Status: proposal, 2026-12-04, updated 2026-12-05. Step 1 of §9 (this
repository and its build wiring) is under way. F3 (a private submodule
repository) and F7 (the `nativescript::common` namespace) are decided; the
rest of §7 is open. iOS #622 has since merged (052675a1); its Android port is
repository and its build wiring) is done, and step 5 (the HTTP policy core)
is built in `ns/http/`. F3 (a submodule repository), F7 (the
`nativescript::common` namespace) and D1–D10 are decided; the rest of §7 is
open. iOS #622 has since merged (052675a1); its Android port is
NativeScript/android #2177.

Baseline: NativeScript/ios `origin/main` 73c99f9f, NativeScript/android
Expand Down Expand Up @@ -381,58 +382,74 @@ using Deadline = std::optional<std::chrono::steady_clock::time_point>;

### 4.5 HTTP transport (report C §3)

The cut is at **one attempt**. The core owns:
- the gate and allowlist;
- the header set;
Built: `ns/http/ModuleTransport.h` (the seam) and `ns/http/ModuleFetch.h` (the
loader's API). The cut is at **one attempt**. The core owns:
- the gate and allowlist, re-checked against the URL a redirect ended at;
- the header set, `User-Agent: NativeScript-HTTP-ESM` included;
- the timeout, retry and deadline policy;
- classification;
- the cache switch and its inspector holders;
- Clear-Site-Data parsing.
- the cache switch and its holders;
- Clear-Site-Data parsing and scope;
- the fetch threads for transports that block, capped per host class.

The transport only performs attempts.
The transport only performs attempts and stores the cache.

```cpp
namespace nativescript::common::http {

struct AttemptRequest {
std::string url; // gated, NormalizeHttpModuleUrl spelling, never canonicalized
FetchPath path; // kGraphWalk | kSynchronousFallback (separate connections)
std::chrono::milliseconds timeout;
bool useCache; // sampled once per fetch by the core
const Headers* headers;
std::chrono::milliseconds timeout; // idle bound, > 0, clamped to the deadline
std::chrono::milliseconds waitBound; // sync only: timeout + 5 s, honoured if cancellable
bool useCache; // sampled once per fetch, when it is issued
std::vector<RequestHeader> headers; // core-built, no-cache pair included when off
};
struct AttemptOutcome {
bool arrived; int status; std::string contentType, body, finalUrl;
bool arrived; // status line, and for a 2xx the whole body
int status; std::string contentType, body;
std::string finalUrl; // after redirects, set whenever `arrived`
std::vector<std::string> clearSiteData; // raw; the core parses and applies
bool malformedUrl, waitExpired; // neither is retried
std::string errorDescription;
};

class ModuleTransport {
public:
virtual const char* Name() const = 0;
virtual AttemptOutcome FetchBlocking(const AttemptRequest&) = 0;
// Default (in core): FetchBlocking on per-host-class lanes (Android's lanes, moved).
virtual void FetchAsync(AttemptRequest, std::function<void(AttemptOutcome)> anyThreadOnce);
virtual bool SchedulesItself() const { return false; } // NSURLSession: true
// Only used when SchedulesItself(); otherwise the core runs FetchBlocking on its
// fetch threads (Android's lanes, moved).
virtual void FetchAsync(AttemptRequest, std::function<void(AttemptOutcome)> anyThreadOnce);
// The retry delay of a self-scheduling transport. Default: one core timer thread;
// iOS overrides it with dispatch_after so each task gets an autorelease pool.
virtual bool PostDelayed(std::chrono::milliseconds, std::function<void()>);
virtual CacheOpResult ClearAll() = 0;
virtual CacheOpResult ClearOrigin(const std::string& origin) = 0;
virtual void OnFetchThreadStart() {} // Android: JVM attach
virtual void OnFetchThreadExit() {} // Android: JVM detach
};

} // namespace nativescript::common::http

namespace nativescript::common::platform {
http::HttpLoaderConfig ReadHttpLoaderConfig(); // once per process, before any cache setter
http::ModuleTransport& HttpTransport();
void OnLaneThreadStart(); // Android: JVM attach
void OnLaneThreadExit(); // Android: JVM detach
}
```

- **iOS** keeps its NSURLSession partitions, NSURLCache generations and
delegate queues inside the transport.
- **iOS** keeps its NSURLSession partitions, NSURLCache generations, launch
options and delegate queues inside the transport.
- **Android** keeps OkHttp, HttpURLConnection, StrictMode and JNI frame
handling inside it.
handling inside it. Its transport cannot cancel a blocking attempt yet, so
its synchronous fallback still has no total-wait bound (D7).
- Both already satisfy this contract (report C §2): completion exactly once, on
any thread, possibly inline; never canonicalize; the sync path never shares
the walk's connections.
- The retry delay of a self-scheduling transport runs through its
`PostDelayed`, holding no connection. On the fetch threads it still sleeps,
holding the slot for 120 ms (D1, v1).

### 4.6 Threads

Expand Down Expand Up @@ -714,22 +731,25 @@ the #383/#444 ↔ android#1965/#2021 work):
| C4 | File `import()` pumping | #622: async; Android main: sync pump | #622 |
| C5 | Boot backstop: rejection on the first poll | Android fatal; iOS not | Android |

### D. HTTP (report C §3 D1–D10, condensed)

- **Sync fallback total wait bound:** take iOS's timeout + 5 s. Android needs a
cancellable call for it.
- **What counts as a transport error:** take Android's rule; a status-bearing
response is never one.
- **Clear-Site-Data scope:** take iOS's rule, response origin plus requesting
origin.
- **Failed cache clears:** report them, as Android does. JS throws and the
inspector answers `-32000`.
- **Inspector bookkeeping:** take iOS's shape, a holder set keyed by connection
id.
- **User-Agent:** one value on both. iOS sends none today.
- **Queue time counts against the deadline,** as on Android.
- **Open, neither side does it:** re-check the gate after redirects. Expose
`finalUrl` now so the check can be added.
### D. HTTP (report C §3 D1–D10): decided 2026-12-05

All ten as report C recommends, built in `ns/http/`:

| # | Decision |
|---|---|
| D1 | The retry delay runs off-thread on a core timer for self-scheduling transports. Fetch threads sleep through it for now. |
| D2 | Queue time counts against the deadline: each attempt's timeout is computed when it starts. |
| D3 | The cache switch is sampled once per fetch, when it is issued; a retry reuses it. |
| D4 | Clear-Site-Data clears the response's origin plus the fetching origin, each once, before the fetch is reported. |
| D5 | Failed cache clears are reported (`CacheOpResult`). JS throws and the inspector answers `-32000`. |
| D6 | Cache holders are a set keyed by an opaque id (`SetModuleHttpCacheDisabledBy`), idempotent per id. |
| D7 | The sync fallback's total wait is the attempt timeout + 5 s. Android cannot cancel an attempt yet, so its wait stays unbounded until its transport can. |
| D8 | `User-Agent: NativeScript-HTTP-ESM` on both. |
| D9 | Deadlines are `optional<steady_clock::time_point>` everywhere. |
| D10 | The gate is re-checked against the final URL after redirects. A transport that does not report it fails closed while an allowlist is in force. The redirect is still followed first, so the request reaches the target before the check. |

Also: a transport error is a response that did not arrive (Android's rule): a
status-bearing answer never is, unless it is a 2xx whose body failed.

### E. Error policy

Expand Down
35 changes: 35 additions & 0 deletions include/ns/Platform.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#ifndef NATIVESCRIPT_COMMON_PLATFORM_H_
#define NATIVESCRIPT_COMMON_PLATFORM_H_

#include <string>
#include <string_view>

// Implemented once by each runtime, in the binary the core links into. None of
// these may call back into the core.
namespace nativescript::common::platform {

enum class TraceCategory {
kEsm, // module resolution, compilation, linking, evaluation
kFetch, // the HTTP module transport
};

// One unconditional diagnostic line (iOS os_log, Android logcat).
void Log(std::string_view message);

// Whether `category` is being traced. Called on every traced path, from any
// thread, so it should cost no more than a load.
bool TraceEnabled(TraceCategory category);
void Trace(TraceCategory category, std::string_view message);

// The loader's spelling of `input` as an absolute http(s) module URL: the
// WHATWG href with the authority as written; `input` itself when the parser
// rejects it but it starts with a lowercase http(s) scheme; empty when it is
// not an http(s) URL.
std::string NormalizeHttpModuleUrl(const std::string& input);

// The WHATWG origin of an absolute http(s) URL; empty for anything else.
std::string HttpUrlOrigin(const std::string& url);

} // namespace nativescript::common::platform

#endif // NATIVESCRIPT_COMMON_PLATFORM_H_
161 changes: 161 additions & 0 deletions include/ns/http/ModuleFetch.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
#ifndef NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_
#define NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_

#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <optional>
#include <string>
#include <vector>

#include "ns/http/ModuleTransport.h"

// The HTTP module loader's policy: which URLs may be fetched, what a response
// means, and the module registry key of an HTTP URL. The transport is the
// platform's (ns/http/ModuleTransport.h).
namespace nativescript::common::http {

// ─── Responses ──────────────────────────────────────────────────────────────

enum class ModuleResponseKind {
kJavaScript,
kJson,
};

// One module fetch's verdict, the same for every fetch path and transport.
struct ModuleFetchResult {
bool ok = false;
int status = 0;
ModuleResponseKind kind = ModuleResponseKind::kJavaScript;
// 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`. It reaches the
// importer's rejection verbatim, so it names the URL and the cause.
std::string failureReason;
};

// ─── Remote-module gate ─────────────────────────────────────────────────────

// The allowlist the gate 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<std::string> entries;
};

// The allowlist for the raw `security.remoteModuleAllowlist` 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<std::vector<std::optional<std::string>>>& items);

// Whether `url` (as fetched) passes `allowlist`: always when it is not in
// force, otherwise when one entry is a prefix of it that ends at a
// URL-component boundary.
bool RemoteUrlAllowedByAllowlist(const std::string& url,
const RemoteModuleAllowlist& allowlist);

// ─── Registry keys ──────────────────────────────────────────────────────────

// Which query params are cache busters, which path prefixes are dev endpoints
// whose queries may be normalized, and which paths keep their query verbatim
// because the query is the identity. Supplied per isolate by the dev client
// (ns:module `configureLoader({ canonicalization })`).
struct CanonicalizationConfig {
std::vector<std::string> stripParams; // query param names to drop
std::vector<std::string> devPathPrefixes; // StartsWith → normalize query
std::vector<std::string> preserveQueryPrefixes; // contains → keep query
};

// The module registry key of a URL already spelled by NormalizeHttpModuleUrl.
// The fragment is always stripped. The query survives unless `vocabulary`
// says otherwise: a path containing a `preserveQueryPrefixes` entry keeps it
// verbatim; a path under a `devPathPrefixes` entry drops every `stripParams`
// name and sorts what remains. A null `vocabulary` keeps every query.
std::string CanonicalizeNormalizedHttpUrlKey(
const std::string& normalizedUrl, const CanonicalizationConfig* vocabulary);

// ─── Fetch concurrency ──────────────────────────────────────────────────────

// Which concurrency cap a module URL's fetches share when the transport
// blocks a thread per request.
// kLoopback: 127.0.0.1, [::1], localhost, or the development machine as seen
// from the Android emulator (10.0.2.2) or Genymotion (10.0.3.2). On a
// device that is almost always `adb reverse`, whose listener overflows
// under a burst of connects, each overflow costing 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);

// The fetch thread cap for `hostClass`: the platform's configured value, or
// the default (loopback 6, remote 32). Unused while the transport schedules
// itself.
size_t ModuleFetchConcurrency(ModuleFetchHostClass hostClass);

// ─── Gate ───────────────────────────────────────────────────────────────────

// Debug builds always allow remote modules; release builds only when the app
// config enables them.
bool IsRemoteModulesAllowed();

// Whether `url` (NormalizeHttpModuleUrl spelling) may be fetched: in debug
// builds always, otherwise when remote modules are enabled and the allowlist
// passes it.
bool IsRemoteUrlAllowed(const std::string& url);

// ─── Fetching ───────────────────────────────────────────────────────────────
//
// `url` is gated, fetched and reported in NormalizeHttpModuleUrl spelling;
// nothing here canonicalizes. Both primitives judge responses alike and share
// the cache. Either retries once, only for a transport error and never for an
// HTTP status.

// Blocks the calling thread for one module. The wait is bounded by the
// attempt timeout plus a margin when the transport can cancel an attempt.
// Returns `result.ok`.
bool HttpFetchModule(const std::string& url, ModuleFetchResult& result);

// The graph load's fetch budget; nullopt is unbounded. Each attempt's timeout
// is clamped to what remains when it starts, so time spent queued counts, and
// no attempt starts past it. A response that lands late is still reported.
using ModuleFetchDeadline =
std::optional<std::chrono::steady_clock::time_point>;

// Never blocks. `completion` runs exactly once, on any thread, possibly
// before this returns (a blocked URL, a deadline already passed). It must not
// touch the engine.
void FetchModuleBodyAsync(const std::string& url, ModuleFetchDeadline deadline,
std::function<void(ModuleFetchResult)> completion);

// ─── HTTP cache ─────────────────────────────────────────────────────────────
//
// Process-wide, from any thread. Each fetch reads the switch once, when it is
// issued, so a change never affects a fetch already in flight.

// The setting, and no holder disabling it.
bool ModuleHttpCacheEnabled();

void SetModuleHttpCacheEnabled(bool enabled);

// Holders (an inspector connection) disable the cache for as long as any
// holds it. Idempotent per id; a holder going away passes false.
void SetModuleHttpCacheDisabledBy(uint64_t holderId, bool disabled);

// Everything the module cache stores, durably before returning.
CacheOpResult ClearModuleHttpCache();

} // namespace nativescript::common::http

#endif // NATIVESCRIPT_COMMON_HTTP_MODULE_FETCH_H_
Loading
Loading