darkwing/server/services/
status_services.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
71
72
73
74
75
76
77
78
79
80
81
82
83
use anyhow::Context;
use mockall::automock;
use redis::Commands;
use sqlx::query;
use std::sync::Arc;
use tracing::info;

use async_trait::async_trait;

use crate::{
  cache::Cache,
  config::DarkwingConfig,
  database::Database,
  server::{
    dtos::health_dto::{DatabaseStatus, HealthResponse, ServiceStatuses},
    error::AppResult,
  },
};

/// A reference counter for our status service allows us to safely pass
/// instances around which depend on the database, and ultimately, our
/// connection pools.
pub type DynStatusService = Arc<dyn StatusServiceTrait + Send + Sync>;

#[automock]
#[async_trait]
pub trait StatusServiceTrait {
  async fn get_health_status(
    &self,
    s3_status: ServiceStatuses,
  ) -> AppResult<HealthResponse>;
}

#[derive(Clone)]
pub struct StatusService {
  config: Arc<DarkwingConfig>,
  database: Arc<Database>,
  cache: Arc<Cache>,
}

impl StatusService {
  pub fn new(
    database: Arc<Database>,
    cache: Arc<Cache>,
    config: Arc<DarkwingConfig>,
  ) -> Self {
    Self {
      database,
      cache,
      config,
    }
  }
}

#[async_trait]
impl StatusServiceTrait for StatusService {
  async fn get_health_status(
    &self,
    s3_status: ServiceStatuses,
  ) -> AppResult<HealthResponse> {
    info!("Checking health status");

    let main_mysql = query("SELECT true")
      .fetch_one(&self.database.pool)
      .await
      .is_ok();

    let redis_cache = self
      .cache
      .pool
      .get_timeout(self.config.redis_timeout())
      .context("Failed to get Redis connection")?
      .set::<_, _, ()>("StatusServiceTest", "test")
      .is_ok();

    let db_status = DatabaseStatus {
      main_mysql,
      redis_cache,
    };

    Ok(HealthResponse::new(Some(db_status), Some(s3_status)))
  }
}