Skip to content

Commit 6db2428

Browse files
authored
Merge pull request #48 from NativeScript/fix/dev-boot-pump
fix(runtime): pump messages during HTTP imports until dev boot completes
2 parents e9f828a + 280b42d commit 6db2428

6 files changed

Lines changed: 96 additions & 5 deletions

File tree

‎packages/common/src/prelude.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,9 @@ pub const PRELUDE: &str = r#"
280280
getLoadedModuleUrls: function getLoadedModuleUrls() {
281281
return g.__nsModuleLoadedUrls();
282282
},
283+
setDevBootComplete: function setDevBootComplete(done) {
284+
if (typeof g.__nsModuleSetDevBootComplete === 'function') { g.__nsModuleSetDevBootComplete(!!done); }
285+
},
283286
createRequire: function createRequire(filenameOrURL) {
284287
var value = filenameOrURL && typeof filenameOrURL === 'object' ? filenameOrURL.href : filenameOrURL;
285288
if (typeof value !== 'string') {

‎packages/windows-v8/src/esm.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,12 @@ pub fn install_ns_module(env: &napi::Env) -> napi::Result<()> {
118118
})?;
119119
global.set_named_property("__nsModuleConfigureLoader", configure)?;
120120

121+
let boot_complete = env.create_function_from_closure("__nsModuleSetDevBootComplete", |ctx: CallContext| {
122+
esm_loader::set_dev_boot_complete(ctx.get::<JsUnknown>(0)?.coerce_to_bool()?.get_value()?);
123+
ctx.env.get_undefined()
124+
})?;
125+
global.set_named_property("__nsModuleSetDevBootComplete", boot_complete)?;
126+
121127
// Registry eviction plus a one-shot cache-bust nonce on each evicted URL's next fetch.
122128
let invalidate = env.create_function_from_closure("__nsModuleInvalidate", |ctx: CallContext| {
123129
let list = ctx.get::<JsUnknown>(0)?;

‎runtime/src/esm_http.rs‎

Lines changed: 61 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
//!
1212
//! Mechanism mirrors ios/NativeScript/runtime/HttpLoader.mm + ModuleInternalCallbacks.mm.
1313
14-
use std::cell::RefCell;
14+
use std::cell::{Cell, RefCell};
1515
use std::collections::{HashMap, HashSet};
1616
use std::sync::{Mutex, OnceLock};
1717

@@ -348,10 +348,63 @@ fn fetch_once(url: &str, key: &str) -> Result<crate::winhttp::Response, String>
348348
Ok(response)
349349
}
350350

351+
static DEV_BOOT_COMPLETE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
352+
353+
thread_local! {
354+
static PUMPING: Cell<bool> = const { Cell::new(false) };
355+
}
356+
357+
/// `ns:module` `setDevBootComplete`: stops pumping messages during HTTP imports.
358+
pub fn set_dev_boot_complete(done: bool) {
359+
DEV_BOOT_COMPLETE.store(done, std::sync::atomic::Ordering::Relaxed);
360+
}
361+
362+
/// Until dev boot completes, runs `fetch` off-thread and pumps messages meanwhile.
363+
fn pumping<R: Send>(fetch: impl FnOnce() -> R + Send) -> R {
364+
if !is_debug_build() || DEV_BOOT_COMPLETE.load(std::sync::atomic::Ordering::Relaxed) || PUMPING.get() {
365+
return fetch();
366+
}
367+
use windows::core::PCWSTR;
368+
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
369+
use windows::Win32::System::Threading::{CreateEventW, SetEvent, INFINITE};
370+
use windows::Win32::UI::WindowsAndMessaging::{MsgWaitForMultipleObjectsEx, MWMO_INPUTAVAILABLE, QS_ALLINPUT};
371+
372+
let Ok(done) = (unsafe { CreateEventW(None, true, false, PCWSTR::null()) }) else {
373+
return fetch();
374+
};
375+
let event = done.0 as usize;
376+
PUMPING.set(true);
377+
let result = std::thread::scope(|s| {
378+
let handle = s.spawn(move || {
379+
let result = fetch();
380+
unsafe {
381+
let _ = SetEvent(HANDLE(event as *mut _));
382+
}
383+
result
384+
});
385+
// WAIT_OBJECT_0 + 1: messages arrived; the event or a failure ends the wait
386+
while unsafe { MsgWaitForMultipleObjectsEx(Some(&[done]), INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE) }.0
387+
== WAIT_OBJECT_0.0 + 1
388+
{
389+
crate::pump_messages();
390+
}
391+
handle.join()
392+
});
393+
PUMPING.set(false);
394+
unsafe {
395+
let _ = CloseHandle(done);
396+
}
397+
result.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
398+
}
399+
400+
pub(crate) fn fetch_module(url: &str, key: &str) -> Result<FetchedModule, String> {
401+
pumping(|| fetch_module_now(url, key))
402+
}
403+
351404
/// Fetch one module over HTTP (one retry on transport error) and classify the response the way
352405
/// the iOS runtime does: 2xx JavaScript (an empty body is the empty module) or JSON; anything else
353406
/// is an import error naming the URL.
354-
pub(crate) fn fetch_module(url: &str, key: &str) -> Result<FetchedModule, String> {
407+
fn fetch_module_now(url: &str, key: &str) -> Result<FetchedModule, String> {
355408
if !remote_url_allowed(url) {
356409
return Err(format!(
357410
"HTTP import blocked: remote module loading is not allowed for {url} (set security.allowRemoteModules in the app's package.json)"
@@ -399,16 +452,20 @@ pub(crate) fn fetch_module(url: &str, key: &str) -> Result<FetchedModule, String
399452

400453
/// Fetch several modules concurrently (bounded), preserving input order.
401454
pub(crate) fn fetch_modules(items: &[(String, String)]) -> Vec<Result<FetchedModule, String>> {
455+
pumping(|| fetch_modules_now(items))
456+
}
457+
458+
fn fetch_modules_now(items: &[(String, String)]) -> Vec<Result<FetchedModule, String>> {
402459
const MAX_PARALLEL: usize = 8;
403460
if items.len() <= 1 {
404-
return items.iter().map(|(u, k)| fetch_module(u, k)).collect();
461+
return items.iter().map(|(u, k)| fetch_module_now(u, k)).collect();
405462
}
406463
let mut out: Vec<Option<Result<FetchedModule, String>>> = (0..items.len()).map(|_| None).collect();
407464
for (chunk_index, chunk) in items.chunks(MAX_PARALLEL).enumerate() {
408465
std::thread::scope(|s| {
409466
let handles: Vec<_> = chunk
410467
.iter()
411-
.map(|(u, k)| s.spawn(move || fetch_module(u, k)))
468+
.map(|(u, k)| s.spawn(move || fetch_module_now(u, k)))
412469
.collect();
413470
for (i, h) in handles.into_iter().enumerate() {
414471
out[chunk_index * MAX_PARALLEL + i] =

‎runtime/src/global_fns.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2656,6 +2656,9 @@ include_str!("js/crypto.js"), r#"
26562656
getLoadedModuleUrls: function getLoadedModuleUrls() {
26572657
return globalThis.__nsModuleLoadedUrls();
26582658
},
2659+
setDevBootComplete: function setDevBootComplete(done) {
2660+
if (typeof globalThis.__nsModuleSetDevBootComplete === 'function') globalThis.__nsModuleSetDevBootComplete(!!done);
2661+
},
26592662
createRequire: function createRequire(filenameOrURL) {
26602663
var value = filenameOrURL && typeof filenameOrURL === 'object' ? filenameOrURL.href : filenameOrURL;
26612664
if (typeof value !== 'string') {
@@ -4415,6 +4418,7 @@ pub(crate) fn init_async_helpers(
44154418
register!("__nsModuleConfigureLoader", crate::handle_ns_module_configure_loader);
44164419
register!("__nsModuleInvalidate", crate::handle_ns_module_invalidate);
44174420
register!("__nsModuleLoadedUrls", crate::handle_ns_module_loaded_urls);
4421+
register!("__nsModuleSetDevBootComplete", crate::handle_ns_module_set_dev_boot_complete);
44184422

44194423
// DevTools host hooks: allow JS to register domain dispatchers and
44204424
// post events/timestamps to the DevTools server when enabled.

‎runtime/src/lib.rs‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2298,7 +2298,8 @@ fn js_error_value<'s>(scope: &mut v8::PinScope<'s, '_>, msg: &str) -> v8::Local<
22982298
const NS_MODULE_SOURCE: &str = "const m = globalThis.__nsModuleBuiltin;\n\
22992299
export default m;\n\
23002300
export const configureLoader = m.configureLoader, invalidateModules = m.invalidateModules, \
2301-
getLoadedModuleUrls = m.getLoadedModuleUrls, createRequire = m.createRequire;\n";
2301+
getLoadedModuleUrls = m.getLoadedModuleUrls, createRequire = m.createRequire, \
2302+
setDevBootComplete = m.setDevBootComplete;\n";
23022303

23032304
/// Registry key for a URL handed in by JS (`invalidateModules`): canonical for HTTP, a path for
23042305
/// `file://`, verbatim otherwise.
@@ -2344,6 +2345,16 @@ pub(crate) fn handle_ns_module_configure_loader(
23442345
}
23452346
}
23462347

2348+
/// `ns:module` `setDevBootComplete(done)`.
2349+
#[cfg(feature = "classic")]
2350+
pub(crate) fn handle_ns_module_set_dev_boot_complete(
2351+
scope: &mut v8::PinScope<'_, '_>,
2352+
args: v8::FunctionCallbackArguments,
2353+
_rv: v8::ReturnValue,
2354+
) {
2355+
crate::esm_http::set_dev_boot_complete(args.get(0).boolean_value(scope));
2356+
}
2357+
23472358
/// `ns:module` `invalidateModules(urls)`: registry eviction plus a one-shot cache-bust nonce on
23482359
/// each evicted URL's next fetch. Returns the number of registry entries removed.
23492360
#[cfg(feature = "classic")]
@@ -2527,6 +2538,10 @@ pub mod esm_loader {
25272538
crate::esm_http::configure_loader(json)
25282539
}
25292540

2541+
pub fn set_dev_boot_complete(done: bool) {
2542+
crate::esm_http::set_dev_boot_complete(done)
2543+
}
2544+
25302545
pub fn mark_keys_for_cache_bust(keys: &[String]) {
25312546
crate::esm_http::mark_keys_for_cache_bust(keys)
25322547
}

‎runtime/src/napi_engine/module_runner.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,12 @@ pub fn install(env: &Env, eval: EvalScript) -> napi::Result<()> {
227227
})?;
228228
global.set_named_property("__nsModuleConfigureLoader", configure)?;
229229

230+
let boot_complete = env.create_function_from_closure("__nsModuleSetDevBootComplete", |ctx: CallContext| {
231+
esm_loader::set_dev_boot_complete(ctx.get::<JsUnknown>(0)?.coerce_to_bool()?.get_value()?);
232+
ctx.env.get_undefined()
233+
})?;
234+
global.set_named_property("__nsModuleSetDevBootComplete", boot_complete)?;
235+
230236
eval(env, RUNNER, "<module-runner>").map_err(|()| {
231237
napi::Error::from_reason(format!("module runner failed to install: {}", take_exception(env)))
232238
})?;

0 commit comments

Comments
 (0)