-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathserver_ping.rs
More file actions
324 lines (288 loc) · 10.9 KB
/
server_ping.rs
File metadata and controls
324 lines (288 loc) · 10.9 KB
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use crate::database::DBProject;
use crate::database::models::DBProjectId;
use crate::database::redis::RedisPool;
use crate::env::ENV;
use crate::models::exp;
use crate::models::ids::ProjectId;
use crate::models::projects::ProjectStatus;
use crate::{database::PgPool, util::error::Context};
use chrono::{TimeDelta, Utc};
use clickhouse::{Client, Row};
use serde::Serialize;
use sqlx::types::Json;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Semaphore;
use tokio::task::JoinSet;
use tracing::{Instrument, info, info_span, trace, warn};
pub struct ServerPingQueue {
pub db: PgPool,
pub redis: RedisPool,
pub clickhouse: Client,
}
pub const REDIS_NAMESPACE: &str = "minecraft_java_server_ping";
pub const CLICKHOUSE_TABLE: &str = "minecraft_java_server_pings";
impl ServerPingQueue {
pub fn new(db: PgPool, redis: RedisPool, clickhouse: Client) -> Self {
Self {
db,
redis,
clickhouse,
}
}
pub async fn ping_minecraft_java_servers(&self) -> eyre::Result<()> {
let server_projects = self.find_servers_to_ping().await?;
info!("Found {} servers to ping", server_projects.len());
let active_pings =
Arc::new(Semaphore::new(ENV.SERVER_PING_MAX_CONCURRENT));
let pings = server_projects
.into_iter()
.map(|(project_id, java_server)| {
let span = info_span!("ping", %project_id, address = %java_server.address);
let active_pings = active_pings.clone();
let address = java_server.address;
let task = async move {
let _permit = active_pings.acquire().await.expect("semaphore should not be closed now");
let mut retries = ENV.SERVER_PING_RETRIES;
let result = loop {
match ping_server(&address, None).await {
Ok(ping) => {
info!(?ping, "Received successful ping");
break Ok(ping);
}
Err(err) if retries == 0 => {
info!("Failed to ping server in {:?}ms, no retries left: {err:#}", ENV.SERVER_PING_TIMEOUT_MS);
break Err(err);
}
Err(err) => {
trace!(%retries, "Failed to ping server in {:?}ms, retrying: {err:#}", ENV.SERVER_PING_TIMEOUT_MS);
retries -= 1;
continue;
}
};
};
(project_id, exp::minecraft::JavaServerPing {
when: Utc::now(),
address,
data: result.ok(),
})
};
tokio::spawn(task.instrument(span))
})
.collect::<JoinSet<_>>()
.join_all()
.await
.into_iter()
.filter_map(|result| result.ok())
.collect::<Vec<_>>();
if !pings.is_empty() {
let mut ch = self
.clickhouse
.insert::<ServerPingRecord>(CLICKHOUSE_TABLE)
.await
.wrap_err("failed to begin inserting ping records")?;
let mut redis = self
.redis
.connect()
.await
.wrap_err("failed to connect to redis")?;
for (project_id, ping) in &pings {
let data = ping.data.as_ref();
let row = ServerPingRecord {
recorded: ping.when.timestamp_nanos_opt().unwrap()
/ 100_000,
project_id: project_id.0,
address: ping.address.clone(),
latency_ms: data.map(|d| d.latency.as_millis() as u32),
description: data.and_then(|d| {
d.description.as_ref().map(|d| {
serde_json::to_string(&d)
.expect("serialization should not fail")
})
}),
version_name: data.map(|d| d.version_name.clone()),
version_protocol: data.map(|d| d.version_protocol),
players_online: data.and_then(|d| d.players_online),
players_max: data.and_then(|d| d.players_max),
};
ch.write(&row)
.await
.wrap_err("failed to write ping record")?;
redis
.set_serialized_to_json(
REDIS_NAMESPACE,
project_id,
ping,
None,
)
.await
.wrap_err("failed to set redis key")?;
DBProject::clear_cache(
(*project_id).into(),
None,
None,
&self.redis,
)
.await
.inspect_err(|err| {
warn!("failed to clear project cache: {err:#}")
})
.ok();
}
ch.end()
.await
.wrap_err("failed to end inserting ping records")?;
}
let num_success =
pings.iter().filter(|(_, ping)| ping.data.is_some()).count();
let num_total = pings.len();
info!(
"Inserted ping results for {} servers - {num_success}/{num_total} successful",
pings.len()
);
Ok(())
}
async fn find_servers_to_ping(
&self,
) -> eyre::Result<Vec<(ProjectId, exp::minecraft::JavaServerProject)>> {
// first select all java servers
let all_server_projects = sqlx::query!(
r#"
SELECT id, components AS "components: Json<exp::ProjectSerial>"
FROM mods
WHERE
status = ANY($1)
AND components ? 'minecraft_java_server'
"#,
&ProjectStatus::iterator()
.filter(|s| s.is_approved())
.map(|s| s.to_string())
.collect::<Vec<_>>()
)
.fetch_all(&self.db)
.await
.wrap_err("failed to fetch servers to ping")?;
if all_server_projects.is_empty() {
// we must early-exit, otherwise we'll run `redis.get_many()`,
// which runs `MGET` with no args; this gives:
// "ResponseError: wrong number of arguments for 'mget' command"
return Ok(Vec::new());
}
let mut redis = self
.redis
.connect()
.await
.wrap_err("failed to connect to redis")?;
// get the last ping info for all of them
// querying redis here, which is a cache, not the source of truth (clickhouse),
// but it should be fine since we don't usually flush redis
// and if we do miss an entry that we shouldn't, we just ping it again
let all_project_ids = all_server_projects
.iter()
.map(|row| ProjectId::from(DBProjectId(row.id)).to_string())
.collect::<Vec<_>>();
let all_server_last_pings = redis
.get_many_deserialized_from_json::<exp::minecraft::JavaServerPing>(
REDIS_NAMESPACE,
&all_project_ids,
)
.await
.wrap_err("failed to fetch server project last pings")?;
let now = Utc::now();
let projects_to_ping = all_server_projects
.into_iter()
.zip(all_server_last_pings)
// only include projects which have and address AND:
// - have not had a ping in redis yet
// - OR their last ping was a failure
// - OR their last successful ping was more than `SERVER_PING_MIN_INTERVAL_SEC` seconds ago
.filter(|(row, ping)| {
if row
.components
.0
.minecraft_java_server
.as_ref()
.is_none_or(|p| p.address.trim().is_empty())
{
return false;
}
let Some(ping) = ping else { return true };
if ping.data.is_none() {
return true;
};
ping.when.signed_duration_since(now)
> TimeDelta::seconds(
ENV.SERVER_PING_MIN_INTERVAL_SEC as i64,
)
})
.filter_map(|(row, _)| {
let server = row.components.0.minecraft_java_server?;
Some((ProjectId::from(DBProjectId(row.id)), server))
})
.collect::<Vec<_>>();
Ok(projects_to_ping)
}
}
pub async fn ping_server(
address: &str,
timeout: Option<Duration>,
) -> eyre::Result<exp::minecraft::JavaServerPingData> {
let start = Instant::now();
let default_duration = Duration::from_millis(ENV.SERVER_PING_TIMEOUT_MS);
let timeout = timeout
.map(|duration| duration.min(default_duration))
.unwrap_or(default_duration);
let conn = async_minecraft_ping::ConnectionConfig::build(address)
.with_srv_lookup()
.with_timeout(timeout)
.connect()
.await
.wrap_err("failed to connect to server")?;
let status = conn
.status()
.await
.wrap_err("failed to get server status")?
.status;
eyre::Ok(exp::minecraft::JavaServerPingData {
latency: start.elapsed(),
version_name: status.version.name,
version_protocol: status.version.protocol,
description: status.description,
players_online: status.players.online,
players_max: status.players.max,
})
}
#[derive(Debug, Row, Serialize, Clone)]
struct ServerPingRecord {
recorded: i64,
project_id: u64,
address: String,
latency_ms: Option<u32>,
description: Option<String>,
version_name: Option<String>,
version_protocol: Option<i32>,
players_online: Option<i32>,
players_max: Option<i32>,
}
#[cfg(test)]
mod tests {
use super::*;
#[actix_rt::test]
async fn test_ping_server_success() {
let _status = ping_server("mc.hypixel.net", None).await.unwrap();
}
#[actix_rt::test]
async fn test_follow_srv_record() {
_ = ping_server("hypixel.net", None).await.unwrap();
}
#[actix_rt::test]
async fn test_ping_server_invalid_address() {
_ = ping_server("invalid.invalid", None).await.unwrap_err();
}
#[actix_rt::test]
async fn test_ping_zero_timeout() {
_ = ping_server("mc.hypixel.net", Some(Duration::ZERO))
.await
.unwrap_err();
}
}