1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#[cfg(feature = "local-reth")]
use std::sync::OnceLock;
use std::{collections::hash_map::Entry, env, fs::OpenOptions, io::Write, sync::Arc};

use alloy_primitives::Address;
#[cfg(feature = "local-clickhouse")]
use brontes_database::clickhouse::Clickhouse;
#[cfg(not(feature = "local-clickhouse"))]
use brontes_database::clickhouse::ClickhouseHttpClient;
pub use brontes_database::libmdbx::{DBWriter, LibmdbxReadWriter, LibmdbxReader};
use brontes_database::{
    libmdbx::LibmdbxInit, AddressToProtocolInfo, PoolCreationBlocks, Tables, TokenDecimals,
};
use brontes_metrics::ParserMetricEvents;
use brontes_types::{
    constants::USDT_ADDRESS,
    db::{
        cex::trades::{window_loader::CexWindow, CexTradeMap},
        metadata::Metadata,
    },
    init_thread_pools,
    structured_trace::TxTrace,
    traits::TracingProvider,
    FastHashMap,
};
use futures::future::join_all;
use indicatif::MultiProgress;
#[cfg(feature = "local-reth")]
use reth_db::DatabaseEnv;
use reth_primitives::{BlockHash, Header, B256};
use reth_provider::ProviderError;
#[cfg(feature = "local-reth")]
use reth_tracing_ext::init_db;
#[cfg(feature = "local-reth")]
use reth_tracing_ext::TracingClient;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::{
    runtime::Handle,
    sync::{
        mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
        OnceCell,
    },
};
use tracing::Level;
use tracing_subscriber::filter::Directive;

use crate::decoding::parser::TraceParser;
#[cfg(not(feature = "local-reth"))]
use crate::local_provider::LocalProvider;

const WINDOW_TIME_SEC: usize = 20;
/// Functionality to load all state needed for any testing requirements
pub struct TraceLoader {
    pub libmdbx:          &'static LibmdbxReadWriter,
    pub tracing_provider: TraceParser<Box<dyn TracingProvider>, LibmdbxReadWriter>,
    // store so when we trace we don't get a closed rx error
    _metrics:             UnboundedReceiver<ParserMetricEvents>,
}

impl TraceLoader {
    pub async fn new() -> Self {
        let handle = tokio::runtime::Handle::current();
        init_thread_pools(32);
        let libmdbx = get_db_handle(handle.clone()).await;

        let (a, b) = unbounded_channel();
        let tracing_provider = init_trace_parser(handle, a, libmdbx, 10).await;

        Self { libmdbx, tracing_provider, _metrics: b }
    }

    pub fn get_provider(&self) -> Arc<Box<dyn TracingProvider>> {
        self.tracing_provider.get_tracer()
    }

    pub async fn trace_block(
        &self,
        block: u64,
    ) -> Result<(BlockHash, Vec<TxTrace>, Header), TraceLoaderError> {
        if let Some(traces) = self.tracing_provider.clone().execute_block(block).await {
            Ok(traces)
        } else {
            self.fetch_missing_traces(block).await.unwrap();
            self.tracing_provider
                .clone()
                .execute_block(block)
                .await
                .ok_or_else(|| TraceLoaderError::BlockTraceError(block))
        }
    }

    pub async fn get_metadata(
        &self,
        block: u64,
        pricing: bool,
    ) -> Result<Metadata, TraceLoaderError> {
        if pricing {
            if let Ok(res) = self.test_metadata_with_pricing(block, USDT_ADDRESS) {
                Ok(res)
            } else {
                tracing::info!("test fetching missing metadata with pricing");
                self.fetch_missing_metadata(block).await?;
                self.test_metadata_with_pricing(block, USDT_ADDRESS)
                    .map_err(|_| TraceLoaderError::NoMetadataFound(block))
            }
        } else if let Ok(res) = self.test_metadata(block, USDT_ADDRESS) {
            Ok(res)
        } else {
            tracing::info!("test fetching missing metadata no pricing");
            self.fetch_missing_metadata(block).await?;
            tracing::info!("fetched missing data");
            return self
                .test_metadata(block, USDT_ADDRESS)
                .map_err(|_| TraceLoaderError::NoMetadataFound(block))
        }
    }

