Skip to content

The headless browser for AI agents and web scraping

fix(js): deliver posted tasks through V8 queue

Jernej Barbaric5fb22f74e525
diff --git a/crates/obscura-js/js/bootstrap.js b/crates/obscura-js/js/bootstrap.js
index f6381771..fea3dfea 100644
--- a/crates/obscura-js/js/bootstrap.js
+++ b/crates/obscura-js/js/bootstrap.js
@@ -1086,9 +1086,9 @@ globalThis.queueMicrotask = globalThis.queueMicrotask || ((fn) => Promise.resolv
// Browser posted tasks need an event-loop boundary but no clock delay. Tokio's
// timer wheel imposes roughly a one-millisecond floor even for delay zero,
// which turns MessageChannel and scheduler chains into artificial latency.
-// Keep one shared priority/FIFO queue in JavaScript and use a yield-only async
-// op solely to wake one delivery. Scheduling the next wake after the callback
-// gives V8 a microtask checkpoint between every pair of posted tasks.
+// Keep one shared priority/FIFO queue in JavaScript and enqueue one callback on
+// deno_core's re-entrant-safe V8 task spawner. Scheduling the next wake after
+// the callback gives V8 a microtask checkpoint between every pair of tasks.
const _browserPostedTaskQueues = Array.from({ length: 6 }, () => []);
let _browserPostedTaskWakePending = false;
@@ -1096,15 +1096,7 @@ function _browserPostedTaskScheduleWake() {
if (_browserPostedTaskWakePending) return;
if (!Deno.core.ops.op_async_runtime_available()) return;
_browserPostedTaskWakePending = true;
- Deno.core.ops.op_posted_task().then(
- _browserPostedTaskRunOne,
- () => {
- _browserPostedTaskWakePending = false;
- if (_browserPostedTaskQueues.some(queue => queue.length)) {
- _scheduleAfter(0, _browserPostedTaskRunOne);
- }
- },
- );
+ Deno.core.ops.op_posted_task(_browserPostedTaskRunOne);
}
function _browserPostedTaskEnqueue(callback, priority) {
diff --git a/crates/obscura-js/src/frame.rs b/crates/obscura-js/src/frame.rs
index 29f97fce..ff4f4957 100644
--- a/crates/obscura-js/src/frame.rs
+++ b/crates/obscura-js/src/frame.rs
@@ -559,6 +559,43 @@ mod tests {
);
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn frame_posted_task_runs_in_its_creation_realm() {
+ let mut parent = page("https://parent.example/", "<html><body></body></html>");
+ let frame = FrameRealm::new(
+ &mut parent,
+ 1,
+ 0,
+ "https://child.example/",
+ "<html><body><output id='result'>pending</output></body></html>",
+ )
+ .expect("frame realm");
+
+ frame
+ .execute_script(
+ &mut parent,
+ "scheduler.postTask(() => {\
+ document.getElementById('result').textContent = location.origin;\
+ });",
+ )
+ .unwrap();
+ parent.run_event_loop_bounded(100).await.unwrap();
+
+ assert_eq!(
+ frame
+ .evaluate(
+ &mut parent,
+ "document.getElementById('result').textContent",
+ )
+ .unwrap(),
+ serde_json::json!("https://child.example"),
+ );
+ assert_eq!(
+ parent.evaluate("document.body.innerHTML").unwrap(),
+ serde_json::json!("")
+ );
+ }
+
#[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.rs
index e02263e9..343ff85b 100644
--- a/crates/obscura-js/src/ops.rs
+++ b/crates/obscura-js/src/ops.rs
@@ -3389,6 +3389,38 @@ mod tests {
);
}
+ /// 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.
+ #[tokio::test(flavor = "current_thread")]
+ async fn posted_task_from_async_op_resolution_avoids_driver_submission() {
+ let mut runtime = ObscuraJsRuntime::new();
+ runtime.set_dom(parse_html("<html><body></body></html>"));
+ runtime.set_url("http://example.com/posted-task-from-async-op");
+ runtime.run_page_init();
+ runtime
+ .execute_script(
+ "posted-task-from-op-resolution",
+ r#"
+ globalThis.__postedFromOp = 0;
+ Deno.core.ops.op_sleep(0).then(() => {
+ const rearm = () => scheduler.postTask(() => {
+ __postedFromOp++;
+ if (__postedFromOp < 250) rearm();
+ });
+ rearm();
+ });
+ "#,
+ )
+ .unwrap();
+
+ runtime.run_event_loop_bounded(300).await.unwrap();
+ assert_eq!(
+ runtime.evaluate("__postedFromOp").unwrap(),
+ serde_json::json!(250.0),
+ );
+ }
+
#[cfg(feature = "render")]
#[test]
fn connected_shadow_nodes_invalidate_without_entering_light_tree_retention() {
@@ -3857,14 +3889,27 @@ fn op_async_runtime_available() -> bool {
tokio::runtime::Handle::try_current().is_ok()
}
-/// Wake one browser posted task without routing through Tokio's timer wheel.
-/// `yield_now` guarantees the op cannot settle in the initiating JavaScript
-/// turn, while avoiding the roughly one-millisecond floor of a zero-duration
-/// timer. The bootstrap owns task priority, FIFO order, and one-at-a-time
-/// delivery; this op supplies only the event-loop wake boundary.
-#[op2(async)]
-async fn op_posted_task() {
- tokio::task::yield_now().await;
+/// Queue one browser posted-task delivery on deno_core's engine-local V8 task
+/// spawner. It is safe to call from an async-op reaction and wakes the event
+/// loop without Tokio's timer-wheel floor or another async-op registration.
+#[op2]
+fn op_posted_task(
+ state: &OpState,
+ #[global] callback: v8::Global<v8::Function>,
+) {
+ let spawner = state.borrow::<deno_core::V8TaskSpawner>().clone();
+ spawner.spawn(move |scope| {
+ 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 message = scope
+ .exception()
+ .map(|exception| exception.to_rust_string_lossy(scope))
+ .unwrap_or_else(|| "execution terminated".to_string());
+ tracing::warn!("posted-task delivery failed: {message}");
+ }
+ });
}
// Records a binding call from page JS. The CDP layer drains this queue