Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

refactor(emulation): coalesce process environment notifications

ldm02d249b069cf0
diff --git a/Cargo.lock b/Cargo.lock
index cafa13de0..c43e3cfbd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2792,7 +2792,6 @@ dependencies = [
"moli-site",
"moli-storage-key",
"moli-storage-service",
- "moli-time",
"moli-trace",
"moli-url",
"moli-url-policy",
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py
index 7e3d14c87..32a218276 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py
@@ -206,12 +206,12 @@ async def run_locale_timezone_runtime_surface_smoke(
assert_equal(
runtime.get("invalidOptions"),
"TypeError",
- "Intl option validation survives default injection",
+ "process defaults preserve native Intl option validation",
)
assert_equal(
runtime.get("intlConstruction"),
[True, True, True, "fr-FR"],
- "Intl constructor proxy preserves subclass newTarget",
+ "process defaults preserve native Intl subclass newTarget",
)
assert_equal(
runtime.get("intlOptionAccess"),
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py
index 8af57423f..3ee48e039 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/process_environment.py
@@ -56,6 +56,24 @@ async def _install_workers(page: Any) -> None:
}""", READ_DEFAULTS)
+async def _burst_environment_updates(control: Any, peer: Any) -> None:
+ # Send a burst without interleaved observations. This is the latest-value
+ # cache invalidation contract, not a requirement to replay every ICU value.
+ updates = []
+ for index in range(24):
+ locale, timezone = ("fr_FR", "Europe/Paris") if index % 2 == 0 else (
+ "de_DE", "Asia/Shanghai"
+ )
+ updates.extend([
+ control.send("Emulation.setLocaleOverride", {"locale": locale}),
+ control.send("Emulation.setTimezoneOverride", {"timezoneId": timezone}),
+ ])
+ await asyncio.wait_for(asyncio.gather(*updates), timeout=10)
+ expected = ["de-DE", "Asia/Shanghai", -480, -480]
+ assert_equal(await peer.evaluate(READ_DEFAULTS), expected, "peer observes final burst defaults")
+ assert_equal(await _worker_defaults(peer), [expected, expected], "workers observe final burst defaults")
+
+
async def _override_while_peer_paused(control: Any, peer: Any, baseline: list[Any]) -> None:
# A paused isolate cannot drain its ordinary foreground notification. The
# explicit owner notification must run before the next nested Inspector
@@ -125,6 +143,8 @@ async def run_process_environment_group(
assert_equal(await _worker_defaults(peer), [baseline, baseline], "worker baseline")
record(results, "process_environment_workers_before_override")
+ await _burst_environment_updates(control, peer)
+ record(results, "process_environment_burst_updates_reach_pages_and_workers")
await _override_while_peer_paused(control, other, baseline)
record(results, "process_environment_paused_change_replace_restore")
expected = ["fr-FR", "Europe/Paris", -60, -120]
diff --git a/moli-protocol/Cargo.toml b/moli-protocol/Cargo.toml
index d7ea42cbf..70af91bf8 100644
--- a/moli-protocol/Cargo.toml
+++ b/moli-protocol/Cargo.toml
@@ -25,7 +25,6 @@ moli-css-parse = { path = "../moli-css-parse" }
moli-shared-worker = { path = "../moli-shared-worker" }
moli-site = { path = "../moli-site" }
moli-storage-key = { path = "../moli-storage-key" }
-moli-time = { path = "../moli-time" }
moli-trace = { path = "../moli-trace" }
moli-url = { path = "../moli-url" }
moli-url-policy = { path = "../moli-url-policy" }
diff --git a/moli-protocol/src/conn/state/devtools_session.rs b/moli-protocol/src/conn/state/devtools_session.rs
index 6b2300f29..b37c48c5d 100644
--- a/moli-protocol/src/conn/state/devtools_session.rs
+++ b/moli-protocol/src/conn/state/devtools_session.rs
@@ -670,7 +670,6 @@ pub(crate) struct DevToolsNetworkSessionState {
pub(crate) struct DevToolsEmulationSessionState {
// UA, Accept-Language, and platform are independent handler contributions.
pub(crate) browser_identity_override: Option<DevToolsBrowserIdentityOverride>,
- // Locale and timezone are exclusive controller claims, unlike UA fields.
pub(crate) network_conditions: Option<super::EmulatedNetworkConditions>,
pub(crate) geolocation_override: Option<super::EmulatedGeolocationOverrideState>,
pub(crate) emulated_media: super::EmulatedMediaOverrides,
diff --git a/moli-protocol/src/domains/tracing/tests.rs b/moli-protocol/src/domains/tracing/tests.rs
index 0ff6d7091..5d5d45d73 100644
--- a/moli-protocol/src/domains/tracing/tests.rs
+++ b/moli-protocol/src/domains/tracing/tests.rs
@@ -322,7 +322,7 @@ async fn owner_cleanup_waits_for_cpu_trace_release_before_replacement_start() {
moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {
let _ = owner_task_tx.send(task);
}),
- |_| {},
+ moli_v8_platform::ProcessEnvironmentNotifications::default().notifier(|| {}),
);
let mut ctx = context_with_page_sessions();
@@ -568,7 +568,7 @@ async fn cpu_trace_start_response_waits_for_existing_isolate_ack() {
moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {
let _ = owner_task_tx.send(task);
}),
- |_| {},
+ moli_v8_platform::ProcessEnvironmentNotifications::default().notifier(|| {}),
);
let mut ctx = context_with_page_sessions();
@@ -635,7 +635,7 @@ async fn cpu_trace_start_reports_chromium_error_when_stopped_before_ack() {
moli_v8_platform::V8ForegroundTaskWake::queued(move |task| {
let _ = owner_task_tx.send(task);
}),
- |_| {},
+ moli_v8_platform::ProcessEnvironmentNotifications::default().notifier(|| {}),
);
let mut ctx = context_with_page_sessions();
diff --git a/moli-renderer-v8/src/devtools/ingress/io.rs b/moli-renderer-v8/src/devtools/ingress/io.rs
index b1edee15b..b6aee6607 100644
--- a/moli-renderer-v8/src/devtools/ingress/io.rs
+++ b/moli-renderer-v8/src/devtools/ingress/io.rs
@@ -8,7 +8,9 @@ use std::{
};
use moli_page_types::{DevToolsSessionKey, RendererDevToolsAgentToken};
-use moli_v8_platform::ProcessEnvironmentChange;
+use moli_v8_platform::{
+ ProcessEnvironmentChange, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,
+};
use parking_lot::Mutex;
use crate::{
@@ -245,7 +247,7 @@ struct RendererInspectorIoState {
commands: VecDeque<RendererInspectorIoCommand>,
// Isolate-owned notifications, not session commands. They remain eligible
// during session detach and an active command's nested debugger pause.
- environment_changes: VecDeque<ProcessEnvironmentChange>,
+ environment_notifications: ProcessEnvironmentNotifications,
active_command_id: Option<u64>,
// One count per lane is enough: every detach guard completes at most once,
// and commands stay blocked until all outstanding guards have completed.
@@ -256,7 +258,7 @@ struct RendererInspectorIoState {
impl RendererInspectorIoState {
fn has_ready(&self) -> bool {
- !self.closed && (!self.environment_changes.is_empty() || self.has_ready_command())
+ !self.closed && (self.environment_notifications.has_pending() || self.has_ready_command())
}
fn has_ready_command(&self) -> bool {
@@ -381,7 +383,7 @@ impl RendererInspectorIoIngress {
shared: Arc::new(RendererInspectorIoShared {
state: Mutex::new(RendererInspectorIoState {
commands: VecDeque::new(),
- environment_changes: VecDeque::new(),
+ environment_notifications: ProcessEnvironmentNotifications::default(),
active_command_id: None,
session_detaches: BTreeMap::new(),
closed: false,
@@ -408,22 +410,21 @@ impl RendererInspectorIoIngress {
.map(|route| route.target.route_id())
}
- /// The process controller publishes before returning to its caller. Reuse
- /// this owner's idle wake, active-JS interrupt and nested-pause wake; a
- /// normal Page foreground task cannot run while the debugger is paused.
- pub(crate) fn enqueue_environment_change(&self, change: ProcessEnvironmentChange) {
- {
- let mut state = self.shared.state.lock();
- if state.closed {
- return;
- }
- state.environment_changes.push_back(change);
- }
- self.notify_execution_opportunities();
+ /// Publication touches only the shared mailbox. The wake runs outside the
+ /// process configuration lock and reuses idle/interrupt/nested-pause routes.
+ pub(crate) fn environment_notifier(&self) -> ProcessEnvironmentNotifier {
+ let ingress = self.clone();
+ self.shared
+ .state
+ .lock()
+ .environment_notifications
+ .notifier(move || {
+ ingress.notify_execution_opportunities();
+ })
}
pub(crate) fn claim_environment_change(&self) -> Option<ProcessEnvironmentChange> {
- self.shared.state.lock().environment_changes.pop_front()
+ self.shared.state.lock().environment_notifications.take()
}
/// Breaks an active V8 call so target teardown can reach the Page owner.
@@ -661,7 +662,7 @@ impl RendererInspectorIoIngress {
let commands = {
let mut state = self.shared.state.lock();
state.closed = true;
- state.environment_changes.clear();
+ state.environment_notifications.close();
state.commands.drain(..).collect::<Vec<_>>()
};
self.shared.pause_wake.notify_all();
@@ -749,7 +750,7 @@ impl std::fmt::Debug for RendererInspectorIoIngress {
.field("queued_tasks", &state.commands.len())
.field(
"environment_notifications",
- &state.environment_changes.len(),
+ &state.environment_notifications.has_pending(),
)
.field("active_command_id", &state.active_command_id)
.field(
@@ -824,8 +825,11 @@ mod tests {
let mut command = ingress.claim_for_owner().unwrap();
let guard = ingress.first_dispatch_guard(&mut command);
ingress.begin_session_detach(agent, command.ticket().session());
- ingress.enqueue_environment_change(ProcessEnvironmentChange::LocaleChanged);
- ingress.enqueue_environment_change(ProcessEnvironmentChange::TimezoneChanged);
+ let notifier = ingress.environment_notifier();
+ for _ in 0..1_000 {
+ notifier.notify(ProcessEnvironmentChange::LocaleChanged);
+ notifier.notify(ProcessEnvironmentChange::TimezoneChanged);
+ }
// A nested pause can receive these without releasing the active
// command slot or creating another Inspector session.
assert!(ingress.claim_for_pause().is_none());
@@ -833,10 +837,6 @@ mod tests {
ingress.claim_environment_change(),
Some(ProcessEnvironmentChange::LocaleChanged)
);
- assert_eq!(
- ingress.claim_environment_change(),
- Some(ProcessEnvironmentChange::TimezoneChanged)
- );
assert_eq!(ingress.claim_environment_change(), None);
drop(guard);
ingress.finish_session_detach(agent, command.ticket().session());
@@ -845,9 +845,10 @@ mod tests {
#[test]
fn closed_isolate_discards_queued_and_late_environment_notifications() {
let ingress = ingress();
- ingress.enqueue_environment_change(ProcessEnvironmentChange::LocaleChanged);
+ let notifier = ingress.environment_notifier();
+ notifier.notify(ProcessEnvironmentChange::LocaleChanged);
ingress.close("isolate disposed");
- ingress.enqueue_environment_change(ProcessEnvironmentChange::TimezoneChanged);
+ notifier.notify(ProcessEnvironmentChange::TimezoneChanged);
assert_eq!(ingress.claim_environment_change(), None);
assert!(!ingress.shared.state.lock().has_ready());
}
diff --git a/moli-renderer-v8/src/script_vm/document_isolate.rs b/moli-renderer-v8/src/script_vm/document_isolate.rs
index bc0ac94a9..a42c21498 100644
--- a/moli-renderer-v8/src/script_vm/document_isolate.rs
+++ b/moli-renderer-v8/src/script_vm/document_isolate.rs
@@ -582,11 +582,13 @@ impl RendererDocumentIsolateHolder {
let inspector_start = timing_enabled.then(std::time::Instant::now);
let inspector_backend = RendererInspectorIsolateBackend::new(&mut isolate);
let inspector_elapsed = inspector_start.map(|start| start.elapsed());
- let environment_ingress = inspector_backend.devtools_target().io_ref().clone();
let platform_registration = V8PlatformIsolateRegistration::register(
&mut isolate,
foreground_wake.into_platform_wake(),
- move |change| environment_ingress.enqueue_environment_change(change),
+ inspector_backend
+ .devtools_target()
+ .io_ref()
+ .environment_notifier(),
);
let isolate_ptr = unsafe { isolate.as_raw_isolate_ptr() };
let isolate_bootstrap;
diff --git a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs
index fa84ffaec..c47d6ee70 100644
--- a/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs
+++ b/moli-renderer-v8/src/script_vm/inspector/v8_backend/interrupt.rs
@@ -137,7 +137,6 @@ pub(crate) fn dispatch_inspector_main_owner_wake(
unsafe { isolate.enter() };
let _entered_isolate = EnteredOwnerWakeIsolateGuard(isolate);
change.notify_isolate(isolate);
- dispatch_environment_notifications(&session_executor, isolate);
}
session_executor.claim_next_main_command_from_owner()
}
@@ -146,7 +145,9 @@ fn dispatch_environment_notifications(
session_executor: &RendererInspectorSessionExecutorLocal,
isolate: &mut v8::Isolate,
) {
- while let Some(change) = session_executor.target.io_ref().claim_environment_change() {
+ // Consume one merged batch. A publication racing application retains its
+ // own wake instead of making this callback drain an unbounded producer.
+ if let Some(change) = session_executor.target.io_ref().claim_environment_change() {
change.notify_isolate(isolate);
}
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs
index c27d464f8..f3565af02 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/date_locale.rs
@@ -201,7 +201,7 @@ fn emulation_locale_fallback_preserves_native_observation_order() {
}
#[test]
-fn emulation_default_arguments_do_not_read_array_prototype() {
+fn process_environment_defaults_do_not_read_array_prototype() {
let environment = moli_v8_platform::ProcessEnvironmentOwner::default();
let mut vm = new_storage_test_vm("https://intl-private-arguments.test/");
environment.set_locale(Some("fr_FR")).unwrap();
@@ -231,7 +231,7 @@ fn emulation_default_arguments_do_not_read_array_prototype() {
}
#[test]
-fn emulation_timezone_boxes_primitive_options_without_losing_defaults() {
+fn process_environment_preserves_native_primitive_options_and_defaults() {
let environment = moli_v8_platform::ProcessEnvironmentOwner::default();
let mut vm = new_storage_test_vm("https://intl-primitive-options.test/");
environment.set_timezone(Some("Europe/Paris")).unwrap();
@@ -306,7 +306,7 @@ fn date_and_intl_native_method_descriptors_are_unchanged() {
}
#[test]
-fn emulation_constructor_envelopes_do_not_convert_page_arguments() {
+fn process_environment_preserves_native_date_and_intl_coercion() {
let environment = moli_v8_platform::ProcessEnvironmentOwner::default();
let mut vm = new_storage_test_vm("https://date-intl-raw-arguments.test/");
let probe = r#"JSON.stringify((() => {
@@ -357,18 +357,18 @@ fn emulation_constructor_envelopes_do_not_convert_page_arguments() {
}
#[test]
-fn emulation_private_declarations_do_not_invoke_inherited_setters() {
+fn process_environment_preserves_native_options_with_inherited_setters() {
let environment = moli_v8_platform::ProcessEnvironmentOwner::default();
- let mut vm = new_storage_test_vm("https://date-intl-private-declarations.test/");
+ let mut vm = new_storage_test_vm("https://date-intl-inherited-options.test/");
environment.set_timezone(Some("Europe/Paris")).unwrap();
let result = vm
.eval(
r#"JSON.stringify((() => {
- const keys = ['get', 'timeZone', 'original', 'timezone'];
+ const keys = ['get', 'timeZone'];
const before = keys.map(key => Object.getOwnPropertyDescriptor(Object.prototype, key));
const sentinel = {};
- // These setters must not participate in building the private handler,
- // callback data or default options objects.
+ // Changing native defaults must not add observable property writes to
+ // option handling, including frozen options and inherited accessors.
try {
for (const key of keys) Object.defineProperty(Object.prototype, key, {
set() { throw sentinel; }, configurable: true
diff --git a/moli-renderer-v8/src/worker/handle.rs b/moli-renderer-v8/src/worker/handle.rs
index 91e00e446..597ad98ce 100644
--- a/moli-renderer-v8/src/worker/handle.rs
+++ b/moli-renderer-v8/src/worker/handle.rs
@@ -146,6 +146,8 @@ pub(crate) enum WorkerMessage {
},
/// Owner-thread dispatch or fallback for one queued Inspector task.
RunInspectorTask(WorkerInspectorTaskMode),
+ /// One coalesced fallback wake for the isolate's environment mailbox.
+ RunEnvironmentNotification,
#[cfg(test)]
/// Inspect worker resource-owner V8 slots from inside the worker thread.
ResourceOwnerSlotDiagnostics {
diff --git a/moli-renderer-v8/src/worker/inspector_task_runner.rs b/moli-renderer-v8/src/worker/inspector_task_runner.rs
index f1dd147b8..f95ffc143 100644
--- a/moli-renderer-v8/src/worker/inspector_task_runner.rs
+++ b/moli-renderer-v8/src/worker/inspector_task_runner.rs
@@ -10,6 +10,7 @@ use std::{
};
use moli_protocol_cdp::CdpInspectorTaskMode;
+use moli_v8_platform::{ProcessEnvironmentNotifications, ProcessEnvironmentNotifier};
use parking_lot::{Condvar, Mutex};
use serde_json::json;
use tokio::sync::{mpsc, oneshot};
@@ -129,6 +130,10 @@ struct WorkerInspectorTaskRunnerState {
struct WorkerInspectorTaskRunnerShared {
state: Mutex<WorkerInspectorTaskRunnerState>,
+ environment_notifications: ProcessEnvironmentNotifications,
+ // Interrupt/pause consumption must not clear this bit: a fallback owner
+ // message can still be in the channel while JS processes many interrupts.
+ environment_owner_wake_armed: AtomicBool,
pause_work: Condvar,
wake_tx: mpsc::UnboundedSender<WorkerMessage>,
isolate_handle: Arc<Mutex<Option<v8::IsolateHandle>>>,
@@ -154,6 +159,8 @@ impl WorkerInspectorTaskRunner {
.expect("worker Inspector route ID exhausted");
Self {
shared: Arc::new(WorkerInspectorTaskRunnerShared {
+ environment_notifications: ProcessEnvironmentNotifications::default(),
+ environment_owner_wake_armed: AtomicBool::new(false),
state: Mutex::new(WorkerInspectorTaskRunnerState {
interrupting_tasks: VecDeque::new(),
dont_interrupting_tasks: VecDeque::new(),
@@ -176,16 +183,54 @@ impl WorkerInspectorTaskRunner {
self.shared.interrupt_target.route_id
}
- /// An isolate notification shares the existing owner/interrupt/pause task
- /// route, but has no Inspector session and invokes no page script.
- pub(crate) fn append_environment_change(
+ /// Share owner/interrupt/pause delivery without appending a task per change.
+ /// The controller publishes the mailbox before calling this wake, unlocked.
+ pub(crate) fn environment_notifier(&self) -> ProcessEnvironmentNotifier {
+ let runner = self.clone();
+ self.shared.environment_notifications.notifier(move || {
+ runner.wake_environment();
+ })
+ }
+
+ fn wake_environment(&self) {
+ if !self.shared.environment_notifications.has_pending() {
+ return;
+ }
+ if !self
+ .shared
+ .environment_owner_wake_armed
+ .swap(true, Ordering::AcqRel)
+ && self
+ .shared
+ .wake_tx
+ .send(WorkerMessage::RunEnvironmentNotification)
+ .is_err()
+ {
+ self.dispose("Worker environment owner is unavailable");
+ return;
+ }
+ self.request_interrupt_if_needed();
+ self.shared.pause_work.notify_one();
+ }
+
+ pub(crate) fn claim_environment_for_owner(
&self,
- change: moli_v8_platform::ProcessEnvironmentChange,
- ) {
- self.append(
- WorkerInspectorTaskMode::Interrupt,
- WorkerInspectorTask::EnvironmentChanged(change),
- );
+ ) -> Option<moli_v8_platform::ProcessEnvironmentChange> {
+ self.shared
+ .environment_owner_wake_armed
+ .store(false, Ordering::Release);
+ self.claim_environment_change()
+ }
+
+ fn claim_environment_task(&self) -> Option<WorkerInspectorTask> {
+ self.claim_environment_change()
+ .map(WorkerInspectorTask::EnvironmentChanged)
+ }
+
+ pub(crate) fn claim_environment_change(
+ &self,
+ ) -> Option<moli_v8_platform::ProcessEnvironmentChange> {
+ self.shared.environment_notifications.take()
}
pub(crate) fn append_protocol_message(
@@ -289,6 +334,14 @@ impl WorkerInspectorTaskRunner {
}
}
+ /// An interrupt can service the mailbox first. An ordinary command wake
+ /// must claim its command instead: using it up on environment work would
+ /// strand that command after an idle Worker consumed both wake messages.
+ pub(crate) fn claim_interrupt_task(&self) -> Option<WorkerInspectorTask> {
+ self.claim_environment_task()
+ .or_else(|| self.claim_task(WorkerInspectorTaskMode::Interrupt))
+ }
+
pub(crate) fn interrupt_callback_started(&self) {
self.shared.interrupt_armed.store(false, Ordering::Release);
}
@@ -296,7 +349,10 @@ impl WorkerInspectorTaskRunner {
pub(crate) fn request_interrupt_if_needed(&self) {
let should_request = {
let state = self.shared.state.lock();
- !state.disposed && state.isolate_ready && !state.interrupting_tasks.is_empty()
+ !state.disposed
+ && state.isolate_ready
+ && (self.shared.environment_notifications.has_pending()
+ || !state.interrupting_tasks.is_empty())
};
if !should_request
|| self
@@ -342,6 +398,9 @@ impl WorkerInspectorTaskRunner {
if state.disposed || state.quit_pause_loop {
return None;
}
+ if let Some(task) = self.claim_environment_task() {
+ return Some(task);
+ }
if let Some(task) = state.interrupting_tasks.pop_front() {
return Some(task);
}
@@ -375,6 +434,7 @@ impl WorkerInspectorTaskRunner {
return;
}
state.disposed = true;
+ self.shared.environment_notifications.close();
state.isolate_ready = false;
state.quit_pause_loop = true;
(
@@ -575,26 +635,97 @@ mod tests {
}
#[test]
- fn environment_notifications_share_interrupt_fifo_and_are_discarded_on_disposal() {
+ fn environment_bursts_and_interrupt_consumption_keep_the_owner_wake_bounded() {
use moli_v8_platform::ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};
- let (runner, _wake_rx) = runner();
- runner.append_environment_change(LocaleChanged);
+ let (runner, mut wake_rx) = runner();
+ let notifier = runner.environment_notifier();
+ for _ in 0..10_000 {
+ notifier.notify(TimezoneChanged);
+ notifier.notify(LocaleChanged);
+ }
+ assert!(matches!(
+ wake_rx.try_recv(),
+ Ok(super::WorkerMessage::RunEnvironmentNotification)
+ ));
+ assert!(wake_rx.try_recv().is_err());
+ assert!(runner.shared.state.lock().interrupting_tasks.is_empty());
+
+ // Simulate JS repeatedly accepting V8 interrupts while the ordinary
+ // owner loop has not handled the already-posted fallback wake.
+ for _ in 0..1_000 {
+ notifier.notify(LocaleChanged);
+ assert!(matches!(
+ runner.claim_interrupt_task(),
+ Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))
+ ));
+ }
+ assert!(wake_rx.try_recv().is_err());
+ assert!(runner.claim_environment_for_owner().is_none());
+ notifier.notify(TimezoneChanged);
+ assert!(matches!(
+ wake_rx.try_recv(),
+ Ok(super::WorkerMessage::RunEnvironmentNotification)
+ ));
+ assert!(matches!(
+ runner.claim_environment_for_owner(),
+ Some(TimezoneChanged)
+ ));
+ assert!(wake_rx.try_recv().is_err());
+ }
+
+ #[test]
+ fn pending_environment_does_not_consume_an_ordinary_command_wake() {
+ use moli_v8_platform::ProcessEnvironmentChange::LocaleChanged;
+ let (runner, mut wake_rx) = runner();
let _command = append_protocol(&runner, 1, "Debugger.resume");
- runner.append_environment_change(TimezoneChanged);
- assert!(runner.begin_pause_loop());
- // The nested pause uses this same interrupting FIFO. No session or
- // ordinary Worker-loop turn is required to receive a notification.
+ runner.environment_notifier().notify(LocaleChanged);
assert!(matches!(
- runner.claim_task(WorkerInspectorTaskMode::Interrupt),
- Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))
+ wake_rx.try_recv(),
+ Ok(super::WorkerMessage::RunInspectorTask(
+ WorkerInspectorTaskMode::Interrupt
+ ))
));
assert!(matches!(
runner.claim_task(WorkerInspectorTaskMode::Interrupt),
Some(WorkerInspectorTask::DispatchProtocolMessage { .. })
));
+ assert!(matches!(
+ wake_rx.try_recv(),
+ Ok(super::WorkerMessage::RunEnvironmentNotification)
+ ));
+ assert_eq!(runner.claim_environment_for_owner(), Some(LocaleChanged));
+ assert!(wake_rx.try_recv().is_err());
+ }
+
+ #[test]
+ fn environment_notifications_merge_before_pause_commands_and_are_discarded_on_disposal() {
+ use moli_v8_platform::ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};
+
+ let (runner, _wake_rx) = runner();
+ let notifier = runner.environment_notifier();
+ let _first = append_protocol(&runner, 1, "Debugger.pause");
+ notifier.notify(LocaleChanged);
+ let _second = append_protocol(&runner, 2, "Debugger.resume");
+ notifier.notify(TimezoneChanged);
+ assert!(runner.begin_pause_loop());
+ // The pause claims one merged invalidation ahead of queued commands,
+ // without a session or ordinary Worker-loop turn.
+ assert!(matches!(
+ runner.wait_for_pause_task(),
+ Some(WorkerInspectorTask::EnvironmentChanged(LocaleChanged))
+ ));
+ assert!(matches!(
+ runner.wait_for_pause_task(),
+ Some(WorkerInspectorTask::DispatchProtocolMessage { raw_json, .. })
+ if raw_json.contains("Debugger.pause")
+ ));
+ assert!(matches!(runner.wait_for_pause_task(),
+ Some(WorkerInspectorTask::DispatchProtocolMessage { raw_json, .. })
+ if raw_json.contains("Debugger.resume")));
+ notifier.notify(TimezoneChanged);
runner.dispose("worker teardown");
- runner.append_environment_change(LocaleChanged);
+ notifier.notify(LocaleChanged);
assert!(
runner
.claim_task(WorkerInspectorTaskMode::Interrupt)
diff --git a/moli-renderer-v8/src/worker/thread/isolate.rs b/moli-renderer-v8/src/worker/thread/isolate.rs
index 590ddce5d..64e032466 100644
--- a/moli-renderer-v8/src/worker/thread/isolate.rs
+++ b/moli-renderer-v8/src/worker/thread/isolate.rs
@@ -54,7 +54,7 @@ impl WorkerIsolateState {
let platform_registration = V8PlatformIsolateRegistration::register(
&mut isolate,
platform_wake.into_platform_wake(),
- move |change| inspector_task_runner.append_environment_change(change),
+ inspector_task_runner.environment_notifier(),
);
Self {
diff --git a/moli-renderer-v8/src/worker/thread/mod.rs b/moli-renderer-v8/src/worker/thread/mod.rs
index b4b3e3ea6..c8e9ac3f1 100644
--- a/moli-renderer-v8/src/worker/thread/mod.rs
+++ b/moli-renderer-v8/src/worker/thread/mod.rs
@@ -1010,6 +1010,13 @@ async fn run_worker_pre_bootstrap_debugger_pause(
return true;
}
match rx.recv().await {
+ Some(WorkerMessage::RunEnvironmentNotification) => {
+ if let Some(change) = inspector_task_runner.claim_environment_for_owner() {
+ // Cache invalidation is control work, not a JS turn or a
+ // reason to run microtasks while bootstrap is paused.
+ change.notify_isolate(worker_isolate.worker_isolate_mut());
+ }
+ }
Some(WorkerMessage::RunInspectorTask(mode)) => {
if let Some(task) = inspector_task_runner.claim_task(mode) {
dispatch_worker_inspector_task(
@@ -2669,6 +2676,11 @@ async fn worker_main(
drain_worker_dynamic_module_imports(scope, &state, &module_graph_fetch_tx);
}
}
+ WorkerLoopWake::Message(Some(WorkerMessage::RunEnvironmentNotification)) => {
+ if let Some(change) = inspector_task_runner.claim_environment_for_owner() {
+ change.notify_isolate(worker_isolate.worker_isolate_mut());
+ }
+ }
WorkerLoopWake::Message(Some(WorkerMessage::RunInspectorTask(mode))) => {
if let Some(task) = inspector_task_runner.claim_task(mode) {
dispatch_worker_inspector_task(
diff --git a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
index c328f35c1..cfea65f30 100644
--- a/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
+++ b/moli-renderer-v8/src/worker/thread/runtime_inspector.rs
@@ -12,9 +12,8 @@ use crate::runtime::{RendererRuntimeInspectorMessage, RendererRuntimeInspectorRe
use crate::worker::{
handle::{WorkerRuntimeInspectorMessageBatch, WorkerToParentMessage},
inspector_task_runner::{
- WorkerInspectorInterruptExecutor, WorkerInspectorTask, WorkerInspectorTaskMode,
- WorkerInspectorTaskRunner, register_worker_inspector_executor,
- unregister_worker_inspector_executor,
+ WorkerInspectorInterruptExecutor, WorkerInspectorTask, WorkerInspectorTaskRunner,
+ register_worker_inspector_executor, unregister_worker_inspector_executor,
},
};
use tokio::sync::mpsc;
@@ -407,10 +406,7 @@ impl WorkerInspectorExecutor {
impl WorkerInspectorInterruptExecutor for WorkerInspectorExecutor {
fn dispatch_interrupt(&self, isolate: v8::UnsafeRawIsolatePtr) {
self.task_runner.interrupt_callback_started();
- let Some(task) = self
- .task_runner
- .claim_task(WorkerInspectorTaskMode::Interrupt)
- else {
+ let Some(task) = self.task_runner.claim_interrupt_task() else {
self.task_runner.request_interrupt_if_needed();
return;
};
@@ -565,6 +561,14 @@ impl WorkerRuntimeInspector {
}
pub(super) fn execute_task(&self, isolate: &mut v8::Isolate, task: WorkerInspectorTask) {
+ // Owner messages for the two Inspector modes use separate queues. An
+ // already-published notification must also precede DontInterrupt work
+ // if that wake is selected before the environment fallback message.
+ if !matches!(task, WorkerInspectorTask::EnvironmentChanged(_))
+ && let Some(change) = self.task_runner.claim_environment_change()
+ {
+ change.notify_isolate(isolate);
+ }
match task {
WorkerInspectorTask::EnvironmentChanged(change) => change.notify_isolate(isolate),
WorkerInspectorTask::DispatchProtocolMessage {
@@ -769,6 +773,7 @@ fn worker_runtime_inspector_message_batch(
#[cfg(test)]
mod tests {
use super::*;
+ use crate::worker::inspector_task_runner::WorkerInspectorTaskMode;
use serde_json::{Value, json};
use std::pin::pin;
@@ -815,11 +820,10 @@ mod tests {
);
let inspector =
WorkerRuntimeInspector::new(&mut isolate, task_runner.clone(), parent_tx, false);
- let notifications = task_runner.clone();
let registration = moli_v8_platform::V8PlatformIsolateRegistration::register(
&mut isolate,
moli_v8_platform::V8ForegroundTaskWake::queued(|_| {}),
- move |change| notifications.append_environment_change(change),
+ task_runner.environment_notifier(),
);
{
let scope = pin!(v8::HandleScope::new(&mut isolate));
@@ -831,7 +835,7 @@ mod tests {
"https://worker-environment.test/worker.js",
);
}
- let read_defaults = |isolate: &mut v8::Isolate| {
+ let read_defaults = |isolate: &mut v8::Isolate, pump_interrupts: bool| {
let (response_tx, mut response_rx) = tokio::sync::oneshot::channel();
assert!(task_runner.append_protocol_message(
None,
@@ -850,8 +854,10 @@ mod tests {
// Pump explicit owner notifications before the non-interrupting
// evaluation. No global-version check or normal Worker entry is
// involved, and a nested pause can consume these same notifications.
- while let Some(task) = task_runner.claim_task(WorkerInspectorTaskMode::Interrupt) {
- inspector.execute_task(isolate, task);
+ if pump_interrupts {
+ while let Some(task) = task_runner.claim_interrupt_task() {
+ inspector.execute_task(isolate, task);
+ }
}
let task = task_runner
.claim_task(WorkerInspectorTaskMode::DontInterrupt)
@@ -862,16 +868,24 @@ mod tests {
assert!(response.get("error").is_none(), "{response:#?}");
response["result"]["result"]["value"].clone()
};
- let baseline = read_defaults(&mut isolate);
+ let baseline = read_defaults(&mut isolate, true);
let owner = moli_v8_platform::ProcessEnvironmentOwner::default();
owner.set_locale(Some("fr_FR")).unwrap();
owner.set_timezone(Some("Europe/Paris")).unwrap();
assert_eq!(
- read_defaults(&mut isolate),
+ read_defaults(&mut isolate, true),
json!(["fr-FR", "Europe/Paris", -60])
);
+ owner.set_locale(Some("de_DE")).unwrap();
+ owner.set_timezone(Some("Asia/Shanghai")).unwrap();
+ // Deliberately choose the non-interrupting command ahead of the
+ // mailbox's fallback wake. It still observes both committed changes.
+ assert_eq!(
+ read_defaults(&mut isolate, false),
+ json!(["de-DE", "Asia/Shanghai", -480])
+ );
owner.release();
- assert_eq!(read_defaults(&mut isolate), baseline);
+ assert_eq!(read_defaults(&mut isolate, false), baseline);
registration.unregister();
task_runner.dispose("test complete");
}
diff --git a/moli-v8-platform/src/cpu_tracing.rs b/moli-v8-platform/src/cpu_tracing.rs
index 747500b37..326fe288c 100644
--- a/moli-v8-platform/src/cpu_tracing.rs
+++ b/moli-v8-platform/src/cpu_tracing.rs
@@ -703,7 +703,7 @@ mod tests {
V8ForegroundTaskWake::queued(move |task| {
let _ = owner_task_tx.send(task);
}),
- |_| {},
+ crate::ProcessEnvironmentNotifications::default().notifier(|| {}),
);
let session = start_v8_cpu_trace(V8CpuTraceConfiguration {
diff --git a/moli-v8-platform/src/environment.rs b/moli-v8-platform/src/environment.rs
index de0455bea..3523b5415 100644
--- a/moli-v8-platform/src/environment.rs
+++ b/moli-v8-platform/src/environment.rs
@@ -14,11 +14,14 @@ use parking_lot::Mutex;
use super::registered_isolate_owners;
+mod notifications;
+pub use notifications::{ProcessEnvironmentNotifications, ProcessEnvironmentNotifier};
+
static ENVIRONMENT: OnceLock<Mutex<Environment>> = OnceLock::new();
/// A committed change to the renderer-process defaults, delivered as owner
-/// work rather than checked at every V8 entry. Delivery must enqueue the
-/// notification; only the isolate's owner may apply it, including in a nested
+/// work rather than checked at every V8 entry. Unconsumed changes are merged;
+/// only the isolate's owner may apply them, including in a nested
/// Inspector pause loop. It carries no isolate pointer or configuration lease.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProcessEnvironmentChange {
@@ -227,17 +230,33 @@ fn release(owner: EnvironmentOwnerId) {
);
}
-/// Keep ICU updates and notification publication serialized, as in Blink's
-/// controllers. Dispatchers only enqueue owner work, never enter V8 or acquire
-/// this configuration lock. Publication finishes before the setter returns,
-/// so a subsequent command cannot be enqueued ahead of its notification.
+/// Serialize ICU updates and typed mailbox publication, not arbitrary owner
+/// callbacks. All mailboxes are marked before unlocking; only then may wakes
+/// acquire ingress locks or request V8 interrupts. Wake order need not match
+/// setter order: each mailbox accumulates invalidations of the latest ICU state.
+///
+/// Publication completes before a setter returns; a coalesced batch shares the
+/// first publisher's wake. There is no process-wide isolate ACK barrier.
+/// Owner observation boundaries consume pending work first; already-running JS
+/// may use old caches until the next notification/interrupt opportunity, as with
+/// Blink's asynchronous Worker notifications.
fn publish_change(
- _state: parking_lot::MutexGuard<'_, Environment>,
+ state: parking_lot::MutexGuard<'_, Environment>,
change: ProcessEnvironmentChange,
) {
- for owner in registered_isolate_owners() {
- if owner.registration.generation.is_active() {
- (owner.registration.environment_changed)(change);
+ let owners: Vec<_> = registered_isolate_owners()
+ .into_iter()
+ .map(|owner| {
+ let wake = owner.registration.generation.is_active()
+ && owner.registration.environment_notifications.publish(change);
+ (owner, wake)
+ })
+ .collect();
+ // Also drop retained callback captures only after releasing this mutex.
+ drop(state);
+ for (owner, wake) in owners {
+ if wake {
+ owner.registration.environment_notifications.wake();
}
}
}
@@ -286,7 +305,7 @@ mod tests {
}
#[test]
- fn environment_changes_are_published_before_return_without_polling_or_redundant_work() {
+ fn environment_publication_precedes_return_and_wakes_run_outside_the_controller_lock() {
moli_v8_init::ensure_v8_initialized(crate::create_platform);
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
@@ -294,24 +313,34 @@ mod tests {
.unwrap();
runtime.block_on(async {
let (tx, rx) = std::sync::mpsc::channel();
+ let notifications = ProcessEnvironmentNotifications::default();
+ let wake_notifications = notifications.clone();
let mut isolate = v8::Isolate::new(Default::default());
let registration = crate::V8PlatformIsolateRegistration::register(
&mut isolate,
crate::V8ForegroundTaskWake::queued(|_| {}),
- move |change| tx.send(change).unwrap(),
+ notifications.notifier(move || {
+ assert!(
+ environment().try_lock().is_some(),
+ "owner wake must not hold ICU lock"
+ );
+ assert!(
+ wake_notifications.has_pending(),
+ "publication must precede wake"
+ );
+ tx.send(()).unwrap();
+ }),
);
let owner = ProcessEnvironmentOwner::default();
owner.set_locale(Some("fr_FR")).unwrap();
owner.set_timezone(Some("Europe/Paris")).unwrap();
- // No runtime yield or isolate entry: publication is synchronous,
- // ordered, and application belongs to the receiving owner.
- assert_eq!(
- rx.try_recv().unwrap(),
- ProcessEnvironmentChange::LocaleChanged
- );
+ // No runtime yield or isolate entry. Both changes publish before
+ // returning, but require only one owner wake and one cache reset.
+ rx.try_recv().unwrap();
+ assert!(rx.try_recv().is_err());
assert_eq!(
- rx.try_recv().unwrap(),
- ProcessEnvironmentChange::TimezoneChanged
+ notifications.take(),
+ Some(ProcessEnvironmentChange::LocaleChanged)
);
owner.set_locale(Some("fr_FR")).unwrap();
owner.set_timezone(Some("Europe/Paris")).unwrap();
@@ -321,10 +350,12 @@ mod tests {
peer.set_timezone(Some("Europe/Paris")).unwrap();
peer.set_timezone(None).unwrap();
assert!(rx.try_recv().is_err());
+ assert!(!notifications.has_pending());
owner.release();
+ rx.try_recv().unwrap();
assert_eq!(
- rx.try_recv().unwrap(),
- ProcessEnvironmentChange::LocaleChanged
+ notifications.take(),
+ Some(ProcessEnvironmentChange::LocaleChanged)
);
owner.release();
assert!(rx.try_recv().is_err());
@@ -332,6 +363,7 @@ mod tests {
drop(registration);
drop(isolate);
owner.set_locale(Some("de_DE")).unwrap();
+ assert_eq!(notifications.take(), None);
assert!(
rx.try_recv().is_err(),
"retired owners receive no notification"
diff --git a/moli-v8-platform/src/environment/notifications.rs b/moli-v8-platform/src/environment/notifications.rs
new file mode 100644
index 000000000..9799064ee
--- /dev/null
+++ b/moli-v8-platform/src/environment/notifications.rs
@@ -0,0 +1,232 @@
+use std::sync::{
+ Arc,
+ atomic::{AtomicU8, Ordering},
+};
+
+use super::ProcessEnvironmentChange;
+
+const TIMEZONE: u8 = 1;
+const LOCALE: u8 = 2;
+const CLOSED: u8 = 4;
+
+/// One bounded mailbox per isolate, shared by its idle, interrupt and pause
+/// routes. These are pending cache invalidations, not configuration versions:
+/// ICU already contains the latest values, so unconsumed changes can be merged.
+#[derive(Clone, Debug, Default)]
+pub struct ProcessEnvironmentNotifications {
+ pending: Arc<AtomicU8>,
+}
+
+impl ProcessEnvironmentNotifications {
+ pub fn notifier(&self, wake: impl Fn() + Send + Sync + 'static) -> ProcessEnvironmentNotifier {
+ ProcessEnvironmentNotifier {
+ notifications: self.clone(),
+ wake: Arc::new(wake),
+ }
+ }
+
+ pub fn has_pending(&self) -> bool {
+ self.pending.load(Ordering::Acquire) & (LOCALE | TIMEZONE) != 0
+ }
+
+ /// Claim only the work published so far. A concurrent publication either
+ /// joins this batch or remains pending for the next owner turn; it cannot
+ /// be cleared by finishing the current notification.
+ pub fn take(&self) -> Option<ProcessEnvironmentChange> {
+ let pending = self.pending.fetch_and(CLOSED, Ordering::AcqRel);
+ if pending & LOCALE != 0 {
+ Some(ProcessEnvironmentChange::LocaleChanged)
+ } else if pending & TIMEZONE != 0 {
+ Some(ProcessEnvironmentChange::TimezoneChanged)
+ } else {
+ None
+ }
+ }
+
+ /// Owner disposal permanently rejects late publishers, including clones
+ /// retained by an in-flight process-wide publication.
+ pub fn close(&self) {
+ self.pending.store(CLOSED, Ordering::Release);
+ }
+
+ fn publish(&self, change: ProcessEnvironmentChange) -> bool {
+ let bits = match change {
+ ProcessEnvironmentChange::LocaleChanged => LOCALE | TIMEZONE,
+ ProcessEnvironmentChange::TimezoneChanged => TIMEZONE,
+ };
+ self.pending
+ .fetch_update(Ordering::AcqRel, Ordering::Acquire, |pending| {
+ (pending & CLOSED == 0).then_some(pending | bits)
+ })
+ == Ok(0)
+ }
+}
+
+/// A typed publication target, not a callback that receives environment state.
+/// Publication only touches the mailbox. Its owner wake runs separately, after
+/// the process controller has released the ICU/configuration mutex.
+#[derive(Clone)]
+pub struct ProcessEnvironmentNotifier {
+ notifications: ProcessEnvironmentNotifications,
+ wake: Arc<dyn Fn() + Send + Sync>,
+}
+
+impl ProcessEnvironmentNotifier {
+ /// Post a cache invalidation outside a process configuration transaction.
+ /// A burst schedules a wake only on the idle-to-pending transition.
+ pub fn notify(&self, change: ProcessEnvironmentChange) {
+ if self.publish(change) {
+ self.wake();
+ }
+ }
+
+ pub(super) fn publish(&self, change: ProcessEnvironmentChange) -> bool {
+ self.notifications.publish(change)
+ }
+
+ pub(super) fn wake(&self) {
+ if self.notifications.has_pending() {
+ (self.wake)();
+ }
+ }
+
+ pub(crate) fn close(&self) {
+ self.notifications.close();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ProcessEnvironmentChange::{LocaleChanged, TimezoneChanged};
+ use std::sync::atomic::AtomicUsize;
+
+ #[test]
+ fn bursts_merge_both_axes_into_one_notification_and_one_wake() {
+ let notifications = ProcessEnvironmentNotifications::default();
+ let wakes = Arc::new(AtomicUsize::new(0));
+ let count = wakes.clone();
+ let notifier = notifications.notifier(move || {
+ count.fetch_add(1, Ordering::Relaxed);
+ });
+ for _ in 0..10_000 {
+ notifier.notify(TimezoneChanged);
+ notifier.notify(LocaleChanged);
+ }
+ assert_eq!(wakes.load(Ordering::Relaxed), 1);
+ assert_eq!(notifications.take(), Some(LocaleChanged));
+ assert_eq!(notifications.take(), None);
+ notifier.notify(TimezoneChanged);
+ assert_eq!(wakes.load(Ordering::Relaxed), 2);
+ assert_eq!(notifications.take(), Some(TimezoneChanged));
+ }
+
+ #[test]
+ fn publication_during_consumption_survives_and_rearms_the_wake() {
+ let notifications = ProcessEnvironmentNotifications::default();
+ let (wake_tx, wake_rx) = std::sync::mpsc::channel();
+ let notifier = notifications.notifier(move || wake_tx.send(()).unwrap());
+ notifier.notify(LocaleChanged);
+ wake_rx.try_recv().unwrap();
+ let applying = notifications.take().unwrap();
+ // The first invalidation has been claimed but has not finished applying.
+ notifier.notify(TimezoneChanged);
+ assert_eq!(applying, LocaleChanged);
+ wake_rx.try_recv().unwrap();
+ assert_eq!(notifications.take(), Some(TimezoneChanged));
+ assert_eq!(notifications.take(), None);
+ }
+
+ #[test]
+ fn concurrent_publication_and_claim_never_lose_either_axis() {
+ let notifications = ProcessEnvironmentNotifications::default();
+ let barrier = std::sync::Barrier::new(2);
+ let mut outcomes = Vec::new();
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ for _ in 0..1_000 {
+ barrier.wait();
+ notifications.publish(LocaleChanged);
+ barrier.wait();
+ }
+ });
+ for _ in 0..1_000 {
+ notifications.publish(TimezoneChanged);
+ barrier.wait();
+ let first = notifications.take();
+ barrier.wait();
+ let second = notifications.take();
+ outcomes.push((first, second, notifications.has_pending()));
+ }
+ });
+ // Check after both threads finish so a regression cannot strand the
+ // producer at a barrier while the assertion unwinds the consumer.
+ for (first, second, pending) in outcomes {
+ assert!(first == Some(LocaleChanged) || second == Some(LocaleChanged));
+ assert!(
+ first.is_some(),
+ "the earlier timezone must also be consumed"
+ );
+ assert!(!pending);
+ }
+ }
+
+ #[test]
+ fn delayed_wake_observes_merged_state_and_never_overwrites_newer_work() {
+ let notifications = ProcessEnvironmentNotifications::default();
+ let (wake_tx, wake_rx) = std::sync::mpsc::channel();
+ let notifier = notifications.notifier(move || wake_tx.send(()).unwrap());
+ assert!(notifier.publish(TimezoneChanged));
+ assert!(!notifier.publish(LocaleChanged));
+ notifier.wake();
+ wake_rx.try_recv().unwrap();
+ assert_eq!(notifications.take(), Some(LocaleChanged));
+ notifier.notify(TimezoneChanged);
+ wake_rx.try_recv().unwrap();
+ assert_eq!(notifications.take(), Some(TimezoneChanged));
+ notifier.wake(); // An old delayed wake carries no configuration value.
+ assert!(wake_rx.try_recv().is_err());
+ }
+
+ #[test]
+ fn concurrent_disposal_and_publication_leave_mailboxes_permanently_closed() {
+ let notifications: Vec<_> = (0..1_000)
+ .map(|_| ProcessEnvironmentNotifications::default())
+ .collect();
+ let barrier = std::sync::Barrier::new(2);
+ std::thread::scope(|scope| {
+ scope.spawn(|| {
+ for mailbox in &notifications {
+ barrier.wait();
+ mailbox.publish(LocaleChanged);
+ barrier.wait();
+ }
+ });
+ for mailbox in &notifications {
+ barrier.wait();
+ mailbox.close();
+ barrier.wait();
+ }
+ });
+ for mailbox in notifications {
+ assert_eq!(mailbox.take(), None);
+ assert!(!mailbox.publish(TimezoneChanged));
+ assert_eq!(mailbox.take(), None);
+ }
+ }
+
+ #[test]
+ fn disposal_cancels_delayed_wakes_and_cannot_be_reopened() {
+ let notifications = ProcessEnvironmentNotifications::default();
+ let notifier = notifications.notifier(|| panic!("closed mailbox woke its owner"));
+ assert!(notifier.publish(LocaleChanged));
+ let delayed = notifier.clone();
+ notifications.close();
+ delayed.wake();
+ for change in [LocaleChanged, TimezoneChanged] {
+ delayed.notify(change);
+ }
+ assert_eq!(notifications.take(), None);
+ assert!(!notifications.has_pending());
+ }
+}
diff --git a/moli-v8-platform/src/lib.rs b/moli-v8-platform/src/lib.rs
index f9e0c5c2d..82b3e980e 100644
--- a/moli-v8-platform/src/lib.rs
+++ b/moli-v8-platform/src/lib.rs
@@ -24,7 +24,10 @@ const MAX_V8_BACKGROUND_WORKER_THREADS: usize = 8;
mod cpu_tracing;
mod environment;
-pub use environment::{ProcessEnvironmentChange, ProcessEnvironmentOwner};
+pub use environment::{
+ ProcessEnvironmentChange, ProcessEnvironmentNotifications, ProcessEnvironmentNotifier,
+ ProcessEnvironmentOwner,
+};
pub use cpu_tracing::{
PendingV8CpuTraceStart, PendingV8CpuTraceStop, V8CpuProfileSegment, V8CpuTraceConfiguration,
@@ -137,7 +140,7 @@ struct IsolateRuntimeRegistration {
handle: tokio::runtime::Handle,
wake: V8ForegroundTaskWake,
generation: IsolateRegistrationGeneration,
- environment_changed: Arc<dyn Fn(ProcessEnvironmentChange) + Send + Sync>,
+ environment_notifications: ProcessEnvironmentNotifier,
}
#[derive(Clone)]
@@ -279,7 +282,7 @@ fn dispatch_isolate_owner_callback(
fn register_isolate_with_wake(
isolate_ptr: v8::UnsafeRawIsolatePtr,
wake: V8ForegroundTaskWake,
- environment_changed: impl Fn(ProcessEnvironmentChange) + Send + Sync + 'static,
+ environment_notifications: ProcessEnvironmentNotifier,
) -> IsolateRegistrationGeneration {
let isolate_key = unsafe_raw_isolate_addr(isolate_ptr);
let Ok(handle) = tokio::runtime::Handle::try_current() else {
@@ -293,12 +296,13 @@ fn register_isolate_with_wake(
handle,
wake,
generation: generation.clone(),
- environment_changed: Arc::new(environment_changed),
+ environment_notifications,
},
) {
// A raw isolate address may be reused after disposal. Invalidate queued
// work from the previous generation before publishing the replacement.
previous.generation.cancel();
+ previous.environment_notifications.close();
}
drop(guard);
trace!(isolate = isolate_key, "registered isolate with V8 platform");
@@ -318,19 +322,19 @@ pub struct V8PlatformIsolateRegistration {
}
impl V8PlatformIsolateRegistration {
- /// Register an isolate and its owner task routes. `environment_changed`
- /// must enqueue a notification on that exact owner, including while paused;
- /// it must not synchronously enter V8. Closing the owner rejects late work.
+ /// Register an isolate and its owner task routes. The environment mailbox
+ /// belongs to this exact isolate; its wake must schedule owner work even
+ /// while paused, never synchronously enter V8. Unregister closes the mailbox.
pub fn register(
isolate: &mut v8::OwnedIsolate,
wake: V8ForegroundTaskWake,
- environment_changed: impl Fn(ProcessEnvironmentChange) + Send + Sync + 'static,
+ environment_notifications: ProcessEnvironmentNotifier,
) -> Self {
// SAFETY: `OwnedIsolate::as_raw_isolate_ptr` returns the V8 isolate
// pointer used by platform foreground-task callbacks. Ownership remains
// with `OwnedIsolate`; this registration stores only the address value.
let isolate_ptr = unsafe { isolate.as_raw_isolate_ptr() };
- let generation = register_isolate_with_wake(isolate_ptr, wake, environment_changed);
+ let generation = register_isolate_with_wake(isolate_ptr, wake, environment_notifications);
// Bootstrap may have primed caches before registration. Register first,
// then reset once: changes before registration are read from ICU, and
// changes racing this reset already have an owner notification queued.
@@ -359,8 +363,9 @@ impl V8PlatformIsolateRegistration {
let mut registry = registry_map();
if registry.get(&isolate_key).is_some_and(|registration| {
registration.generation.is_same_generation(&self.generation)
- }) {
- registry.remove(&isolate_key);
+ }) && let Some(registration) = registry.remove(&isolate_key)
+ {
+ registration.environment_notifications.close();
}
trace!(
isolate = isolate_key,
@@ -554,7 +559,7 @@ mod tests {
let _ = register_isolate_with_wake(
v8::UnsafeRawIsolatePtr::null(),
V8ForegroundTaskWake::new(|| {}),
- |_| {},
+ ProcessEnvironmentNotifications::default().notifier(|| {}),
);
}
@@ -569,8 +574,13 @@ mod tests {
let isolate_ptr = fake_isolate_ptr(raw);
runtime.block_on(async {
- let generation =
- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});
+ let notifications = ProcessEnvironmentNotifications::default();
+ let notifier = notifications.notifier(|| {});
+ let generation = register_isolate_with_wake(
+ isolate_ptr,
+ V8ForegroundTaskWake::new(|| {}),
+ notifier.clone(),
+ );
let registration = lookup_registration(raw)
.expect("registered isolate should expose its runtime registration");
let owner = V8PlatformIsolateRegistration {
@@ -579,6 +589,12 @@ mod tests {
};
owner.unregister();
+ notifier.notify(ProcessEnvironmentChange::LocaleChanged);
+ assert_eq!(
+ notifications.take(),
+ None,
+ "unregister closes retained mailbox clones"
+ );
assert!(
!registration.generation.is_active(),
@@ -599,15 +615,21 @@ mod tests {
let isolate_ptr = fake_isolate_ptr(raw);
runtime.block_on(async {
- let first_generation =
- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});
+ let first_generation = register_isolate_with_wake(
+ isolate_ptr,
+ V8ForegroundTaskWake::new(|| {}),
+ ProcessEnvironmentNotifications::default().notifier(|| {}),
+ );
let first = V8PlatformIsolateRegistration {
isolate_ptr: AtomicCell::new(isolate_ptr),
generation: first_generation.clone(),
};
- let second_generation =
- register_isolate_with_wake(isolate_ptr, V8ForegroundTaskWake::new(|| {}), |_| {});
+ let second_generation = register_isolate_with_wake(
+ isolate_ptr,
+ V8ForegroundTaskWake::new(|| {}),
+ ProcessEnvironmentNotifications::default().notifier(|| {}),
+ );
let second = V8PlatformIsolateRegistration {
isolate_ptr: AtomicCell::new(isolate_ptr),
generation: second_generation.clone(),