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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use std::fmt;

use crate::check::NamedChecker;

use once_cell::sync::Lazy;
use ops_core::{async_trait, CheckResponse, Checker, Health};
use prometheus::{opts, register_gauge_vec, GaugeVec};
use serde_json::{json, Value};

const HEALTHCHECK_NAME: &str = "healthcheck_name";
const HEALTHCHECK_RESULT: &str = "healthcheck_result";
const HEALTHCHECK_STATUS: &str = "healthcheck_status";

static CHECK_RESULT_GAUGE: Lazy<GaugeVec> = Lazy::new(|| {
    register_gauge_vec!(
        opts!(
            HEALTHCHECK_STATUS,
            "Meters the healthcheck status based for each check and for each result"
        ),
        &[HEALTHCHECK_NAME, HEALTHCHECK_RESULT]
    )
    .unwrap()
});

enum Ready {
    Always,
    Never,
}

#[async_trait]
pub trait Status: Send + Sync {
    /// Details of the application, as JSON.
    fn about(&self) -> Value;

    /// Determines the readiness of the application.
    async fn ready(&self) -> Option<bool>;

    /// Checks the health of the application.
    async fn check(&self) -> Option<HealthResult>;
}

#[derive(Debug)]
/// Converts the health result entry to JSON.
pub struct HealthResult {
    name: String,
    description: String,
    health: Health,
    checks: Vec<HealthResultEntry>,
}

impl HealthResult {
    fn new(
        name: String,
        description: String,
        health: Health,
        checks: Vec<HealthResultEntry>,
    ) -> HealthResult {
        HealthResult {
            name,
            description,
            health,
            checks,
        }
    }

    pub(crate) fn to_json(&self) -> Value {
        let health: &'static str = self.health.into();

        json!({
            "name": self.name,
            "description": self.description,
            "health": health,
            "checks": self.checks.iter().map(|c| c.to_json()).collect::<Vec<_>>(),
        })
    }
}

#[derive(Debug)]
struct HealthResultEntry {
    name: String,
    health: Health,
    output: String,
    action: Option<String>,
    impact: Option<String>,
}

impl HealthResultEntry {
    fn new(
        name: String,
        health: Health,
        output: String,
        action: Option<String>,
        impact: Option<String>,
    ) -> HealthResultEntry {
        HealthResultEntry {
            name,
            health,
            output,
            action,
            impact,
        }
    }

    fn to_json(&self) -> Value {
        let health: &'static str = self.health.into();

        json!({
            "name": self.name,
            "health": health,
            "output": self.output,
            "action": self.action,
            "impact": self.impact,
        })
    }
}

/// Builds a status object.
#[derive(Debug)]
pub struct StatusBuilder {}

impl StatusBuilder {
    /// Always returns a status that is always ready.
    pub fn always(name: &str, description: &str) -> StatusNoChecks {
        StatusNoChecks {
            name: name.to_owned(),
            description: description.to_owned(),
            ready: Some(Ready::Always),
            revision: None,
            owners: Vec::new(),
            links: Vec::new(),
        }
    }

    /// Never returns a status that is never ready.
    pub fn never(name: &str, description: &str) -> StatusNoChecks {
        StatusNoChecks {
            name: name.to_owned(),
            description: description.to_owned(),
            ready: Some(Ready::Never),
            revision: None,
            owners: Vec::new(),
            links: Vec::new(),
        }
    }

    /// None returns a status has no concept of readiness.
    pub fn none(name: &str, description: &str) -> StatusNoChecks {
        StatusNoChecks {
            name: name.to_owned(),
            description: description.to_owned(),
            ready: None,
            revision: None,
            owners: Vec::new(),
            links: Vec::new(),
        }
    }

    /// Healthchecks returns a status that expects one or more [`NamedChecker`](struct.NamedChecker.html).
    pub fn healthchecks(name: &str, description: &str) -> StatusWithChecks {
        StatusWithChecks {
            name: name.to_owned(),
            description: description.to_owned(),
            checkers: Vec::new(),
            revision: None,
            owners: Vec::new(),
            links: Vec::new(),
        }
    }
}

/// A status with no health checks
pub struct StatusNoChecks {
    name: String,
    description: String,
    ready: Option<Ready>,
    revision: Option<String>,
    owners: Vec<Owner>,
    links: Vec<Link>,
}

impl fmt::Debug for StatusNoChecks {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StatusNoChecks")
            .field("name", &self.name)
            .field("description", &self.description)
            .finish()
    }
}

impl StatusNoChecks {
    /// Sets the revision, this should be a version control ref.
    pub fn revision(mut self, revision: &str) -> Self {
        self.revision = Some(revision.to_owned());
        self
    }

    /// Adds an owner.
    pub fn owner(mut self, name: &str, slack: &str) -> Self {
        self.owners.push(Owner::new(name, slack));
        self
    }

    /// Adds a link.
    pub fn link(mut self, description: &str, url: &str) -> Self {
        self.links.push(Link::new(description, url));
        self
    }
}

