2021-01-10 21:59:07 -05:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-09-05 20:34:02 -04:00
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
//! This module helps deno implement timers.
|
|
|
|
//!
|
|
|
|
//! As an optimization, we want to avoid an expensive calls into rust for every
|
|
|
|
//! setTimeout in JavaScript. Thus in //js/timers.ts a data structure is
|
|
|
|
//! implemented that calls into Rust for only the smallest timeout. Thus we
|
2020-09-22 13:33:29 -04:00
|
|
|
//! only need to be able to start, cancel and await a single timer (or Delay, as Tokio
|
2020-09-19 19:17:35 -04:00
|
|
|
//! calls it) for an entire Isolate. This is what is implemented here.
|
|
|
|
|
2020-12-07 08:27:25 -05:00
|
|
|
use super::dispatch_minimal::minimal_op;
|
|
|
|
use super::dispatch_minimal::MinimalOp;
|
|
|
|
use crate::metrics::metrics_op;
|
2020-09-19 19:17:35 -04:00
|
|
|
use crate::permissions::Permissions;
|
2020-12-07 08:27:25 -05:00
|
|
|
use deno_core::error::type_error;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2020-09-21 12:36:37 -04:00
|
|
|
use deno_core::futures;
|
|
|
|
use deno_core::futures::channel::oneshot;
|
|
|
|
use deno_core::futures::FutureExt;
|
|
|
|
use deno_core::futures::TryFutureExt;
|
|
|
|
use deno_core::serde_json;
|
|
|
|
use deno_core::serde_json::json;
|
|
|
|
use deno_core::serde_json::Value;
|
2020-08-28 11:08:24 -04:00
|
|
|
use deno_core::BufVec;
|
2020-09-10 09:57:45 -04:00
|
|
|
use deno_core::OpState;
|
2020-04-23 05:51:07 -04:00
|
|
|
use deno_core::ZeroCopyBuf;
|
2020-09-16 12:43:08 -04:00
|
|
|
use serde::Deserialize;
|
2020-09-10 09:57:45 -04:00
|
|
|
use std::cell::RefCell;
|
2020-09-19 19:17:35 -04:00
|
|
|
use std::future::Future;
|
2020-09-22 13:33:29 -04:00
|
|
|
use std::pin::Pin;
|
2020-08-18 12:30:13 -04:00
|
|
|
use std::rc::Rc;
|
2020-10-15 21:06:31 -04:00
|
|
|
use std::thread::sleep;
|
2019-08-14 11:03:02 -04:00
|
|
|
use std::time::Duration;
|
|
|
|
use std::time::Instant;
|
2020-09-22 13:33:29 -04:00
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
pub type StartTime = Instant;
|
|
|
|
|
2020-09-22 13:33:29 -04:00
|
|
|
type TimerFuture = Pin<Box<dyn Future<Output = Result<(), ()>>>>;
|
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct GlobalTimer {
|
|
|
|
tx: Option<oneshot::Sender<()>>,
|
2020-09-22 13:33:29 -04:00
|
|
|
pub future: Option<TimerFuture>,
|
2020-09-19 19:17:35 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl GlobalTimer {
|
|
|
|
pub fn cancel(&mut self) {
|
|
|
|
if let Some(tx) = self.tx.take() {
|
|
|
|
tx.send(()).ok();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-22 13:33:29 -04:00
|
|
|
pub fn new_timeout(&mut self, deadline: Instant) {
|
2020-09-19 19:17:35 -04:00
|
|
|
if self.tx.is_some() {
|
|
|
|
self.cancel();
|
|
|
|
}
|
|
|
|
assert!(self.tx.is_none());
|
2020-09-22 13:33:29 -04:00
|
|
|
self.future.take();
|
2020-09-19 19:17:35 -04:00
|
|
|
|
|
|
|
let (tx, rx) = oneshot::channel();
|
|
|
|
self.tx = Some(tx);
|
|
|
|
|
2021-01-12 02:50:02 -05:00
|
|
|
let delay = tokio::time::sleep_until(deadline.into()).boxed_local();
|
2020-09-19 19:17:35 -04:00
|
|
|
let rx = rx
|
|
|
|
.map_err(|err| panic!("Unexpected error in receiving channel {:?}", err));
|
|
|
|
|
2020-09-22 13:33:29 -04:00
|
|
|
let fut = futures::future::select(delay, rx)
|
|
|
|
.then(|_| futures::future::ok(()))
|
|
|
|
.boxed_local();
|
|
|
|
self.future = Some(fut);
|
2020-09-19 19:17:35 -04:00
|
|
|
}
|
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
pub fn init(rt: &mut deno_core::JsRuntime) {
|
2020-09-28 06:14:11 -04:00
|
|
|
{
|
|
|
|
let op_state = rt.op_state();
|
|
|
|
let mut state = op_state.borrow_mut();
|
|
|
|
state.put::<GlobalTimer>(GlobalTimer::default());
|
|
|
|
state.put::<StartTime>(StartTime::now());
|
|
|
|
}
|
2020-09-10 09:57:45 -04:00
|
|
|
super::reg_json_sync(rt, "op_global_timer_stop", op_global_timer_stop);
|
2020-09-22 13:33:29 -04:00
|
|
|
super::reg_json_sync(rt, "op_global_timer_start", op_global_timer_start);
|
2020-09-10 09:57:45 -04:00
|
|
|
super::reg_json_async(rt, "op_global_timer", op_global_timer);
|
2021-02-21 13:20:31 -05:00
|
|
|
rt.register_op("op_now", metrics_op("op_now", minimal_op(op_now)));
|
2020-10-15 21:06:31 -04:00
|
|
|
super::reg_json_sync(rt, "op_sleep_sync", op_sleep_sync);
|
2019-10-11 14:41:54 -04:00
|
|
|
}
|
|
|
|
|
2021-02-12 05:08:36 -05:00
|
|
|
#[allow(clippy::unnecessary_wraps)]
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_global_timer_stop(
|
2020-09-10 09:57:45 -04:00
|
|
|
state: &mut OpState,
|
2019-08-26 08:50:21 -04:00
|
|
|
_args: Value,
|
2020-06-01 14:20:47 -04:00
|
|
|
_zero_copy: &mut [ZeroCopyBuf],
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2020-09-18 14:39:47 -04:00
|
|
|
let global_timer = state.borrow_mut::<GlobalTimer>();
|
|
|
|
global_timer.cancel();
|
2020-08-28 11:08:24 -04:00
|
|
|
Ok(json!({}))
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct GlobalTimerArgs {
|
|
|
|
timeout: u64,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
2020-09-22 13:33:29 -04:00
|
|
|
// Set up a timer that will be later awaited by JS promise.
|
|
|
|
// It's a separate op, because canceling a timeout immediately
|
|
|
|
// after setting it caused a race condition (because Tokio timeout)
|
|
|
|
// might have been registered after next event loop tick.
|
|
|
|
//
|
|
|
|
// See https://github.com/denoland/deno/issues/7599 for more
|
|
|
|
// details.
|
|
|
|
fn op_global_timer_start(
|
|
|
|
state: &mut OpState,
|
2019-08-26 08:50:21 -04:00
|
|
|
args: Value,
|
2020-09-22 13:33:29 -04:00
|
|
|
_zero_copy: &mut [ZeroCopyBuf],
|
2020-09-14 12:48:57 -04:00
|
|
|
) -> Result<Value, AnyError> {
|
2019-08-26 08:50:21 -04:00
|
|
|
let args: GlobalTimerArgs = serde_json::from_value(args)?;
|
|
|
|
let val = args.timeout;
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2019-09-19 18:09:43 -04:00
|
|
|
let deadline = Instant::now() + Duration::from_millis(val);
|
2020-09-22 13:33:29 -04:00
|
|
|
let global_timer = state.borrow_mut::<GlobalTimer>();
|
|
|
|
global_timer.new_timeout(deadline);
|
|
|
|
Ok(json!({}))
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn op_global_timer(
|
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
_args: Value,
|
|
|
|
_zero_copy: BufVec,
|
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
let maybe_timer_fut = {
|
2020-09-18 14:39:47 -04:00
|
|
|
let mut s = state.borrow_mut();
|
|
|
|
let global_timer = s.borrow_mut::<GlobalTimer>();
|
2020-09-22 13:33:29 -04:00
|
|
|
global_timer.future.take()
|
2020-09-10 09:57:45 -04:00
|
|
|
};
|
2020-09-22 13:33:29 -04:00
|
|
|
if let Some(timer_fut) = maybe_timer_fut {
|
|
|
|
let _ = timer_fut.await;
|
|
|
|
}
|
2020-08-28 11:08:24 -04:00
|
|
|
Ok(json!({}))
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
2019-10-11 14:41:54 -04:00
|
|
|
|
|
|
|
// Returns a milliseconds and nanoseconds subsec
|
|
|
|
// since the start time of the deno runtime.
|
|
|
|
// If the High precision flag is not set, the
|
|
|
|
// nanoseconds are rounded on 2ms.
|
|
|
|
fn op_now(
|
2020-12-07 08:27:25 -05:00
|
|
|
state: Rc<RefCell<OpState>>,
|
|
|
|
// Arguments are discarded
|
|
|
|
_sync: bool,
|
|
|
|
_x: i32,
|
|
|
|
mut zero_copy: BufVec,
|
|
|
|
) -> MinimalOp {
|
|
|
|
match zero_copy.len() {
|
|
|
|
0 => return MinimalOp::Sync(Err(type_error("no buffer specified"))),
|
|
|
|
1 => {}
|
|
|
|
_ => {
|
|
|
|
return MinimalOp::Sync(Err(type_error("Invalid number of arguments")))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let op_state = state.borrow();
|
|
|
|
let start_time = op_state.borrow::<StartTime>();
|
2020-09-19 19:17:35 -04:00
|
|
|
let seconds = start_time.elapsed().as_secs();
|
2020-12-07 08:27:25 -05:00
|
|
|
let mut subsec_nanos = start_time.elapsed().subsec_nanos() as f64;
|
|
|
|
let reduced_time_precision = 2_000_000.0; // 2ms in nanoseconds
|
2019-10-11 14:41:54 -04:00
|
|
|
|
|
|
|
// If the permission is not enabled
|
|
|
|
// Round the nano result on 2 milliseconds
|
|
|
|
// see: https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#Reduced_time_precision
|
2020-12-07 08:27:25 -05:00
|
|
|
if op_state.borrow::<Permissions>().check_hrtime().is_err() {
|
2020-08-25 18:22:15 -04:00
|
|
|
subsec_nanos -= subsec_nanos % reduced_time_precision;
|
2019-10-11 14:41:54 -04:00
|
|
|
}
|
|
|
|
|
2020-12-07 08:27:25 -05:00
|
|
|
let result = (seconds * 1_000) as f64 + (subsec_nanos / 1_000_000.0);
|
|
|
|
|
|
|
|
(&mut zero_copy[0]).copy_from_slice(&result.to_be_bytes());
|
|
|
|
|
|
|
|
MinimalOp::Sync(Ok(0))
|
2019-10-11 14:41:54 -04:00
|
|
|
}
|
2020-10-15 21:06:31 -04:00
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct SleepArgs {
|
|
|
|
millis: u64,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn op_sleep_sync(
|
|
|
|
state: &mut OpState,
|
|
|
|
args: Value,
|
|
|
|
_zero_copy: &mut [ZeroCopyBuf],
|
|
|
|
) -> Result<Value, AnyError> {
|
|
|
|
super::check_unstable(state, "Deno.sleepSync");
|
|
|
|
let args: SleepArgs = serde_json::from_value(args)?;
|
|
|
|
sleep(Duration::from_millis(args.millis));
|
|
|
|
Ok(json!({}))
|
|
|
|
}
|