Skip to main content

datumesh_store/
pool.rs

1//! A small connection pool: no global state, no background threads, and a per-connection
2//! cache of prepared statements (each statement is prepared once per connection, on first
3//! use, never when connecting).
4
5use std::collections::HashMap;
6use std::ops::{Deref, DerefMut};
7use std::sync::{Condvar, Mutex, MutexGuard};
8use std::time::{Duration, Instant};
9
10use postgres::{Client, Statement};
11use rustls::pki_types::pem::PemObject;
12use rustls::pki_types::CertificateDer;
13use rustls::RootCertStore;
14
15use crate::error::{Db, Error, Result};
16use crate::sql::Q;
17
18/// Opens a new connection.
19pub(crate) type Connector = Box<dyn Fn() -> core::result::Result<Client, postgres::Error> + Send + Sync>;
20
21/// A recording clock, compared by identity (the options derive their equality; a clock has none of its own).
22#[derive(Clone)]
23pub(crate) struct ClockRef(pub(crate) crate::RecordingClock);
24
25impl PartialEq for ClockRef {
26    fn eq(&self, other: &ClockRef) -> bool {
27        std::sync::Arc::ptr_eq(&self.0, &other.0)
28    }
29}
30
31impl Eq for ClockRef {}
32
33/// How the pool behaves, and the roots TLS connections are verified against.
34///
35/// Builder style: `PoolOptions::new().max_size(4).tls_root_certificates_pem(&pem)?`.
36#[derive(Clone, PartialEq, Eq)]
37pub struct PoolOptions {
38    max_size: usize,
39    checkout_timeout: Duration,
40    pub(crate) webpki_roots: bool,
41    pub(crate) tls_roots: Vec<CertificateDer<'static>>,
42    pub(crate) recording_clock: Option<ClockRef>,
43    /// How long the barrier waits for a version writer in flight (decided 27 Nov, B2/B3).
44    pub(crate) barrier_timeout: Duration,
45}
46
47impl std::fmt::Debug for PoolOptions {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_struct("PoolOptions")
50            .field("max_size", &self.max_size)
51            .field("checkout_timeout", &self.checkout_timeout)
52            .field("webpki_roots", &self.webpki_roots)
53            .field("tls_root_certificates", &self.tls_roots.len())
54            .field("recording_clock", &self.recording_clock.is_some())
55            .field("barrier_timeout", &self.barrier_timeout)
56            .finish()
57    }
58}
59
60impl Default for PoolOptions {
61    fn default() -> PoolOptions {
62        PoolOptions::new()
63    }
64}
65
66impl PoolOptions {
67    /// At most 8 connections; wait at most 30 seconds for one; TLS connections verified
68    /// against the Mozilla roots (`webpki-roots`).
69    pub fn new() -> PoolOptions {
70        PoolOptions {
71            max_size: 8,
72            checkout_timeout: Duration::from_secs(30),
73            webpki_roots: true,
74            tls_roots: Vec::new(),
75            recording_clock: None,
76            barrier_timeout: Duration::from_secs(5),
77        }
78    }
79
80    /// How long a barrier ([`Store::barrier`](crate::Store::barrier)) waits for a version writer in flight
81    /// before it fails with [`Error::Timeout`](crate::Error::Timeout) (the http layer answers 503). Default
82    /// 5 s. On PostgreSQL the barrier is one statement under `lock_timeout` of this value. Since 0.6.5.
83    pub fn barrier_timeout(mut self, d: Duration) -> PoolOptions {
84        self.barrier_timeout = d;
85        self
86    }
87
88    /// The clock the store records its versions at (G9, [`RecordingClock`](crate::RecordingClock)): read at each insert,
89    /// `recorded = max(signed tx, clock())`. Without one a version is recorded at its signed tx.
90    /// Since 0.6.5.
91    pub fn recording_clock(mut self, clock: crate::RecordingClock) -> PoolOptions {
92        self.recording_clock = Some(ClockRef(clock));
93        self
94    }
95
96    /// The most connections open at once (at least 1).
97    pub fn max_size(mut self, n: usize) -> PoolOptions {
98        self.max_size = n.max(1);
99        self
100    }
101
102    /// How long a call waits for a free connection before failing with
103    /// [`Error::PoolTimeout`] (reads: `None`).
104    pub fn checkout_timeout(mut self, d: Duration) -> PoolOptions {
105        self.checkout_timeout = d;
106        self
107    }
108
109    /// Adds the certificates of a PEM bundle (one or more `CERTIFICATE` sections; other
110    /// sections are ignored) to the roots TLS connections are verified against: a private
111    /// CA, or a server's self-signed certificate. Calls append. A bundle with no
112    /// certificate, or with one that does not parse, is [`Error::Config`].
113    pub fn tls_root_certificates_pem(mut self, pem: &[u8]) -> Result<PoolOptions> {
114        let mut check = RootCertStore::empty();
115        let mut n = 0;
116        for cert in CertificateDer::pem_slice_iter(pem) {
117            n += 1;
118            let cert = cert.map_err(|e| Error::Config(format!("root certificate {n} of the PEM bundle: {e}")))?;
119            check
120                .add(cert.clone())
121                .map_err(|e| Error::Config(format!("root certificate {n} of the PEM bundle: {e}")))?;
122            self.tls_roots.push(cert);
123        }
124        if n == 0 {
125            return Err(Error::Config("the PEM bundle holds no certificate".into()));
126        }
127        Ok(self)
128    }
129
130    /// Whether the Mozilla roots (`webpki-roots`, compiled in) are trusted too: yes by
131    /// default. `false` trusts only the roots added with
132    /// [`tls_root_certificates_pem`](Self::tls_root_certificates_pem) (a private CA).
133    pub fn tls_webpki_roots(mut self, yes: bool) -> PoolOptions {
134        self.webpki_roots = yes;
135        self
136    }
137}
138
139/// A connection and the statements prepared on it.
140pub(crate) struct Conn {
141    pub(crate) client: Client,
142    statements: HashMap<Q, Statement>,
143}
144
145impl Conn {
146    /// The prepared statement for `q`, preparing it on first use.
147    pub(crate) fn stmt(&mut self, q: Q) -> Result<Statement> {
148        if let Some(s) = self.statements.get(&q) {
149            return Ok(s.clone());
150        }
151        let s = self.client.prepare_typed(q.sql(), q.types()).db()?;
152        self.statements.insert(q, s.clone());
153        Ok(s)
154    }
155}
156
157struct State {
158    idle: Vec<Conn>,
159    open: usize,
160}
161
162pub(crate) struct Pool {
163    connect: Connector,
164    state: Mutex<State>,
165    freed: Condvar,
166    options: PoolOptions,
167}
168
169/// Settings every connection gets: the append-only triggers rely on READ COMMITTED.
170const SESSION: &str = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL READ COMMITTED; \
171                       SET TIME ZONE 'UTC'; SET DateStyle = 'ISO, YMD'";
172
173impl Pool {
174    pub(crate) fn new(connect: Connector, options: PoolOptions) -> Pool {
175        Pool { connect, state: Mutex::new(State { idle: Vec::new(), open: 0 }), freed: Condvar::new(), options }
176    }
177
178    fn lock(&self) -> MutexGuard<'_, State> {
179        // A panic while holding the lock cannot leave State inconsistent (two fields, each
180        // updated in one step), so a poisoned lock is still usable.
181        self.state.lock().unwrap_or_else(|e| e.into_inner())
182    }
183
184    /// A free connection, a new one if fewer than `max_size` are open, or one freed within
185    /// the checkout timeout.
186    pub(crate) fn get(&self) -> Result<Pooled<'_>> {
187        let deadline = Instant::now() + self.options.checkout_timeout;
188        let mut state = self.lock();
189        loop {
190            while let Some(conn) = state.idle.pop() {
191                if conn.client.is_closed() {
192                    state.open -= 1;
193                    close_detached(vec![conn]);
194                    continue;
195                }
196                return Ok(Pooled { pool: self, conn: Some(conn) });
197            }
198            if state.open < self.options.max_size {
199                state.open += 1;
200                drop(state);
201                return match self.open() {
202                    Ok(conn) => Ok(Pooled { pool: self, conn: Some(conn) }),
203                    Err(e) => {
204                        self.lock().open -= 1;
205                        self.freed.notify_one();
206                        Err(e)
207                    }
208                };
209            }
210            let now = Instant::now();
211            if now >= deadline {
212                return Err(Error::PoolTimeout);
213            }
214            state = self.freed.wait_timeout(state, deadline - now).unwrap_or_else(|e| e.into_inner()).0;
215        }
216    }
217
218    fn open(&self) -> Result<Conn> {
219        let mut client = (self.connect)().db()?;
220        client.batch_execute(SESSION).db()?;
221        Ok(Conn { client, statements: HashMap::new() })
222    }
223
224    fn put_back(&self, conn: Conn) {
225        let mut state = self.lock();
226        if conn.client.is_closed() {
227            state.open -= 1;
228            close_detached(vec![conn]);
229        } else {
230            state.idle.push(conn);
231        }
232        drop(state);
233        self.freed.notify_one();
234    }
235}
236
237/// Drops connections on a thread of their own, which nobody joins. A sync client runs a
238/// runtime of its own, and dropping a runtime on a thread that is inside another runtime (an
239/// async task, a `block_on`) panics: so a store dropped there, or a connection the pool
240/// discards there, is closed off the calling thread. If the thread cannot be started, the
241/// connections are dropped on the calling thread (the only case where that happens).
242pub(crate) fn close_detached(conns: Vec<Conn>) {
243    if conns.is_empty() {
244        return;
245    }
246    let spawned = std::thread::Builder::new().name("datumesh-store-close".into()).spawn(move || drop(conns));
247    if let Err(e) = spawned {
248        tracing::warn!(target: "datumesh_store", error = %e, "no thread to close connections on");
249    }
250}
251
252impl Drop for Pool {
253    fn drop(&mut self) {
254        // Nothing is checked out (a Pooled borrows the pool), so every connection is idle.
255        let idle = std::mem::take(&mut self.state.get_mut().unwrap_or_else(|e| e.into_inner()).idle);
256        close_detached(idle);
257    }
258}
259
260/// A connection checked out of the pool; returned to it when dropped (or discarded if the
261/// server closed it).
262pub(crate) struct Pooled<'a> {
263    pool: &'a Pool,
264    conn: Option<Conn>,
265}
266
267impl Deref for Pooled<'_> {
268    type Target = Conn;
269    fn deref(&self) -> &Conn {
270        // Some from creation until drop.
271        self.conn.as_ref().expect("connection present until drop")
272    }
273}
274
275impl DerefMut for Pooled<'_> {
276    fn deref_mut(&mut self) -> &mut Conn {
277        self.conn.as_mut().expect("connection present until drop")
278    }
279}
280
281impl Drop for Pooled<'_> {
282    fn drop(&mut self) {
283        if let Some(conn) = self.conn.take() {
284            self.pool.put_back(conn);
285        }
286    }
287}