-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheartbeat_store.rs
70 lines (60 loc) · 2.58 KB
/
heartbeat_store.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use crate::store::core::RedisStore;
use alloy::primitives::Address;
use redis::Commands;
use shared::models::heartbeat::HeartbeatRequest;
use std::str::FromStr;
use std::sync::Arc;
const ORCHESTRATOR_UNHEALTHY_COUNTER_KEY: &str = "orchestrator:unhealthy_counter";
const ORCHESTRATOR_HEARTBEAT_KEY: &str = "orchestrator:heartbeat";
pub struct HeartbeatStore {
redis: Arc<RedisStore>,
}
impl HeartbeatStore {
pub fn new(redis: Arc<RedisStore>) -> Self {
Self { redis }
}
pub fn beat(&self, payload: &HeartbeatRequest) {
let mut con = self.redis.client.get_connection().unwrap();
let address = Address::from_str(&payload.address).unwrap();
let key = format!("{}:{}", ORCHESTRATOR_HEARTBEAT_KEY, address);
let payload_string = serde_json::to_string(payload).unwrap();
let _: () = con
.set_options(
&key,
payload_string,
redis::SetOptions::default().with_expiration(redis::SetExpiry::EX(60)),
)
.unwrap();
}
pub fn get_heartbeat(&self, address: &Address) -> Option<HeartbeatRequest> {
let mut con = self.redis.client.get_connection().unwrap();
let key = format!("{}:{}", ORCHESTRATOR_HEARTBEAT_KEY, address);
let value: Option<String> = con.get(key).unwrap();
value.and_then(|v| serde_json::from_str(&v).ok())
}
pub fn get_unhealthy_counter(&self, address: &Address) -> u32 {
let mut con = self.redis.client.get_connection().unwrap();
let key = format!("{}:{}", ORCHESTRATOR_UNHEALTHY_COUNTER_KEY, address);
let value: Option<String> = con.get(key).unwrap();
match value {
Some(value) => value.parse::<u32>().unwrap(),
None => 0,
}
}
#[cfg(test)]
pub fn set_unhealthy_counter(&self, address: &Address, counter: u32) {
let mut con = self.redis.client.get_connection().unwrap();
let key = format!("{}:{}", ORCHESTRATOR_UNHEALTHY_COUNTER_KEY, address);
let _: () = con.set(key, counter.to_string()).unwrap();
}
pub fn increment_unhealthy_counter(&self, address: &Address) {
let mut con = self.redis.client.get_connection().unwrap();
let key = format!("{}:{}", ORCHESTRATOR_UNHEALTHY_COUNTER_KEY, address);
let _: () = con.incr(key, 1).unwrap();
}
pub fn clear_unhealthy_counter(&self, address: &Address) {
let mut con = self.redis.client.get_connection().unwrap();
let key = format!("{}:{}", ORCHESTRATOR_UNHEALTHY_COUNTER_KEY, address);
let _: () = con.del(key).unwrap();
}
}