1pub(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 pub fn mark_in_blocking_pool() {
27 CALLED_FROM_BLOCKING_POOL.with(|in_blocking_pool| *in_blocking_pool.borrow_mut() = true);
28 }
29
30 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 #[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 #[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 #[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 #[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 #[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 #[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 #[macro_export]
298 macro_rules! run_query_async {
299 ($pool:expr, $query:expr) => {{ spawn_read_only_blocking!($pool, $query, false) }};
300 }
301
302 #[macro_export]
305 macro_rules! run_query_repeatable_async {
306 ($pool:expr, $query:expr) => {{ spawn_read_only_blocking!($pool, $query, true) }};
307 }
308
309 #[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 #[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 #[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}