1
use sqlx::postgres::PgPoolOptions;
2
use sqlx::{Connection, PgPool};
3
use std::sync::atomic::{AtomicUsize, Ordering};
4
use std::sync::{Arc, Mutex};
5
use std::time::Duration;
6

            
7
/// A pool of one connection whose returned checkouts are counted, with an
8
/// acquire timeout only a real deadlock reaches.
9
pub struct CountingPool {
10
    pub pool: PgPool,
11
    releases: Arc<AtomicUsize>,
12
}
13

            
14
impl CountingPool {
15
2
    pub async fn single(like: &PgPool) -> Result<Self, sqlx::Error> {
16
2
        let releases = Arc::new(AtomicUsize::new(0));
17
2
        let counter = releases.clone();
18
2
        let pool = PgPoolOptions::new()
19
2
            .max_connections(1)
20
2
            .acquire_timeout(Duration::from_secs(60))
21
5
            .after_release(move |_, _| {
22
5
                counter.fetch_add(1, Ordering::SeqCst);
23
5
                Box::pin(async { Ok(true) })
24
5
            })
25
2
            .connect_with((*like.connect_options()).clone())
26
2
            .await?;
27
2
        Ok(Self { pool, releases })
28
2
    }
29

            
30
    /// Connections returned so far. The probe acquire waits for any release
31
    /// still in flight and is closed without being returned, so it is not
32
    /// counted.
33
3
    pub async fn checkouts(&self) -> Result<usize, sqlx::Error> {
34
3
        self.pool.acquire().await?.detach().close().await?;
35
3
        Ok(self.releases.load(Ordering::SeqCst))
36
3
    }
37
}
38

            
39
/// Records how many connections the pool had taken back whenever an ERROR
40
/// was logged, without touching the database.
41
#[derive(Clone)]
42
pub struct ErrorMarks {
43
    releases: Arc<AtomicUsize>,
44
    marks: Arc<Mutex<Vec<usize>>>,
45
}
46

            
47
impl std::io::Write for ErrorMarks {
48
1
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
49
1
        if let Ok(mut marks) = self.marks.lock()
50
1
            && String::from_utf8_lossy(bytes).contains("ERROR")
51
        {
52
1
            marks.push(self.releases.load(Ordering::SeqCst));
53
        }
54
1
        Ok(bytes.len())
55
1
    }
56

            
57
    fn flush(&mut self) -> std::io::Result<()> {
58
        Ok(())
59
    }
60
}
61

            
62
impl ErrorMarks {
63
1
    pub fn of(pool: &CountingPool) -> Self {
64
1
        Self {
65
1
            releases: pool.releases.clone(),
66
1
            marks: Arc::default(),
67
1
        }
68
1
    }
69

            
70
1
    pub fn marks(&self) -> Vec<usize> {
71
1
        self.marks.lock().map(|m| m.clone()).unwrap_or_default()
72
1
    }
73

            
74
1
    pub fn subscriber(&self) -> impl tracing::Subscriber + Send + Sync + 'static {
75
1
        let writer = self.clone();
76
1
        tracing_subscriber::fmt()
77
1
            .with_writer(move || writer.clone())
78
            .finish()
79
1
    }
80
}