Skip to main content

snodra_messaging_sqlx/
store.rs

1//! [`SqlxStore`]: the stores together, their transactions, and [`SqlxTxExt`].
2
3use std::sync::{Arc, RwLock};
4
5use futures::future::BoxFuture;
6use snodra_messaging::Config;
7use snodra_messaging::saga::Clock;
8use snodra_messaging::store::{
9    DeadLetterStore, ExternalCallStore, MessageStore, OutboxStore, ProcessedEventStore,
10    ProcessorControlStore, SagaStores, StoreError, Tx, TxProvider,
11};
12use tokio_util::sync::CancellationToken;
13
14#[cfg(feature = "mysql")]
15use sqlx::mysql::{MySql, MySqlPool};
16#[cfg(feature = "postgres")]
17use sqlx::postgres::{PgPool, Postgres};
18
19use crate::SqlxSettings;
20use crate::db::{Db, Held, Pool};
21
22/// The SQL message store: see the crate docs. Every clone is the same store.
23#[derive(Clone)]
24pub struct SqlxStore {
25    inner: Arc<Inner>,
26}
27
28struct Inner {
29    db: Arc<Db>,
30    settings: SqlxSettings,
31    clock: Arc<RwLock<Clock>>,
32    outbox: Arc<crate::outbox::SqlOutboxStore>,
33    processed: Arc<crate::outbox::SqlProcessedEventStore>,
34    dead_letters: Arc<crate::dead_letters::SqlDeadLetterStore>,
35    control: Arc<crate::control::SqlProcessorControlStore>,
36    external: Arc<crate::external::SqlExternalCallStore>,
37    sagas: Arc<crate::sagas::SqlSagaStore>,
38}
39
40impl std::fmt::Debug for SqlxStore {
41    /// The dialect and the settings: never the pool's connect options (they hold the password).
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        f.debug_struct("SqlxStore")
44            .field("dialect", &self.inner.db.dialect().name())
45            .field("settings", &self.inner.settings)
46            .finish()
47    }
48}
49
50impl SqlxStore {
51    /// The store on a PostgreSQL pool (at least 2 connections), with the default settings.
52    #[cfg(feature = "postgres")]
53    pub fn postgres(pool: PgPool) -> SqlxStore {
54        Self::build(Pool::Pg(pool), SqlxSettings::default())
55    }
56
57    /// The store on a MySQL pool (at least 2 connections), with the default settings.
58    #[cfg(feature = "mysql")]
59    pub fn mysql(pool: MySqlPool) -> SqlxStore {
60        Self::build(Pool::My(pool), SqlxSettings::default())
61    }
62
63    /// The same store with `settings` (e.g. [`SqlxSettings::from_env`]).
64    pub fn with_settings(self, settings: SqlxSettings) -> SqlxStore {
65        let clock = self
66            .inner
67            .clock
68            .read()
69            .unwrap_or_else(|p| p.into_inner())
70            .clone();
71        let store = Self::build(self.inner.db.pool.clone(), settings);
72        store.use_clock(clock);
73        store
74    }
75
76    fn build(pool: Pool, settings: SqlxSettings) -> SqlxStore {
77        let clock = Arc::new(RwLock::new(Clock::system()));
78        let db = Arc::new(Db::new(pool, Arc::clone(&clock)));
79        SqlxStore {
80            inner: Arc::new(Inner {
81                outbox: Arc::new(crate::outbox::SqlOutboxStore::new(
82                    Arc::clone(&db),
83                    settings.notify,
84                )),
85                processed: Arc::new(crate::outbox::SqlProcessedEventStore::new(Arc::clone(&db))),
86                dead_letters: Arc::new(crate::dead_letters::SqlDeadLetterStore::new(Arc::clone(
87                    &db,
88                ))),
89                control: Arc::new(crate::control::SqlProcessorControlStore::new(Arc::clone(
90                    &db,
91                ))),
92                external: Arc::new(crate::external::SqlExternalCallStore::new(Arc::clone(&db))),
93                sagas: Arc::new(crate::sagas::SqlSagaStore::new(Arc::clone(&db))),
94                db,
95                settings,
96                clock,
97            }),
98        }
99    }
100
101    /// The store's settings.
102    pub fn settings(&self) -> &SqlxSettings {
103        &self.inner.settings
104    }
105
106    /// Checks the server and applies schema version 1 unless the database has it: what
107    /// [`MessageStore::init_schema`] does.
108    pub async fn apply_schema(&self) -> Result<(), StoreError> {
109        crate::schema::verify(&self.inner.db.pool).await?;
110        crate::schema::apply(&self.inner.db.pool, self.inner.db.dialect()).await
111    }
112
113    /// For a service that applies the schema itself: checks the server, and fails unless the
114    /// database has the schema version this library needs, or later.
115    pub async fn require_schema(&self) -> Result<(), StoreError> {
116        crate::schema::verify(&self.inner.db.pool).await?;
117        crate::schema::require(&self.inner.db.pool, self.inner.db.dialect()).await
118    }
119
120    /// Deletes what the retentions of `config` let go, the expired dead letters and the dispatch
121    /// leases that passed, in batches of 1000 (each its own transaction); how many rows went. The
122    /// background task of [`MessageStore::background`] runs it every
123    /// [`SqlxSettings::purge_interval`].
124    pub async fn purge_expired(&self, config: &Config) -> Result<u64, StoreError> {
125        crate::purge::run(&self.inner.db, config).await
126    }
127
128    /// How many times the relay wake-up established `LISTEN snodra_outbox` and woke the relays
129    /// (tests: a NOTIFY committed after this grew reaches the listener).
130    #[doc(hidden)]
131    pub fn listens(&self) -> u64 {
132        self.inner.outbox.listens()
133    }
134}
135
136impl MessageStore for SqlxStore {
137    fn name(&self) -> &'static str {
138        match self.inner.db.dialect() {
139            #[cfg(feature = "postgres")]
140            crate::db::Dialect::Postgres => "postgres",
141            #[cfg(feature = "mysql")]
142            crate::db::Dialect::MySql => "mysql",
143        }
144    }
145
146    /// The server checked, then schema version 1 applied unless the database has it.
147    fn init_schema<'a>(&'a self, _config: &'a Config) -> BoxFuture<'a, Result<(), StoreError>> {
148        Box::pin(self.apply_schema())
149    }
150
151    /// The server checked, and the schema at version 1 or later.
152    fn check_schema(&self) -> BoxFuture<'_, Result<(), StoreError>> {
153        Box::pin(self.require_schema())
154    }
155
156    /// The purge every [`SqlxSettings::purge_interval`] (none when it is zero).
157    fn background(
158        &self,
159        config: &Config,
160        stop: CancellationToken,
161    ) -> Option<BoxFuture<'static, ()>> {
162        let interval = self.inner.settings.purge_interval;
163        if interval.is_zero() {
164            return None;
165        }
166        let (store, config) = (self.clone(), config.clone());
167        Some(Box::pin(async move {
168            loop {
169                tokio::select! {
170                    _ = stop.cancelled() => return,
171                    _ = tokio::time::sleep(interval) => {}
172                }
173                match store.purge_expired(&config).await {
174                    Ok(0) => {}
175                    Ok(n) => tracing::debug!(rows = n, "purged the message store"),
176                    Err(e) => tracing::warn!(
177                        "the message store purge failed (retried at the next interval): {e}"
178                    ),
179                }
180            }
181        }))
182    }
183
184    fn use_clock(&self, clock: Clock) {
185        *self
186            .inner
187            .clock
188            .write()
189            .unwrap_or_else(|poisoned| poisoned.into_inner()) = clock;
190    }
191
192    fn tx(&self) -> Arc<dyn TxProvider> {
193        Arc::new(SqlTx {
194            db: Arc::clone(&self.inner.db),
195        })
196    }
197
198    fn outbox(&self) -> Arc<dyn OutboxStore> {
199        self.inner.outbox.clone()
200    }
201
202    fn processed_events(&self) -> Arc<dyn ProcessedEventStore> {
203        self.inner.processed.clone()
204    }
205
206    fn dead_letters(&self) -> Arc<dyn DeadLetterStore> {
207        self.inner.dead_letters.clone()
208    }
209
210    fn processor_control(&self) -> Arc<dyn ProcessorControlStore> {
211        self.inner.control.clone()
212    }
213
214    fn external_calls(&self) -> Arc<dyn ExternalCallStore> {
215        self.inner.external.clone()
216    }
217
218    fn sagas(&self) -> SagaStores {
219        let sagas = &self.inner.sagas;
220        SagaStores {
221            sagas: sagas.clone(),
222            dispatch: sagas.clone(),
223            deadlines: sagas.clone(),
224            failures: sagas.clone(),
225            markers: sagas.clone(),
226        }
227    }
228}
229
230/// The connection of a [`Tx`] of the SQL store, in its transaction, for a handler's own writes in
231/// the transaction of the message it handles:
232///
233/// ```ignore
234/// let mut tx = ctx.tx.lock().await;
235/// sqlx::query("INSERT INTO orders (id) VALUES ($1)")
236///     .bind(&order.id)
237///     .execute(tx.connection::<sqlx::Postgres>())
238///     .await?;
239/// ```
240///
241/// The transaction is the store's (`TxProvider::begin`, `commit`, `abort`): never run `BEGIN`,
242/// `COMMIT` or `ROLLBACK` on the connection by raw SQL. A nested transaction through sqlx
243/// (`connection.begin()`, `Connection::transaction`) is a savepoint of the store's transaction:
244/// nothing commits before the store's commit, and one left open fails it. Do not change the
245/// session either (`SET`, `LISTEN`, advisory locks): the connection goes back to the pool.
246///
247/// Return a statement's error rather than going on: on PostgreSQL a failed statement aborts the
248/// whole transaction, and the store's commit then fails (nothing of it is committed); on MySQL a
249/// failed statement is undone alone, but a deadlock rolls the whole transaction back unseen
250/// (see the crate README, "Transactions").
251pub trait SqlxTxExt {
252    /// The connection.
253    ///
254    /// # Panics
255    ///
256    /// When the transaction is not an open one of the SQL store on `DB` (another store's,
257    /// [`Tx::none`], one that ended, or one of the other database).
258    fn connection<DB: sqlx::Database>(&mut self) -> &mut DB::Connection;
259
260    /// The connection; `None` where [`connection`](Self::connection) panics.
261    fn try_connection<DB: sqlx::Database>(&mut self) -> Option<&mut DB::Connection>;
262}
263
264impl SqlxTxExt for Tx {
265    fn connection<DB: sqlx::Database>(&mut self) -> &mut DB::Connection {
266        self.try_connection::<DB>().unwrap_or_else(|| {
267            panic!(
268                "the transaction is not an open one of the SQL message store on {}",
269                DB::NAME
270            )
271        })
272    }
273
274    fn try_connection<DB: sqlx::Database>(&mut self) -> Option<&mut DB::Connection> {
275        self.get_mut::<Held<DB>>().and_then(Held::connection)
276    }
277}
278
279/// Transactions on connections of the pool, at the database's default isolation.
280struct SqlTx {
281    db: Arc<Db>,
282}
283
284impl TxProvider for SqlTx {
285    fn begin(&self) -> BoxFuture<'_, Result<Tx, StoreError>> {
286        Box::pin(async move {
287            Ok(match &self.db.pool {
288                #[cfg(feature = "postgres")]
289                Pool::Pg(p) => Tx::new(Held::<Postgres>::begin(p, crate::db::BEGIN).await?),
290                #[cfg(feature = "mysql")]
291                Pool::My(p) => Tx::new(Held::<MySql>::begin(p, crate::db::START).await?),
292            })
293        })
294    }
295
296    /// No transaction: each store call runs in a short transaction of its own.
297    fn plain(&self) -> BoxFuture<'_, Result<Tx, StoreError>> {
298        Box::pin(async { Ok(Tx::none()) })
299    }
300
301    fn commit<'a>(&'a self, tx: &'a mut Tx) -> BoxFuture<'a, Result<(), StoreError>> {
302        Box::pin(async move {
303            let ended = || crate::db::storage("the transaction has ended already".into());
304            #[cfg(feature = "postgres")]
305            if let Some(held) = tx.get_mut::<Held<Postgres>>() {
306                if !held.is_open() {
307                    return Err(ended());
308                }
309                return held.commit_checked().await;
310            }
311            #[cfg(feature = "mysql")]
312            if let Some(held) = tx.get_mut::<Held<MySql>>() {
313                if !held.is_open() {
314                    return Err(ended());
315                }
316                return held.end(true).await;
317            }
318            let _ = ended;
319            // No transaction (`plain`, `Tx::none`): every write committed already.
320            Ok(())
321        })
322    }
323
324    fn abort<'a>(&'a self, tx: &'a mut Tx) -> BoxFuture<'a, ()> {
325        Box::pin(async move {
326            #[cfg(feature = "postgres")]
327            if let Some(held) = tx.get_mut::<Held<Postgres>>() {
328                let _ = held.end(false).await;
329            }
330            #[cfg(feature = "mysql")]
331            if let Some(held) = tx.get_mut::<Held<MySql>>() {
332                let _ = held.end(false).await;
333            }
334        })
335    }
336}