1
//! Database pool series: the connection gauges and the acquire-failure counter.
2

            
3
use super::recorder::{DB_POOL_ACQUIRE_FAILURES, DB_POOL_CONNECTIONS};
4
use sqlx::PgPool;
5
use std::ops::Add;
6
use tokio::time::{Duration, MissedTickBehavior, interval};
7

            
8
const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
9

            
10
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11
pub enum PoolKind {
12
    Admin,
13
    Tenant,
14
}
15

            
16
impl PoolKind {
17
    #[must_use]
18
389
    pub const fn as_str(self) -> &'static str {
19
389
        match self {
20
374
            Self::Admin => "admin",
21
15
            Self::Tenant => "tenant",
22
        }
23
389
    }
24
}
25

            
26
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27
pub enum AcquireFailure {
28
    Timeout,
29
    Residency,
30
}
31

            
32
impl AcquireFailure {
33
    #[must_use]
34
373
    pub const fn as_str(self) -> &'static str {
35
373
        match self {
36
369
            Self::Timeout => "timeout",
37
4
            Self::Residency => "residency",
38
        }
39
373
    }
40
}
41

            
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
enum ConnectionState {
44
    Idle,
45
    Used,
46
}
47

            
48
impl ConnectionState {
49
16
    const fn as_str(self) -> &'static str {
50
16
        match self {
51
8
            Self::Idle => "idle",
52
8
            Self::Used => "used",
53
        }
54
16
    }
55
}
56

            
57
/// Open and idle connections of one pool, or the sum over several.
58
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59
pub struct PoolUsage {
60
    open: usize,
61
    idle: usize,
62
}
63

            
64
impl PoolUsage {
65
    #[must_use]
66
6
    pub fn of(pool: &PgPool) -> Self {
67
6
        Self {
68
6
            open: pool.size() as usize,
69
6
            idle: pool.num_idle(),
70
6
        }
71
6
    }
72

            
73
8
    const fn used(self) -> usize {
74
8
        self.open.saturating_sub(self.idle)
75
8
    }
76
}
77

            
78
impl Add for PoolUsage {
79
    type Output = Self;
80

            
81
3
    fn add(self, other: Self) -> Self {
82
3
        Self {
83
3
            open: self.open + other.open,
84
3
            idle: self.idle + other.idle,
85
3
        }
86
3
    }
87
}
88

            
89
/// Sets both state gauges of `pool` from `usage`.
90
8
pub fn record_connections(pool: PoolKind, usage: PoolUsage) {
91
8
    for (state, count) in [
92
8
        (ConnectionState::Idle, usage.idle),
93
8
        (ConnectionState::Used, usage.used()),
94
8
    ] {
95
16
        metrics::gauge!(
96
16
            DB_POOL_CONNECTIONS,
97
16
            "pool" => pool.as_str(),
98
16
            "state" => state.as_str()
99
16
        )
100
16
        .set(count as f64);
101
    }
102
8
}
103

            
104
371
pub fn record_acquire_failure(pool: PoolKind, reason: AcquireFailure) {
105
371
    metrics::counter!(
106
371
        DB_POOL_ACQUIRE_FAILURES,
107
371
        "pool" => pool.as_str(),
108
371
        "reason" => reason.as_str()
109
371
    )
110
371
    .increment(1);
111
371
}
112

            
113
/// Counts a failed acquisition; only a pool timeout is a pool failure.
114
1452
pub fn record_acquire_error(pool: PoolKind, error: &sqlx::Error) {
115
1452
    if matches!(error, sqlx::Error::PoolTimedOut) {
116
368
        record_acquire_failure(pool, AcquireFailure::Timeout);
117
1084
    }
118
1452
}
119

            
120
/// Publishes the live pools; a tenant pool that left the registry no longer counts.
121
3
pub fn sample_pools() {
122
3
    if let Some(usage) = crate::db::admin_usage() {
123
3
        record_connections(PoolKind::Admin, usage);
124
    }
125
3
    record_connections(PoolKind::Tenant, crate::user::tenant_usage());
126
3
}
127

            
128
/// Samples every 15 s until the process, and so the task, ends.
129
1
pub async fn run_pool_sampler() {
130
1
    let mut ticks = interval(SAMPLE_INTERVAL);
131
1
    ticks.set_missed_tick_behavior(MissedTickBehavior::Skip);
132
    loop {
133
3
        ticks.tick().await;
134
2
        sample_pools();
135
    }
136
}