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
|
use std::{collections::HashMap, fmt::Display};
use futures::{stream::FuturesOrdered, TryStreamExt};
use http::Http;
use serde::Deserialize;
use systemd::Systemd;
use tcp::Tcp;
use crate::{Error, Status};
pub mod http;
pub mod systemd;
pub mod tcp;
#[derive(Debug, Clone, Deserialize)]
pub struct Services {
#[serde(flatten)]
inner: HashMap<String, Service>,
#[serde(skip, default = "Services::default_client")]
client: reqwest::Client,
}
impl Services {
pub fn new(services: HashMap<String, Service>) -> Self {
let client = reqwest::Client::new();
Self {
inner: services,
client,
}
}
fn default_client() -> reqwest::Client {
reqwest::Client::new()
}
pub async fn check(&self) -> Result<HashMap<String, Status>, Error> {
let checks = self
.inner
.values()
.map(|service| service.check(self.client.clone()))
.collect::<FuturesOrdered<_>>()
.try_collect::<Vec<_>>()
.await?;
Ok(self
.inner
.keys()
.cloned()
.zip(checks)
.collect::<HashMap<_, _>>())
}
pub async fn check_one(&self, name: &str) -> Option<Result<Status, Error>> {
Some(self.inner.get(name)?.check(self.client.clone()).await)
}
pub async fn check_filtered<P>(&self, mut predicate: P) -> Result<HashMap<String, Status>, Error>
where
P: FnMut(&String) -> bool,
{
let checks = self
.inner
.iter()
.filter_map(|(s, service)| predicate(s).then_some(service))
.map(|service| service.check(self.client.clone()))
.collect::<FuturesOrdered<_>>()
.try_collect::<Vec<_>>()
.await?;
Ok(self
.inner
.keys()
.cloned()
.zip(checks)
.collect::<HashMap<_, _>>())
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum Service {
Http(Http),
Tcp(Tcp),
Systemd(Systemd),
}
impl Service {
pub async fn check(&self, client: reqwest::Client) -> Result<Status, Error> {
match self {
Service::Http(http) => http.check(client).await,
Service::Tcp(tcp) => tcp.check().await,
Service::Systemd(systemd) => systemd.check().await,
}
}
}
impl Display for Service {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Service::Http(http) => http.fmt(f),
Service::Tcp(tcp) => tcp.fmt(f),
Service::Systemd(systemd) => systemd.fmt(f),
}
}
}
|