From 5caeee13d085f2ede9ca51550a4718906a465e57 Mon Sep 17 00:00:00 2001 From: Gautam Dhameja Date: Tue, 23 Jul 2019 10:59:37 +0200 Subject: [PATCH] sleep_until off-chain API (#3164) * sleep_until Offchain API * addressed review comments --- substrate/core/offchain/src/api.rs | 33 ++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/substrate/core/offchain/src/api.rs b/substrate/core/offchain/src/api.rs index 2598945dca..949602f3f7 100644 --- a/substrate/core/offchain/src/api.rs +++ b/substrate/core/offchain/src/api.rs @@ -18,7 +18,8 @@ use std::{ str::FromStr, sync::Arc, convert::{TryFrom, TryInto}, - time::SystemTime + time::{SystemTime, Duration}, + thread::sleep, }; use client::backend::OffchainStorage; use crate::AuthorityKeyProvider; @@ -26,7 +27,8 @@ use futures::{Stream, Future, sync::mpsc}; use log::{info, debug, warn, error}; use parity_codec::{Encode, Decode}; use primitives::offchain::{ - Timestamp, HttpRequestId, HttpRequestStatus, HttpError, + Timestamp, + HttpRequestId, HttpRequestStatus, HttpError, Externalities as OffchainExt, CryptoKind, CryptoKey, StorageKind, @@ -329,8 +331,13 @@ where } } - fn sleep_until(&mut self, _deadline: Timestamp) { - unavailable_yet::<()>("sleep_until") + fn sleep_until(&mut self, deadline: Timestamp) { + // Get current timestamp. + let now = self.timestamp(); + // Calculate the diff with the deadline. + let diff = deadline.diff(&now); + // Call thread::sleep for the diff duration. + sleep(Duration::from_millis(diff.millis())); } fn random_seed(&mut self) -> [u8; 32] { @@ -608,6 +615,24 @@ mod tests { assert_eq!(timestamp.unix_millis(), d); } + #[test] + fn should_sleep() { + let mut api = offchain_api().0; + + // Arrange. + let now = api.timestamp(); + let delta = primitives::offchain::Duration::from_millis(100); + let deadline = now.add(delta); + + // Act. + api.sleep_until(deadline); + let new_now = api.timestamp(); + + // Assert. + // The diff could be more than the sleep duration. + assert!(new_now.unix_millis() - 100 >= now.unix_millis()); + } + #[test] fn should_set_and_get_local_storage() { // given