1use 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
24pub 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
124pub 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(®istry);
145 let indexer_metrics = IndexerMetrics::new(®istry);
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, ®istry, 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
200pub 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 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 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 pub fn create(&mut self) {
238 self.connection
239 .batch_execute(&format!("CREATE DATABASE {}", self.db_name))
240 .unwrap();
241 }
242
243 pub fn recreate(&mut self) {
245 self.drop_if_exists();
246 self.create();
247 }
248
249 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(®istry);
262 let indexer_metrics = IndexerMetrics::new(®istry);
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 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 ..self.full_response.clone()
381 }
382 }
383}
384
385pub fn db_url(db_name: &str) -> String {
389 format!("postgres://postgres:postgrespw@localhost:5432/{db_name}")
390}
391
392#[derive(QueryableByName, Debug)]
394pub struct RowCount {
395 #[diesel(sql_type = BigInt)]
396 pub cnt: i64,
397}