Skip to content

The headless browser for AI agents and web scraping

fix(js): cancel watchdog threads on drop

Jernej Barbaric24ec0e27e4ca
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 16a2fde9..839005a4 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -283,10 +283,10 @@ pub fn spawn_watchdog(handle: IsolateHandle, budget: std::time::Duration) -> Wat
}
impl WatchdogToken {
- /// Stop the watchdog. Returns true if it had already fired (terminated the
- /// isolate). The caller must then clear the termination flag via
- /// [`ObscuraJsRuntime::cancel_termination`] before the next eval.
- pub fn stop(mut self) -> bool {
+ fn cancel_and_join(&mut self) {
+ if self.join.is_none() {
+ return;
+ }
{
let (lock, cvar) = &*self.pair;
*lock.lock().unwrap() = true;
@@ -295,10 +295,26 @@ impl WatchdogToken {
if let Some(j) = self.join.take() {
let _ = j.join();
}
+ }
+
+ /// Stop the watchdog. Returns true if it had already fired (terminated the
+ /// isolate). The caller must then clear the termination flag via
+ /// [`ObscuraJsRuntime::cancel_termination`] before the next eval.
+ pub fn stop(mut self) -> bool {
+ self.cancel_and_join();
self.fired.load(std::sync::atomic::Ordering::SeqCst)
}
}
+impl Drop for WatchdogToken {
+ fn drop(&mut self) {
+ // Futures which own a watchdog may be cancelled while parked on I/O.
+ // Dropping the token must not leave a detached thread which later
+ // terminates an isolate that has already moved on to another task.
+ self.cancel_and_join();
+ }
+}
+
// Observation deadlines are checked between browser tasks. A task which has
// already started receives this bounded completion allowance, matching the
// fixed-wait path while retaining an absolute backstop for infinite script.
@@ -6188,6 +6204,18 @@ mod tests {
);
}
+ #[test]
+ fn dropping_a_watchdog_cannot_terminate_later_work() {
+ let mut rt = setup_runtime("<html><body></body></html>");
+ {
+ let _cancelled = rt.arm_watchdog(std::time::Duration::from_millis(500));
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ std::thread::sleep(std::time::Duration::from_millis(600));
+
+ assert_eq!(rt.evaluate("1 + 1").unwrap(), serde_json::json!(2.0));
+ }
+
#[tokio::test(flavor = "current_thread")]
async fn quiescent_event_loop_retains_delayed_network_and_dom_update() {
let mut rt = setup_runtime("<html><body></body></html>");