use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, OnceLock};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use deno_core::v8;
use crate::execution::Interrupt;
pub(super) type IsolateSlot = Arc<OnceLock<v8::IsolateHandle>>;
const FINEST: Duration = Duration::from_millis(1);
const COARSEST: Duration = Duration::from_millis(100);
pub(super) struct Watchdog {
stop: Option<mpsc::Sender<()>>,
thread: Option<JoinHandle<()>>,
}
impl Watchdog {
pub fn start(
interrupt: &Interrupt,
startup_timeout: Option<Duration>,
isolate: &IsolateSlot,
) -> std::io::Result<Option<Self>> {
let shortest = match (interrupt.busy_timeout(), startup_timeout) {
(Some(busy), Some(startup)) => busy.min(startup),
(Some(timeout), None) | (None, Some(timeout)) => timeout,
(None, None) => return Ok(None),
};
let interval = (shortest / 4).clamp(FINEST, COARSEST);
let (stop, stopped) = mpsc::channel::<()>();
let interrupt = interrupt.clone();
let isolate = isolate.clone();
let thread = thread::Builder::new()
.name("fetchlet-v8-watchdog".into())
.spawn(move || {
while let Err(RecvTimeoutError::Timeout) = stopped.recv_timeout(interval) {
if interrupt.expired()
&& let Some(isolate) = isolate.get()
{
isolate.terminate_execution();
}
}
})?;
Ok(Some(Self {
stop: Some(stop),
thread: Some(thread),
}))
}
}
impl Drop for Watchdog {
fn drop(&mut self) {
drop(self.stop.take());
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}