mind_sdk_lb 0.1.2

Mind Network Rust SDK
Documentation
use sha3::Digest;

/////////////////////////////////////////////////////////////////////////// LoadBalancer
#[derive(Debug, Clone)]
pub struct LoadBalancer {
    pub cluster_node_id: u64,
    pub cluster_node_total: u64,
}

impl LoadBalancer {
    pub fn new(cluster_node_id: u64, cluster_node_total: u64) -> Self {
        Self {
            cluster_node_id: cluster_node_id,
            cluster_node_total: cluster_node_total,
        }
        //Self { cluster_node_id: config.cluster_node_id, cluster_node_total: config.cluster_node_total }
    }
    pub fn new_from_file(my_node_id: u64, total_nodes: u64) -> Self {
        Self {
            cluster_node_id: my_node_id,
            cluster_node_total: total_nodes,
        }
    }
    pub fn get_node_for_event(&self, hash_string: String) -> Result<u64, mind_sdk_util::MindError> {
        let last_two_chars = &hash_string[hash_string.len() - 2..];
        let last_two_bytes = u8::from_str_radix(last_two_chars, 16)?;
        let result = last_two_bytes as u64;
        return Ok(result % self.cluster_node_total);
    }

    pub fn match_node_id(
        &self,
        log: &alloy::rpc::types::Log,
    ) -> Result<bool, mind_sdk_util::MindError> {
        let tx_hash = log.transaction_hash.unwrap();
        log::debug!(
            "load balance: Txhash: {:?} at block_number: {:?}",
            tx_hash,
            log.block_number
        );
        let log_index = log.log_index.unwrap();
        let balancer_str = format!("{}{}", tx_hash.to_string(), log_index.to_string());
        let content_digest = sha3::Keccak256::new_with_prefix(balancer_str.as_bytes());
        let content_digest = content_digest.finalize();
        let balancer_hash = hex::encode(content_digest);
        let target_node_id = self.get_node_for_event(balancer_hash)?;
        log::debug!(
            "load balance: Event {:?} is assigned to node {:?}",
            tx_hash,
            target_node_id
        );
        if target_node_id == self.cluster_node_id {
            log::debug!("load balance: Event is assigned to current node!");
            return Ok(true);
        } else {
            log::debug!("load balance: Event is not assigned to current node!");
            return Ok(false);
        }
    }
}