use std::{
cell::Cell,
thread,
time::{Duration, Instant},
};
use zksync_dal::{Connection, Core, DalError};
use zksync_web3_decl::error::Web3Error;
pub(crate) async fn open_readonly_transaction<'r>(
conn: &'r mut Connection<'_, Core>,
) -> Result<Connection<'r, Core>, Web3Error> {
let builder = conn.transaction_builder().map_err(DalError::generalize)?;
Ok(builder
.set_readonly()
.build()
.await
.map_err(DalError::generalize)?)
}
#[derive(Debug)]
pub(super) struct ReportFilter {
interval: Duration,
last_timestamp: &'static thread::LocalKey<Cell<Option<Instant>>>,
}
impl ReportFilter {
pub const fn new(
interval: Duration,
last_timestamp: &'static thread::LocalKey<Cell<Option<Instant>>>,
) -> Self {
Self {
interval,
last_timestamp,
}
}
pub fn should_report(&self) -> bool {
let timestamp = self.last_timestamp.get();
let now = Instant::now();
if timestamp.map_or(true, |ts| now - ts > self.interval) {
self.last_timestamp.set(Some(now));
true
} else {
false
}
}
}
macro_rules! report_filter {
($interval:expr) => {{
thread_local! {
static LAST_TIMESTAMP: std::cell::Cell<Option<std::time::Instant>> = std::cell::Cell::new(None);
}
ReportFilter::new($interval, &LAST_TIMESTAMP)
}};
}