From eecbc34904d29165d9be611a439cdbe8b80a117f Mon Sep 17 00:00:00 2001 From: hanabi1224 Date: Tue, 8 Jul 2025 18:52:04 +0800 Subject: [PATCH] chore: replace once_cell utils with std equivalents --- Cargo.lock | 1 - Cargo.toml | 1 - src/blocks/election_proof.rs | 6 +-- src/blocks/header.rs | 18 ++++---- src/blocks/tipset.rs | 19 ++++---- src/chain_sync/metrics.rs | 29 ++++++------ src/chain_sync/network_context.rs | 7 ++- src/cli/subcommands/f3_cmd.rs | 5 +-- src/daemon/bundle.rs | 4 +- src/db/car/plain.rs | 8 ++-- src/db/migration/migration_map.rs | 5 +-- src/libp2p/behaviour.rs | 14 +++--- src/libp2p/metrics.rs | 8 ++-- src/libp2p/service.rs | 6 +-- src/libp2p_bitswap/metrics.rs | 8 ++-- src/message_pool/msgpool/metrics.rs | 4 +- src/metrics/mod.rs | 15 +++---- src/networks/actors_bundle.rs | 6 +-- src/networks/butterflynet/mod.rs | 16 +++---- src/networks/calibnet/mod.rs | 12 ++--- src/networks/devnet/mod.rs | 8 ++-- src/networks/drand.rs | 8 ++-- src/networks/mainnet/mod.rs | 12 ++--- src/networks/mod.rs | 7 +-- src/rpc/auth_layer.rs | 5 +-- src/rpc/client.rs | 4 +- src/rpc/methods/chain.rs | 9 ++-- src/rpc/methods/common.rs | 4 +- src/rpc/methods/eth.rs | 7 ++- src/rpc/methods/eth/utils.rs | 4 +- src/rpc/methods/f3.rs | 17 ++++--- src/rpc/methods/f3/types.rs | 4 +- src/rpc/methods/f3/util.rs | 6 +-- src/rpc/mod.rs | 5 +-- src/rpc/registry/actors_reg.rs | 4 +- src/rpc/registry/methods_reg.rs | 5 ++- src/rpc/segregation_layer.rs | 45 ++++++++++--------- src/shim/actors/version.rs | 4 +- src/shim/address.rs | 8 ++-- src/shim/econ.rs | 6 +-- src/shim/machine/mod.rs | 5 +-- src/state_migration/nv17/datacap.rs | 7 ++- .../subcommands/api_cmd/api_compare_tests.rs | 10 +++-- src/utils/net.rs | 5 +-- src/utils/reqwest_resume/tests.rs | 4 +- src/utils/version/mod.rs | 10 ++--- 46 files changed, 209 insertions(+), 196 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 976ec103b552..6cd943f7bf22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3123,7 +3123,6 @@ dependencies = [ "num-traits", "num_cpus", "nunny", - "once_cell", "openrpc-types", "parity-db", "parking_lot", diff --git a/Cargo.toml b/Cargo.toml index 51e53d6e1d72..3c2db2509da6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -153,7 +153,6 @@ num-rational = "0.4" num-traits = "0.2" num_cpus = "1" nunny = { version = "0.2", features = ["serde", "quickcheck", "schemars1"] } -once_cell = "1" openrpc-types = "0.5" parity-db = { version = "0.5", default-features = false } parking_lot = { version = "0.12", features = ["deadlock_detection"] } diff --git a/src/blocks/election_proof.rs b/src/blocks/election_proof.rs index a5d2769a35e0..0d07c388fda4 100644 --- a/src/blocks/election_proof.rs +++ b/src/blocks/election_proof.rs @@ -8,8 +8,8 @@ use num::{ BigInt, Integer, bigint::{ParseBigIntError, Sign}, }; -use once_cell::sync::Lazy; use serde_tuple::{self, Deserialize_tuple, Serialize_tuple}; +use std::sync::LazyLock; const PRECISION: u64 = 256; const MAX_WIN_COUNT: i64 = 3 * BLOCKS_PER_EPOCH as i64; @@ -25,7 +25,7 @@ fn parse(strings: &[&str]) -> Result, ParseBigIntError> { .collect() } -static EXP_NUM_COEF: Lazy> = Lazy::new(|| { +static EXP_NUM_COEF: LazyLock> = LazyLock::new(|| { parse(&[ "-648770010757830093818553637600", "67469480939593786226847644286976", @@ -38,7 +38,7 @@ static EXP_NUM_COEF: Lazy> = Lazy::new(|| { ]) .unwrap() }); -static EXP_DENO_COEF: Lazy> = Lazy::new(|| { +static EXP_DENO_COEF: LazyLock> = LazyLock::new(|| { parse(&[ "1225524182432722209606361", "114095592300906098243859450", diff --git a/src/blocks/header.rs b/src/blocks/header.rs index 6a3c10fcd6bf..dbbb19f3af6f 100644 --- a/src/blocks/header.rs +++ b/src/blocks/header.rs @@ -2,7 +2,10 @@ // SPDX-License-Identifier: Apache-2.0, MIT use std::ops::Deref; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{ + OnceLock, + atomic::{AtomicBool, Ordering}, +}; use super::{ElectionProof, Error, Ticket, TipsetKey}; use crate::beacon::{BeaconEntry, BeaconSchedule}; @@ -16,22 +19,21 @@ use cid::Cid; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::CborStore as _; use num::BigInt; -use once_cell::sync::OnceCell; use serde::{Deserialize, Serialize}; use serde_tuple::{Deserialize_tuple, Serialize_tuple}; // See // and #[cfg(test)] -static FILECOIN_GENESIS_CID: once_cell::sync::Lazy = once_cell::sync::Lazy::new(|| { +static FILECOIN_GENESIS_CID: std::sync::LazyLock = std::sync::LazyLock::new(|| { "bafyreiaqpwbbyjo4a42saasj36kkrpv4tsherf2e7bvezkert2a7dhonoi" .parse() .expect("Infallible") }); #[cfg(test)] -pub static GENESIS_BLOCK_PARENTS: once_cell::sync::Lazy = - once_cell::sync::Lazy::new(|| nunny::vec![*FILECOIN_GENESIS_CID].into()); +pub static GENESIS_BLOCK_PARENTS: std::sync::LazyLock = + std::sync::LazyLock::new(|| nunny::vec![*FILECOIN_GENESIS_CID].into()); #[derive(Deserialize_tuple, Serialize_tuple, Clone, Hash, Eq, PartialEq, Debug)] pub struct RawBlockHeader { @@ -222,7 +224,7 @@ impl RawBlockHeader { #[derive(Debug)] pub struct CachingBlockHeader { uncached: RawBlockHeader, - cid: OnceCell, + cid: OnceLock, has_ever_been_verified_against_any_signature: AtomicBool, } @@ -266,7 +268,7 @@ impl CachingBlockHeader { pub fn new(uncached: RawBlockHeader) -> Self { Self { uncached, - cid: OnceCell::new(), + cid: OnceLock::new(), has_ever_been_verified_against_any_signature: AtomicBool::new(false), } } @@ -278,7 +280,7 @@ impl CachingBlockHeader { if let Some(uncached) = store.get_cbor::(&cid)? { Ok(Some(Self { uncached, - cid: OnceCell::with_value(cid), + cid: cid.into(), has_ever_been_verified_against_any_signature: AtomicBool::new(false), })) } else { diff --git a/src/blocks/tipset.rs b/src/blocks/tipset.rs index f04c3177cb62..1d449079f0b7 100644 --- a/src/blocks/tipset.rs +++ b/src/blocks/tipset.rs @@ -1,8 +1,10 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use std::sync::Arc; -use std::{fmt, sync::OnceLock}; +use std::{ + fmt, + sync::{Arc, OnceLock}, +}; use crate::cid_collections::SmallCidNonEmptyVec; use crate::networks::{calibnet, mainnet}; @@ -16,7 +18,6 @@ use fvm_ipld_encoding::CborStore; use itertools::Itertools as _; use num::BigInt; use nunny::{Vec as NonEmpty, vec as nonempty}; -use once_cell::sync::OnceCell; use serde::{Deserialize, Serialize}; use thiserror::Error; use tracing::info; @@ -145,7 +146,7 @@ pub struct Tipset { /// Sorted headers: NonEmpty, // key is lazily initialized via `fn key()`. - key: OnceCell, + key: OnceLock, } impl From for Tipset { @@ -164,7 +165,7 @@ impl From for Tipset { fn from(value: CachingBlockHeader) -> Self { Self { headers: nonempty![value], - key: OnceCell::new(), + key: OnceLock::new(), } } } @@ -238,7 +239,7 @@ impl Tipset { Ok(Self { headers, - key: OnceCell::new(), + key: OnceLock::new(), }) } @@ -448,7 +449,7 @@ impl Tipset { pub struct FullTipset { blocks: NonEmpty, // key is lazily initialized via `fn key()`. - key: OnceCell, + key: OnceLock, } impl std::hash::Hash for FullTipset { @@ -462,7 +463,7 @@ impl From for FullTipset { fn from(block: Block) -> Self { FullTipset { blocks: nonempty![block], - key: OnceCell::new(), + key: OnceLock::new(), } } } @@ -489,7 +490,7 @@ impl FullTipset { Ok(Self { blocks, - key: OnceCell::new(), + key: OnceLock::new(), }) } /// Returns the first block of the tipset. diff --git a/src/chain_sync/metrics.rs b/src/chain_sync/metrics.rs index 0cc65ab5244c..95efe617cd74 100644 --- a/src/chain_sync/metrics.rs +++ b/src/chain_sync/metrics.rs @@ -1,13 +1,13 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use once_cell::sync::Lazy; use prometheus_client::{ encoding::{EncodeLabelKey, EncodeLabelSet, EncodeLabelValue, LabelSetEncoder}, metrics::{counter::Counter, family::Family, gauge::Gauge, histogram::Histogram}, }; +use std::sync::LazyLock; -pub static TIPSET_PROCESSING_TIME: Lazy = Lazy::new(|| { +pub static TIPSET_PROCESSING_TIME: LazyLock = LazyLock::new(|| { let metric = crate::metrics::default_histogram(); crate::metrics::default_registry().register( "tipset_processing_time", @@ -16,7 +16,7 @@ pub static TIPSET_PROCESSING_TIME: Lazy = Lazy::new(|| { ); metric }); -pub static BLOCK_VALIDATION_TIME: Lazy = Lazy::new(|| { +pub static BLOCK_VALIDATION_TIME: LazyLock = LazyLock::new(|| { let metric = crate::metrics::default_histogram(); crate::metrics::default_registry().register( "block_validation_time", @@ -25,16 +25,17 @@ pub static BLOCK_VALIDATION_TIME: Lazy = Lazy::new(|| { ); metric }); -pub static LIBP2P_MESSAGE_TOTAL: Lazy> = Lazy::new(|| { - let metric = Family::default(); - crate::metrics::default_registry().register( - "libp2p_messsage_total", - "Total number of libp2p messages by type", - metric.clone(), - ); - metric -}); -pub static INVALID_TIPSET_TOTAL: Lazy = Lazy::new(|| { +pub static LIBP2P_MESSAGE_TOTAL: LazyLock> = + LazyLock::new(|| { + let metric = Family::default(); + crate::metrics::default_registry().register( + "libp2p_messsage_total", + "Total number of libp2p messages by type", + metric.clone(), + ); + metric + }); +pub static INVALID_TIPSET_TOTAL: LazyLock = LazyLock::new(|| { let metric = Counter::default(); crate::metrics::default_registry().register( "invalid_tipset_total", @@ -43,7 +44,7 @@ pub static INVALID_TIPSET_TOTAL: Lazy = Lazy::new(|| { ); metric }); -pub static HEAD_EPOCH: Lazy = Lazy::new(|| { +pub static HEAD_EPOCH: LazyLock = LazyLock::new(|| { let metric = Gauge::default(); crate::metrics::default_registry().register( "head_epoch", diff --git a/src/chain_sync/network_context.rs b/src/chain_sync/network_context.rs index 505198c6cec1..3dfabe1411c7 100644 --- a/src/chain_sync/network_context.rs +++ b/src/chain_sync/network_context.rs @@ -5,7 +5,7 @@ use std::{ convert::TryFrom, num::NonZeroU64, sync::{ - Arc, + Arc, LazyLock, atomic::{AtomicU64, Ordering}, }, time::{Duration, Instant}, @@ -28,7 +28,6 @@ use crate::{ }; use anyhow::Context as _; use fvm_ipld_blockstore::Blockstore; -use once_cell::sync::Lazy; use parking_lot::Mutex; use std::future::Future; use tokio::sync::Semaphore; @@ -38,8 +37,8 @@ use tracing::{debug, trace}; /// Timeout milliseconds for response from an RPC request // This value is automatically adapted in the range of [5, 60] for different network conditions, // being decreased on success and increased on failure -static CHAIN_EXCHANGE_TIMEOUT_MILLIS: Lazy> = - Lazy::new(|| ExponentialAdaptiveValueProvider::new(5000, 2000, 60000, false)); +static CHAIN_EXCHANGE_TIMEOUT_MILLIS: LazyLock> = + LazyLock::new(|| ExponentialAdaptiveValueProvider::new(5000, 2000, 60000, false)); /// Maximum number of concurrent chain exchange request being sent to the /// network. diff --git a/src/cli/subcommands/f3_cmd.rs b/src/cli/subcommands/f3_cmd.rs index 195f55cc8926..edf0dd91ae7b 100644 --- a/src/cli/subcommands/f3_cmd.rs +++ b/src/cli/subcommands/f3_cmd.rs @@ -4,7 +4,7 @@ #[cfg(test)] mod tests; -use std::{borrow::Cow, time::Duration}; +use std::{borrow::Cow, sync::LazyLock, time::Duration}; use crate::{ blocks::TipsetKey, @@ -24,7 +24,6 @@ use anyhow::Context as _; use cid::Cid; use clap::{Subcommand, ValueEnum}; use itertools::Itertools as _; -use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use serde_with::{DisplayFromStr, serde_as}; use tera::Tera; @@ -33,7 +32,7 @@ const MANIFEST_TEMPLATE_NAME: &str = "manifest.tpl"; const CERTIFICATE_TEMPLATE_NAME: &str = "certificate.tpl"; const PROGRESS_TEMPLATE_NAME: &str = "progress.tpl"; -static TEMPLATES: Lazy = Lazy::new(|| { +static TEMPLATES: LazyLock = LazyLock::new(|| { let mut tera = Tera::default(); tera.add_raw_template(MANIFEST_TEMPLATE_NAME, include_str!("f3_cmd/manifest.tpl")) .unwrap(); diff --git a/src/daemon/bundle.rs b/src/daemon/bundle.rs index aa039a7d2e7c..f90adda70636 100644 --- a/src/daemon/bundle.rs +++ b/src/daemon/bundle.rs @@ -11,9 +11,9 @@ use ahash::HashSet; use cid::Cid; use directories::ProjectDirs; use futures::{TryStreamExt, stream::FuturesUnordered}; -use once_cell::sync::Lazy; use std::mem::discriminant; use std::path::PathBuf; +use std::sync::LazyLock; use std::{io::Cursor, path::Path}; use tracing::{info, warn}; @@ -77,7 +77,7 @@ pub async fn load_actor_bundles_from_path( Ok(()) } -pub static ACTOR_BUNDLE_CACHE_DIR: Lazy = Lazy::new(|| { +pub static ACTOR_BUNDLE_CACHE_DIR: LazyLock = LazyLock::new(|| { let project_dir = ProjectDirs::from("com", "ChainSafe", "Forest"); project_dir .map(|d| d.cache_dir().to_path_buf()) diff --git a/src/db/car/plain.rs b/src/db/car/plain.rs index 9a7b7b9b4bc3..ac4c541b819b 100644 --- a/src/db/car/plain.rs +++ b/src/db/car/plain.rs @@ -493,8 +493,8 @@ mod tests { }; use futures::{TryStreamExt as _, executor::block_on}; use fvm_ipld_blockstore::{Blockstore, MemoryBlockstore}; - use once_cell::sync::Lazy; use std::io::Cursor; + use std::sync::LazyLock; use tokio::io::{AsyncBufRead, AsyncSeek, BufReader}; #[test] @@ -571,7 +571,8 @@ mod tests { } fn chain4_car() -> &'static [u8] { - static CAR: Lazy> = Lazy::new(|| zstd::decode_all(chain4_car_zst()).unwrap()); + static CAR: LazyLock> = + LazyLock::new(|| zstd::decode_all(chain4_car_zst()).unwrap()); CAR.as_slice() } @@ -580,7 +581,8 @@ mod tests { } fn carv2_car() -> &'static [u8] { - static CAR: Lazy> = Lazy::new(|| zstd::decode_all(carv2_car_zst()).unwrap()); + static CAR: LazyLock> = + LazyLock::new(|| zstd::decode_all(carv2_car_zst()).unwrap()); CAR.as_slice() } } diff --git a/src/db/migration/migration_map.rs b/src/db/migration/migration_map.rs index ad762adb23d8..0b435fd4d67f 100644 --- a/src/db/migration/migration_map.rs +++ b/src/db/migration/migration_map.rs @@ -4,7 +4,7 @@ use std::{ path::{Path, PathBuf}, str::FromStr, - sync::Arc, + sync::{Arc, LazyLock}, }; use crate::Config; @@ -14,7 +14,6 @@ use anyhow::Context as _; use anyhow::bail; use itertools::Itertools; use multimap::MultiMap; -use once_cell::sync::Lazy; use semver::Version; use tracing::debug; @@ -133,7 +132,7 @@ type MigrationsMap = MultiMap; /// ` -> @ ` macro_rules! create_migrations { ($($from:literal -> $to:literal @ $migration:tt),* $(,)?) => { -pub(super) static MIGRATIONS: Lazy = Lazy::new(|| { +pub(super) static MIGRATIONS: LazyLock = LazyLock::new(|| { MigrationsMap::from_iter( [ $(( diff --git a/src/libp2p/behaviour.rs b/src/libp2p/behaviour.rs index 48ccccf3e7b9..a1fb5a2f9056 100644 --- a/src/libp2p/behaviour.rs +++ b/src/libp2p/behaviour.rs @@ -1,7 +1,10 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use std::{num::NonZeroUsize, sync::Arc}; +use std::{ + num::NonZeroUsize, + sync::{Arc, LazyLock}, +}; use super::{ PeerManager, @@ -32,7 +35,6 @@ use libp2p::{ ping, request_response, swarm::NetworkBehaviour, }; -use once_cell::sync::Lazy; use tracing::info; /// Libp2p behavior for the Forest node. This handles all sub protocols needed @@ -74,15 +76,17 @@ impl ForestBehaviour { peer_manager: Arc, ) -> anyhow::Result { const MAX_ESTABLISHED_PER_PEER: u32 = 4; - static MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER: Lazy = Lazy::new(|| { - std::env::var("FOREST_MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER") + static MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER: LazyLock = LazyLock::new( + || { + std::env::var("FOREST_MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER") .ok() .map(|it| it.parse::() .expect("Failed to parse the `FOREST_MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER` environment variable value, a positive integer is expected.") .get()) .unwrap_or(10) - }); + }, + ); let max_concurrent_request_response_streams = (config.target_peer_count as usize) .saturating_mul(*MAX_CONCURRENT_REQUEST_RESPONSE_STREAMS_PER_PEER); diff --git a/src/libp2p/metrics.rs b/src/libp2p/metrics.rs index ee99d23250b5..db4735948184 100644 --- a/src/libp2p/metrics.rs +++ b/src/libp2p/metrics.rs @@ -1,10 +1,10 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use once_cell::sync::Lazy; use prometheus_client::metrics::{counter::Counter, gauge::Gauge}; +use std::sync::LazyLock; -pub static PEER_FAILURE_TOTAL: Lazy = Lazy::new(|| { +pub static PEER_FAILURE_TOTAL: LazyLock = LazyLock::new(|| { let metric = Counter::default(); crate::metrics::default_registry().register( "peer_failure_total", @@ -14,7 +14,7 @@ pub static PEER_FAILURE_TOTAL: Lazy = Lazy::new(|| { metric }); -pub static FULL_PEERS: Lazy = Lazy::new(|| { +pub static FULL_PEERS: LazyLock = LazyLock::new(|| { let metric = Gauge::default(); crate::metrics::default_registry().register( "full_peers", @@ -24,7 +24,7 @@ pub static FULL_PEERS: Lazy = Lazy::new(|| { metric }); -pub static BAD_PEERS: Lazy = Lazy::new(|| { +pub static BAD_PEERS: LazyLock = LazyLock::new(|| { let metric = Gauge::default(); crate::metrics::default_registry().register( "bad_peers", diff --git a/src/libp2p/service.rs b/src/libp2p/service.rs index 36ab3ae75efe..e81b9d62e6cd 100644 --- a/src/libp2p/service.rs +++ b/src/libp2p/service.rs @@ -52,13 +52,13 @@ use crate::libp2p::{ }; pub(in crate::libp2p) mod metrics { - use once_cell::sync::Lazy; use prometheus_client::metrics::{family::Family, gauge::Gauge}; + use std::sync::LazyLock; use crate::metrics::KindLabel; - pub static NETWORK_CONTAINER_CAPACITIES: Lazy> = { - Lazy::new(|| { + pub static NETWORK_CONTAINER_CAPACITIES: LazyLock> = { + LazyLock::new(|| { let metric = Family::default(); crate::metrics::default_registry().register( "network_container_capacities", diff --git a/src/libp2p_bitswap/metrics.rs b/src/libp2p_bitswap/metrics.rs index fc071932ada6..629ee681e7c0 100644 --- a/src/libp2p_bitswap/metrics.rs +++ b/src/libp2p_bitswap/metrics.rs @@ -1,13 +1,13 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use once_cell::sync::Lazy; use parking_lot::MappedRwLockReadGuard; use prometheus_client::{ encoding::EncodeLabelSet, metrics::{counter::Counter, family::Family, gauge::Gauge, histogram::Histogram}, registry::Registry, }; +use std::sync::LazyLock; #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)] struct TypeLabel { @@ -20,9 +20,9 @@ impl TypeLabel { } } -static MESSAGE_COUNTER: Lazy> = Lazy::new(Default::default); -static CONTAINER_CAPACITIES: Lazy> = Lazy::new(Default::default); -pub(in crate::libp2p_bitswap) static GET_BLOCK_TIME: Lazy = Lazy::new(|| { +static MESSAGE_COUNTER: LazyLock> = LazyLock::new(Default::default); +static CONTAINER_CAPACITIES: LazyLock> = LazyLock::new(Default::default); +pub(in crate::libp2p_bitswap) static GET_BLOCK_TIME: LazyLock = LazyLock::new(|| { Histogram::new([ 0.1, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, ]) diff --git a/src/message_pool/msgpool/metrics.rs b/src/message_pool/msgpool/metrics.rs index 42301d928972..921283db5cbe 100644 --- a/src/message_pool/msgpool/metrics.rs +++ b/src/message_pool/msgpool/metrics.rs @@ -1,10 +1,10 @@ // Copyright 2019-2025 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT -use once_cell::sync::Lazy; use prometheus_client::metrics::gauge::Gauge; +use std::sync::LazyLock; -pub static MPOOL_MESSAGE_TOTAL: Lazy = Lazy::new(|| { +pub static MPOOL_MESSAGE_TOTAL: LazyLock = LazyLock::new(|| { let metric = Gauge::default(); crate::metrics::default_registry().register( "mpool_message_total", diff --git a/src/metrics/mod.rs b/src/metrics/mod.rs index 3482f7f0630c..99921425f98f 100644 --- a/src/metrics/mod.rs +++ b/src/metrics/mod.rs @@ -5,7 +5,6 @@ pub mod db; use crate::db::DBStatistics; use axum::{Router, http::StatusCode, response::IntoResponse, routing::get}; -use once_cell::sync::Lazy; use parking_lot::{RwLock, RwLockWriteGuard}; use prometheus_client::{ encoding::EncodeLabelSet, @@ -15,27 +14,27 @@ use prometheus_client::{ histogram::{Histogram, exponential_buckets}, }, }; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use std::{path::PathBuf, time::Instant}; use tokio::net::TcpListener; use tower_http::compression::CompressionLayer; use tracing::warn; -static DEFAULT_REGISTRY: Lazy> = - Lazy::new(Default::default); +static DEFAULT_REGISTRY: LazyLock> = + LazyLock::new(Default::default); pub fn default_registry<'a>() -> RwLockWriteGuard<'a, prometheus_client::registry::Registry> { DEFAULT_REGISTRY.write() } -pub static LRU_CACHE_HIT: Lazy> = Lazy::new(|| { +pub static LRU_CACHE_HIT: LazyLock> = LazyLock::new(|| { let metric = Family::default(); DEFAULT_REGISTRY .write() .register("lru_cache_hit", "Stats of lru cache hit", metric.clone()); metric }); -pub static LRU_CACHE_MISS: Lazy> = Lazy::new(|| { +pub static LRU_CACHE_MISS: LazyLock> = LazyLock::new(|| { let metric = Family::default(); DEFAULT_REGISTRY .write() @@ -43,7 +42,7 @@ pub static LRU_CACHE_MISS: Lazy> = Lazy::new(|| { metric }); -pub static RPC_METHOD_FAILURE: Lazy> = Lazy::new(|| { +pub static RPC_METHOD_FAILURE: LazyLock> = LazyLock::new(|| { let metric = Family::default(); DEFAULT_REGISTRY.write().register( "rpc_method_failure", @@ -53,7 +52,7 @@ pub static RPC_METHOD_FAILURE: Lazy> = Lazy::new metric }); -pub static RPC_METHOD_TIME: Lazy> = Lazy::new(|| { +pub static RPC_METHOD_TIME: LazyLock> = LazyLock::new(|| { let metric = Family::::new_with_constructor(|| { // Histogram with 5 buckets starting from 0.1ms going to 1s, each bucket 10 times as big as the last. Histogram::new(exponential_buckets(0.1, 10., 5)) diff --git a/src/networks/actors_bundle.rs b/src/networks/actors_bundle.rs index ff10b2fbcf61..cfa1abe9d056 100644 --- a/src/networks/actors_bundle.rs +++ b/src/networks/actors_bundle.rs @@ -3,6 +3,7 @@ use std::io::{self, Cursor}; use std::path::Path; +use std::sync::LazyLock; use ahash::HashMap; use anyhow::ensure; @@ -13,7 +14,6 @@ use futures::{StreamExt, TryStreamExt, stream}; use fvm_ipld_blockstore::MemoryBlockstore; use itertools::Itertools; use nunny::Vec as NonEmpty; -use once_cell::sync::Lazy; use reqwest::Url; use serde::{Deserialize, Serialize}; use serde_with::{DisplayFromStr, serde_as}; @@ -69,7 +69,7 @@ macro_rules! actor_bundle_info { } } -pub static ACTOR_BUNDLES: Lazy> = Lazy::new(|| { +pub static ACTOR_BUNDLES: LazyLock> = LazyLock::new(|| { Box::new(actor_bundle_info![ "bafy2bzacedrdn6z3z7xz7lx4wll3tlgktirhllzqxb766dxpaqp3ukxsjfsba" @ "8.0.0-rc.1" for "calibrationnet", "bafy2bzacedbedgynklc4dgpyxippkxmba2mgtw7ecntoneclsvvl4klqwuyyy" @ "v9.0.3" for "calibrationnet", @@ -129,7 +129,7 @@ impl ActorBundleMetadata { type ActorBundleMetadataMap = HashMap<(NetworkChain, String), ActorBundleMetadata>; -pub static ACTOR_BUNDLES_METADATA: Lazy = Lazy::new(|| { +pub static ACTOR_BUNDLES_METADATA: LazyLock = LazyLock::new(|| { let json: &str = include_str!("../../build/manifest.json"); let metadata_vec: Vec = serde_json::from_str(json).expect("invalid manifest"); diff --git a/src/networks/butterflynet/mod.rs b/src/networks/butterflynet/mod.rs index 7ee4215931c6..dc6e3b401d83 100644 --- a/src/networks/butterflynet/mod.rs +++ b/src/networks/butterflynet/mod.rs @@ -4,8 +4,8 @@ use ahash::HashMap; use cid::Cid; use libp2p::Multiaddr; -use once_cell::sync::Lazy; use std::str::FromStr; +use std::sync::LazyLock; use url::Url; use crate::{ @@ -45,12 +45,12 @@ pub async fn fetch_genesis(db: &DB) -> anyhow::Result } /// Genesis CID -pub static GENESIS_CID: Lazy = Lazy::new(|| { +pub static GENESIS_CID: LazyLock = LazyLock::new(|| { Cid::from_str("bafy2bzacec4thmmboc5ye5lionzlyuvd4rfncggwdzrbbvqcepdrexny5qrx2").unwrap() }); /// Compressed genesis file. It is compressed with zstd and cuts the download size by 80% (from 10 MB to 2 MB). -static GENESIS_URL: Lazy = Lazy::new(|| { +static GENESIS_URL: LazyLock = LazyLock::new(|| { "https://forest-snapshots.fra1.cdn.digitaloceanspaces.com/genesis/butterflynet-bafy2bzacec4thmmboc5ye5lionzlyuvd4rfncggwdzrbbvqcepdrexny5qrx2.car.zst" .parse() .expect("hard-coded URL must parse") @@ -58,7 +58,7 @@ static GENESIS_URL: Lazy = Lazy::new(|| { /// Alternative URL for the genesis file. This is hosted on the `lotus` repository. /// `` -static GENESIS_URL_ALT: Lazy = Lazy::new(|| { +static GENESIS_URL_ALT: LazyLock = LazyLock::new(|| { "https://github.com/filecoin-project/lotus/raw/c6068b60c526d44270bfc5d612045f0b27322dfb/build/genesis/butterflynet.car.zst".parse().expect("hard-coded URL must parse") }); @@ -67,8 +67,8 @@ pub(crate) const MINIMUM_VERIED_ALLOCATION: i64 = 1 << 20; pub(crate) const PRE_COMMIT_CHALLENGE_DELAY: i64 = 150; /// Default bootstrap peer ids. -pub static DEFAULT_BOOTSTRAP: Lazy> = - Lazy::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/butterflynet"))); +pub static DEFAULT_BOOTSTRAP: LazyLock> = + LazyLock::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/butterflynet"))); // https://github.com/ethereum-lists/chains/blob/4731f6713c6fc2bf2ae727388642954a6545b3a9/_data/chains/eip155-314159.json pub const ETH_CHAIN_ID: EthChainId = 3141592; @@ -76,7 +76,7 @@ pub const ETH_CHAIN_ID: EthChainId = 3141592; pub const BREEZE_GAS_TAMPING_DURATION: i64 = 120; /// Height epochs. -pub static HEIGHT_INFOS: Lazy> = Lazy::new(|| { +pub static HEIGHT_INFOS: LazyLock> = LazyLock::new(|| { HashMap::from_iter([ make_height!(Breeze, -50), make_height!(Smoke, -2), @@ -118,7 +118,7 @@ fn get_bundle_cid(version: &str) -> Cid { .bundle_cid } -pub(super) static DRAND_SCHEDULE: Lazy<[DrandPoint<'static>; 1]> = Lazy::new(|| { +pub(super) static DRAND_SCHEDULE: LazyLock<[DrandPoint<'static>; 1]> = LazyLock::new(|| { [DrandPoint { height: 0, config: &DRAND_QUICKNET, diff --git a/src/networks/calibnet/mod.rs b/src/networks/calibnet/mod.rs index 38185cafcde7..382ea97668dc 100644 --- a/src/networks/calibnet/mod.rs +++ b/src/networks/calibnet/mod.rs @@ -4,8 +4,8 @@ use ahash::HashMap; use cid::Cid; use libp2p::Multiaddr; -use once_cell::sync::Lazy; use std::str::FromStr; +use std::sync::LazyLock; use crate::{ eth::EthChainId, @@ -29,14 +29,14 @@ pub const NETWORK_GENESIS_NAME: &str = "calibrationnet"; /// Default genesis car file bytes. pub const DEFAULT_GENESIS: &[u8] = include_bytes!("genesis.car"); /// Genesis CID -pub static GENESIS_CID: Lazy = Lazy::new(|| { +pub static GENESIS_CID: LazyLock = LazyLock::new(|| { Cid::from_str("bafy2bzacecyaggy24wol5ruvs6qm73gjibs2l2iyhcqmvi7r7a4ph7zx3yqd4").unwrap() }); pub const GENESIS_NETWORK_VERSION: NetworkVersion = NetworkVersion::V0; /// Default bootstrap peer ids. -pub static DEFAULT_BOOTSTRAP: Lazy> = - Lazy::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/calibnet"))); +pub static DEFAULT_BOOTSTRAP: LazyLock> = + LazyLock::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/calibnet"))); const LIGHTNING_EPOCH: i64 = 489_094; @@ -51,7 +51,7 @@ pub const ETH_CHAIN_ID: EthChainId = 314159; pub const BREEZE_GAS_TAMPING_DURATION: i64 = 120; /// Height epochs. -pub static HEIGHT_INFOS: Lazy> = Lazy::new(|| { +pub static HEIGHT_INFOS: LazyLock> = LazyLock::new(|| { HashMap::from_iter([ make_height!(Breeze, -1), make_height!(Smoke, -2), @@ -103,7 +103,7 @@ fn get_bundle_cid(version: &str) -> Cid { .bundle_cid } -pub(super) static DRAND_SCHEDULE: Lazy<[DrandPoint<'static>; 2]> = Lazy::new(|| { +pub(super) static DRAND_SCHEDULE: LazyLock<[DrandPoint<'static>; 2]> = LazyLock::new(|| { [ DrandPoint { height: 0, diff --git a/src/networks/devnet/mod.rs b/src/networks/devnet/mod.rs index efbcc4b2b983..789de682b47f 100644 --- a/src/networks/devnet/mod.rs +++ b/src/networks/devnet/mod.rs @@ -3,7 +3,7 @@ use ahash::HashMap; use cid::Cid; -use once_cell::sync::Lazy; +use std::sync::LazyLock; use crate::{eth::EthChainId, make_height, shim::version::NetworkVersion}; @@ -17,7 +17,7 @@ pub const ETH_CHAIN_ID: EthChainId = 31415926; pub const BREEZE_GAS_TAMPING_DURATION: i64 = 0; -pub static GENESIS_NETWORK_VERSION: Lazy = Lazy::new(|| { +pub static GENESIS_NETWORK_VERSION: LazyLock = LazyLock::new(|| { if let Ok(version) = std::env::var("FOREST_GENESIS_NETWORK_VERSION") { NetworkVersion::from( version @@ -32,7 +32,7 @@ pub static GENESIS_NETWORK_VERSION: Lazy = Lazy::new(|| { /// Height epochs. /// Environment variable names follow /// -pub static HEIGHT_INFOS: Lazy> = Lazy::new(|| { +pub static HEIGHT_INFOS: LazyLock> = LazyLock::new(|| { HashMap::from_iter([ make_height!( Breeze, @@ -174,7 +174,7 @@ fn get_bundle_cid(version: &str) -> Cid { .bundle_cid } -pub(super) static DRAND_SCHEDULE: Lazy<[DrandPoint<'static>; 1]> = Lazy::new(|| { +pub(super) static DRAND_SCHEDULE: LazyLock<[DrandPoint<'static>; 1]> = LazyLock::new(|| { [DrandPoint { height: 0, config: &DRAND_QUICKNET, diff --git a/src/networks/drand.rs b/src/networks/drand.rs index 33531b1ef861..2b7c960052fa 100644 --- a/src/networks/drand.rs +++ b/src/networks/drand.rs @@ -2,10 +2,10 @@ // SPDX-License-Identifier: Apache-2.0, MIT use crate::beacon::{ChainInfo, DrandConfig, DrandNetwork}; -use once_cell::sync::Lazy; use std::borrow::Cow; +use std::sync::LazyLock; -pub(super) static DRAND_MAINNET: Lazy> = Lazy::new(|| { +pub(super) static DRAND_MAINNET: LazyLock> = LazyLock::new(|| { let default = DrandConfig { // https://drand.love/developer/http-api/#public-endpoints servers: vec![ @@ -32,7 +32,7 @@ pub(super) static DRAND_MAINNET: Lazy> = Lazy::new(|| { parse_drand_config_from_env_var("FOREST_DRAND_MAINNET_CONFIG").unwrap_or(default) }); -pub(super) static DRAND_QUICKNET: Lazy> = Lazy::new(|| { +pub(super) static DRAND_QUICKNET: LazyLock> = LazyLock::new(|| { let default = DrandConfig { // https://drand.love/developer/http-api/#public-endpoints servers: vec![ @@ -59,7 +59,7 @@ pub(super) static DRAND_QUICKNET: Lazy> = Lazy::new(|| { parse_drand_config_from_env_var("FOREST_DRAND_QUICKNET_CONFIG").unwrap_or(default) }); -pub(super) static DRAND_INCENTINET: Lazy> = Lazy::new(|| { +pub(super) static DRAND_INCENTINET: LazyLock> = LazyLock::new(|| { let default = DrandConfig { // Note: This URL is no longer valid. // See and its related issues diff --git a/src/networks/mainnet/mod.rs b/src/networks/mainnet/mod.rs index 71a8e553dc76..4772bdef237d 100644 --- a/src/networks/mainnet/mod.rs +++ b/src/networks/mainnet/mod.rs @@ -12,8 +12,8 @@ use crate::{ use ahash::HashMap; use cid::Cid; use libp2p::Multiaddr; -use once_cell::sync::Lazy; use std::str::FromStr; +use std::sync::LazyLock; use super::{ DrandPoint, Height, HeightInfo, NetworkChain, @@ -33,13 +33,13 @@ pub const NETWORK_GENESIS_NAME: &str = "testnetnet"; /// Default genesis car file bytes. pub const DEFAULT_GENESIS: &[u8] = include_bytes!("genesis.car"); /// Genesis CID -pub static GENESIS_CID: Lazy = Lazy::new(|| { +pub static GENESIS_CID: LazyLock = LazyLock::new(|| { Cid::from_str("bafy2bzacecnamqgqmifpluoeldx7zzglxcljo6oja4vrmtj7432rphldpdmm2").unwrap() }); pub const GENESIS_NETWORK_VERSION: NetworkVersion = NetworkVersion::V0; -pub static DEFAULT_BOOTSTRAP: Lazy> = - Lazy::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/mainnet"))); +pub static DEFAULT_BOOTSTRAP: LazyLock> = + LazyLock::new(|| parse_bootstrap_peers(include_str!("../../../build/bootstrap/mainnet"))); // The rollover period is the duration between nv19 and nv20 which both old // proofs (v1) and the new proofs (v1_1) proofs will be accepted by the @@ -52,7 +52,7 @@ pub const ETH_CHAIN_ID: EthChainId = 314; pub const BREEZE_GAS_TAMPING_DURATION: i64 = 120; /// Height epochs. -pub static HEIGHT_INFOS: Lazy> = Lazy::new(|| { +pub static HEIGHT_INFOS: LazyLock> = LazyLock::new(|| { HashMap::from_iter([ make_height!(Breeze, 41_280), make_height!(Smoke, SMOKE_HEIGHT), @@ -100,7 +100,7 @@ fn get_bundle_cid(version: &str) -> Cid { .bundle_cid } -pub(super) static DRAND_SCHEDULE: Lazy<[DrandPoint<'static>; 3]> = Lazy::new(|| { +pub(super) static DRAND_SCHEDULE: LazyLock<[DrandPoint<'static>; 3]> = LazyLock::new(|| { [ DrandPoint { height: 0, diff --git a/src/networks/mod.rs b/src/networks/mod.rs index a381fb97c8a5..d450a81f7f49 100644 --- a/src/networks/mod.rs +++ b/src/networks/mod.rs @@ -2,13 +2,13 @@ // SPDX-License-Identifier: Apache-2.0, MIT use std::str::FromStr; +use std::sync::LazyLock; use ahash::HashMap; use cid::Cid; use fil_actors_shared::v13::runtime::Policy; use itertools::Itertools; use libp2p::Multiaddr; -use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use strum_macros::Display; use tracing::warn; @@ -49,7 +49,8 @@ const ENV_FOREST_BLOCK_DELAY_SECS: &str = "FOREST_BLOCK_DELAY_SECS"; const ENV_FOREST_PROPAGATION_DELAY_SECS: &str = "FOREST_PROPAGATION_DELAY_SECS"; const ENV_PLEDGE_RULE_RAMP: &str = "FOREST_PLEDGE_RULE_RAMP"; -static INITIAL_FIL_RESERVED: Lazy = Lazy::new(|| TokenAmount::from_whole(300_000_000)); +static INITIAL_FIL_RESERVED: LazyLock = + LazyLock::new(|| TokenAmount::from_whole(300_000_000)); /// Forest builtin `filecoin` network chains. In general only `mainnet` and its /// chain information should be considered stable. @@ -229,7 +230,7 @@ pub struct HeightInfo { #[derive(Clone)] struct DrandPoint<'a> { pub height: ChainEpoch, - pub config: &'a Lazy>, + pub config: &'a LazyLock>, } /// Defines all network configuration parameters. diff --git a/src/rpc/auth_layer.rs b/src/rpc/auth_layer.rs index d7f1ee2f65b8..fa94c945751f 100644 --- a/src/rpc/auth_layer.rs +++ b/src/rpc/auth_layer.rs @@ -16,13 +16,12 @@ use jsonrpsee::core::middleware::{Batch, BatchEntry, BatchEntryErr, Notification use jsonrpsee::server::middleware::rpc::RpcServiceT; use jsonrpsee::types::Id; use jsonrpsee::types::{ErrorObject, error::ErrorCode}; -use once_cell::sync::Lazy; use parking_lot::RwLock; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use tower::Layer; use tracing::debug; -static METHOD_NAME2REQUIRED_PERMISSION: Lazy> = Lazy::new(|| { +static METHOD_NAME2REQUIRED_PERMISSION: LazyLock> = LazyLock::new(|| { let mut access = HashMap::new(); macro_rules! insert { diff --git a/src/rpc/client.rs b/src/rpc/client.rs index faeebf9e8bce..1ea2c10bfb56 100644 --- a/src/rpc/client.rs +++ b/src/rpc/client.rs @@ -11,6 +11,7 @@ use std::env; use std::fmt::{self, Debug}; +use std::sync::LazyLock; use std::time::Duration; use anyhow::{Context as _, bail}; @@ -21,7 +22,6 @@ use jsonrpsee::core::ClientError; use jsonrpsee::core::client::ClientT as _; use jsonrpsee::core::params::{ArrayParams, ObjectParams}; use jsonrpsee::core::traits::ToRpcParams; -use once_cell::sync::Lazy; use serde::de::DeserializeOwned; use tracing::{Instrument, Level, debug}; use url::Url; @@ -44,7 +44,7 @@ impl Client { /// /// If `token` is provided, use that over the token in either of the above. pub fn default_or_from_env(token: Option<&str>) -> anyhow::Result { - static DEFAULT: Lazy = Lazy::new(|| "http://127.0.0.1:2345/".parse().unwrap()); + static DEFAULT: LazyLock = LazyLock::new(|| "http://127.0.0.1:2345/".parse().unwrap()); let mut base_url = match env::var("FULLNODE_API_INFO") { Ok(it) => { diff --git a/src/rpc/methods/chain.rs b/src/rpc/methods/chain.rs index b03f372a977a..b0704c041995 100644 --- a/src/rpc/methods/chain.rs +++ b/src/rpc/methods/chain.rs @@ -33,11 +33,14 @@ use ipld_core::ipld::Ipld; use jsonrpsee::types::Params; use jsonrpsee::types::error::ErrorObjectOwned; use num::BigInt; -use once_cell::sync::Lazy; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use sha2::Sha256; -use std::{collections::VecDeque, path::PathBuf, sync::Arc}; +use std::{ + collections::VecDeque, + path::PathBuf, + sync::{Arc, LazyLock}, +}; use tokio::sync::{ Mutex, broadcast::{self, Receiver as Subscriber}, @@ -242,7 +245,7 @@ impl RpcMethod<1> for ChainExport { dry_run, } = params; - static LOCK: Lazy> = Lazy::new(|| Mutex::new(())); + static LOCK: LazyLock> = LazyLock::new(|| Mutex::new(())); let _locked = LOCK.try_lock(); if _locked.is_err() { diff --git a/src/rpc/methods/common.rs b/src/rpc/methods/common.rs index 04796e9a0d14..666375b1f8f4 100644 --- a/src/rpc/methods/common.rs +++ b/src/rpc/methods/common.rs @@ -6,13 +6,13 @@ use crate::rpc::error::ServerError; use crate::rpc::{ApiPaths, Ctx, Permission, RpcMethod}; use enumflags2::BitFlags; use fvm_ipld_blockstore::Blockstore; -use once_cell::sync::Lazy; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::any::Any; +use std::sync::LazyLock; use uuid::Uuid; -static SESSION_UUID: Lazy = Lazy::new(crate::utils::rand::new_uuid_v4); +static SESSION_UUID: LazyLock = LazyLock::new(crate::utils::rand::new_uuid_v4); /// The returned session UUID uniquely identifies the API node. pub enum Session {} diff --git a/src/rpc/methods/eth.rs b/src/rpc/methods/eth.rs index 3cd21bd8bee6..c6cce4b2e6b1 100644 --- a/src/rpc/methods/eth.rs +++ b/src/rpc/methods/eth.rs @@ -65,17 +65,16 @@ use fvm_ipld_encoding::{CBOR, DAG_CBOR, IPLD_RAW, RawBytes}; use ipld_core::ipld::Ipld; use itertools::Itertools; use num::{BigInt, Zero as _}; -use once_cell::sync::Lazy; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::ops::RangeInclusive; use std::str::FromStr; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use tracing::log; use utils::{decode_payload, lookup_eth_address}; -static FOREST_TRACE_FILTER_MAX_RESULT: Lazy = - Lazy::new(|| env_or_default("FOREST_TRACE_FILTER_MAX_RESULT", 500)); +static FOREST_TRACE_FILTER_MAX_RESULT: LazyLock = + LazyLock::new(|| env_or_default("FOREST_TRACE_FILTER_MAX_RESULT", 500)); const MASKED_ID_PREFIX: [u8; 12] = [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; diff --git a/src/rpc/methods/eth/utils.rs b/src/rpc/methods/eth/utils.rs index 4be77ac3a1ec..09db9e0f511f 100644 --- a/src/rpc/methods/eth/utils.rs +++ b/src/rpc/methods/eth/utils.rs @@ -14,8 +14,8 @@ use cbor4ii::core::Value; use cbor4ii::core::dec::Decode as _; use fvm_ipld_blockstore::Blockstore; use fvm_ipld_encoding::{CBOR, DAG_CBOR, IPLD_RAW, RawBytes}; -use once_cell::sync::Lazy; use serde::de; +use std::sync::LazyLock; use tracing::log; pub fn lookup_eth_address( @@ -121,7 +121,7 @@ const ERROR_FUNCTION_SELECTOR: [u8; 4] = [0x08, 0xc3, 0x79, 0xa0]; // keccak256( const PANIC_FUNCTION_SELECTOR: [u8; 4] = [0x4e, 0x48, 0x7b, 0x71]; // keccak256("Panic(uint256)") [first 4 bytes] // Lazily initialized HashMap for panic codes -static PANIC_ERROR_CODES: Lazy> = Lazy::new(|| { +static PANIC_ERROR_CODES: LazyLock> = LazyLock::new(|| { let mut m = HashMap::new(); m.insert(0x00, "Panic()"); m.insert(0x01, "Assert()"); diff --git a/src/rpc/methods/f3.rs b/src/rpc/methods/f3.rs index 5a9169b6628d..e2dfffaf91a5 100644 --- a/src/rpc/methods/f3.rs +++ b/src/rpc/methods/f3.rs @@ -52,12 +52,15 @@ use jsonrpsee::core::{client::ClientT as _, params::ArrayParams}; use libp2p::PeerId; use lru::LruCache; use num::Signed as _; -use once_cell::sync::Lazy; -use once_cell::sync::OnceCell; use parking_lot::RwLock; -use std::{borrow::Cow, fmt::Display, str::FromStr as _, sync::Arc}; +use std::{ + borrow::Cow, + fmt::Display, + str::FromStr as _, + sync::{Arc, LazyLock, OnceLock}, +}; -pub static F3_LEASE_MANAGER: OnceCell = OnceCell::new(); +pub static F3_LEASE_MANAGER: OnceLock = OnceLock::new(); pub enum GetRawNetworkName {} @@ -163,7 +166,7 @@ impl GetPowerTable { ) -> anyhow::Result> { // The RAM overhead on mainnet is ~14MiB const BLOCKSTORE_CACHE_CAP: usize = 65536; - static BLOCKSTORE_CACHE: Lazy> = Lazy::new(|| { + static BLOCKSTORE_CACHE: LazyLock> = LazyLock::new(|| { Arc::new(LruBlockstoreReadCache::new( BLOCKSTORE_CACHE_CAP.try_into().expect("Infallible"), )) @@ -469,8 +472,8 @@ impl RpcMethod<1> for GetPowerTable { ctx: Ctx, (f3_tsk,): Self::Params, ) -> Result { - static CACHE: Lazy>>> = - Lazy::new(|| { + static CACHE: LazyLock>>> = + LazyLock::new(|| { tokio::sync::Mutex::new(LruCache::new(32.try_into().expect("Infallible"))) }); let tsk = f3_tsk.try_into()?; diff --git a/src/rpc/methods/f3/types.rs b/src/rpc/methods/f3/types.rs index 99377809ffc2..e965da8ea485 100644 --- a/src/rpc/methods/f3/types.rs +++ b/src/rpc/methods/f3/types.rs @@ -18,11 +18,11 @@ use fvm_shared4::ActorID; use itertools::Itertools as _; use libp2p::PeerId; use num::Zero as _; -use once_cell::sync::Lazy; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use serde_with::{DisplayFromStr, serde_as}; use std::io::Read as _; +use std::sync::LazyLock; use std::{cmp::Ordering, time::Duration}; const MAX_LEASE_INSTANCES: u64 = 5; @@ -53,7 +53,7 @@ impl TryFrom for TipsetKey { type Error = anyhow::Error; fn try_from(tsk: F3TipSetKey) -> Result { - static BLOCK_HEADER_CID_LEN: Lazy = Lazy::new(|| { + static BLOCK_HEADER_CID_LEN: LazyLock = LazyLock::new(|| { let buf = [0_u8; 256]; let cid = Cid::new_v1( fvm_ipld_encoding::DAG_CBOR, diff --git a/src/rpc/methods/f3/util.rs b/src/rpc/methods/f3/util.rs index f7933ca8313c..5c9571f047e8 100644 --- a/src/rpc/methods/f3/util.rs +++ b/src/rpc/methods/f3/util.rs @@ -2,13 +2,13 @@ // SPDX-License-Identifier: Apache-2.0, MIT use super::*; -use once_cell::sync::Lazy; +use std::sync::LazyLock; const F3_PERMANENT_PARTICIPATING_MINER_IDS_ENV_KEY: &str = "FOREST_F3_PERMANENT_PARTICIPATING_MINER_ADDRESSES"; -pub static F3_PERMANENT_PARTICIPATING_MINER_IDS: Lazy>> = - Lazy::new(get_f3_permanent_participating_miner_ids); +pub static F3_PERMANENT_PARTICIPATING_MINER_IDS: LazyLock>> = + LazyLock::new(get_f3_permanent_participating_miner_ids); /// loads f3 permanent participating miner IDs. /// Note that this environment variable should only be used for testing purpose. diff --git a/src/rpc/mod.rs b/src/rpc/mod.rs index 723f0e3dd883..d37221c23a5c 100644 --- a/src/rpc/mod.rs +++ b/src/rpc/mod.rs @@ -410,11 +410,10 @@ use jsonrpsee::{ core::middleware::RpcServiceBuilder, server::{RpcModule, Server, StopHandle, TowerServiceBuilder, stop_channel}, }; -use once_cell::sync::Lazy; use parking_lot::RwLock; use std::env; use std::net::SocketAddr; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use std::time::Duration; use tokio::sync::mpsc; use tower::Service; @@ -425,7 +424,7 @@ use openrpc_types::{self, ParamStructure}; pub const DEFAULT_PORT: u16 = 2345; /// Request timeout read from environment variables -static DEFAULT_REQUEST_TIMEOUT: Lazy = Lazy::new(|| { +static DEFAULT_REQUEST_TIMEOUT: LazyLock = LazyLock::new(|| { env::var("FOREST_RPC_DEFAULT_TIMEOUT") .ok() .and_then(|it| Duration::from_secs(it.parse().ok()?).into()) diff --git a/src/rpc/registry/actors_reg.rs b/src/rpc/registry/actors_reg.rs index 5885b9ca1f96..2b7cf13bd297 100644 --- a/src/rpc/registry/actors_reg.rs +++ b/src/rpc/registry/actors_reg.rs @@ -14,8 +14,8 @@ use ahash::{HashMap, HashMapExt}; use anyhow::{Context, Result, anyhow}; use cid::Cid; use fvm_ipld_blockstore::Blockstore; -use once_cell::sync::Lazy; use serde_json::Value; +use std::sync::LazyLock; #[derive(Debug)] pub struct ActorRegistry { @@ -48,7 +48,7 @@ impl ActorRegistry { } } -pub(crate) static ACTOR_REGISTRY: Lazy = Lazy::new(ActorRegistry::new); +pub(crate) static ACTOR_REGISTRY: LazyLock = LazyLock::new(ActorRegistry::new); pub fn get_actor_type_from_code(code_cid: &Cid) -> Result<(BuiltinActor, u64)> { ACTOR_REGISTRY diff --git a/src/rpc/registry/methods_reg.rs b/src/rpc/registry/methods_reg.rs index 1eb526e83db7..e839a838abf6 100644 --- a/src/rpc/registry/methods_reg.rs +++ b/src/rpc/registry/methods_reg.rs @@ -7,14 +7,15 @@ use crate::shim::message::MethodNum; use ahash::{HashMap, HashMapExt}; use anyhow::{Context, Result, bail}; use cid::Cid; -use once_cell::sync::Lazy; use serde::de::DeserializeOwned; use serde_json::Value; +use std::sync::LazyLock; use crate::rpc::registry::actors_reg::{ACTOR_REGISTRY, get_actor_type_from_code}; // Global registry for method parameter deserialization -static METHOD_REGISTRY: Lazy = Lazy::new(MethodRegistry::with_known_methods); +static METHOD_REGISTRY: LazyLock = + LazyLock::new(MethodRegistry::with_known_methods); type ParamDeserializerFn = Box Result + Send + Sync>; diff --git a/src/rpc/segregation_layer.rs b/src/rpc/segregation_layer.rs index 2c1c3b2c52f0..c723331c16a5 100644 --- a/src/rpc/segregation_layer.rs +++ b/src/rpc/segregation_layer.rs @@ -10,35 +10,36 @@ use jsonrpsee::MethodResponse; use jsonrpsee::core::middleware::{Batch, BatchEntry, BatchEntryErr, Notification}; use jsonrpsee::server::middleware::rpc::RpcServiceT; use jsonrpsee::types::{ErrorObject, Id}; -use once_cell::sync::Lazy; +use std::sync::LazyLock; use tower::Layer; -static VERSION_METHODS_MAPPINGS: Lazy>> = Lazy::new(|| { - let mut map = HashMap::default(); - for version in [ApiPaths::V0, ApiPaths::V1, ApiPaths::V2] { - let mut supported = HashSet::default(); - - macro_rules! insert { - ($ty:ty) => { - if <$ty>::API_PATHS.contains(version) { - supported.insert(<$ty>::NAME); - if let Some(alias) = <$ty>::NAME_ALIAS { - supported.insert(alias); +static VERSION_METHODS_MAPPINGS: LazyLock>> = + LazyLock::new(|| { + let mut map = HashMap::default(); + for version in [ApiPaths::V0, ApiPaths::V1, ApiPaths::V2] { + let mut supported = HashSet::default(); + + macro_rules! insert { + ($ty:ty) => { + if <$ty>::API_PATHS.contains(version) { + supported.insert(<$ty>::NAME); + if let Some(alias) = <$ty>::NAME_ALIAS { + supported.insert(alias); + } } - } - }; - } + }; + } - for_each_rpc_method!(insert); + for_each_rpc_method!(insert); - supported.insert(crate::rpc::chain::CHAIN_NOTIFY); - supported.insert(crate::rpc::channel::CANCEL_METHOD_NAME); + supported.insert(crate::rpc::chain::CHAIN_NOTIFY); + supported.insert(crate::rpc::channel::CANCEL_METHOD_NAME); - map.insert(version, supported); - } + map.insert(version, supported); + } - map -}); + map + }); /// JSON-RPC middleware layer for segregating RPC methods by the versions they support. #[derive(Clone, Default)] diff --git a/src/shim/actors/version.rs b/src/shim/actors/version.rs index 9f77bf0949c9..a3fd21337434 100644 --- a/src/shim/actors/version.rs +++ b/src/shim/actors/version.rs @@ -3,14 +3,14 @@ use crate::utils::multihash::prelude::*; use cid::Cid; use fil_actors_shared::v11::runtime::builtins::Type; -use once_cell::sync::Lazy; use paste::paste; +use std::sync::LazyLock; macro_rules! impl_actor_cids_type_actor { ($($actor_type:ident, $actor:ident),*) => { $( paste! { -static [<$actor:upper _ACTOR_CIDS>]: Lazy> = Lazy::new(|| { +static [<$actor:upper _ACTOR_CIDS>]: LazyLock> = LazyLock::new(|| { let mut actors: Vec<_> = crate::networks::ACTOR_BUNDLES_METADATA .values() .filter_map(|bundle| { diff --git a/src/shim/address.rs b/src/shim/address.rs index 47c179d8f665..de4290638878 100644 --- a/src/shim/address.rs +++ b/src/shim/address.rs @@ -16,15 +16,17 @@ use fvm_shared4::address::Address as Address_latest; pub use fvm_shared4::address::{Error, Network, PAYLOAD_HASH_LEN, Payload, Protocol}; use integer_encoding::VarInt; use num_traits::FromPrimitive; -use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{ + LazyLock, + atomic::{AtomicU8, Ordering}, +}; /// Zero address used to avoid allowing it to be used for verification. /// This is intentionally disallowed because it is an edge case with Filecoin's BLS /// signature verification. // Copied from ref-fvm due to a bug in their definition. -pub static ZERO_ADDRESS: Lazy
= Lazy::new(|| { +pub static ZERO_ADDRESS: LazyLock
= LazyLock::new(|| { Network::Mainnet .parse_address( "f3yaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaby2smx7a", diff --git a/src/shim/econ.rs b/src/shim/econ.rs index 0c5877da521a..b3b53818e59a 100644 --- a/src/shim/econ.rs +++ b/src/shim/econ.rs @@ -4,6 +4,7 @@ use std::{ fmt, ops::{Add, AddAssign, Deref, DerefMut, Mul, MulAssign, Sub, SubAssign}, + sync::LazyLock, }; use super::fvm_shared_latest::econ::TokenAmount as TokenAmount_latest; @@ -13,7 +14,6 @@ pub use fvm_shared3::{BLOCK_GAS_LIMIT, TOTAL_FILECOIN_BASE}; use fvm_shared4::econ::TokenAmount as TokenAmount_v4; use num_bigint::BigInt; use num_traits::Zero; -use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use static_assertions::const_assert_eq; @@ -21,8 +21,8 @@ const_assert_eq!(BLOCK_GAS_LIMIT, fvm_shared2::BLOCK_GAS_LIMIT as u64); const_assert_eq!(TOTAL_FILECOIN_BASE, fvm_shared2::TOTAL_FILECOIN_BASE); /// Total Filecoin available to the network. -pub static TOTAL_FILECOIN: Lazy = - Lazy::new(|| TokenAmount::from_whole(TOTAL_FILECOIN_BASE)); +pub static TOTAL_FILECOIN: LazyLock = + LazyLock::new(|| TokenAmount::from_whole(TOTAL_FILECOIN_BASE)); #[derive(Clone, PartialEq, Eq, Ord, PartialOrd, Hash, Serialize, Deserialize, Default)] #[serde(transparent)] diff --git a/src/shim/machine/mod.rs b/src/shim/machine/mod.rs index 45d3d988b64f..1cda82b3c2ba 100644 --- a/src/shim/machine/mod.rs +++ b/src/shim/machine/mod.rs @@ -7,10 +7,9 @@ pub use manifest::{BuiltinActor, BuiltinActorManifest}; use fvm2::machine::MultiEngine as MultiEngine_v2; use fvm3::engine::MultiEngine as MultiEngine_v3; use fvm4::engine::MultiEngine as MultiEngine_v4; -use once_cell::sync::Lazy; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; -pub static GLOBAL_MULTI_ENGINE: Lazy> = Lazy::new(Default::default); +pub static GLOBAL_MULTI_ENGINE: LazyLock> = LazyLock::new(Default::default); pub struct MultiEngine { pub v2: MultiEngine_v2, diff --git a/src/state_migration/nv17/datacap.rs b/src/state_migration/nv17/datacap.rs index d5d6f08dbb18..7cd4947aa2c6 100644 --- a/src/state_migration/nv17/datacap.rs +++ b/src/state_migration/nv17/datacap.rs @@ -4,8 +4,6 @@ //! This module contains the migration logic for the `NV17` upgrade for the `datacap` //! actor. -use std::str::FromStr; - use crate::shim::address::Address; use crate::shim::bigint::BigInt; use crate::shim::state_tree::{ActorState, StateTree}; @@ -17,13 +15,14 @@ use fil_actors_shared::frc46_token::token::state::TokenState; use fil_actors_shared::fvm_ipld_hamt::BytesKey; use fvm_ipld_blockstore::Blockstore; use num_traits::Zero; -use once_cell::sync::Lazy; use std::ops::Deref; +use std::str::FromStr; +use std::sync::LazyLock; use super::util::hamt_addr_key_to_key; const DATA_CAP_GRANULARITY: u64 = TokenAmount::PRECISION; -static INFINITE_ALLOWANCE: Lazy = Lazy::new(|| { +static INFINITE_ALLOWANCE: LazyLock = LazyLock::new(|| { StoragePower::from_str("1000000000000000000000").expect("Failed to parse INFINITE_ALLOWANCE") * TokenAmount::PRECISION }); diff --git a/src/tool/subcommands/api_cmd/api_compare_tests.rs b/src/tool/subcommands/api_cmd/api_compare_tests.rs index be6a336c8868..3458bf937d03 100644 --- a/src/tool/subcommands/api_cmd/api_compare_tests.rs +++ b/src/tool/subcommands/api_cmd/api_compare_tests.rs @@ -52,14 +52,18 @@ use itertools::Itertools as _; use jsonrpsee::types::ErrorCode; use libp2p::PeerId; use num_traits::Signed; -use once_cell::sync::Lazy; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::Value; use similar::{ChangeTag, TextDiff}; use std::path::Path; use std::time::Instant; -use std::{path::PathBuf, str::FromStr, sync::Arc, time::Duration}; +use std::{ + path::PathBuf, + str::FromStr, + sync::{Arc, LazyLock}, + time::Duration, +}; use tokio::sync::Semaphore; use tracing::debug; @@ -67,7 +71,7 @@ const COLLECTION_SAMPLE_SIZE: usize = 5; /// This address has been funded by the calibnet faucet and the private keys /// has been discarded. It should always have a non-zero balance. -static KNOWN_CALIBNET_ADDRESS: Lazy
= Lazy::new(|| { +static KNOWN_CALIBNET_ADDRESS: LazyLock
= LazyLock::new(|| { crate::shim::address::Network::Testnet .parse_address("t1c4dkec3qhrnrsa4mccy7qntkyq2hhsma4sq7lui") .unwrap() diff --git a/src/utils/net.rs b/src/utils/net.rs index e426988652c2..8016cc05f327 100644 --- a/src/utils/net.rs +++ b/src/utils/net.rs @@ -8,10 +8,9 @@ use crate::utils::io::WithProgress; use crate::utils::reqwest_resume; use cid::Cid; use futures::{AsyncWriteExt, TryStreamExt}; -use once_cell::sync::Lazy; use reqwest::Response; use std::path::Path; -use std::sync::Arc; +use std::sync::{Arc, LazyLock}; use tap::Pipe; use tokio::io::AsyncBufRead; use tokio_util::{ @@ -22,7 +21,7 @@ use tracing::info; use url::Url; pub fn global_http_client() -> reqwest::Client { - static CLIENT: Lazy = Lazy::new(reqwest::Client::new); + static CLIENT: LazyLock = LazyLock::new(reqwest::Client::new); CLIENT.clone() } diff --git a/src/utils/reqwest_resume/tests.rs b/src/utils/reqwest_resume/tests.rs index 74957c8ce89a..4001515e2433 100644 --- a/src/utils/reqwest_resume/tests.rs +++ b/src/utils/reqwest_resume/tests.rs @@ -7,10 +7,10 @@ use axum::response::IntoResponse; use bytes::Bytes; use futures::stream; use http_range_header::parse_range_header; -use once_cell::sync::Lazy; use rand::Rng; use std::net::{Ipv4Addr, SocketAddr}; use std::ops::Range; +use std::sync::LazyLock; use std::time::Duration; use tokio::net::TcpListener; use tokio_stream::StreamExt as _; @@ -18,7 +18,7 @@ use tokio_stream::StreamExt as _; const CHUNK_LEN: usize = 2048; // `RANDOM_BYTES` size is arbitrarily chosen. We could use something smaller or bigger here. // The only constraint is that `CHUNK_LEN < RANDOM_BYTES.len()`. -static RANDOM_BYTES: Lazy = Lazy::new(|| { +static RANDOM_BYTES: LazyLock = LazyLock::new(|| { let mut rng = crate::utils::rand::forest_rng(); (0..8192).map(|_| rng.r#gen()).collect() }); diff --git a/src/utils/version/mod.rs b/src/utils/version/mod.rs index 497a6bb1a337..193e572f7d82 100644 --- a/src/utils/version/mod.rs +++ b/src/utils/version/mod.rs @@ -2,12 +2,12 @@ // SPDX-License-Identifier: Apache-2.0, MIT use git_version::git_version; -use once_cell::sync::Lazy; use prometheus_client::{ collector::Collector, encoding::{DescriptorEncoder, EncodeLabelSet, EncodeMetric}, metrics::{family::Family, gauge::Gauge}, }; +use std::sync::LazyLock; /// Current git commit hash of the Forest repository. pub const GIT_HASH: &str = @@ -15,11 +15,11 @@ pub const GIT_HASH: &str = /// Current version of the Forest repository with git hash embedded /// E.g., `0.8.0+git.e69baf3e4` -pub static FOREST_VERSION_STRING: Lazy = - Lazy::new(|| format!("{}+git.{}", env!("CARGO_PKG_VERSION"), GIT_HASH)); +pub static FOREST_VERSION_STRING: LazyLock = + LazyLock::new(|| format!("{}+git.{}", env!("CARGO_PKG_VERSION"), GIT_HASH)); -pub static FOREST_VERSION: Lazy = - Lazy::new(|| semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("Invalid version")); +pub static FOREST_VERSION: LazyLock = + LazyLock::new(|| semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("Invalid version")); #[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)] pub struct VersionLabel {