Skip to main content

iota_indexer/store/
mod.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5pub(crate) use indexer_analytics_store::{IndexerAnalyticalStore, WatermarkLowerBounds};
6pub(crate) use indexer_store::*;
7pub use pg_indexer_analytical_store::PgIndexerAnalyticalStore;
8pub use pg_indexer_store::PgIndexerStore;
9
10mod indexer_analytics_store;
11pub mod indexer_store;
12pub mod package_resolver;
13mod pg_indexer_analytical_store;
14mod pg_indexer_store;
15pub mod pg_partition_manager;
16
17pub mod diesel_macro {
18    thread_local! {
19        pub static CALLED_FROM_BLOCKING_POOL: std::cell::RefCell<bool> = const { std::cell::RefCell::new(false) };
20    }
21
22    /// Marks the current thread as being in a blocking pool.
23    ///
24    /// Prefer [`spawn_blocking_task`], which spawns the closure and marks the
25    /// thread in one step.
26    pub fn mark_in_blocking_pool() {
27        CALLED_FROM_BLOCKING_POOL.with(|in_blocking_pool| *in_blocking_pool.borrow_mut() = true);
28    }
29
30    /// Spawns a closure on the blocking thread pool and marks the thread as
31    /// being in a blocking pool, so the closure can run blocking DB
32    /// operations. The current tracing span is propagated into the closure.
33    pub fn spawn_blocking_task<F, R>(f: F) -> tokio::task::JoinHandle<R>
34    where
35        F: FnOnce() -> R + Send + 'static,
36        R: Send + 'static,
37    {
38        let current_span = tracing::Span::current();
39        tokio::task::spawn_blocking(move || {
40            mark_in_blocking_pool();
41            let _guard = current_span.enter();
42            f()
43        })
44    }
45
46    /// Runs a read-only, repeatable-read SQL transaction, blocking the
47    /// calling thread until it completes.
48    ///
49    /// # Panics
50    ///
51    /// Panics when called on an async runtime thread; run it on a blocking
52    /// thread instead, e.g. via `spawn_blocking_task`.
53    #[macro_export]
54    macro_rules! read_only_repeatable_blocking {
55        ($pool:expr, $query:expr) => {{
56            use downcast::Any;
57            use $crate::db::{PoolConnection, get_pool_connection};
58
59            $crate::blocking_call_is_ok_or_panic!();
60            let mut pool_conn = get_pool_connection($pool)?;
61            pool_conn
62                .as_any_mut()
63                .downcast_mut::<PoolConnection>()
64                .unwrap()
65                .build_transaction()
66                .read_only()
67                .repeatable_read()
68                .run($query)
69                .map_err(|e| {
70                    tracing::error!("failed to read from PostgresDB: {e:?}");
71                    $crate::errors::IndexerError::PostgresRead
72                })
73        }};
74    }
75
76    /// Runs a read-only SQL transaction, blocking the calling thread until it
77    /// completes.
78    ///
79    /// # Panics
80    ///
81    /// Panics when called on an async runtime thread; run it on a blocking
82    /// thread instead, e.g. via `spawn_blocking_task`.
83    #[macro_export]
84    macro_rules! read_only_blocking {
85        ($pool:expr, $query:expr) => {{
86            use downcast::Any;
87            use $crate::db::{PoolConnection, get_pool_connection};
88
89            $crate::blocking_call_is_ok_or_panic!();
90            let mut pool_conn = get_pool_connection($pool)?;
91            pool_conn
92                .as_any_mut()
93                .downcast_mut::<PoolConnection>()
94                .unwrap()
95                .build_transaction()
96                .read_only()
97                .run($query)
98                .map_err(|e| {
99                    tracing::error!("failed to read from PostgresDB: {e:?}");
100                    $crate::errors::IndexerError::PostgresRead
101                })
102        }};
103    }
104
105    /// Runs a read-write SQL transaction, blocking the calling thread until
106    /// it completes. Failures are retried with exponential backoff.
107    ///
108    /// # Panics
109    ///
110    /// Panics when called on an async runtime thread; run it on a blocking
111    /// thread instead, e.g. via `spawn_blocking_task`.
112    #[macro_export]
113    macro_rules! transactional_blocking_with_retry {
114        ($pool:expr, $query:expr, $max_elapsed:expr) => {{
115            use $crate::{
116                db::{PoolConnection, get_pool_connection},
117                errors::IndexerError,
118            };
119            $crate::blocking_call_is_ok_or_panic!();
120            let mut backoff = backoff::ExponentialBackoff::default();
121            backoff.max_elapsed_time = Some($max_elapsed);
122            let result = match backoff::retry(backoff, || {
123                let mut pool_conn =
124                    get_pool_connection($pool).map_err(|err| backoff::Error::Transient {
125                        err,
126                        retry_after: None,
127                    })?;
128                pool_conn
129                    .as_any_mut()
130                    .downcast_mut::<PoolConnection>()
131                    .unwrap()
132                    .build_transaction()
133                    .read_write()
134                    .run($query)
135                    .map_err(|e| {
136                        tracing::error!("error with persisting data into DB: {e:?}, retrying...");
137                        backoff::Error::Transient {
138                            err: IndexerError::PostgresWrite,
139                            retry_after: None,
140                        }
141                    })
142            }) {
143                Ok(v) => Ok(v),
144                Err(backoff::Error::Transient { err, .. }) => Err(err),
145                Err(backoff::Error::Permanent(err)) => Err(err),
146            };
147
148            result
149        }};
150    }
151
152    /// Runs a read-write SQL transaction, blocking the calling thread until
153    /// it completes. Failures are retried with exponential backoff, except
154    /// for errors matching the abort condition, which stop the retries.
155    ///
156    /// # Panics
157    ///
158    /// Panics when called on an async runtime thread; run it on a blocking
159    /// thread instead, e.g. via `spawn_blocking_task`.
160    #[macro_export]
161    macro_rules! transactional_blocking_with_retry_with_conditional_abort {
162        ($pool:expr, $query:expr, $abort_condition:expr, $max_elapsed:expr) => {{
163            use $crate::{
164                db::{PoolConnection, get_pool_connection},
165                errors::IndexerError,
166            };
167            $crate::blocking_call_is_ok_or_panic!();
168            let mut backoff = backoff::ExponentialBackoff::default();
169            backoff.max_elapsed_time = Some($max_elapsed);
170            let result = match backoff::retry(backoff, || {
171                let mut pool_conn =
172                    get_pool_connection($pool).map_err(|err| backoff::Error::Transient {
173                        err,
174                        retry_after: None,
175                    })?;
176                pool_conn
177                    .as_any_mut()
178                    .downcast_mut::<PoolConnection>()
179                    .unwrap()
180                    .build_transaction()
181                    .read_write()
182                    .run($query)
183                    .map_err(|e| {
184                        tracing::error!("error with persisting data into DB: {e:?}, retrying...");
185                        if $abort_condition(&e) {
186                            backoff::Error::Permanent(e)
187                        } else {
188                            backoff::Error::Transient {
189                                err: IndexerError::PostgresWrite,
190                                retry_after: None,
191                            }
192                        }
193                    })
194            }) {
195                Ok(v) => Ok(v),
196                Err(backoff::Error::Transient { err, .. }) => Err(err),
197                Err(backoff::Error::Permanent(err)) => Err(err),
198            };
199
200            result
201        }};
202    }
203
204    /// Runs a read-only SQL transaction on a spawned blocking thread and
205    /// awaits its result. Safe to call from async code.
206    #[macro_export]
207    macro_rules! spawn_read_only_blocking {
208        ($pool:expr, $query:expr, $repeatable_read:expr) => {{
209            $crate::store::diesel_macro::spawn_blocking_task(move || {
210                if $repeatable_read {
211                    $crate::read_only_repeatable_blocking!($pool, $query)
212                } else {
213                    $crate::read_only_blocking!($pool, $query)
214                }
215            })
216            .await
217            .expect("blocking call failed")
218        }};
219    }
220
221    #[macro_export]
222    macro_rules! insert_or_ignore_into {
223        ($table:expr, $values:expr, $conn:expr) => {{
224            use diesel::RunQueryDsl;
225            let error_message = concat!("failed to write to ", stringify!($table), " DB");
226
227            diesel::insert_into($table)
228                .values($values)
229                .on_conflict_do_nothing()
230                .execute($conn)
231                .map_err(IndexerError::from)
232                .context(error_message)?;
233        }};
234    }
235
236    #[macro_export]
237    macro_rules! on_conflict_do_update {
238        ($table:expr, $values:expr, $target:expr, $pg_columns:expr, $conn:expr) => {{
239            use diesel::{ExpressionMethods, RunQueryDsl};
240
241            diesel::insert_into($table)
242                .values($values)
243                .on_conflict($target)
244                .do_update()
245                .set($pg_columns)
246                .execute($conn)?;
247        }};
248    }
249
250    #[macro_export]
251    macro_rules! on_conflict_do_update_with_condition {
252        ($table:expr, $values:expr, $target:expr, $pg_columns:expr, $condition:expr, $conn:expr) => {{
253            use diesel::{ExpressionMethods, RunQueryDsl, query_dsl::methods::FilterDsl};
254
255            diesel::insert_into($table)
256                .values($values)
257                .on_conflict($target)
258                .do_update()
259                .set($pg_columns)
260                .filter($condition)
261                .execute($conn)?;
262        }};
263    }
264
265    /// Runs a read-only SQL transaction, blocking the calling thread until it
266    /// completes. Failures are retried with exponential backoff.
267    ///
268    /// # Panics
269    ///
270    /// Panics when called on an async runtime thread; run it on a blocking
271    /// thread instead, e.g. via `spawn_blocking_task`.
272    #[macro_export]
273    macro_rules! run_query_with_retry {
274        ($pool:expr, $query:expr, $max_elapsed:expr) => {{
275            let mut backoff = backoff::ExponentialBackoff::default();
276            backoff.max_elapsed_time = Some($max_elapsed);
277            let result = match backoff::retry(backoff, || {
278                read_only_blocking!($pool, $query).map_err(|e| {
279                    tracing::error!("error with reading data from DB: {e:?}, retrying...");
280                    backoff::Error::Transient {
281                        err: e,
282                        retry_after: None,
283                    }
284                })
285            }) {
286                Ok(v) => Ok(v),
287                Err(backoff::Error::Transient { err, .. }) => Err(err),
288                Err(backoff::Error::Permanent(err)) => Err(err),
289            };
290
291            result
292        }};
293    }
294
295    /// Runs a read-only SQL transaction on a spawned blocking thread and
296    /// awaits its result. Safe to call from async code.
297    #[macro_export]
298    macro_rules! run_query_async {
299        ($pool:expr, $query:expr) => {{ spawn_read_only_blocking!($pool, $query, false) }};
300    }
301
302    /// Runs a read-only, repeatable-read SQL transaction on a spawned
303    /// blocking thread and awaits its result. Safe to call from async code.
304    #[macro_export]
305    macro_rules! run_query_repeatable_async {
306        ($pool:expr, $query:expr) => {{ spawn_read_only_blocking!($pool, $query, true) }};
307    }
308
309    /// Check that we are in a context conducive to making blocking calls.
310    /// This is done by either:
311    /// - Checking that we are not inside a tokio runtime context
312    ///
313    /// Or:
314    /// - If we are inside a tokio runtime context, ensure that the call went through a spawned
315    ///   blocking task that called `mark_in_blocking_pool`, such as
316    ///   `store::diesel_macro::spawn_blocking_task`, `IndexerReader::spawn_blocking` or
317    ///   `PgIndexerStore::execute_in_blocking_worker`.
318    #[macro_export]
319    macro_rules! blocking_call_is_ok_or_panic {
320        () => {{
321            use $crate::store::diesel_macro::CALLED_FROM_BLOCKING_POOL;
322            if tokio::runtime::Handle::try_current().is_ok()
323                && !CALLED_FROM_BLOCKING_POOL.with(|in_blocking_pool| *in_blocking_pool.borrow())
324            {
325                panic!(
326                    "you are calling a blocking DB operation directly on an async thread. \
327                        Please move the operation to a blocking thread, e.g. with \
328                        store::diesel_macro::spawn_blocking_task, \
329                        IndexerReader::spawn_blocking or \
330                        PgIndexerStore::execute_in_blocking_worker"
331                );
332            }
333        }};
334    }
335
336    /// This macro provides a standardized way to bulk insert data into database
337    /// tables with built-in performance monitoring, error handling, and
338    /// retry logic. It automatically subdivides large chunks into smaller
339    /// batches to optimize database performance and avoid overwhelming
340    /// individual transactions.
341    ///
342    /// # Parameters
343    ///
344    /// * `$table` - The target database table (e.g., `events::table`, `transactions::table`)
345    /// * `$chunk` - Collection of data to persist (must implement `.len()` and `.chunks()`)
346    /// * `$pool` - Database connection pool reference
347    ///
348    /// # Behavior
349    ///
350    /// 1. **Performance Timing**: Records operation duration for monitoring
351    /// 2. **Automatic Batching**: Splits data into chunks of `PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX`
352    ///    rows
353    /// 3. **Transaction Safety**: Uses `transactional_blocking_with_retry!` for atomic operations
354    /// 4. **Conflict Resolution**: Employs `INSERT ... ON CONFLICT DO NOTHING` strategy
355    /// 5. **Retry Logic**: Automatically retries failed operations with timeout of
356    ///    `PG_DB_COMMIT_SLEEP_DURATION`
357    /// 6. **Comprehensive Logging**: Logs success/failure with timing and row count information
358    ///
359    /// # Examples
360    ///
361    /// ```rust,ignore
362    /// let event_batch = vec![/* event data */];
363    /// // Persist event data
364    /// persist_chunk_into_table!(
365    ///     events::table,
366    ///     event_batch,
367    ///     &connection_pool
368    /// ).unwrap();
369    ///
370    /// let sender_data = vec![/* sender data */];
371    /// // Persist transaction senders
372    /// persist_chunk_into_table!(
373    ///     tx_senders::table,
374    ///     sender_data,
375    ///     &blocking_pool
376    /// ).unwrap();
377    /// ```
378    #[macro_export]
379    macro_rules! persist_chunk_into_table {
380        ($table:expr, $chunk:expr, $pool:expr) => {{
381            let now = std::time::Instant::now();
382            let chunk_len = $chunk.len();
383            transactional_blocking_with_retry!(
384                $pool,
385                |conn| {
386                    persist_chunk_into_table_in_existing_connection!($table, $chunk, conn);
387                    Ok::<(), IndexerError>(())
388                },
389                PG_DB_COMMIT_SLEEP_DURATION
390            )
391            .tap_ok(|_| {
392                let elapsed = now.elapsed().as_secs_f64();
393                info!(
394                    elapsed,
395                    "Persisted {} rows to {}",
396                    chunk_len,
397                    stringify!($table),
398                );
399            })
400            .tap_err(|e| {
401                tracing::error!("failed to persist {} with error: {e:?}", stringify!($table));
402            })
403        }};
404    }
405
406    #[macro_export]
407    macro_rules! persist_chunk_into_table_in_existing_connection {
408        ($table:expr, $chunk:expr, $conn:expr) => {{
409            for chunk in $chunk.chunks(PG_COMMIT_CHUNK_SIZE_INTRA_DB_TX) {
410                insert_or_ignore_into!($table, chunk, $conn);
411            }
412        }};
413    }
414
415    pub use blocking_call_is_ok_or_panic;
416    pub use read_only_blocking;
417    pub use read_only_repeatable_blocking;
418    pub use run_query_async;
419    pub use run_query_repeatable_async;
420    pub use spawn_read_only_blocking;
421    pub use transactional_blocking_with_retry;
422}
423
424#[cfg(test)]
425mod tests {
426    use super::diesel_macro::{
427        blocking_call_is_ok_or_panic, mark_in_blocking_pool, spawn_blocking_task,
428    };
429
430    // The simulator's `tokio::runtime::Handle::try_current` panics instead of
431    // reporting that no runtime is running, so this case can only be checked
432    // outside the simulator.
433    #[cfg(not(msim))]
434    #[test]
435    fn blocking_call_is_allowed_outside_a_runtime() {
436        blocking_call_is_ok_or_panic!();
437    }
438
439    #[tokio::test]
440    #[should_panic(expected = "calling a blocking DB operation directly on an async thread")]
441    async fn blocking_call_panics_on_an_async_thread() {
442        blocking_call_is_ok_or_panic!();
443    }
444
445    #[tokio::test]
446    async fn blocking_call_is_allowed_on_a_marked_blocking_thread() {
447        tokio::task::spawn_blocking(|| {
448            mark_in_blocking_pool();
449            blocking_call_is_ok_or_panic!();
450        })
451        .await
452        .unwrap();
453    }
454
455    #[tokio::test]
456    async fn blocking_call_is_allowed_in_spawn_blocking_task() {
457        spawn_blocking_task(|| {
458            blocking_call_is_ok_or_panic!();
459        })
460        .await
461        .unwrap();
462    }
463}