consensus-shipyard / ipc

🌳 Spawn multi-level trees of customized, scalable, EVM-compatible networks with IPC. L2++ powered by FVM, Wasm, libp2p, IPFS/IPLD, and CometBFT.
https://ipc.space
Apache License 2.0
41 stars 35 forks source link

Improvement Suggestion for `IPCProviderProxyWithLatency` #1091

Open karlem opened 2 months ago

karlem commented 2 months ago

Summary

Refactor the IPCProviderProxyWithLatency struct to use a macro for cleaner and more maintainable code.

Current Code Links

Suggested Refactor

Define a macro to simplify the repetitive code and improve the overall structure:


macro_rules! define_proxy_method {
    ($method:ident, $metric:expr) => {
        #[instrument(skip(self))]
        async fn $method(&self, height: Option<BlockHeight>) -> anyhow::Result<_> {
            emit_event_with_latency(
                &self.inner.parent_subnet.to_string(),
                $metric,
                || async {
                    match height {
                        Some(h) => self.inner.$method(h).await,
                        None => self.inner.$method().await,
                    }
                },
            ).await
        }
    };
}

pub struct IPCProviderProxyWithLatency {
    inner: IPCProviderProxy,
}

impl IPCProviderProxyWithLatency {
    pub fn new(inner: IPCProviderProxy) -> Self {
        Self { inner }
    }
}

#[async_trait]
impl ParentQueryProxy for IPCProviderProxyWithLatency {
    define_proxy_method!(get_chain_head_height, "chain_head");
    define_proxy_method!(get_genesis_epoch, "genesis_epoch");
    define_proxy_method!(get_block_hash, "get_block_hash");
    define_proxy_method!(get_top_down_msgs, "get_top_down_msgs");
    define_proxy_method!(get_validator_changes, "get_validator_changeset");
}