Skip to content

Commit

Permalink
Fix caching when main chain addresses changes between queries
Browse files Browse the repository at this point in the history
  • Loading branch information
LGLO committed Dec 16, 2024
1 parent a2ff155 commit d795e21
Showing 1 changed file with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub struct NativeTokenManagementDataSourceImpl {
cache: Arc<Mutex<Cache>>,
}

type CacheConfig = (MainchainAddress, PolicyId, AssetName);

observed_async_trait!(
impl NativeTokenManagementDataSource for NativeTokenManagementDataSourceImpl {
// after_block is always less or equal to_block
Expand All @@ -37,7 +39,7 @@ impl NativeTokenManagementDataSource for NativeTokenManagementDataSourceImpl {
if let Some(after_block) = after_block {
if after_block == to_block {
Ok(NativeTokenAmount(0))
} else if let Some(amount) = self.get_from_cache(&after_block, &to_block) {
} else if let Some(amount) = self.get_from_cache(&after_block, &to_block, (address.clone(), policy_id.clone(), asset_name.clone())) {
log::debug!(
"Illiquid supply transfers sum from cache after block '{:?}' to block '{:?}' is {}",
after_block, to_block, amount.0
Expand All @@ -59,7 +61,7 @@ impl NativeTokenManagementDataSource for NativeTokenManagementDataSourceImpl {
log::debug!("Amount of illiquid supply transfers is {}", amount);

if let Ok(mut cache) = self.cache.lock() {
cache.update(block_to_amount)
cache.update(block_to_amount, (address.clone(), policy_id.clone(), asset_name.clone()))
}
Ok(NativeTokenAmount(amount))
}
Expand Down Expand Up @@ -95,9 +97,14 @@ impl NativeTokenManagementDataSourceImpl {
&self,
after_block: &McBlockHash,
to_block: &McBlockHash,
cache_config: CacheConfig,
) -> Option<NativeTokenAmount> {
let cache = self.cache.lock().ok()?;
cache.get_sum_in_range(after_block, to_block).map(NativeTokenAmount)
if cache.config == Some(cache_config) {
cache.get_sum_in_range(after_block, to_block).map(NativeTokenAmount)
} else {
None
}
}

// invariant: to_block is always a stable block
Expand Down Expand Up @@ -202,6 +209,7 @@ async fn get_latest_block(pool: &PgPool) -> Result<Block> {
pub(crate) struct Cache {
/// Continous blocks with their respective total native token transfer amount
block_hash_to_amount: Vec<(McBlockHash, u128)>,
pub(crate) config: Option<CacheConfig>,
}

impl Cache {
Expand All @@ -215,7 +223,8 @@ impl Cache {
Some(after_to.iter().map(|(_, amount)| amount).sum())
}

pub fn update(&mut self, block_hash_to_amount: Vec<(McBlockHash, u128)>) {
pub fn update(&mut self, block_hash_to_amount: Vec<(McBlockHash, u128)>, config: CacheConfig) {
self.block_hash_to_amount = block_hash_to_amount;
self.config = Some(config);
}
}

0 comments on commit d795e21

Please sign in to comment.