Skip to content

chore: replace once_cell utils with std equivalents #5821

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"] }
Expand Down
6 changes: 3 additions & 3 deletions src/blocks/election_proof.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -25,7 +25,7 @@ fn parse(strings: &[&str]) -> Result<Vec<BigInt>, ParseBigIntError> {
.collect()
}

static EXP_NUM_COEF: Lazy<Vec<BigInt>> = Lazy::new(|| {
static EXP_NUM_COEF: LazyLock<Vec<BigInt>> = LazyLock::new(|| {
parse(&[
"-648770010757830093818553637600",
"67469480939593786226847644286976",
Expand All @@ -38,7 +38,7 @@ static EXP_NUM_COEF: Lazy<Vec<BigInt>> = Lazy::new(|| {
])
.unwrap()
});
static EXP_DENO_COEF: Lazy<Vec<BigInt>> = Lazy::new(|| {
static EXP_DENO_COEF: LazyLock<Vec<BigInt>> = LazyLock::new(|| {
parse(&[
"1225524182432722209606361",
"114095592300906098243859450",
Expand Down
18 changes: 10 additions & 8 deletions src/blocks/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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 <https://github.com/filecoin-project/lotus/blob/d3ca54d617f4783a1a492993f06e737ea87a5834/chain/gen/genesis/genesis.go#L627>
// and <https://github.com/filecoin-project/lotus/commit/13e5b72cdbbe4a02f3863c04f9ecb69c21c3f80f#diff-fda2789d966ea533e74741c076f163070cbc7eb265b5513cd0c0f3bdee87245cR437>
#[cfg(test)]
static FILECOIN_GENESIS_CID: once_cell::sync::Lazy<Cid> = once_cell::sync::Lazy::new(|| {
static FILECOIN_GENESIS_CID: std::sync::LazyLock<Cid> = std::sync::LazyLock::new(|| {
"bafyreiaqpwbbyjo4a42saasj36kkrpv4tsherf2e7bvezkert2a7dhonoi"
.parse()
.expect("Infallible")
});

#[cfg(test)]
pub static GENESIS_BLOCK_PARENTS: once_cell::sync::Lazy<TipsetKey> =
once_cell::sync::Lazy::new(|| nunny::vec![*FILECOIN_GENESIS_CID].into());
pub static GENESIS_BLOCK_PARENTS: std::sync::LazyLock<TipsetKey> =
std::sync::LazyLock::new(|| nunny::vec![*FILECOIN_GENESIS_CID].into());

#[derive(Deserialize_tuple, Serialize_tuple, Clone, Hash, Eq, PartialEq, Debug)]
pub struct RawBlockHeader {
Expand Down Expand Up @@ -222,7 +224,7 @@ impl RawBlockHeader {
#[derive(Debug)]
pub struct CachingBlockHeader {
uncached: RawBlockHeader,
cid: OnceCell<Cid>,
cid: OnceLock<Cid>,
has_ever_been_verified_against_any_signature: AtomicBool,
}

Expand Down Expand Up @@ -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),
}
}
Expand All @@ -278,7 +280,7 @@ impl CachingBlockHeader {
if let Some(uncached) = store.get_cbor::<RawBlockHeader>(&cid)? {
Ok(Some(Self {
uncached,
cid: OnceCell::with_value(cid),
cid: cid.into(),
has_ever_been_verified_against_any_signature: AtomicBool::new(false),
}))
} else {
Expand Down
19 changes: 10 additions & 9 deletions src/blocks/tipset.rs
Original file line number Diff line number Diff line change
@@ -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};
Expand All @@ -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;
Expand Down Expand Up @@ -145,7 +146,7 @@ pub struct Tipset {
/// Sorted
headers: NonEmpty<CachingBlockHeader>,
// key is lazily initialized via `fn key()`.
key: OnceCell<TipsetKey>,
key: OnceLock<TipsetKey>,
}

impl From<RawBlockHeader> for Tipset {
Expand All @@ -164,7 +165,7 @@ impl From<CachingBlockHeader> for Tipset {
fn from(value: CachingBlockHeader) -> Self {
Self {
headers: nonempty![value],
key: OnceCell::new(),
key: OnceLock::new(),
}
}
}
Expand Down Expand Up @@ -238,7 +239,7 @@ impl Tipset {

Ok(Self {
headers,
key: OnceCell::new(),
key: OnceLock::new(),
})
}

Expand Down Expand Up @@ -448,7 +449,7 @@ impl Tipset {
pub struct FullTipset {
blocks: NonEmpty<Block>,
// key is lazily initialized via `fn key()`.
key: OnceCell<TipsetKey>,
key: OnceLock<TipsetKey>,
}

impl std::hash::Hash for FullTipset {
Expand All @@ -462,7 +463,7 @@ impl From<Block> for FullTipset {
fn from(block: Block) -> Self {
FullTipset {
blocks: nonempty![block],
key: OnceCell::new(),
key: OnceLock::new(),
}
}
}
Expand All @@ -489,7 +490,7 @@ impl FullTipset {

Ok(Self {
blocks,
key: OnceCell::new(),
key: OnceLock::new(),
})
}
/// Returns the first block of the tipset.
Expand Down
29 changes: 15 additions & 14 deletions src/chain_sync/metrics.rs
Original file line number Diff line number Diff line change
@@ -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<Histogram> = Lazy::new(|| {
pub static TIPSET_PROCESSING_TIME: LazyLock<Histogram> = LazyLock::new(|| {
let metric = crate::metrics::default_histogram();
crate::metrics::default_registry().register(
"tipset_processing_time",
Expand All @@ -16,7 +16,7 @@ pub static TIPSET_PROCESSING_TIME: Lazy<Histogram> = Lazy::new(|| {
);
metric
});
pub static BLOCK_VALIDATION_TIME: Lazy<Histogram> = Lazy::new(|| {
pub static BLOCK_VALIDATION_TIME: LazyLock<Histogram> = LazyLock::new(|| {
let metric = crate::metrics::default_histogram();
crate::metrics::default_registry().register(
"block_validation_time",
Expand All @@ -25,16 +25,17 @@ pub static BLOCK_VALIDATION_TIME: Lazy<Histogram> = Lazy::new(|| {
);
metric
});
pub static LIBP2P_MESSAGE_TOTAL: Lazy<Family<Libp2pMessageKindLabel, Counter>> = 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<Counter> = Lazy::new(|| {
pub static LIBP2P_MESSAGE_TOTAL: LazyLock<Family<Libp2pMessageKindLabel, Counter>> =
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<Counter> = LazyLock::new(|| {
let metric = Counter::default();
crate::metrics::default_registry().register(
"invalid_tipset_total",
Expand All @@ -43,7 +44,7 @@ pub static INVALID_TIPSET_TOTAL: Lazy<Counter> = Lazy::new(|| {
);
metric
});
pub static HEAD_EPOCH: Lazy<Gauge> = Lazy::new(|| {
pub static HEAD_EPOCH: LazyLock<Gauge> = LazyLock::new(|| {
let metric = Gauge::default();
crate::metrics::default_registry().register(
"head_epoch",
Expand Down
7 changes: 3 additions & 4 deletions src/chain_sync/network_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::{
convert::TryFrom,
num::NonZeroU64,
sync::{
Arc,
Arc, LazyLock,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
Expand All @@ -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;
Expand All @@ -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<ExponentialAdaptiveValueProvider<u64>> =
Lazy::new(|| ExponentialAdaptiveValueProvider::new(5000, 2000, 60000, false));
static CHAIN_EXCHANGE_TIMEOUT_MILLIS: LazyLock<ExponentialAdaptiveValueProvider<u64>> =
LazyLock::new(|| ExponentialAdaptiveValueProvider::new(5000, 2000, 60000, false));

/// Maximum number of concurrent chain exchange request being sent to the
/// network.
Expand Down
5 changes: 2 additions & 3 deletions src/cli/subcommands/f3_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
Expand All @@ -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<Tera> = Lazy::new(|| {
static TEMPLATES: LazyLock<Tera> = LazyLock::new(|| {
let mut tera = Tera::default();
tera.add_raw_template(MANIFEST_TEMPLATE_NAME, include_str!("f3_cmd/manifest.tpl"))
.unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/daemon/bundle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -77,7 +77,7 @@ pub async fn load_actor_bundles_from_path(
Ok(())
}

pub static ACTOR_BUNDLE_CACHE_DIR: Lazy<PathBuf> = Lazy::new(|| {
pub static ACTOR_BUNDLE_CACHE_DIR: LazyLock<PathBuf> = LazyLock::new(|| {
let project_dir = ProjectDirs::from("com", "ChainSafe", "Forest");
project_dir
.map(|d| d.cache_dir().to_path_buf())
Expand Down
8 changes: 5 additions & 3 deletions src/db/car/plain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -571,7 +571,8 @@ mod tests {
}

fn chain4_car() -> &'static [u8] {
static CAR: Lazy<Vec<u8>> = Lazy::new(|| zstd::decode_all(chain4_car_zst()).unwrap());
static CAR: LazyLock<Vec<u8>> =
LazyLock::new(|| zstd::decode_all(chain4_car_zst()).unwrap());
CAR.as_slice()
}

Expand All @@ -580,7 +581,8 @@ mod tests {
}

fn carv2_car() -> &'static [u8] {
static CAR: Lazy<Vec<u8>> = Lazy::new(|| zstd::decode_all(carv2_car_zst()).unwrap());
static CAR: LazyLock<Vec<u8>> =
LazyLock::new(|| zstd::decode_all(carv2_car_zst()).unwrap());
CAR.as_slice()
}
}
5 changes: 2 additions & 3 deletions src/db/migration/migration_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
sync::{Arc, LazyLock},
};

use crate::Config;
Expand All @@ -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;

Expand Down Expand Up @@ -133,7 +132,7 @@ type MigrationsMap = MultiMap<Version, (Version, Migrator)>;
/// `<FROM version> -> <TO version> @ <Migrator object>`
macro_rules! create_migrations {
($($from:literal -> $to:literal @ $migration:tt),* $(,)?) => {
pub(super) static MIGRATIONS: Lazy<MigrationsMap> = Lazy::new(|| {
pub(super) static MIGRATIONS: LazyLock<MigrationsMap> = LazyLock::new(|| {
MigrationsMap::from_iter(
[
$((
Expand Down
Loading
Loading