use crate::runtime::{scheduler, Timer};
use crate::time::{error::Error, Duration, Instant};
use crate::util::trace;
use pin_project_lite::pin_project;
use std::future::Future;
use std::panic::Location;
use std::pin::Pin;
use std::task::{self, ready, Poll};
#[cfg_attr(docsrs, doc(alias = "delay_until"))]
#[track_caller]
pub fn sleep_until(deadline: Instant) -> Sleep {
Sleep::new_timeout(deadline, trace::caller_location())
}
#[cfg_attr(docsrs, doc(alias = "delay_for"))]
#[cfg_attr(docsrs, doc(alias = "wait"))]
#[track_caller]
pub fn sleep(duration: Duration) -> Sleep {
let location = trace::caller_location();
match Instant::now().checked_add(duration) {
Some(deadline) => Sleep::new_timeout(deadline, location),
None => Sleep::new_timeout(Instant::far_future(), location),
}
}
pin_project! {
#[project(!Unpin)]
#[cfg_attr(docsrs, doc(alias = "Delay"))]
#[derive(Debug)]
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct Sleep {
deadline: Instant,
driver: scheduler::Handle,
inner: Inner,
#[pin]
timer: Option<Timer>,
}
}
cfg_trace! {
#[derive(Debug)]
struct Inner {
ctx: trace::AsyncOpTracingCtx,
}
}
cfg_not_trace! {
#[derive(Debug)]
struct Inner {
}
}
impl Sleep {
#[cfg_attr(not(all(tokio_unstable, feature = "tracing")), allow(unused_variables))]
#[track_caller]
pub(crate) fn new_timeout(
deadline: Instant,
location: Option<&'static Location<'static>>,
) -> Sleep {
let handle = scheduler::Handle::current();
_ = handle.driver().time();
#[cfg(all(tokio_unstable, feature = "tracing"))]
let inner = {
let location = location.expect("should have location if tracing");
let resource_span = tracing::trace_span!(
parent: None,
"runtime.resource",
concrete_type = "Sleep",
kind = "timer",
loc.file = location.file(),
loc.line = location.line(),
loc.col = location.column(),
);
let async_op_span = tracing::trace_span!(
parent: &resource_span,
"runtime.resource.async_op",
source = "Sleep::new_timeout",
);
let async_op_poll_span =
tracing::trace_span!(parent: &async_op_span, "runtime.resource.async_op.poll");
let ctx = trace::AsyncOpTracingCtx {
async_op_span,
async_op_poll_span,
resource_span,
};
Inner { ctx }
};
#[cfg(not(all(tokio_unstable, feature = "tracing")))]
let inner = Inner {};
Sleep {
deadline,
driver: handle,
inner,
timer: None,
}
}
pub(crate) fn far_future(location: Option<&'static Location<'static>>) -> Sleep {
Self::new_timeout(Instant::far_future(), location)
}
pub fn deadline(&self) -> Instant {
self.deadline
}
pub fn is_elapsed(&self) -> bool {
self.timer.as_ref().is_some_and(Timer::is_elapsed)
}
pub fn reset(self: Pin<&mut Self>, deadline: Instant) {
let mut this = self.project();
*this.deadline = deadline;
let handle = this.driver;
#[cfg(all(tokio_unstable, feature = "tracing"))]
{
let _resource_enter = this.inner.ctx.resource_span.enter();
this.inner.ctx.async_op_span =
tracing::trace_span!("runtime.resource.async_op", source = "Sleep::reset");
let _async_op_enter = this.inner.ctx.async_op_span.enter();
this.inner.ctx.async_op_poll_span =
tracing::trace_span!("runtime.resource.async_op.poll");
let clock = handle.driver().clock();
let time_source = handle.driver().time().time_source();
let now = time_source.now(clock);
let tick = time_source.deadline_to_tick(deadline);
tracing::trace!(
target: "runtime::resource::state_update",
duration = tick.saturating_sub(now),
duration.unit = "ms",
duration.op = "override",
);
}
match this.timer.as_mut().as_pin_mut() {
Some(timer) => timer.reset(handle.clone(), deadline),
None => {
let timer = Timer::new(handle.clone(), deadline);
this.timer.set(Some(timer));
this.timer.as_pin_mut().unwrap().init(deadline);
}
}
}
pub(super) fn reset_without_timer(self: Pin<&mut Self>, deadline: Instant) {
let mut this = self.project();
*this.deadline = deadline;
this.timer.set(None);
}
fn poll_elapsed(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Result<(), Error>> {
ready!(crate::trace::trace_leaf());
let mut this = self.project();
#[cfg(all(tokio_unstable, feature = "tracing"))]
let _res_span = this.inner.ctx.resource_span.enter();
#[cfg(all(tokio_unstable, feature = "tracing"))]
let _ao_span = this.inner.ctx.async_op_span.enter();
#[cfg(all(tokio_unstable, feature = "tracing"))]
let _ao_poll_span = this.inner.ctx.async_op_poll_span.enter();
#[cfg(all(tokio_unstable, feature = "tracing"))]
let coop = ready!(trace_poll_op!(
"poll_elapsed",
crate::task::coop::poll_proceed(cx),
));
#[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
let coop = ready!(crate::task::coop::poll_proceed(cx));
let timer = match this.timer.as_mut().as_pin_mut() {
Some(timer) => timer,
None => {
let handle = this.driver;
#[cfg(all(tokio_unstable, feature = "tracing"))]
{
let clock = handle.driver().clock();
let time_source = handle.driver().time().time_source();
let now = time_source.now(clock);
let tick = time_source.deadline_to_tick(*this.deadline);
tracing::trace!(
target: "runtime::resource::state_update",
duration = tick.saturating_sub(now),
duration.unit = "ms",
duration.op = "override",
);
}
let timer = Timer::new(handle.clone(), *this.deadline);
this.timer.set(Some(timer));
let mut timer = this.timer.as_pin_mut().unwrap();
timer.as_mut().init(*this.deadline);
timer
}
};
let result = timer.poll_elapsed(cx).map(move |r| {
coop.made_progress();
r
});
#[cfg(all(tokio_unstable, feature = "tracing"))]
return trace_poll_op!("poll_elapsed", result);
#[cfg(any(not(tokio_unstable), not(feature = "tracing")))]
return result;
}
}
impl Future for Sleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
match ready!(self.poll_elapsed(cx)) {
Ok(()) => Poll::Ready(()),
Err(e) => panic!("timer error: {e}"),
}
}
}