Skip to content

Commit

Permalink
rpc: retry Latest block if we couldn't retrieve it via cache
Browse files Browse the repository at this point in the history
  • Loading branch information
tcoratger committed Oct 17, 2024
1 parent 52848a3 commit 9562ea3
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions crates/rpc/rpc-eth-api/src/helpers/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,18 +233,41 @@ pub trait LoadBlock: LoadPendingBlock + SpawnBlocking {
};
}

// We retrieve the block hash for the given block id via the provider
let block_hash = match LoadPendingBlock::provider(self)
.block_hash_for_id(block_id)
.map_err(Self::Error::from_eth_err)?
{
Some(block_hash) => block_hash,
// If the block hash is not found, we return `None` directly
None => return Ok(None),
};

self.cache()
.get_sealed_block_with_senders(block_hash)
.await
.map_err(Self::Error::from_eth_err)
// Initialize the maximum number of retries for handling reorg cases.
//
// A reorg may cause the latest block to be temporarily absent from the cache.
//
// By retrying once, we give the system a chance to update the cache with
// the new latest block information after a reorganization.
let max_retries = 1;

// Attempt to fetch the block from cache
for _ in 0..=max_retries {
match self.cache().get_sealed_block_with_senders(block_hash).await {
// If a block is found in the cache, return it
Ok(Some(block)) => return Ok(Some(block)),
// If no block is found and the `block_id` refers to the latest block,
// we retry the fetch, as this may indicate a reorg scenario
Ok(None) if block_id.is_latest() => continue,
// If no block is found and the `block_id` is not the latest, return `None`
Ok(None) => return Ok(None),
// If an error occurs while fetching from the cache, return it as an error
Err(err) => return Err(Self::Error::from_eth_err(err)),
}
}

// Return `None` if all retries have been exhausted without finding the block
Ok(None)
}
}
}

0 comments on commit 9562ea3

Please sign in to comment.