Skip to content

Commit

Permalink
Remove cache from fee ticker
Browse files Browse the repository at this point in the history
Signed-off-by: deniallugo <[email protected]>
  • Loading branch information
Deniallugo committed Mar 22, 2022
1 parent d34f9ef commit f7d4b85
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 88 deletions.
5 changes: 1 addition & 4 deletions core/bin/server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,7 @@ async fn run_server(components: &ComponentsToRun) {
let common_config = CommonApiConfig::from_env();
let chain_config = ChainConfig::from_env();
let fee_ticker_config = TickerConfig::from_env();
let ticker_info = Box::new(TickerInfo::new(
connection_pool.clone(),
fee_ticker_config.with_cache,
));
let ticker_info = Box::new(TickerInfo::new(connection_pool.clone()));

let ticker = FeeTicker::new_with_default_validator(
ticker_info,
Expand Down
81 changes: 4 additions & 77 deletions core/bin/zksync_api/src/fee_ticker/ticker_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,13 @@
#[cfg(test)]
use std::any::Any;

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::time::Instant;
// External deps
use anyhow::format_err;
use async_trait::async_trait;
use chrono::Utc;
use num::rational::Ratio;
use num::BigUint;
use tokio::sync::RwLock;
// Workspace deps
use zksync_storage::ConnectionPool;
use zksync_types::aggregated_operations::AggregatedActionType;
Expand All @@ -23,26 +20,6 @@ use zksync_types::{Address, Token, TokenId, TokenLike, TokenPrice};
use crate::fee_ticker::PriceError;
use crate::utils::token_db_cache::TokenDBCache;

const API_PRICE_EXPIRATION_TIME_SECS: Duration = Duration::from_secs(30 * 60);

#[derive(Debug, Clone)]
struct TokenCacheEntry {
price: TokenPrice,
}

impl TokenCacheEntry {
fn new(price: TokenPrice) -> Self {
Self { price }
}

fn is_cache_entry_expired(&self) -> bool {
Utc::now()
.signed_duration_since(self.price.last_updated)
.num_seconds()
> API_PRICE_EXPIRATION_TIME_SECS.as_secs() as i64
}
}

pub trait FeeTickerClone {
fn clone_box(&self) -> Box<dyn FeeTickerInfo>;
}
Expand Down Expand Up @@ -92,19 +69,13 @@ pub trait FeeTickerInfo: FeeTickerClone + Send + Sync + 'static {
pub struct TickerInfo {
db: ConnectionPool,
token_db_cache: TokenDBCache,
price_cache: Arc<RwLock<HashMap<TokenId, TokenCacheEntry>>>,
gas_price_cache: Arc<RwLock<Option<(BigUint, Instant)>>>,
with_cache: bool,
}

impl TickerInfo {
pub fn new(db: ConnectionPool, with_cache: bool) -> Self {
pub fn new(db: ConnectionPool) -> Self {
Self {
db,
token_db_cache: Default::default(),
price_cache: Default::default(),
gas_price_cache: Default::default(),
with_cache,
}
}
}
Expand Down Expand Up @@ -230,24 +201,12 @@ impl FeeTickerInfo for TickerInfo {
});
}

if self.with_cache {
if let Some(cached_value) = self.get_stored_value(token.id).await {
metrics::histogram!("ticker_info.get_last_token_price", start.elapsed(), "type" => "cached");
return Ok(cached_value);
}
}

let historical_price = self
.get_historical_ticker_price(token.id)
.get_ticker_price(token.id)
.await
.map_err(|e| vlog::warn!("Failed to get historical ticker price: {}", e));

if let Ok(Some(historical_price)) = historical_price {
if self.with_cache {
self.update_cached_value(token.id, historical_price.clone())
.await;
}
metrics::histogram!("ticker_info.get_last_token_price", start.elapsed(), "type" => "historical");
return Ok(historical_price);
}

Expand All @@ -258,16 +217,6 @@ impl FeeTickerInfo for TickerInfo {
/// Get current gas price in ETH
async fn get_gas_price_wei(&self) -> Result<BigUint, anyhow::Error> {
let start = Instant::now();
if self.with_cache {
let cached_value = self.gas_price_cache.read().await;

if let Some((cached_gas_price, cache_time)) = cached_value.as_ref() {
if cache_time.elapsed() < API_PRICE_EXPIRATION_TIME_SECS {
return Ok(cached_gas_price.clone());
}
}
drop(cached_value);
}

let mut storage = self
.db
Expand All @@ -282,10 +231,6 @@ impl FeeTickerInfo for TickerInfo {
.as_u64();
let average_gas_price = BigUint::from(average_gas_price);

if self.with_cache {
*self.gas_price_cache.write().await = Some((average_gas_price.clone(), Instant::now()));
}

metrics::histogram!("ticker_info.get_gas_price_wei", start.elapsed());
Ok(average_gas_price)
}
Expand Down Expand Up @@ -320,25 +265,7 @@ impl FeeTickerInfo for TickerInfo {
}

impl TickerInfo {
async fn update_cached_value(&self, token_id: TokenId, price: TokenPrice) {
self.price_cache
.write()
.await
.insert(token_id, TokenCacheEntry::new(price.clone()));
}

async fn get_stored_value(&self, token_id: TokenId) -> Option<TokenPrice> {
let price_cache = self.price_cache.read().await;

if let Some(cached_entry) = price_cache.get(&token_id) {
if !cached_entry.is_cache_entry_expired() {
return Some(cached_entry.price.clone());
}
}
None
}

async fn get_historical_ticker_price(
async fn get_ticker_price(
&self,
token_id: TokenId,
) -> Result<Option<TokenPrice>, anyhow::Error> {
Expand Down
4 changes: 0 additions & 4 deletions core/lib/config/src/configs/ticker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ pub struct TickerConfig {
pub number_of_ticker_actors: u8,
/// Subsidized price for ChangePubKey in cents scaled by SUBSIDY_USD_AMOUNTS_SCALE
pub subsidy_cpk_price_usd_scaled: u64,
/// Use cache for ticker config
pub with_cache: bool,
}

impl TickerConfig {
Expand Down Expand Up @@ -82,7 +80,6 @@ mod tests {
token_market_update_time: 120,
number_of_ticker_actors: 4,
subsidy_cpk_price_usd_scaled: 100,
with_cache: true,
}
}

Expand All @@ -102,7 +99,6 @@ FEE_TICKER_NUMBER_OF_TICKER_ACTORS="4"
FEE_TICKER_SUBSIDIZED_TOKENS_LIMITS=156
FEE_TICKER_SCALE_FEE_PERCENT=100
FEE_TICKER_SUBSIDY_CPK_PRICE_USD_SCALED=100
FEE_TICKER_WITH_CACHE="true"
"#;
set_env(config);

Expand Down
3 changes: 0 additions & 3 deletions etc/env/base/fee_ticker.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,3 @@ scale_fee_percent=100
# Please note, that the prices are scaled by 10^6
# CPK price is 0.00001 USD
subsidy_cpk_price_usd_scaled=10

# Using cache for ticker info
with_cache=false

0 comments on commit f7d4b85

Please sign in to comment.