1use 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#[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 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 #[cfg(feature = "postgres")]
53 pub fn postgres(pool: PgPool) -> SqlxStore {
54 Self::build(Pool::Pg(pool), SqlxSettings::default())
55 }
56
57 #[cfg(feature = "mysql")]
59 pub fn mysql(pool: MySqlPool) -> SqlxStore {
60 Self::build(Pool::My(pool), SqlxSettings::default())
61 }
62
63 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 pub fn settings(&self) -> &SqlxSettings {
103 &self.inner.settings
104 }
105
106 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 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 pub async fn purge_expired(&self, config: &Config) -> Result<u64, StoreError> {
125 crate::purge::run(&self.inner.db, config).await
126 }
127
128 #[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 fn init_schema<'a>(&'a self, _config: &'a Config) -> BoxFuture<'a, Result<(), StoreError>> {
148 Box::pin(self.apply_schema())
149 }
150
151 fn check_schema(&self) -> BoxFuture<'_, Result<(), StoreError>> {
153 Box::pin(self.require_schema())
154 }
155
156 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
230pub trait SqlxTxExt {
252 fn connection<DB: sqlx::Database>(&mut self) -> &mut DB::Connection;
259
260 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
279struct 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 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 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}