Skip to content

Commit 02635fb

Browse files
[runtime/tokio] Simplify sleep_until (#3464)
1 parent 2e532fe commit 02635fb

2 files changed

Lines changed: 26 additions & 8 deletions

File tree

runtime/src/lib.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -824,7 +824,7 @@ mod tests {
824824
use commonware_utils::{
825825
channel::{mpsc, oneshot},
826826
sync::Mutex,
827-
NZUsize,
827+
NZUsize, SystemTimeExt,
828828
};
829829
use futures::{
830830
future::{pending, ready},
@@ -889,6 +889,17 @@ mod tests {
889889
});
890890
}
891891

892+
fn test_clock_sleep_until_far_future<R: Runner>(runner: R)
893+
where
894+
R::Context: Spawner + Clock,
895+
{
896+
runner.start(|context| async move {
897+
let sleep = context.sleep_until(SystemTime::limit());
898+
let result = context.timeout(Duration::from_millis(1), sleep).await;
899+
assert!(matches!(result, Err(Error::Timeout)));
900+
});
901+
}
902+
892903
fn test_clock_timeout<R: Runner>(runner: R)
893904
where
894905
R::Context: Spawner + Clock,
@@ -3147,6 +3158,12 @@ mod tests {
31473158
test_clock_sleep_until(executor);
31483159
}
31493160

3161+
#[test]
3162+
fn test_deterministic_clock_sleep_until_far_future() {
3163+
let executor = deterministic::Runner::default();
3164+
test_clock_sleep_until_far_future(executor);
3165+
}
3166+
31503167
#[test]
31513168
fn test_deterministic_clock_timeout() {
31523169
let executor = deterministic::Runner::default();
@@ -3490,6 +3507,12 @@ mod tests {
34903507
test_clock_sleep_until(executor);
34913508
}
34923509

3510+
#[test]
3511+
fn test_tokio_clock_sleep_until_far_future() {
3512+
let executor = tokio::Runner::default();
3513+
test_clock_sleep_until_far_future(executor);
3514+
}
3515+
34933516
#[test]
34943517
fn test_tokio_clock_timeout() {
34953518
let executor = tokio::Runner::default();

runtime/src/tokio/runtime.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -740,13 +740,8 @@ impl Clock for Context {
740740
}
741741

742742
fn sleep_until(&self, deadline: SystemTime) -> impl Future<Output = ()> + Send + 'static {
743-
let now = SystemTime::now();
744-
let duration_until_deadline = deadline.duration_since(now).unwrap_or_else(|_| {
745-
// Deadline is in the past
746-
Duration::from_secs(0)
747-
});
748-
let target_instant = tokio::time::Instant::now() + duration_until_deadline;
749-
tokio::time::sleep_until(target_instant)
743+
let duration_until_deadline = deadline.duration_since(self.current()).unwrap_or_default();
744+
tokio::time::sleep(duration_until_deadline)
750745
}
751746
}
752747

0 commit comments

Comments
 (0)