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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use chrono::Utc;
use tokio_postgres::types::ToSql;
use primitives::{
balances::BalancesState,
sentry::{message::MessageResponse, validator_messages::ValidatorMessage},
validator::{ApproveState, Heartbeat, MessageType, MessageTypes, NewState},
Channel, ChannelId, ValidatorId,
};
use super::{DbPool, PoolError};
pub async fn insert_validator_message(
pool: &DbPool,
channel: &Channel,
from: &ValidatorId,
validator_message: &MessageTypes,
) -> Result<bool, PoolError> {
let client = pool.get().await?;
let stmt = client.prepare("INSERT INTO validator_messages (channel_id, \"from\", msg, received) values ($1, $2, $3, $4)").await?;
let row = client
.execute(
&stmt,
&[&channel.id(), &from, &validator_message, &Utc::now()],
)
.await?;
let inserted = row == 1;
Ok(inserted)
}
pub async fn get_validator_messages(
pool: &DbPool,
channel_id: &ChannelId,
validator_id: &Option<ValidatorId>,
message_types: &[MessageType],
limit: u64,
) -> Result<Vec<ValidatorMessage>, PoolError> {
let client = pool.get().await?;
let mut where_clauses: Vec<String> = vec!["channel_id = $1".to_string()];
let mut params: Vec<&(dyn ToSql + Sync)> = vec![&channel_id];
if let Some(validator_id) = validator_id {
where_clauses.push(format!(r#""from" = ${}"#, params.len() + 1));
params.push(validator_id);
}
add_message_types_params(&mut where_clauses, &mut params, message_types);
let statement = format!(
r#"SELECT "from", msg, received FROM validator_messages WHERE {} ORDER BY received DESC LIMIT {}"#,
where_clauses.join(" AND "),
limit
);
let select = client.prepare(&statement).await?;
let results = client.query(&select, params.as_slice()).await?;
let messages = results.iter().map(ValidatorMessage::from).collect();
Ok(messages)
}
fn add_message_types_params<'a>(
where_clauses: &mut Vec<String>,
params: &mut Vec<&'a (dyn ToSql + Sync)>,
message_types: &'a [MessageType],
) {
let mut msg_prep = vec![];
for message_type in message_types.iter() {
msg_prep.push(format!("${}", params.len() + 1));
params.push(message_type);
}
if !msg_prep.is_empty() {
where_clauses.push(format!("msg->>'type' IN ({})", msg_prep.join(",")));
}
}
pub async fn latest_approve_state(
pool: &DbPool,
channel: &Channel,
) -> Result<Option<MessageResponse<ApproveState>>, PoolError> {
let client = pool.get().await?;
let select = client.prepare("SELECT \"from\", msg, received FROM validator_messages WHERE channel_id = $1 AND \"from\" = $2 AND msg ->> 'type' = 'ApproveState' ORDER BY received DESC LIMIT 1").await?;
let rows = client
.query(&select, &[&channel.id(), &channel.follower])
.await?;
rows.get(0)
.map(MessageResponse::<ApproveState>::try_from)
.transpose()
.map_err(PoolError::Backend)
}
pub async fn latest_new_state<S: BalancesState>(
pool: &DbPool,
channel: &Channel,
state_root: &str,
) -> Result<Option<MessageResponse<NewState<S>>>, PoolError> {
let client = pool.get().await?;
let select = client.prepare("SELECT \"from\", msg, received FROM validator_messages WHERE channel_id = $1 AND \"from\" = $2 AND msg ->> 'type' = 'NewState' AND msg->> 'stateRoot' = $3 ORDER BY received DESC LIMIT 1").await?;
let rows = client
.query(&select, &[&channel.id(), &channel.leader, &state_root])
.await?;
rows.get(0)
.map(MessageResponse::<NewState<S>>::try_from)
.transpose()
.map_err(PoolError::Backend)
}
pub async fn latest_heartbeats(
pool: &DbPool,
channel_id: &ChannelId,
validator_id: &ValidatorId,
) -> Result<Vec<MessageResponse<Heartbeat>>, PoolError> {
let client = pool.get().await?;
let select = client.prepare("SELECT \"from\", msg, received FROM validator_messages WHERE channel_id = $1 AND \"from\" = $2 AND msg ->> 'type' = 'Heartbeat' ORDER BY received DESC LIMIT 2").await?;
let rows = client.query(&select, &[&channel_id, &validator_id]).await?;
rows.iter()
.map(MessageResponse::<Heartbeat>::try_from)
.collect::<Result<_, _>>()
.map_err(PoolError::Backend)
}