Skip to main content

server/telemetry/
pools.rs

1//! Database pool series: the connection gauges and the acquire-failure counter.
2
3use super::recorder::{DB_POOL_ACQUIRE_FAILURES, DB_POOL_CONNECTIONS};
4use sqlx::PgPool;
5use std::ops::Add;
6use tokio::time::{Duration, MissedTickBehavior, interval};
7
8const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum PoolKind {
12    Admin,
13    Tenant,
14}
15
16impl PoolKind {
17    #[must_use]
18    pub const fn as_str(self) -> &'static str {
19        match self {
20            Self::Admin => "admin",
21            Self::Tenant => "tenant",
22        }
23    }
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum AcquireFailure {
28    Timeout,
29    Residency,
30}
31
32impl AcquireFailure {
33    #[must_use]
34    pub const fn as_str(self) -> &'static str {
35        match self {
36            Self::Timeout => "timeout",
37            Self::Residency => "residency",
38        }
39    }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43enum ConnectionState {
44    Idle,
45    Used,
46}
47
48impl ConnectionState {
49    const fn as_str(self) -> &'static str {
50        match self {
51            Self::Idle => "idle",
52            Self::Used => "used",
53        }
54    }
55}
56
57/// Open and idle connections of one pool, or the sum over several.
58#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
59pub struct PoolUsage {
60    open: usize,
61    idle: usize,
62}
63
64impl PoolUsage {
65    #[must_use]
66    pub fn of(pool: &PgPool) -> Self {
67        Self {
68            open: pool.size() as usize,
69            idle: pool.num_idle(),
70        }
71    }
72
73    const fn used(self) -> usize {
74        self.open.saturating_sub(self.idle)
75    }
76}
77
78impl Add for PoolUsage {
79    type Output = Self;
80
81    fn add(self, other: Self) -> Self {
82        Self {
83            open: self.open + other.open,
84            idle: self.idle + other.idle,
85        }
86    }
87}
88
89/// Sets both state gauges of `pool` from `usage`.
90pub fn record_connections(pool: PoolKind, usage: PoolUsage) {
91    for (state, count) in [
92        (ConnectionState::Idle, usage.idle),
93        (ConnectionState::Used, usage.used()),
94    ] {
95        metrics::gauge!(
96            DB_POOL_CONNECTIONS,
97            "pool" => pool.as_str(),
98            "state" => state.as_str()
99        )
100        .set(count as f64);
101    }
102}
103
104pub fn record_acquire_failure(pool: PoolKind, reason: AcquireFailure) {
105    metrics::counter!(
106        DB_POOL_ACQUIRE_FAILURES,
107        "pool" => pool.as_str(),
108        "reason" => reason.as_str()
109    )
110    .increment(1);
111}
112
113/// Counts a failed acquisition; only a pool timeout is a pool failure.
114pub fn record_acquire_error(pool: PoolKind, error: &sqlx::Error) {
115    if matches!(error, sqlx::Error::PoolTimedOut) {
116        record_acquire_failure(pool, AcquireFailure::Timeout);
117    }
118}
119
120/// Publishes the live pools; a tenant pool that left the registry no longer counts.
121pub fn sample_pools() {
122    if let Some(usage) = crate::db::admin_usage() {
123        record_connections(PoolKind::Admin, usage);
124    }
125    record_connections(PoolKind::Tenant, crate::user::tenant_usage());
126}
127
128/// Samples every 15 s until the process, and so the task, ends.
129pub async fn run_pool_sampler() {
130    let mut ticks = interval(SAMPLE_INTERVAL);
131    ticks.set_missed_tick_behavior(MissedTickBehavior::Skip);
132    loop {
133        ticks.tick().await;
134        sample_pools();
135    }
136}