    pub async fn fetch_missing_traces(&self, block: u64) -> eyre::Result<()> {
        tracing::info!(%block, "fetching missing trces");

        let clickhouse = Box::leak(Box::new(load_clickhouse().await));
        let multi = MultiProgress::default();
        let tables = Arc::new(vec![(
            Tables::TxTraces,
            Tables::TxTraces.build_init_state_progress_bar(&multi, 4),
        )]);

        self.libmdbx
            .initialize_table(
                clickhouse,
                self.tracing_provider.get_tracer(),
                Tables::TxTraces,
                false,
                Some((block - 2, block + 2)),
                tables,
                false,
            )
            .await?;
        multi.clear().unwrap();

        Ok(())
    }

    pub async fn fetch_missing_metadata(&self, block: u64) -> eyre::Result<()> {
        tracing::info!(%block, "fetching missing metadata");

        let clickhouse = Box::leak(Box::new(load_clickhouse().await));
        let multi = MultiProgress::default();
        let tables = Arc::new(vec![
            (Tables::BlockInfo, Tables::BlockInfo.build_init_state_progress_bar(&multi, 4)),
            (Tables::CexPrice, Tables::CexPrice.build_init_state_progress_bar(&multi, 50)),
            (Tables::CexTrades, Tables::CexTrades.build_init_state_progress_bar(&multi, 6)),
        ]);

        futures::try_join!(
            self.libmdbx.initialize_table(
                clickhouse,
                self.tracing_provider.get_tracer(),
                Tables::BlockInfo,
                false,
                Some((block - 2, block + 2)),
                tables.clone(),
                false,
            ),
            self.libmdbx.initialize_table(
                clickhouse,
                self.tracing_provider.get_tracer(),
                Tables::CexPrice,
                false,
                Some((block - 25, block + 25)),
                tables.clone(),
                false,
            ),
            self.libmdbx.initialize_table(
                clickhouse,
                self.tracing_provider.get_tracer(),
                Tables::CexTrades,
                false,
                Some((block - 10, block + 10)),
                tables,
                false
            ),
        )?;

        multi.clear().unwrap();

        Ok(())
    }

    pub async fn fetch_missing_trades(&self, block: u64) -> eyre::Result<()> {
        tracing::info!(%block, "fetching missing metadata");

        let clickhouse = Box::leak(Box::new(load_clickhouse().await));
        let multi = MultiProgress::default();
        let tables = Arc::new(vec![(
            Tables::CexPrice,
            Tables::CexPrice.build_init_state_progress_bar(&multi, 50),
        )]);

        self.libmdbx
            .initialize_table(
                clickhouse,
                self.tracing_provider.get_tracer(),
                Tables::CexTrades,
                false,
                Some((block - 5, block + 5)),
                tables,
                false,
            )
            .await?;

        multi.clear().unwrap();
        Ok(())
    }

    pub fn test_metadata_with_pricing(
        &self,
        block_num: u64,
        quote_asset: Address,
    ) -> eyre::Result<Metadata> {
        let mut meta = self.libmdbx.get_metadata(block_num, quote_asset)?;
        meta.cex_trades = Some(self.load_cex_trades(block_num));

        Ok(meta)
    }

    pub fn test_metadata(&self, block_num: u64, quote_asset: Address) -> eyre::Result<Metadata> {
        let mut meta = self
            .libmdbx
            .get_metadata_no_dex_price(block_num, quote_asset)?;
        meta.cex_trades = Some(self.load_cex_trades(block_num));

        Ok(meta)
    }

    fn load_cex_trades(&self, block: u64) -> CexTradeMap {
        let mut cex_window = CexWindow::new(WINDOW_TIME_SEC);
        let window = cex_window.get_window_lookahead();
        // given every download is -6 + 6 around the block
        // we calculate the offset from the current block that we need
        let offsets = (window / 12) as u64;
        let mut trades = Vec::new();
        tracing::debug!(?offsets);
        for block in block - offsets..=block + offsets {
            if let Ok(res) = self.libmdbx.get_cex_trades(block) {
                trades.push(res);
            }
        }
        let last_block = block + offsets;
        cex_window.init(last_block, trades);

        cex_window.cex_trade_map()
    }

    pub async fn get_block_traces_with_header(
        &self,
        block: u64,
    ) -> Result<BlockTracesWithHeaderAnd<()>, TraceLoaderError> {
        let (_, traces, header) = self.trace_block(block).await?;
        Ok(BlockTracesWithHeaderAnd { traces, header, block, other: () })
    }