#[async_trait]
impl Status for StatusNoChecks {
    fn about(&self) -> Value {
        json!({
            "name": self.name,
            "description": self.description,
            "links": self.links.iter().map(|l| l.to_json()).collect::<Vec<_>>(),
            "owners": self.owners.iter().map(|o| o.to_json()).collect::<Vec<_>>(),
            "build-info": {
                "revision": self.revision,
            },
        })
    }

    async fn ready(&self) -> Option<bool> {
        match self.ready {
            Some(Ready::Always) => Some(true),
            Some(Ready::Never) => Some(false),
            None => None,
        }
    }

    async fn check(&self) -> Option<HealthResult> {
        None
    }
}

/// A status with health checks
pub struct StatusWithChecks {
    name: String,
    description: String,
    checkers: Vec<NamedChecker>,
    revision: Option<String>,
    owners: Vec<Owner>,
    links: Vec<Link>,
}

impl fmt::Debug for StatusWithChecks {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StatusWithChecks")
            .field("name", &self.name)
            .field("description", &self.description)
            .finish()
    }
}

impl StatusWithChecks {
    /// Adds a [`NamedChecker`](`struct.NamedChecker.html`).
    pub fn checker(mut self, checker: NamedChecker) -> Self {
        self.checkers.push(checker);
        self
    }

    /// Sets the revision, this should be a version control ref.
    pub fn revision(mut self, revision: &str) -> Self {
        self.revision = Some(revision.to_owned());
        self
    }

    /// Adds an owner.
    pub fn owner(mut self, name: &str, slack: &str) -> Self {
        self.owners.push(Owner::new(name, slack));
        self
    }

    /// Adds a link.
    pub fn link(mut self, description: &str, url: &str) -> Self {
        self.links.push(Link::new(description, url));
        self
    }

    async fn use_health_check(&self) -> bool {
        match self.check().await.unwrap().health {
            Health::Healthy => true,
            Health::Degraded => true,
            Health::Unhealthy => false,
        }
    }

    fn update_check_metrics(&self, checker: &NamedChecker, response: &CheckResponse) {
        use std::collections::HashMap;

        let res = response.health();

        let map = [
            (HEALTHCHECK_NAME, checker.name()),
            (HEALTHCHECK_RESULT, res.into()),
        ]
        .iter()
        .cloned()
        .collect::<HashMap<&str, &str>>();

        crate::health::HEALTH_STATUSES.iter().for_each(|hs| {
            if &response.health() == hs {
                CHECK_RESULT_GAUGE.with(&map).set(1.0);
            } else {
                CHECK_RESULT_GAUGE.with(&map).set(0.0);
            }
        });
    }
}

#[async_trait]
impl Status for StatusWithChecks {
    fn about(&self) -> Value {
        json!({
            "name": self.name,
            "description": self.description,
            "links": self.links.iter().map(|l| l.to_json()).collect::<Vec<_>>(),
            "owners": self.owners.iter().map(|o| o.to_json()).collect::<Vec<_>>(),
            "build-info": {
                "revision": self.revision,
            },
        })
    }

    async fn ready(&self) -> Option<bool> {
        Some(self.use_health_check().await)
    }

    async fn check(&self) -> Option<HealthResult> {
        let checkers = self.checkers.iter().map(|c| c.check());

        let checks = futures_util::future::join_all(checkers).await;

        let checks = checks.iter().zip(self.checkers.iter());

        let mut health_result = HealthResult::new(
            self.name.to_owned(),
            self.description.to_owned(),
            Health::Unhealthy,
            checks
                .map(|(resp, checker)| {
                    self.update_check_metrics(checker, resp);
                    HealthResultEntry::new(
                        checker.name().to_owned(),
                        resp.health().to_owned(),
                        resp.output().to_owned(),
                        resp.action().map(str::to_string),
                        resp.impact().map(str::to_string),
                    )
                })
                .collect(),
        );

        // Finds the highest enum value in the list of checker responses
        health_result.health = match health_result
            .checks
            .iter()
            .max_by(|x, y| x.health.cmp(&y.health))
        {
            Some(status) => status.health,
            None => Health::Unhealthy,
        };

        Some(health_result)
    }
}

struct Owner {
    name: String,
    slack: String,
}

impl Owner {
    fn new(name: &str, slack: &str) -> Self {
        Self {
            name: name.to_owned(),
            slack: slack.to_owned(),
        }
    }

    pub(crate) fn to_json(&self) -> Value {
        json!({
            "name": self.name,
            "slack": self.slack,
        })
    }
}

struct Link {
    description: String,
    url: String,
}

impl Link {
    fn new(description: &str, url: &str) -> Self {
        Self {
            description: description.to_owned(),
            url: url.to_owned(),
        }
    }

    pub(crate) fn to_json(&self) -> Value {
        json!({
            "description": self.description,
            "url": self.url,
        })
    }
}