The headless browser for AI agents and web scraping
fix(js): cancel posted tasks across realm teardown
Jernej Barbarica240419ac841
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.jsindex fea3dfea..66fb585c 100644--- a/crates/obscura-js/js/bootstrap.js+++ b/crates/obscura-js/js/bootstrap.js@@ -1091,26 +1091,61 @@ globalThis.queueMicrotask = globalThis.queueMicrotask || ((fn) => Promise.resolv// the callback gives V8 a microtask checkpoint between every pair of tasks.const _browserPostedTaskQueues = Array.from({ length: 6 }, () => []);let _browserPostedTaskWakePending = false;+const _invalidPostedTaskGeneration = -1;++function _browserPostedTaskGeneration() {+ return Deno.core.ops.op_posted_task_generation(_realmFrameId);+}++function _browserPostedTaskDiscardQueue(queue) {+ const entries = queue.splice(0, queue.length);+ for (const entry of entries) {+ if (entry.discard) {+ try { entry.discard(); } catch (_) {}+ }+ }+}function _browserPostedTaskScheduleWake() {if (_browserPostedTaskWakePending) return;if (!Deno.core.ops.op_async_runtime_available()) return;- _browserPostedTaskWakePending = true;- Deno.core.ops.op_posted_task(_browserPostedTaskRunOne);+ const generation = Deno.core.ops.op_posted_task(+ _realmFrameId, _browserPostedTaskRunOne);+ _browserPostedTaskWakePending = generation !== _invalidPostedTaskGeneration;+ if (!_browserPostedTaskWakePending) {+ for (const queue of _browserPostedTaskQueues) _browserPostedTaskDiscardQueue(queue);+ }}-function _browserPostedTaskEnqueue(callback, priority) {- _browserPostedTaskQueues[priority].push(callback);+function _browserPostedTaskEnqueue(+ callback, priority, generation = _browserPostedTaskGeneration(), discard = null) {+ _browserPostedTaskQueues[priority].push({ callback, generation, discard });_browserPostedTaskScheduleWake();}-function _browserPostedTaskRunOne() {+function _browserPostedTaskRunOne(currentGeneration = _invalidPostedTaskGeneration) {+ // Document replacement and frame teardown are cancellation boundaries.+ // Borrow contention is cancelled too: a browser task must not unwind through+ // V8 or enter a realm whose native owner is unavailable._browserPostedTaskWakePending = false;+ if (currentGeneration === _invalidPostedTaskGeneration) {+ for (const queue of _browserPostedTaskQueues) _browserPostedTaskDiscardQueue(queue);+ return;+ }let callback = null;for (let priority = _browserPostedTaskQueues.length - 1; priority >= 0; priority--) {const queue = _browserPostedTaskQueues[priority];+ let staleCount = 0;+ while (staleCount < queue.length &&+ queue[staleCount].generation !== currentGeneration) staleCount++;+ const staleEntries = staleCount ? queue.splice(0, staleCount) : [];+ for (const stale of staleEntries) {+ if (stale.discard) {+ try { stale.discard(); } catch (_) {}+ }+ }if (queue.length) {- callback = queue.shift();+ callback = queue.shift().callback;break;}}@@ -1142,7 +1177,11 @@ let _schedulerCurrentState = null;function _schedulerRemoveAbort(task) {if (task.signal && task.abortHandler) {- task.signal.removeEventListener("abort", task.abortHandler);+ // Scheduler options accept only this realm's AbortSignal. Use its private+ // listener store so page code cannot intercept teardown by overriding the+ // public removeEventListener method.+ const index = task.signal._listeners.indexOf(task.abortHandler);+ if (index >= 0) task.signal._listeners.splice(index, 1);task.abortHandler = null;}}@@ -1151,7 +1190,13 @@ function _schedulerEnqueue(task, continuation) {if (task.canceled) return;const effectivePriority = _schedulerPriorityRank[task.priority] * 2+ (continuation ? 1 : 0);- _browserPostedTaskEnqueue(() => _schedulerRunTask(task), effectivePriority);+ _browserPostedTaskEnqueue(+ () => _schedulerRunTask(task), effectivePriority, task.documentGeneration,+ () => {+ task.canceled = true;+ task.callback = null;+ _schedulerRemoveAbort(task);+ });}function _schedulerRunTask(task) {@@ -1211,6 +1256,7 @@ function _schedulerNormalizeOptions(options) {function _schedulerCreateTask(callback, state, resolve, reject) {const task = {callback, state, resolve, reject,+ documentGeneration: _browserPostedTaskGeneration(),priority: state.priority,signal: state.signal,abortHandler: null,@@ -1227,7 +1273,8 @@ function _schedulerCreateTask(callback, state, resolve, reject) {_schedulerRemoveAbort(task);reject(task.signal.reason);};- task.signal.addEventListener("abort", task.abortHandler);+ // See _schedulerRemoveAbort: the public method is intentionally bypassed.+ task.signal._listeners.push(task.abortHandler);}return task;}@@ -1339,6 +1386,7 @@ function _messagePortInstallEventHandler(port, type, callback) {function _messagePortScheduleDelivery(port) {const state = _messagePortStateFor(port);if (state.closed || !state.messageQueueEnabled || state.messageDeliveryPending || !state.messageQueue.length) return;+ const deliveryGeneration = state.messageQueue[0].generation;state.messageDeliveryPending = true;// User-visible ordinary rank. Scheduler continuations at the same priority// remain immediately above this task; FIFO holds across all ordinary tasks.@@ -1347,7 +1395,7 @@ function _messagePortScheduleDelivery(port) {if (!current) return;current.messageDeliveryPending = false;if (current.closed || !current.messageQueueEnabled || !current.messageQueue.length) return;- const data = current.messageQueue.shift();+ const data = current.messageQueue.shift().data;const event = new MessageEvent("message", {data,origin: "",@@ -1357,7 +1405,14 @@ function _messagePortScheduleDelivery(port) {});_eventTargetDispatch(port, event);_messagePortScheduleDelivery(port);- }, _schedulerPriorityRank["user-visible"] * 2);+ }, _schedulerPriorityRank["user-visible"] * 2, deliveryGeneration, () => {+ const current = _messagePortState.get(port);+ if (!current) return;+ current.messageDeliveryPending = false;+ current.messageQueue = current.messageQueue.filter(+ entry => entry.generation !== deliveryGeneration);+ _messagePortScheduleDelivery(port);+ });}class MessagePort {constructor(key) {@@ -1388,7 +1443,10 @@ class MessagePort {const target = state.entangled;const targetState = target && _messagePortState.get(target);if (state.closed || !targetState || targetState.closed) return;- targetState.messageQueue.push(cloned);+ targetState.messageQueue.push({+ data: cloned,+ generation: _browserPostedTaskGeneration(),+ });_messagePortScheduleDelivery(target);}start() {@@ -9107,6 +9165,11 @@ let _intersectionDeliveryTaskPending = false;function _scheduleIntersectionObserverDelivery(observer) {if (!observer._connected || !observer._records.length) return;+ const documentGeneration = _browserPostedTaskGeneration();+ if (observer._documentGeneration !== documentGeneration) {+ observer._records.length = 0;+ return;+ }_intersectionDeliveryObservers.add(observer);if (_intersectionDeliveryTaskPending) return;_intersectionDeliveryTaskPending = true;@@ -9124,7 +9187,17 @@ function _scheduleIntersectionObserverDelivery(observer) {const records = current.takeRecords();try { current._callback(records, current); } catch (e) {}}- }, _schedulerPriorityRank["user-visible"] * 2);+ }, _schedulerPriorityRank["user-visible"] * 2, documentGeneration, () => {+ _intersectionDeliveryTaskPending = false;+ const currentGeneration = _browserPostedTaskGeneration();+ const current = [];+ for (const pending of _intersectionDeliveryObservers) {+ if (pending._documentGeneration === currentGeneration) current.push(pending);+ else pending._records.length = 0;+ }+ _intersectionDeliveryObservers.clear();+ for (const pending of current) _scheduleIntersectionObserverDelivery(pending);+ });}function _scheduleIntersectionRenderCheckpoint() {@@ -9268,6 +9341,7 @@ globalThis.IntersectionObserver = class IntersectionObserver {this._targets = new Set();this._previous = new Map();this._records = [];+ this._documentGeneration = _browserPostedTaskGeneration();this._connected = true;globalThis.__intersectionObservers.push(this);}@@ -14774,6 +14848,8 @@ if (typeof ShadowRoot !== 'undefined' && !ShadowRoot.prototype.elementFromPoint)globalThis.__obscura_init = function() {// The host sets __obscura_frameId on a frame realm before calling this._realmFrameId = globalThis.__obscura_frameId >>> 0;+ _browserPostedTaskWakePending = false;+ for (const queue of _browserPostedTaskQueues) _browserPostedTaskDiscardQueue(queue);_fpSeed = Date.now() ^ (Math.random() * 0xFFFFFFFF >>> 0);_fpCache = null;// A real navigation just completed (this runs after set_url), so drop anydiff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rsindex ff4f4957..12d1fe2d 100644--- a/crates/obscura-js/src/frame.rs+++ b/crates/obscura-js/src/frame.rs@@ -574,7 +574,8 @@ mod tests {frame.execute_script(&mut parent,- "scheduler.postTask(() => {\+ "globalThis.__obscura_frameId = 0;\+ scheduler.postTask(() => {\document.getElementById('result').textContent = location.origin;\});",)@@ -596,6 +597,86 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn dropping_frame_cancels_its_queued_posted_task() {+ let mut parent = page(+ "https://parent.example/",+ "<html><body data-owner='parent'></body></html>",+ );+ let frame = FrameRealm::new(+ &mut parent,+ 1,+ 0,+ "https://parent.example/child",+ "<html><body data-owner='frame'></body></html>",+ )+ .expect("frame realm");++ frame+ .execute_script(+ &mut parent,+ "const staleController = new AbortController();\+ globalThis.__staleController = staleController;\+ staleController.signal.removeEventListener = () => {\+ document.body.setAttribute('data-stale-cleanup', 'ran');\+ parent.postMessage('stale-cleanup', '*');\+ };\+ scheduler.postTask(() => {\+ document.body.setAttribute('data-stale-task', 'ran');\+ parent.postMessage('stale-posted-task', '*');\+ }, { signal: staleController.signal });\+ setTimeout(() => scheduler.postTask(() => {\+ document.body.setAttribute('data-delayed-stale-task', 'ran');\+ parent.postMessage('delayed-stale-posted-task', '*');\+ }), 1);",+ )+ .unwrap();+ drop(frame);+ parent.run_event_loop_bounded(100).await.unwrap();++ assert!(+ parent.take_pending_frame_messages().is_empty(),+ "a posted task from the detached frame still executed",+ );++ assert_eq!(+ parent.evaluate("document.body.getAttribute('data-owner')").unwrap(),+ serde_json::json!("parent"),+ );+ assert_eq!(+ parent+ .evaluate("document.body.getAttribute('data-stale-task')")+ .unwrap(),+ serde_json::Value::Null,+ );+ assert_eq!(+ parent+ .evaluate("document.body.getAttribute('data-delayed-stale-task')")+ .unwrap(),+ serde_json::Value::Null,+ );+ assert_eq!(+ parent+ .evaluate("document.body.getAttribute('data-stale-cleanup')")+ .unwrap(),+ serde_json::Value::Null,+ );+ assert_eq!(+ parent+ .evaluate(+ "(function(){\+ const window = globalThis.__obscura_frameObjects[1]?.window;\+ const controller = window?.__staleController;\+ return [typeof window, typeof controller,\+ controller?.signal?._listeners?.length];\+ })()",+ )+ .unwrap(),+ serde_json::json!(["object", "object", 0]),+ "the retained frame realm did not discard its scheduler listener",+ );+ }+#[test]fn one_bad_frame_script_does_not_stop_the_rest() {let mut parent = page("https://parent.example/", "<html><body></body></html>");diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 343ff85b..0a3fcfbc 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -3057,15 +3057,19 @@ fn glob_match(pattern: &str, url: &str) -> bool {#[cfg(test)]mod tests {- use super::{cors_response_allows, glob_match, validate_fetch_url, FetchCredentials};+ use super::{+ cors_response_allows, glob_match, validate_fetch_url, FetchCredentials, ObscuraState,+ };use crate::runtime::ObscuraJsRuntime;use obscura_dom::parse_html;+ use std::cell::RefCell;+ use std::rc::Rc;#[cfg(feature = "render")]use super::{ensure_prepared_geometry, ensure_prepared_render, node_is_connected,queue_retained_style_mutation, retained_style_mutation,- shadow_including_connected_nodes, ObscuraState, MAX_PENDING_STYLE_MUTATIONS,+ shadow_including_connected_nodes, MAX_PENDING_STYLE_MUTATIONS,};#[cfg(feature = "render")]use obscura_dom::ShadowRootMode;@@ -3389,6 +3393,31 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn bulk_posted_task_batch_completes() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html("<html><body></body></html>"));+ runtime.set_url("http://example.com/posted-task-bulk");+ runtime.run_page_init();+ runtime+ .execute_script(+ "posted-task-bulk",+ r#"+ globalThis.__bulkPosted = { count: 0 };+ const tasks = [];+ for (let i = 0; i < 4096; i++) {+ tasks.push(scheduler.postTask(() => __bulkPosted.count++));+ }+ Promise.all(tasks);+ "#,+ )+ .unwrap();++ runtime.run_event_loop_bounded(500).await.unwrap();+ let result = runtime.evaluate("__bulkPosted").unwrap();+ assert_eq!(result["count"].as_f64(), Some(4096.0));+ }+/// A network-op Promise reaction can schedule browser work while/// deno_core is dispatching an async-op result batch. Posted tasks must not/// recursively submit another async op through that borrowed driver.@@ -3421,6 +3450,100 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn posted_task_is_cancelled_when_its_document_is_replaced() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html("<html><body data-document='old'></body></html>"));+ runtime.set_url("http://example.com/posted-task-old-document");+ runtime.run_page_init();+ runtime+ .execute_script(+ "posted-task-old-document",+ "const staleController = new AbortController();\+ scheduler.postTask(\+ () => document.body.setAttribute('data-stale-task', 'ran'),\+ { signal: staleController.signal });",+ )+ .unwrap();++ runtime.set_dom(parse_html("<html><body data-document='new'></body></html>"));+ runtime+ .execute_script(+ "posted-task-new-document",+ "scheduler.postTask(() => document.body.setAttribute('data-fresh-task', 'ran'));",+ )+ .unwrap();+ runtime.run_event_loop_bounded(100).await.unwrap();++ assert_eq!(+ runtime+ .evaluate("document.body.getAttribute('data-stale-task')")+ .unwrap(),+ serde_json::Value::Null,+ );+ assert_eq!(+ runtime+ .evaluate("document.body.getAttribute('data-document')")+ .unwrap(),+ serde_json::json!("new"),+ );+ assert_eq!(+ runtime+ .evaluate("document.body.getAttribute('data-fresh-task')")+ .unwrap(),+ serde_json::json!("ran"),+ );+ }++ #[tokio::test(flavor = "current_thread")]+ async fn delayed_posted_task_keeps_its_creation_document_generation() {+ let mut runtime = ObscuraJsRuntime::new();+ runtime.set_dom(parse_html("<html><body data-document='old'></body></html>"));+ runtime.set_url("http://example.com/delayed-posted-task-old-document");+ runtime.run_page_init();+ runtime+ .execute_script(+ "delayed-posted-task-old-document",+ "scheduler.postTask(\+ () => document.body.setAttribute('data-delayed-stale-task', 'ran'),\+ { delay: 1 });",+ )+ .unwrap();++ runtime.set_dom(parse_html("<html><body data-document='new'></body></html>"));+ runtime.run_event_loop_bounded(100).await.unwrap();++ assert_eq!(+ runtime+ .evaluate("document.body.getAttribute('data-delayed-stale-task')")+ .unwrap(),+ serde_json::Value::Null,+ );+ }++ #[test]+ fn posted_task_owner_contention_is_panic_safe() {+ let owner = Rc::new(RefCell::new(ObscuraState::new()));+ let weak = Rc::downgrade(&owner);+ let generation = owner.borrow().document_generation;++ let held = owner.borrow_mut();+ assert_eq!(+ super::posted_task_owner_status(&weak),+ super::PostedTaskOwnerStatus::Busy,+ );+ drop(held);+ assert_eq!(+ super::posted_task_owner_status(&weak),+ super::PostedTaskOwnerStatus::Generation(generation),+ );+ drop(owner);+ assert_eq!(+ super::posted_task_owner_status(&weak),+ super::PostedTaskOwnerStatus::Gone,+ );+ }+#[cfg(feature = "render")]#[test]fn connected_shadow_nodes_invalidate_without_entering_light_tree_retention() {@@ -3895,14 +4018,31 @@ fn op_async_runtime_available() -> bool {#[op2]fn op_posted_task(state: &OpState,+ frame_id: u32,#[global] callback: v8::Global<v8::Function>,-) {+) -> f64 {+ let Some(owner) = posted_task_owner(state, frame_id) else {+ return INVALID_POSTED_TASK_GENERATION;+ };+ let Ok(owner_state) = owner.try_borrow() else {+ return INVALID_POSTED_TASK_GENERATION;+ };+ let document_generation = owner_state.document_generation;+ drop(owner_state);+ let owner = Rc::downgrade(&owner);let spawner = state.borrow::<deno_core::V8TaskSpawner>().clone();spawner.spawn(move |scope| {+ let current_generation = match posted_task_owner_status(&owner) {+ PostedTaskOwnerStatus::Gone | PostedTaskOwnerStatus::Busy => {+ INVALID_POSTED_TASK_GENERATION+ }+ PostedTaskOwnerStatus::Generation(generation) => generation as f64,+ };let scope = &mut v8::TryCatch::new(scope);let callback = v8::Local::new(scope, callback);let receiver = v8::undefined(scope).into();- if callback.call(scope, receiver, &[]).is_none() {+ let current_generation = v8::Number::new(scope, current_generation);+ if callback.call(scope, receiver, &[current_generation.into()]).is_none() {let message = scope.exception().map(|exception| exception.to_rust_string_lossy(scope))@@ -3910,6 +4050,49 @@ fn op_posted_task(tracing::warn!("posted-task delivery failed: {message}");}});+ document_generation as f64+}++const INVALID_POSTED_TASK_GENERATION: f64 = -1.0;++#[derive(Debug, PartialEq, Eq)]+enum PostedTaskOwnerStatus {+ Gone,+ Busy,+ Generation(u64),+}++fn posted_task_owner_status(+ owner: &std::rc::Weak<RefCell<ObscuraState>>,+) -> PostedTaskOwnerStatus {+ let Some(owner) = owner.upgrade() else {+ return PostedTaskOwnerStatus::Gone;+ };+ let Ok(owner) = owner.try_borrow() else {+ return PostedTaskOwnerStatus::Busy;+ };+ PostedTaskOwnerStatus::Generation(owner.document_generation)+}++#[op2(fast)]+fn op_posted_task_generation(state: &OpState, frame_id: u32) -> f64 {+ let Some(owner) = posted_task_owner(state, frame_id) else {+ return INVALID_POSTED_TASK_GENERATION;+ };+ let generation = owner+ .try_borrow()+ .map(|owner| owner.document_generation as f64)+ .unwrap_or(INVALID_POSTED_TASK_GENERATION);+ generation+}++fn posted_task_owner(state: &OpState, frame_id: u32) -> Option<SharedState> {+ if frame_id == 0 {+ return Some(state.borrow::<SharedState>().clone());+ }+ let registry = state.try_borrow::<Rc<RefCell<RealmStates>>>()?.clone();+ let owner = registry.try_borrow().ok()?.by_frame_id(frame_id);+ owner}// Records a binding call from page JS. The CDP layer drains this queue@@ -4650,6 +4833,7 @@ pub fn build_extension() -> Extension {op_sleep(),op_async_runtime_available(),op_posted_task(),+ op_posted_task_generation(),op_binding_called(),op_subtle_digest(),op_subtle_hmac(),diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 8b2df06a..46fe52c8 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -3836,6 +3836,36 @@ mod tests {);}+ #[tokio::test(flavor = "current_thread")]+ async fn message_port_drops_old_document_payloads_before_fresh_delivery() {+ let mut rt = setup_runtime("<html><body data-document='old'></body></html>");+ rt.execute_script(+ "message-port-old-document",+ r#"+ globalThis.__replacementPortOrder = [];+ globalThis.__replacementChannel = new MessageChannel();+ __replacementChannel.port2.onmessage = event => {+ __replacementPortOrder.push(event.data);+ };+ __replacementChannel.port1.postMessage("old");+ "#,+ )+ .unwrap();++ rt.set_dom(parse_html("<html><body data-document='new'></body></html>"));+ rt.execute_script(+ "message-port-new-document",+ r#"__replacementChannel.port1.postMessage("fresh");"#,+ )+ .unwrap();+ rt.run_event_loop_bounded(100).await.unwrap();++ assert_eq!(+ rt.evaluate("__replacementPortOrder").unwrap(),+ serde_json::json!(["fresh"]),+ );+ }+#[tokio::test(flavor = "current_thread")]async fn message_port_close_discards_delivery_already_queued_for_a_task() {let mut rt = setup_runtime("<html><body></body></html>");@@ -10470,6 +10500,45 @@ mod tests {);}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn intersection_delivery_recovers_across_document_replacement() {+ let mut rt = ObscuraJsRuntime::new();+ rt.set_dom(parse_html("<html><body></body></html>"));+ rt.run_page_init();+ rt.execute_script(+ "old-intersection-delivery",+ r#"+ globalThis.__intersectionReplacementOrder = [];+ const oldObserver = new IntersectionObserver(() => {+ __intersectionReplacementOrder.push("old");+ });+ oldObserver._records.push({ old: true });+ oldObserver._check([], false, new Map());+ "#,+ )+ .unwrap();++ rt.set_dom(parse_html("<html><body></body></html>"));+ rt.execute_script(+ "fresh-intersection-delivery",+ r#"+ const freshObserver = new IntersectionObserver(() => {+ __intersectionReplacementOrder.push("fresh");+ });+ freshObserver._records.push({ fresh: true });+ freshObserver._check([], false, new Map());+ "#,+ )+ .unwrap();++ rt.run_event_loop_bounded(100).await.unwrap();+ assert_eq!(+ rt.evaluate("__intersectionReplacementOrder").unwrap(),+ serde_json::json!(["fresh"]),+ );+ }+#[cfg(feature = "render")]#[tokio::test(flavor = "current_thread")]async fn intersection_observer_element_root_uses_live_padding_box_and_scroll() {@@ -17548,5 +17617,3 @@ mod tests {);}}--