iota_indexer/
test_utils.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::path::PathBuf;
6
7use diesel::{QueryableByName, connection::SimpleConnection, sql_types::BigInt};
8use iota_json_rpc_types::IotaTransactionBlockResponse;
9use iota_metrics::init_metrics;
10use tokio::task::JoinHandle;
11use tokio_util::sync::CancellationToken;
12
13use crate::{
14    IndexerMetrics,
15    config::{
16        IngestionConfig, IotaNamesOptions, PruningOptions, RetentionConfig, SnapshotLagConfig,
17    },
18    db::{ConnectionPool, ConnectionPoolConfig, PoolConnection, new_connection_pool},
19    errors::IndexerError,
20    indexer::Indexer,
21    store::{PgIndexerAnalyticalStore, PgIndexerStore},
22};
23
24/// Type to create hooks to alter initial indexer DB state in tests.
25/// Those hooks are meant to be called after DB reset (if it occurs) and before
26/// indexer is started.
27///
28/// Example:
29///
30/// ```ignore
31/// let emulate_insertion_order_set_earlier_by_optimistic_indexing: DBInitHook =
32///     Box::new(move |pg_store: &PgIndexerStore| {
33///         transactional_blocking_with_retry!(
34///             &pg_store.blocking_cp(),
35///             |conn| {
36///                 insert_or_ignore_into!(
37///                     tx_insertion_order::table,
38///                     (
39///                         tx_insertion_order::dsl::tx_digest.eq(digest.inner().to_vec()),
40///                         tx_insertion_order::dsl::insertion_order.eq(123),
41///                     ),
42///                     conn
43///                 );
44///                 Ok::<(), IndexerError>(())
45///             },
46///             Duration::from_secs(60)
47///         )
48///             .unwrap()
49///     });
50///
51/// let (_, pg_store, _) = start_simulacrum_rest_api_with_write_indexer(
52///     Arc::new(sim),
53///     data_ingestion_path,
54///     None,
55///     Some("indexer_ingestion_tests_db"),
56///     Some(emulate_insertion_order_set_earlier_by_optimistic_indexing),
57/// )
58/// .await;
59/// ```
60pub type DBInitHook = Box<dyn FnOnce(&PgIndexerStore) + Send>;
61
62pub enum IndexerTypeConfig {
63    Reader {
64        reader_mode_rpc_url: String,
65    },
66    Writer {
67        snapshot_config: SnapshotLagConfig,
68        retention_config: Option<RetentionConfig>,
69        optimistic_pruner_batch_size: Option<u64>,
70    },
71    AnalyticalWorker,
72}
73
74impl IndexerTypeConfig {
75    pub fn reader_mode(reader_mode_rpc_url: String) -> Self {
76        Self::Reader {
77            reader_mode_rpc_url,
78        }
79    }
80
81    pub fn writer_mode(
82        snapshot_config: Option<SnapshotLagConfig>,
83        pruning_options: Option<PruningOptions>,
84    ) -> Self {
85        Self::Writer {
86            snapshot_config: snapshot_config.unwrap_or_default(),
87            retention_config: pruning_options.as_ref().and_then(|pruning_options| {
88                pruning_options
89                    .epochs_to_keep
90                    .map(RetentionConfig::new_with_default_retention_only_for_testing)
91            }),
92            optimistic_pruner_batch_size: pruning_options
93                .and_then(|pruning_options| pruning_options.optimistic_pruner_batch_size),
94        }
95    }
96}
97
98pub async fn start_test_indexer(
99    db_url: String,
100    reset_db: bool,
101    db_init_hook: Option<DBInitHook>,
102    rpc_url: String,
103    reader_writer_config: IndexerTypeConfig,
104    data_ingestion_path: Option<PathBuf>,
105) -> (
106    PgIndexerStore,
107    JoinHandle<Result<(), IndexerError>>,
108    CancellationToken,
109) {
110    let token = CancellationToken::new();
111    let (store, handle) = start_test_indexer_impl(
112        db_url,
113        reset_db,
114        db_init_hook,
115        rpc_url,
116        reader_writer_config,
117        data_ingestion_path,
118        token.clone(),
119    )
120    .await;
121    (store, handle, token)
122}
123
124/// Starts an indexer reader or writer for testing depending on the
125/// `reader_writer_config`.
126pub async fn start_test_indexer_impl(
127    db_url: String,
128    reset_db: bool,
129    db_init_hook: Option<DBInitHook>,
130    rpc_url: String,
131    reader_writer_config: IndexerTypeConfig,
132    data_ingestion_path: Option<PathBuf>,
133    cancel: CancellationToken,
134) -> (PgIndexerStore, JoinHandle<Result<(), IndexerError>>) {
135    let store = create_pg_store(&db_url, reset_db);
136    if reset_db {
137        crate::db::reset_database(&mut store.blocking_cp().get().unwrap()).unwrap();
138    }
139    if let Some(db_init_hook) = db_init_hook {
140        db_init_hook(&store);
141    }
142
143    let registry = prometheus::Registry::default();
144    init_metrics(&registry);
145    let indexer_metrics = IndexerMetrics::new(&registry);
146
147    let handle = match reader_writer_config {
148        IndexerTypeConfig::Reader {
149            reader_mode_rpc_url,
150        } => {
151            let config = crate::config::JsonRpcConfig {
152                iota_names_options: IotaNamesOptions::default(),
153                rpc_address: reader_mode_rpc_url.parse().unwrap(),
154                rpc_client_url: rpc_url,
155            };
156            let pool = store.blocking_cp();
157            let store_clone = store.clone();
158            tokio::spawn(async move {
159                Indexer::start_reader(&config, store_clone, &registry, pool, indexer_metrics).await
160            })
161        }
162        IndexerTypeConfig::Writer {
163            snapshot_config,
164            retention_config,
165            optimistic_pruner_batch_size,
166        } => {
167            let store_clone = store.clone();
168            let mut ingestion_config = IngestionConfig::default();
169            ingestion_config.sources.remote_store_url = data_ingestion_path
170                .is_none()
171                .then_some(format!("{rpc_url}/api/v1").parse().unwrap());
172            ingestion_config.sources.data_ingestion_path = data_ingestion_path;
173            ingestion_config.sources.rpc_client_url = Some(rpc_url.parse().unwrap());
174
175            tokio::spawn(async move {
176                Indexer::start_writer_with_config(
177                    &ingestion_config,
178                    store_clone,
179                    indexer_metrics,
180                    snapshot_config,
181                    retention_config,
182                    optimistic_pruner_batch_size,
183                    cancel,
184                )
185                .await
186            })
187        }
188        IndexerTypeConfig::AnalyticalWorker => {
189            let store = PgIndexerAnalyticalStore::new(store.blocking_cp());
190
191            tokio::spawn(
192                async move { Indexer::start_analytical_worker(store, indexer_metrics).await },
193            )
194        }
195    };
196
197    (store, handle)
198}
199
200/// Manage a test database for integration tests.
201pub struct TestDatabase {
202    pub url: String,
203    db_name: String,
204    connection: PoolConnection,
205    pool_config: ConnectionPoolConfig,
206}
207
208impl TestDatabase {
209    pub fn new(db_url: String) -> Self {
210        // Reduce the connection pool size to 5 for testing
211        // to prevent maxing out
212        let pool_config = ConnectionPoolConfig {
213            pool_size: 5,
214            ..Default::default()
215        };
216
217        let db_name = db_url.split('/').next_back().unwrap().into();
218        let (default_url, _) = replace_db_name(&db_url, "postgres");
219        let blocking_pool = new_connection_pool(&default_url, &pool_config).unwrap();
220        let connection = blocking_pool.get().unwrap();
221        Self {
222            url: db_url,
223            db_name,
224            connection,
225            pool_config,
226        }
227    }
228
229    /// Drop the database in the server if it exists.
230    pub fn drop_if_exists(&mut self) {
231        self.connection
232            .batch_execute(&format!("DROP DATABASE IF EXISTS {}", self.db_name))
233            .unwrap();
234    }
235
236    /// Create the database in the server.
237    pub fn create(&mut self) {
238        self.connection
239            .batch_execute(&format!("CREATE DATABASE {}", self.db_name))
240            .unwrap();
241    }
242
243    /// Drop and recreate the database in the server.
244    pub fn recreate(&mut self) {
245        self.drop_if_exists();
246        self.create();
247    }
248
249    /// Create a new connection pool to the database.
250    pub fn to_connection_pool(&self) -> ConnectionPool {
251        new_connection_pool(&self.url, &self.pool_config).unwrap()
252    }
253
254    pub fn reset_db(&mut self) {
255        crate::db::reset_database(&mut self.to_connection_pool().get().unwrap()).unwrap();
256    }
257}
258
259pub fn create_pg_store(db_url: &str, reset_database: bool) -> PgIndexerStore {
260    let registry = prometheus::Registry::default();
261    init_metrics(&registry);
262    let indexer_metrics = IndexerMetrics::new(&registry);
263
264    let mut test_db = TestDatabase::new(db_url.to_string());
265    if reset_database {
266        test_db.recreate();
267    }
268
269    PgIndexerStore::new(test_db.to_connection_pool(), indexer_metrics.clone())
270}
271
272fn replace_db_name(db_url: &str, new_db_name: &str) -> (String, String) {
273    let pos = db_url.rfind('/').expect("Unable to find / in db_url");
274    let old_db_name = &db_url[pos + 1..];
275
276    (
277        format!("{}/{}", &db_url[..pos], new_db_name),
278        old_db_name.to_string(),
279    )
280}
281
282pub async fn force_delete_database(db_url: String) {
283    // Replace the database name with the default `postgres`, which should be the
284    // last string after `/` This is necessary because you can't drop a database
285    // while being connected to it. Hence switch to the default `postgres`
286    // database to drop the active database.
287    let (default_db_url, db_name) = replace_db_name(&db_url, "postgres");
288    let mut pool_config = ConnectionPoolConfig::default();
289    pool_config.set_pool_size(1);
290
291    let blocking_pool = new_connection_pool(&default_db_url, &pool_config).unwrap();
292    blocking_pool
293        .get()
294        .unwrap()
295        .batch_execute(&format!("DROP DATABASE IF EXISTS {db_name} WITH (FORCE)"))
296        .unwrap();
297}
298
299#[derive(Clone)]
300pub struct IotaTransactionBlockResponseBuilder<'a> {
301    response: IotaTransactionBlockResponse,
302    full_response: &'a IotaTransactionBlockResponse,
303}
304
305impl<'a> IotaTransactionBlockResponseBuilder<'a> {
306    pub fn new(full_response: &'a IotaTransactionBlockResponse) -> Self {
307        Self {
308            response: IotaTransactionBlockResponse::default(),
309            full_response,
310        }
311    }
312
313    pub fn with_input(mut self) -> Self {
314        self.response = IotaTransactionBlockResponse {
315            transaction: self.full_response.transaction.clone(),
316            ..self.response
317        };
318        self
319    }
320
321    pub fn with_raw_input(mut self) -> Self {
322        self.response = IotaTransactionBlockResponse {
323            raw_transaction: self.full_response.raw_transaction.clone(),
324            ..self.response
325        };
326        self
327    }
328
329    pub fn with_effects(mut self) -> Self {
330        self.response = IotaTransactionBlockResponse {
331            effects: self.full_response.effects.clone(),
332            ..self.response
333        };
334        self
335    }
336
337    pub fn with_events(mut self) -> Self {
338        self.response = IotaTransactionBlockResponse {
339            events: self.full_response.events.clone(),
340            ..self.response
341        };
342        self
343    }
344
345    pub fn with_balance_changes(mut self) -> Self {
346        self.response = IotaTransactionBlockResponse {
347            balance_changes: self.full_response.balance_changes.clone(),
348            ..self.response
349        };
350        self
351    }
352
353    pub fn with_object_changes(mut self) -> Self {
354        self.response = IotaTransactionBlockResponse {
355            object_changes: self.full_response.object_changes.clone(),
356            ..self.response
357        };
358        self
359    }
360
361    pub fn with_input_and_changes(mut self) -> Self {
362        self.response = IotaTransactionBlockResponse {
363            transaction: self.full_response.transaction.clone(),
364            balance_changes: self.full_response.balance_changes.clone(),
365            object_changes: self.full_response.object_changes.clone(),
366            ..self.response
367        };
368        self
369    }
370
371    pub fn build(self) -> IotaTransactionBlockResponse {
372        IotaTransactionBlockResponse {
373            transaction: self.response.transaction,
374            raw_transaction: self.response.raw_transaction,
375            effects: self.response.effects,
376            events: self.response.events,
377            balance_changes: self.response.balance_changes,
378            object_changes: self.response.object_changes,
379            // Use full response for any fields that aren't showable
380            ..self.full_response.clone()
381        }
382    }
383}
384
385/// Returns a database URL for testing purposes.
386/// It uses a default user and password, and connects to a local PostgreSQL
387/// instance.
388pub fn db_url(db_name: &str) -> String {
389    format!("postgres://postgres:postgrespw@localhost:5432/{db_name}")
390}
391
392/// Represents a row count result from a SQL query.
393#[derive(QueryableByName, Debug)]
394pub struct RowCount {
395    #[diesel(sql_type = BigInt)]
396    pub cnt: i64,
397}