Skip to content

Commit

Permalink
Browser time (#2452)
Browse files Browse the repository at this point in the history
* `linera-base`: abstract away from `tokio::time` for the Web

* `linera-rpc`: remove path prefix on `Duration`

Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>
Signed-off-by: James Kay <twey@twey.co.uk>

---------

Signed-off-by: James Kay <twey@twey.co.uk>
Co-authored-by: Janito Vaqueiro Ferreira Filho <janito.vff@gmail.com>
  • Loading branch information
Twey and jvff authored Sep 5, 2024
1 parent e3d0ab1 commit c74afeb
Show file tree
Hide file tree
Showing 39 changed files with 101 additions and 109 deletions.
3 changes: 1 addition & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion examples/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion linera-base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ web = [
"rand/std",
"rand/std_rng",
"tracing-web",
"web-time",
"wasmtimer",
"wasm-bindgen-futures",
"web-time",
]

[dependencies]
Expand Down Expand Up @@ -52,9 +53,11 @@ serde_json.workspace = true
sha3.workspace = true
test-strategy = { workspace = true, optional = true }
thiserror.workspace = true
tokio = { workspace = true, features = ["time"] }
tracing.workspace = true
tracing-subscriber = { workspace = true, features = ["json", "fmt", "ansi"] }
wasm-bindgen-futures = { workspace = true, optional = true }
wasmtimer = { workspace = true, optional = true }
web-time = { workspace = true, optional = true }

[target.'cfg(target_arch = "wasm32")'.dependencies]
Expand Down
10 changes: 1 addition & 9 deletions linera-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod ownership;
pub mod prometheus_util;
#[cfg(not(chain))]
pub mod task;
pub mod time;
pub mod tracing;
#[cfg(test)]
mod unit_tests;
Expand All @@ -31,15 +32,6 @@ pub use graphql::BcsHexParseError;
#[doc(hidden)]
pub use {async_graphql, bcs, hex};

cfg_if::cfg_if! {
if #[cfg(web)] {
#[cfg(web)]
pub use web_time as time;
} else {
pub use std::time;
}
}

/// A macro for asserting that a condition is true, returning an error if it is not.
///
/// # Examples
Expand Down
4 changes: 2 additions & 2 deletions linera-base/src/prometheus_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@

//! This module defines util functions for interacting with Prometheus (logging metrics, etc)
use std::time::Instant;

use prometheus::{
histogram_opts, register_histogram_vec, register_int_counter_vec, Error, HistogramVec,
IntCounterVec, Opts,
};

use crate::time::Instant;

const LINERA_NAMESPACE: &str = "linera";

/// Wrapper arount prometheus register_int_counter_vec! macro which also sets the linera namespace
Expand Down
16 changes: 16 additions & 0 deletions linera-base/src/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

/*!
Abstractions over time that can be used natively or on the Web.
*/

cfg_if::cfg_if! {
if #[cfg(web)] {
pub use web_time::*;
pub use wasmtimer::tokio as timer;
} else {
pub use std::time::*;
pub use tokio::time as timer;
}
}
2 changes: 1 addition & 1 deletion linera-client/src/chain_listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ where

async fn maybe_sleep(delay_ms: u64) {
if delay_ms > 0 {
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
linera_base::time::timer::sleep(Duration::from_millis(delay_ms)).await;
}
}
}
9 changes: 3 additions & 6 deletions linera-client/src/client_context.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
collections::BTreeMap,
sync::Arc,
time::{Duration, Instant},
};
use std::{collections::BTreeMap, sync::Arc};