    pub async fn get_block_traces_with_header_range(
        &self,
        start_block: u64,
        end_block: u64,
    ) -> Result<Vec<BlockTracesWithHeaderAnd<()>>, TraceLoaderError> {
        join_all((start_block..=end_block).map(|block| async move {
            let (_, traces, header) = self.trace_block(block).await?;
            Ok(BlockTracesWithHeaderAnd { traces, header, block, other: () })
        }))
        .await
        .into_iter()
        .collect()
    }

    pub async fn get_block_traces_with_header_and_metadata(
        &self,
        block: u64,
    ) -> Result<BlockTracesWithHeaderAnd<Metadata>, TraceLoaderError> {
        let (_, traces, header) = self.trace_block(block).await?;
        let metadata = self.get_metadata(block, false).await?;

        Ok(BlockTracesWithHeaderAnd { block, traces, header, other: metadata })
    }

    pub async fn get_block_traces_with_header_and_metadata_range(
        &self,
        start_block: u64,
        end_block: u64,
    ) -> Result<Vec<BlockTracesWithHeaderAnd<Metadata>>, TraceLoaderError> {
        join_all((start_block..=end_block).map(|block| async move {
            let (_, traces, header) = self.trace_block(block).await?;
            let metadata = self.get_metadata(block, false).await?;
            Ok(BlockTracesWithHeaderAnd { traces, header, block, other: metadata })
        }))
        .await
        .into_iter()
        .collect()
    }

    pub async fn get_tx_trace_with_header(
        &self,
        tx_hash: B256,
    ) -> Result<TxTracesWithHeaderAnd<()>, TraceLoaderError> {
        let (block, tx_idx) = self
            .tracing_provider
            .get_tracer()
            .block_and_tx_index(tx_hash)
            .await?;
        let (_, traces, header) = self.trace_block(block).await?;
        let trace = traces[tx_idx].clone();

        Ok(TxTracesWithHeaderAnd { block, tx_hash, trace, header, other: () })
    }

    pub async fn get_tx_traces_with_header(
        &self,
        tx_hashes: Vec<B256>,
    ) -> Result<Vec<BlockTracesWithHeaderAnd<()>>, TraceLoaderError> {
        let mut flattened: FastHashMap<u64, BlockTracesWithHeaderAnd<()>> = FastHashMap::default();

        for res in join_all(tx_hashes.into_iter().map(|tx_hash| async move {
            let (block, tx_idx) = self
                .tracing_provider
                .get_tracer()
                .block_and_tx_index(tx_hash)
                .await?;
            let (_, traces, header) = self.trace_block(block).await?;
            let trace = traces[tx_idx].clone();

            Ok::<_, TraceLoaderError>(TxTracesWithHeaderAnd {
                block,
                tx_hash,
                trace,
                header,
                other: (),
            })
        }))
        .await
        {
            let res = res?;
            match flattened.entry(res.block) {
                Entry::Occupied(mut o) => {
                    let e = o.get_mut();
                    e.traces.push(res.trace)
                }
                Entry::Vacant(v) => {
                    let entry = BlockTracesWithHeaderAnd {
                        traces: vec![res.trace],
                        block:  res.block,
                        other:  (),
                        header: res.header,
                    };
                    v.insert(entry);
                }
            }
        }

        let mut res = flattened
            .into_values()
            .map(|mut traces| {
                traces
                    .traces
                    .sort_by(|t0, t1| t0.tx_index.cmp(&t1.tx_index));
                traces
            })
            .collect::<Vec<_>>();
        res.sort_by(|a, b| a.block.cmp(&b.block));

        Ok(res)
    }

    pub async fn get_tx_trace_with_header_and_metadata(
        &self,
        tx_hash: B256,
    ) -> Result<TxTracesWithHeaderAnd<Metadata>, TraceLoaderError> {
        let (block, tx_idx) = self
            .tracing_provider
            .get_tracer()
            .block_and_tx_index(tx_hash)
            .await?;
        let (_, traces, header) = self.trace_block(block).await?;
        let metadata = self.get_metadata(block, false).await?;
        let trace = traces[tx_idx].clone();

        Ok(TxTracesWithHeaderAnd { block, tx_hash, trace, header, other: metadata })
    }

