Lines
98.48 %
Functions
66.67 %
Branches
100 %
//! Database pool series: the connection gauges and the acquire-failure counter.
use super::recorder::{DB_POOL_ACQUIRE_FAILURES, DB_POOL_CONNECTIONS};
use sqlx::PgPool;
use std::ops::Add;
use tokio::time::{Duration, MissedTickBehavior, interval};
const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolKind {
Admin,
Tenant,
}
impl PoolKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Admin => "admin",
Self::Tenant => "tenant",
pub enum AcquireFailure {
Timeout,
Residency,
impl AcquireFailure {
Self::Timeout => "timeout",
Self::Residency => "residency",
enum ConnectionState {
Idle,
Used,
impl ConnectionState {
const fn as_str(self) -> &'static str {
Self::Idle => "idle",
Self::Used => "used",
/// Open and idle connections of one pool, or the sum over several.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PoolUsage {
open: usize,
idle: usize,
impl PoolUsage {
pub fn of(pool: &PgPool) -> Self {
Self {
open: pool.size() as usize,
idle: pool.num_idle(),
const fn used(self) -> usize {
self.open.saturating_sub(self.idle)
impl Add for PoolUsage {
type Output = Self;
fn add(self, other: Self) -> Self {
open: self.open + other.open,
idle: self.idle + other.idle,
/// Sets both state gauges of `pool` from `usage`.
pub fn record_connections(pool: PoolKind, usage: PoolUsage) {
for (state, count) in [
(ConnectionState::Idle, usage.idle),
(ConnectionState::Used, usage.used()),
] {
metrics::gauge!(
DB_POOL_CONNECTIONS,
"pool" => pool.as_str(),
"state" => state.as_str()
)
.set(count as f64);
pub fn record_acquire_failure(pool: PoolKind, reason: AcquireFailure) {
metrics::counter!(
DB_POOL_ACQUIRE_FAILURES,
"reason" => reason.as_str()
.increment(1);
/// Counts a failed acquisition; only a pool timeout is a pool failure.
pub fn record_acquire_error(pool: PoolKind, error: &sqlx::Error) {
if matches!(error, sqlx::Error::PoolTimedOut) {
record_acquire_failure(pool, AcquireFailure::Timeout);
/// Publishes the live pools; a tenant pool that left the registry no longer counts.
pub fn sample_pools() {
if let Some(usage) = crate::db::admin_usage() {
record_connections(PoolKind::Admin, usage);
record_connections(PoolKind::Tenant, crate::user::tenant_usage());
/// Samples every 15 s until the process, and so the task, ends.
pub async fn run_pool_sampler() {
let mut ticks = interval(SAMPLE_INTERVAL);
ticks.set_missed_tick_behavior(MissedTickBehavior::Skip);
loop {
ticks.tick().await;
sample_pools();