use async_trait::async_trait;
use futures::Future;
Expand All @@ -14,6 +10,7 @@ use linera_base::{
data_types::{BlockHeight, Timestamp},
identifiers::{Account, ChainId},
ownership::ChainOwnership,
time::{Duration, Instant},
};
use linera_chain::data_types::Certificate;
use linera_core::{
Expand Down Expand Up @@ -618,7 +615,7 @@ where
let chain_client = self.make_chain_client(chain_id);
async move {
for i in 0..5 {
tokio::time::sleep(Duration::from_secs(i)).await;
linera_base::time::timer::sleep(Duration::from_secs(i)).await;
chain_client.process_inbox().await?;
let chain_state = chain_client.chain_state_view().await?;
if chain_state
Expand Down
5 changes: 3 additions & 2 deletions linera-client/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashSet, num::ParseIntError, str::FromStr, time::Duration};
use std::{collections::HashSet, num::ParseIntError, str::FromStr};

use futures::future;
use linera_base::{
crypto::CryptoError,
data_types::{TimeDelta, Timestamp},
identifiers::ChainId,
time::Duration,
};
use linera_core::{data_types::RoundTimeout, node::NotificationStream, worker::Reason};
use tokio_stream::StreamExt as _;
Expand Down Expand Up @@ -36,7 +37,7 @@ pub async fn wait_for_next_round(stream: &mut NotificationStream, timeout: Round
});
future::select(
Box::pin(stream.next()),
Box::pin(tokio::time::sleep(
Box::pin(linera_base::time::timer::sleep(
timeout.timestamp.duration_since(Timestamp::now()),
)),
)
Expand Down
3 changes: 0 additions & 3 deletions linera-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,13 @@ web = [
"linera-execution/web",
"linera-storage/web",
"linera-views/web",
"wasmtimer",
]

[dependencies]
anyhow = { workspace = true, optional = true }
async-graphql.workspace = true
async-trait.workspace = true
bcs.workspace = true
cfg-if.workspace = true
clap.workspace = true
dashmap.workspace = true
futures.workspace = true
Expand All @@ -77,7 +75,6 @@ tokio-stream.workspace = true
tonic.workspace = true
tracing.workspace = true
trait-variant.workspace = true
wasmtimer = { workspace = true, optional = true }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
linera-storage-service.workspace = true
Expand Down
3 changes: 1 addition & 2 deletions linera-core/benches/client_benchmarks.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::time::Duration;

use criterion::{criterion_group, criterion_main, measurement::Measurement, BatchSize, Criterion};
use linera_base::{
data_types::Amount,
identifiers::{Account, ChainDescription},
time::Duration,
};
use linera_core::{
client,
Expand Down
4 changes: 2 additions & 2 deletions linera-core/src/chain_worker/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@

//! Configuration parameters for the chain worker.
use std::{sync::Arc, time::Duration};
use std::sync::Arc;

use linera_base::crypto::KeyPair;
use linera_base::{crypto::KeyPair, time::Duration};

/// Configuration parameters for the [`ChainWorkerState`][`super::state::ChainWorkerState`].
#[derive(Clone, Default)]
Expand Down
4 changes: 2 additions & 2 deletions linera-core/src/unit_tests/worker_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3635,7 +3635,7 @@ where
}

drop(worker);
tokio::time::sleep(Duration::from_millis(10)).await;
linera_base::time::timer::sleep(Duration::from_millis(10)).await;
application.assert_no_more_expected_calls();
application.assert_no_active_instances();

Expand Down Expand Up @@ -3805,7 +3805,7 @@ where
}

drop(worker);
tokio::time::sleep(Duration::from_millis(10)).await;
linera_base::time::timer::sleep(Duration::from_millis(10)).await;
application.assert_no_more_expected_calls();
application.assert_no_active_instances();

Expand Down
10 changes: 1 addition & 9 deletions linera-core/src/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use linera_base::{
data_types::{BlockHeight, Round},
ensure,
identifiers::ChainId,
time::{Duration, Instant},
time::{timer::timeout, Duration, Instant},
};
use linera_chain::data_types::{BlockProposal, Certificate, LiteVote};
use linera_execution::committee::{Committee, ValidatorName};
Expand All @@ -28,14 +28,6 @@ use crate::{
node::{CrossChainMessageDelivery, LocalValidatorNode, NodeError},
};

cfg_if::cfg_if! {
if #[cfg(web)] {
use wasmtimer::tokio::timeout;
} else {
use tokio::time::timeout;
}
}

/// The amount of time we wait for additional validators to contribute to the result, as a fraction
/// of how long it took to reach a quorum.
const GRACE_PERIOD: f64 = 0.2;
Expand Down
2 changes: 1 addition & 1 deletion linera-core/src/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use linera_base::{
data_types::{ArithmeticError, Blob, BlockHeight, Round, UserApplicationDescription},
doc_scalar,
identifiers::{BlobId, ChainId, Owner, UserApplicationId},
time::timer::{sleep, timeout},
};
use linera_chain::{
data_types::{
Expand All @@ -33,7 +34,6 @@ use thiserror::Error;
use tokio::{
sync::{mpsc, oneshot, OwnedRwLockReadGuard},
task::JoinSet,
time::{sleep, timeout},
};
use tracing::{error, instrument, trace, warn, Instrument as _};
#[cfg(with_metrics)]
Expand Down
6 changes: 3 additions & 3 deletions linera-indexer/example/tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async fn run_indexer(path_provider: &PathProvider) -> Child {
let child = command.spawn().unwrap();
let client = reqwest_client();
for i in 0..10 {
tokio::time::sleep(Duration::from_secs(i)).await;
linera_base::time::timer::sleep(Duration::from_secs(i)).await;
let request = client
.get(format!("http://localhost:{}/", port))
.send()
Expand Down Expand Up @@ -118,9 +118,9 @@ async fn test_end_to_end_operations_indexer(config: impl LineraNetConfig) {
let chain1 = ChainId::root(1);
for _ in 0..10 {
transfer(&req_client, chain0, chain1, "0.1").await;
tokio::time::sleep(Duration::from_millis(TRANSFER_DELAY_MILLIS)).await;
linera_base::time::timer::sleep(Duration::from_millis(TRANSFER_DELAY_MILLIS)).await;
}
tokio::time::sleep(Duration::from_secs(2)).await;
linera_base::time::timer::sleep(Duration::from_secs(2)).await;

// checking indexer state
let variables = block::Variables {
Expand Down
6 changes: 3 additions & 3 deletions linera-indexer/lib/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

//! This module defines the service client for the indexer.
use std::time::Duration;

use async_tungstenite::{
tokio::connect_async,
tungstenite::{client::IntoClientRequest, http::HeaderValue},
Expand All @@ -15,7 +13,9 @@ use futures::{
};
use graphql_client::reqwest::post_graphql;
use graphql_ws_client::{graphql::StreamingOperation, GraphQLClientClientBuilder};
use linera_base::{crypto::CryptoHash, data_types::BlockHeight, identifiers::ChainId};
use linera_base::{
crypto::CryptoHash, data_types::BlockHeight, identifiers::ChainId, time::Duration,
};
use linera_chain::data_types::HashedCertificateValue;
use linera_core::worker::Reason;
use linera_service_graphql_client::{block, chains, notifications, Block, Chains, Notifications};
Expand Down
5 changes: 3 additions & 2 deletions linera-rpc/src/grpc/client.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{iter, time::Duration};
use std::iter;

use futures::{future, stream, StreamExt};
use linera_base::{
crypto::CryptoHash,
data_types::{Blob, BlobContent},
identifiers::{BlobId, ChainId},
time::Duration,
};
use linera_chain::data_types::{self, Certificate, CertificateValue, HashedCertificateValue};
#[cfg(web)]
Expand Down Expand Up @@ -248,7 +249,7 @@ impl ValidatorNode for GrpcClient {
let delay = notification_retry_delay.saturating_mul(retry_count);
retry_count += 1;
future::Either::Right(async move {
tokio::time::sleep(delay).await;
linera_base::time::timer::sleep(delay).await;
true
})
})
Expand Down
3 changes: 1 addition & 2 deletions linera-rpc/src/grpc/pool.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::time::Duration;

use dashmap::DashMap;
use linera_base::time::Duration;

use super::{transport, GrpcError};

Expand Down
6 changes: 4 additions & 2 deletions linera-rpc/src/grpc/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,10 @@ where

for i in 0..cross_chain_max_retries {
// Delay increases linearly with the attempt number.
tokio::time::sleep(cross_chain_sender_delay + cross_chain_retry_delay * i)
.await;
linera_base::time::timer::sleep(
cross_chain_sender_delay + cross_chain_retry_delay * i,
)
.await;

let result = || async {
let cross_chain_request = cross_chain_request.clone().try_into()?;
Expand Down
4 changes: 2 additions & 2 deletions linera-rpc/src/grpc/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::NodeOptions;

#[derive(Clone, Debug, Default)]
pub struct Options {
pub connect_timeout: Option<std::time::Duration>,
pub timeout: Option<std::time::Duration>,
pub connect_timeout: Option<linera_base::time::Duration>,
pub timeout: Option<linera_base::time::Duration>,
}

impl From<&'_ NodeOptions> for Options {
Expand Down
3 changes: 1 addition & 2 deletions linera-rpc/src/node_provider.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::time::Duration;

use linera_base::time::Duration;
use linera_core::node::{LocalValidatorNodeProvider, NodeError};

#[cfg(with_simple_network)]
Expand Down
Loading

0 comments on commit c74afeb

Please sign in to comment.