    pub async fn get_tx_traces_with_header_and_metadata(
        &self,
        tx_hashes: Vec<B256>,
    ) -> Result<Vec<TxTracesWithHeaderAnd<Metadata>>, TraceLoaderError> {
        join_all(tx_hashes.into_iter().map(|tx_hash| async move {
            let (block, tx_idx) = self
                .tracing_provider
                .get_tracer()
                .block_and_tx_index(tx_hash)
                .await?;
            let (_, traces, header) = self.trace_block(block).await?;
            let metadata = self.get_metadata(block, false).await?;
            let trace = traces[tx_idx].clone();

            Ok(TxTracesWithHeaderAnd { block, tx_hash, trace, header, other: metadata })
        }))
        .await
        .into_iter()
        .collect()
    }
}

#[derive(Debug, Error)]
pub enum TraceLoaderError {
    #[error("no metadata found in libmdbx for block: {0}")]
    NoMetadataFound(u64),
    #[error("failed to trace block: {0}")]
    BlockTraceError(u64),
    #[error(transparent)]
    ProviderError(#[from] ProviderError),
    #[error(transparent)]
    EyreError(#[from] eyre::Report),
}

pub struct TxTracesWithHeaderAnd<T> {
    pub block:   u64,
    pub tx_hash: B256,
    pub trace:   TxTrace,
    pub header:  Header,
    pub other:   T,
}

pub struct BlockTracesWithHeaderAnd<T> {
    pub block:  u64,
    pub traces: Vec<TxTrace>,
    pub header: Header,
    pub other:  T,
}

// done because we can only have 1 instance of libmdbx or we error
static DB_HANDLE: tokio::sync::OnceCell<&'static LibmdbxReadWriter> = OnceCell::const_new();
#[cfg(feature = "local-reth")]
static RETH_DB_HANDLE: OnceLock<Arc<DatabaseEnv>> = OnceLock::new();

pub async fn get_db_handle(handle: Handle) -> &'static LibmdbxReadWriter {
    *DB_HANDLE
        .get_or_init(|| async {
            let _ = dotenv::dotenv();
            init_tracing();
            let brontes_db_path =
                env::var("BRONTES_TEST_DB_PATH").expect("No BRONTES_TEST_DB_PATH in .env");

            let this = &*Box::leak(Box::new(
                LibmdbxReadWriter::init_db_tests(&brontes_db_path).unwrap_or_else(|e| {
                    panic!("failed to open db path {}, err={}", brontes_db_path, e)
                }),
            ));

            let (tx, _rx) = unbounded_channel();
            let clickhouse = Box::leak(Box::new(load_clickhouse().await));
            let tracer = init_trace_parser(handle, tx, this, 5).await;
            if init_crit_tables(this) {
                tracing::info!("initting crit tables");
                this.initialize_full_range_tables(clickhouse, tracer.get_tracer(), false)
                    .await
                    .unwrap();
            } else {
                tracing::info!("skipping crit table init");
            }

            this
        })
        .await
}

/// will trigger a update if a test with a new highest block is written
/// or if any of the 3 critical tables are empty
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CritTablesCache {
    pub biggest_block: u64,
    pub tables:        FastHashMap<Tables, usize>,
}

fn init_crit_tables(db: &LibmdbxReadWriter) -> bool {
    // try load table cache
    let tables =
        &[Tables::PoolCreationBlocks, Tables::AddressToProtocolInfo, Tables::TokenDecimals];

    let mut is_init = true;
    let mut map = FastHashMap::default();
    for table in tables {
        let cnt = match table {
            Tables::PoolCreationBlocks => db.get_table_entry_count::<PoolCreationBlocks>().unwrap(),
            Tables::AddressToProtocolInfo => {
                db.get_table_entry_count::<AddressToProtocolInfo>().unwrap()
            }
            Tables::TokenDecimals => db.get_table_entry_count::<TokenDecimals>().unwrap(),
            _ => unreachable!(),
        };
        is_init &= cnt != 0;
        map.insert(*table, cnt);
    }

    let write_fn = |block: u64| {
        let cache = CritTablesCache { biggest_block: block, tables: map };
        let mut file = OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(".test_cache.json")
            .unwrap();
        let strd = serde_json::to_string(&cache).unwrap();

        write!(&mut file, "{}", strd).unwrap();
        file.flush().unwrap();
    };

    // try fetch highest block number. if there is no highest block number.
    // init crit tables and save current cache.
    let Ok(max_block) = db.get_highest_block_number() else {
        tracing::info!("no highest block found");
        write_fn(0);

        return true
    };
    // try load file.
    let Ok(cache_data) = std::fs::read_to_string(".test_cache.json") else {
        tracing::info!("no .test_cache.json found");
        write_fn(max_block);
        return true
    };

    let stats: CritTablesCache = serde_json::from_str(&cache_data).unwrap();
    // now that we have loaded the stats. lets update them.
    write_fn(max_block);

    // we init if stats.biggest block is < the db biggest block or we have a table
    // with zero entries
    tracing::info!(cache_block=?stats.biggest_block, ?max_block, ?is_init);
    stats.biggest_block < max_block || !is_init
}

#[cfg(feature = "local-reth")]
pub fn get_reth_db_handle() -> Arc<DatabaseEnv> {
    RETH_DB_HANDLE
        .get_or_init(|| {
            let db_path = env::var("DB_PATH").expect("No DB_PATH in .env");
            Arc::new(init_db(db_path).unwrap())
        })
        .clone()
}

// if we want more tracing/logging/metrics layers, build and push to this vec
// the stdout one (logging) is the only 1 we need
//
// peep the Database repo -> bin/sorella-db/src/cli.rs line 34 for example
pub fn init_tracing() {
    // all lower level logging directives include higher level ones (Trace includes
    // all, Debug includes all but Trace, ...)
    let verbosity_level = Level::INFO; // Error >= Warn >= Info >= Debug >= Trace
    let directive: Directive = format!("{verbosity_level}").parse().unwrap();
    let layers = vec![brontes_tracing::stdout(directive)];

    brontes_tracing::init(layers);
}

#[cfg(feature = "local-reth")]
pub async fn init_trace_parser(
    handle: Handle,
    metrics_tx: UnboundedSender<ParserMetricEvents>,
    libmdbx: &'static LibmdbxReadWriter,
    max_tasks: u32,
) -> TraceParser<Box<dyn TracingProvider>, LibmdbxReadWriter> {
    let executor = brontes_types::BrontesTaskManager::new(handle.clone(), true);

    let db_path = env::var("DB_PATH").expect("No DB_PATH in .env");
    let db_path = std::path::Path::new(&db_path);
    let mut static_files = db_path.to_path_buf();
    static_files.pop();
    static_files.push("static_files");

    let client = TracingClient::new_with_db(
        get_reth_db_handle(),
        max_tasks as u64,
        executor.executor(),
        static_files,
    );
    handle.spawn(executor);
    let tracer = Box::new(client) as Box<dyn TracingProvider>;

    TraceParser::new(libmdbx, Arc::new(tracer), Arc::new(metrics_tx)).await
}

#[cfg(not(feature = "local-reth"))]
pub async fn init_trace_parser(
    _handle: Handle,
    metrics_tx: UnboundedSender<ParserMetricEvents>,
    libmdbx: &'static LibmdbxReadWriter,
    _max_tasks: u32,
) -> TraceParser<Box<dyn TracingProvider>, LibmdbxReadWriter> {
    let db_endpoint = env::var("RETH_ENDPOINT").expect("No db Endpoint in .env");
    let db_port = env::var("RETH_PORT").expect("No DB port.env");
    let url = format!("{db_endpoint}:{db_port}");
    let tracer = Box::new(LocalProvider::new(url, 15)) as Box<dyn TracingProvider>;

    TraceParser::new(libmdbx, Arc::new(tracer), Arc::new(metrics_tx)).await
}

#[cfg(feature = "local-clickhouse")]
pub async fn load_clickhouse() -> Clickhouse {
    Clickhouse::new_default(None).await
}

#[cfg(not(feature = "local-clickhouse"))]
pub async fn load_clickhouse() -> ClickhouseHttpClient {
    let clickhouse_api = env::var("CLICKHOUSE_API").expect("No CLICKHOUSE_API in .env");
    let clickhouse_api_key = env::var("CLICKHOUSE_API_KEY").ok();
    ClickhouseHttpClient::new(clickhouse_api, clickhouse_api_key).await
}