hacker-challenge/src/grpc/mod.rs
Valentyn Faychuk fc933c0647
connections refactoring
Signed-off-by: Valentyn Faychuk <valy@detee.ltd>
2024-12-24 01:09:06 +02:00

74 lines
2.2 KiB
Rust

pub mod client;
pub mod server;
use crate::{datastore::NodeInfo, NodeUpdate};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub mod challenge {
tonic::include_proto!("challenge");
}
impl From<(String, NodeInfo)> for NodeUpdate {
fn from((ip, info): (String, NodeInfo)) -> Self {
Self {
ip,
started_at: Some(prost_types::Timestamp::from(info.started_at)),
keepalive: Some(prost_types::Timestamp::from(info.keepalive)),
mint_requests: info.mint_requests,
mints: info.mints,
mratls_conns: info.mratls_conns,
quote_attacks: info.net_attacks,
public: info.public,
restarts: info.restarts,
disk_attacks: info.disk_attacks,
}
}
}
impl From<NodeUpdate> for (String, NodeInfo) {
fn from(upd: NodeUpdate) -> (String, NodeInfo) {
let ip = upd.ip;
let started_at: SystemTime = grpc_timestamp_to_systemtime(upd.started_at);
let keepalive: SystemTime = grpc_timestamp_to_systemtime(upd.keepalive);
let self_info = NodeInfo {
started_at,
keepalive,
mint_requests: upd.mint_requests,
mints: upd.mints,
mratls_conns: upd.mratls_conns,
net_attacks: upd.quote_attacks,
public: upd.public,
restarts: upd.restarts,
disk_attacks: upd.disk_attacks,
};
(ip, self_info)
}
}
fn grpc_timestamp_to_systemtime(ts: Option<prost_types::Timestamp>) -> SystemTime {
if let Some(ts) = ts {
let duration = Duration::new(ts.seconds as u64, ts.nanos as u32);
UNIX_EPOCH.checked_add(duration).unwrap_or(SystemTime::now())
} else {
println!("Timestamp is None");
SystemTime::now()
}
}
#[derive(Clone, PartialEq)]
pub struct InternalNodeUpdate {
pub sender_ip: String,
pub update: NodeUpdate,
}
impl From<(String, NodeInfo)> for InternalNodeUpdate {
fn from((ip, info): (String, NodeInfo)) -> Self {
Self { sender_ip: ip.clone(), update: (ip, info).into() }
}
}
impl From<(String, NodeUpdate)> for InternalNodeUpdate {
fn from((ip, update): (String, NodeUpdate)) -> Self {
Self { sender_ip: ip, update }
}
}