Lines
90.48 %
Functions
92.31 %
Branches
100 %
use sqlx::postgres::PgPoolOptions;
use sqlx::{Connection, PgPool};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
/// A pool of one connection whose returned checkouts are counted, with an
/// acquire timeout only a real deadlock reaches.
pub struct CountingPool {
pub pool: PgPool,
releases: Arc<AtomicUsize>,
}
impl CountingPool {
pub async fn single(like: &PgPool) -> Result<Self, sqlx::Error> {
let releases = Arc::new(AtomicUsize::new(0));
let counter = releases.clone();
let pool = PgPoolOptions::new()
.max_connections(1)
.acquire_timeout(Duration::from_secs(60))
.after_release(move |_, _| {
counter.fetch_add(1, Ordering::SeqCst);
Box::pin(async { Ok(true) })
})
.connect_with((*like.connect_options()).clone())
.await?;
Ok(Self { pool, releases })
/// Connections returned so far. The probe acquire waits for any release
/// still in flight and is closed without being returned, so it is not
/// counted.
pub async fn checkouts(&self) -> Result<usize, sqlx::Error> {
self.pool.acquire().await?.detach().close().await?;
Ok(self.releases.load(Ordering::SeqCst))
/// Records how many connections the pool had taken back whenever an ERROR
/// was logged, without touching the database.
#[derive(Clone)]
pub struct ErrorMarks {
marks: Arc<Mutex<Vec<usize>>>,
impl std::io::Write for ErrorMarks {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
if let Ok(mut marks) = self.marks.lock()
&& String::from_utf8_lossy(bytes).contains("ERROR")
{
marks.push(self.releases.load(Ordering::SeqCst));
Ok(bytes.len())
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
impl ErrorMarks {
pub fn of(pool: &CountingPool) -> Self {
Self {
releases: pool.releases.clone(),
marks: Arc::default(),
pub fn marks(&self) -> Vec<usize> {
self.marks.lock().map(|m| m.clone()).unwrap_or_default()
pub fn subscriber(&self) -> impl tracing::Subscriber + Send + Sync + 'static {
let writer = self.clone();
tracing_subscriber::fmt()
.with_writer(move || writer.clone())
.finish()