use std::fmt;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use std::time::{Duration, Instant};
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(fetchlet_process, derive(serde::Serialize, serde::Deserialize))]
pub(crate) enum StopReason {
Deadline,
Startup,
Busy,
Heap,
}
impl StopReason {
const fn code(self) -> u8 {
match self {
Self::Deadline => 1,
Self::Startup => 2,
Self::Busy => 3,
Self::Heap => 4,
}
}
const fn from_code(code: u8) -> Option<Self> {
match code {
1 => Some(Self::Deadline),
2 => Some(Self::Startup),
3 => Some(Self::Busy),
4 => Some(Self::Heap),
_ => None,
}
}
}
#[derive(Debug)]
pub(crate) struct Interrupted(pub StopReason);
impl fmt::Display for Interrupted {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self.0 {
StopReason::Deadline => "JavaScript ran past its deadline",
StopReason::Startup => "the module ran past its startup timeout",
StopReason::Busy => "JavaScript ran past its busy timeout",
StopReason::Heap => "JavaScript reached the engine's heap limit",
})
}
}
impl std::error::Error for Interrupted {}
impl From<Interrupted> for Error {
fn from(interrupted: Interrupted) -> Self {
match interrupted.0 {
StopReason::Deadline | StopReason::Startup => Error::DeadlineExceeded,
StopReason::Busy => Error::LimitExceeded("engine busy time"),
StopReason::Heap => Error::LimitExceeded("engine heap"),
}
}
}
#[derive(Clone, Default)]
pub(crate) struct Interrupt {
inner: Arc<InterruptState>,
}
#[derive(Default)]
struct InterruptState {
busy: Option<Duration>,
deadline: AtomicU64,
deadline_reason: AtomicU8,
busy_until: AtomicU64,
reason: AtomicU8,
}
impl Interrupt {
pub fn new(busy: Option<Duration>) -> Self {
Self {
inner: Arc::new(InterruptState {
busy,
..InterruptState::default()
}),
}
}
#[cfg_attr(not(feature = "v8"), allow(dead_code))]
pub fn busy_timeout(&self) -> Option<Duration> {
self.inner.busy
}
pub fn arm(&self, deadline: Option<Instant>) {
self.arm_with(deadline, StopReason::Deadline);
}
pub fn arm_startup(&self, deadline: Option<Instant>) {
self.arm_with(deadline, StopReason::Startup);
}
fn arm_with(&self, deadline: Option<Instant>, reason: StopReason) {
let state = &self.inner;
state.reason.store(0, Ordering::Relaxed);
state.busy_until.store(0, Ordering::Relaxed);
state
.deadline_reason
.store(reason.code(), Ordering::Relaxed);
state
.deadline
.store(deadline.map_or(0, encode), Ordering::Relaxed);
}
pub fn disarm(&self) {
self.inner.deadline.store(0, Ordering::Relaxed);
self.inner.busy_until.store(0, Ordering::Relaxed);
}
pub fn enter(&self) {
if let Some(busy) = self.inner.busy {
let until = Instant::now().checked_add(busy).map_or(u64::MAX, encode);
self.inner.busy_until.store(until, Ordering::Relaxed);
}
}
pub fn leave(&self) {
self.inner.busy_until.store(0, Ordering::Relaxed);
}
#[cfg_attr(not(any(feature = "quickjs", feature = "v8")), allow(dead_code))]
pub fn stop(&self, reason: StopReason) {
self.inner.reason.store(reason.code(), Ordering::Relaxed);
}
pub fn expired(&self) -> bool {
let state = &self.inner;
if state.reason.load(Ordering::Relaxed) == StopReason::Heap.code() {
return true;
}
let deadline = state.deadline.load(Ordering::Relaxed);
let busy_until = state.busy_until.load(Ordering::Relaxed);
if deadline == 0 && busy_until == 0 {
return false;
}
let now = encode(Instant::now());
let reason = if deadline != 0 && now >= deadline {
state.deadline_reason.load(Ordering::Relaxed)
} else if busy_until != 0 && now >= busy_until {
StopReason::Busy.code()
} else {
return false;
};
state.reason.store(reason, Ordering::Relaxed);
true
}
pub fn stopped(&self) -> Option<StopReason> {
StopReason::from_code(self.inner.reason.load(Ordering::Relaxed))
}
}
fn base() -> Instant {
static BASE: OnceLock<Instant> = OnceLock::new();
*BASE.get_or_init(Instant::now)
}
fn encode(instant: Instant) -> u64 {
let nanos = instant.saturating_duration_since(base()).as_nanos();
u64::try_from(nanos)
.unwrap_or(u64::MAX - 1)
.saturating_add(1)
}
#[cfg(test)]
mod tests {
use super::*;
const HOUR: Duration = Duration::from_secs(3600);
#[test]
fn only_an_armed_past_deadline_expires() {
let interrupt = Interrupt::default();
assert!(!interrupt.expired());
interrupt.arm(None);
assert!(!interrupt.expired());
interrupt.arm(Some(Instant::now() + HOUR));
assert!(!interrupt.expired());
assert_eq!(interrupt.stopped(), None);
interrupt.arm(Some(Instant::now()));
assert!(interrupt.expired());
assert_eq!(interrupt.stopped(), Some(StopReason::Deadline));
interrupt.disarm();
assert!(!interrupt.expired());
assert_eq!(interrupt.stopped(), Some(StopReason::Deadline));
interrupt.arm(None);
assert_eq!(interrupt.stopped(), None);
interrupt.arm_startup(Some(Instant::now()));
assert!(interrupt.expired());
assert_eq!(interrupt.stopped(), Some(StopReason::Startup));
}
#[test]
fn a_heap_stop_expires_until_the_next_evaluation() {
let interrupt = Interrupt::default();
interrupt.arm(None);
interrupt.stop(StopReason::Heap);
assert!(interrupt.expired());
interrupt.arm_with(Some(Instant::now()), StopReason::Deadline);
interrupt.stop(StopReason::Heap);
assert!(interrupt.expired());
assert_eq!(interrupt.stopped(), Some(StopReason::Heap));
interrupt.disarm();
assert!(interrupt.expired());
}
#[test]
fn the_busy_clock_runs_only_inside_javascript() {
let interrupt = Interrupt::new(Some(Duration::ZERO));
interrupt.arm(Some(Instant::now() + HOUR));
assert!(!interrupt.expired());
interrupt.enter();
assert!(interrupt.expired());
assert_eq!(interrupt.stopped(), Some(StopReason::Busy));
interrupt.leave();
assert!(!interrupt.expired());
let patient = Interrupt::new(Some(HOUR));
patient.arm(None);
patient.enter();
assert!(!patient.expired());
let unlimited = Interrupt::new(None);
unlimited.arm(None);
unlimited.enter();
assert!(!unlimited.expired());
}
}