solana-hbase-reader 3.1.8

Solana HBase storage reader library
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#![allow(clippy::integer_arithmetic)]

use {
    crate::{
        deserializer::deserialize_protobuf_or_bincode_cell_data,
        tx_utils::{
            calculate_epoch,
            determine_transaction_type,
        },
        tx_cache::{
            get_cached_transaction,
        },
        storage_config::LedgerStorageConfig,
        hbase_error,
        connection,
        hbase,
    },
    async_trait::async_trait,
    log::*,
    // TODO: Implement metrics
    // solana_metrics::Metrics,
    //-------------------------
    // solana_metrics::{datapoint_info, inc_new_counter_debug},
    solana_clock::{
        Slot,
    },
    solana_pubkey::{
        Pubkey,
    },
    solana_signature::{
        Signature,
    },
    dexter_storage_proto_tx::convert::{generated},
    solana_storage_proto::convert::{
        tx_by_addr
    },
    solana_transaction_status::{
        ConfirmedBlock, ConfirmedTransactionStatusWithSignature,
        ConfirmedTransactionWithStatusMeta,
        TransactionByAddrInfo,
    },
    solana_transaction_status_client_types::{
        TransactionStatus,
    },
    solana_storage_reader::{
        Error, Result, LedgerStorageAdapter,
        StoredConfirmedBlock,
        StoredConfirmedTransactionWithStatusMeta,
        LegacyTransactionByAddrInfo,
    },
    solana_storage_utils::{
        tx_info::TransactionInfo,
        slot_to_blocks_key,
        slot_to_tx_by_addr_key,
        key_to_slot,
    },
    std::{
        convert::{TryInto},
        time::{Duration, Instant},
        boxed::Box,
    },
    memcache::Client as MemcacheClient,
    tokio::task,
};

// impl std::convert::From<hbase::Error> for Error {
//     fn from(err: hbase::Error) -> Self {
//         Self::StorageBackendError(Box::new(err))
//     }
// }

impl From<hbase_error::Error> for Error {
    fn from(err: hbase_error::Error) -> Self {
        Self::StorageBackendError(Box::new(err))
    }
}

#[derive(Clone)]
pub struct LedgerStorage {
    connection: connection::HBaseConnection,
    use_md5_row_key_salt: bool,
    cache_client: Option<MemcacheClient>,
    disable_tx_fallback: bool,
    // TODO: Implement metrics
    // metrics: Arc<Metrics>,
    //----------------------
}

impl LedgerStorage {
    #[allow(dead_code)]
    pub async fn new(
        read_only: bool,
        timeout: Option<std::time::Duration>,
        // TODO: Implement metrics
        // metrics: Arc<Metrics>,
        //-----------------------
    ) -> Result<Self> {
        Self::new_with_config(LedgerStorageConfig {
                read_only,
                timeout,
                ..LedgerStorageConfig::default()
            },
           // TODO: Implement metrics
           // metrics.clone(),
           //---------------------
        )
            .await
    }

    #[allow(dead_code)]
    pub async fn new_with_config(
        config: LedgerStorageConfig,
        // TODO: Implement metrics
        // metrics: Arc<Metrics>
        //-----------------------
    ) -> Result<Self> {
        debug!("Creating ledger storage instance with config: {:?}", config);
        let LedgerStorageConfig {
            read_only,
            timeout,
            address,
            use_md5_row_key_salt,
            enable_full_tx_cache,
            disable_tx_fallback,
            cache_address,
        } = config;
        let connection = connection::HBaseConnection::new(
            address.as_str(),
            read_only,
            timeout,
        )
            .await?;

        let cache_client = if enable_full_tx_cache {
            if let Some(cache_addr) = cache_address {
                let cache_addr = format!("memcache://{}?timeout=1&protocol=ascii", cache_addr);

                let cache_addr_clone = cache_addr.clone();

                match task::spawn_blocking(move || MemcacheClient::connect(cache_addr_clone.as_str())).await {
                    Ok(Ok(client)) => Some(client),
                    Ok(Err(e)) => {
                        error!("Failed to connect to cache server at {}: {}", cache_addr, e);
                        None
                    },
                    Err(e) => {
                        error!("Tokio task join error while connecting to cache server: {}", e);
                        None
                    }
                }
            } else {
                None
            }
        } else {
            None
        };

        Ok(Self {
            connection,
            use_md5_row_key_salt,
            cache_client,
            disable_tx_fallback,
            // TODO: Implement metrics
            // metrics,
            //------------------------
        })
    }
}

#[async_trait]
impl LedgerStorageAdapter for LedgerStorage {
    /// Return the available slot that contains a block
    async fn get_first_available_block(&self) -> Result<Option<Slot>> {
        debug!("LedgerStorage::get_first_available_block request received");

        if self.use_md5_row_key_salt {
            return Ok(Some(0));
        }

        // inc_new_counter_debug!("storage-hbase-query", 1);
        let mut hbase = self.connection.client();
        let blocks = hbase.get_row_keys("blocks", None, None, 1, false).await?;
        if blocks.is_empty() {
            return Ok(None);
        }
        Ok(key_to_slot(&blocks[0]))
    }

    /// Fetch the next slots after the provided slot that contains a block
    ///
    /// start_slot: slot to start the search from (inclusive)
    /// limit: stop after this many slots have been found
    async fn get_confirmed_blocks(&self, start_slot: Slot, limit: usize) -> Result<Vec<Slot>> {
        debug!(
            "LedgerStorage::get_confirmed_blocks request received: {:?} {:?}",
            start_slot, limit
        );

        if self.use_md5_row_key_salt {
            return Ok(vec![]);
        }

        // inc_new_counter_debug!("storage-hbase-query", 1);
        let mut hbase = self.connection.client();
        let blocks = hbase
            .get_row_keys(
                "blocks",
                Some(slot_to_blocks_key(start_slot, false)),
                Some(slot_to_blocks_key(start_slot + limit as u64, false)), // None,
                limit as i64,
                false
            )
            .await?;
        Ok(blocks.into_iter().filter_map(|s| key_to_slot(&s)).collect())
    }

    /// Fetch the confirmed block from the desired slot
    async fn get_confirmed_block(&self, slot: Slot) -> Result<ConfirmedBlock> {
        debug!(
            "LedgerStorage::get_confirmed_block request received: {:?}",
            slot
        );
        // inc_new_counter_debug!("storage-hbase-query", 1);

        let start = Instant::now();
        let mut hbase = self.connection.client();
        let duration: Duration = start.elapsed();
        debug!("HBase connection took {:?}", duration);

        let block_cell_data_serialized = hbase
            .get_protobuf_or_bincode_cell_serialized::<StoredConfirmedBlock, generated::ConfirmedBlock>(
                "blocks",
                slot_to_blocks_key(slot, self.use_md5_row_key_salt),
            )
            .await
            .map_err(|err| {
                match err {
                    hbase_error::Error::RowNotFound => Error::BlockNotFound(slot),
                    _ => err.into(),
                }
            })?;

        let block_cell_data =
            deserialize_protobuf_or_bincode_cell_data::<StoredConfirmedBlock, generated::ConfirmedBlock>(
                &block_cell_data_serialized,
                "blocks",
                slot_to_blocks_key(slot, self.use_md5_row_key_salt),
            )?;

        let block: ConfirmedBlock = match block_cell_data {
            hbase::CellData::Bincode(block) => block.into(),
            hbase::CellData::Protobuf(block) => block.try_into().map_err(|_err| {
                error!("Protobuf object is corrupted");
                hbase_error::Error::ObjectCorrupt(format!("blocks/{}", slot_to_blocks_key(slot, self.use_md5_row_key_salt)))
            })?,
        };

        Ok(block)
    }

    async fn get_signature_status(&self, signature: &Signature) -> Result<TransactionStatus> {
        debug!(
            "LedgerStorage::get_signature_status request received: {:?}",
            signature
        );
        // inc_new_counter_debug!("storage-hbase-query", 1);
        let mut hbase = self.connection.client();
        let transaction_info = hbase
            .get_bincode_cell::<TransactionInfo>("tx", signature.to_string())
            .await
            .map_err(|err| match err {
                // hbase::Error::RowNotFound => Error::SignatureNotFound,
                hbase_error::Error::RowNotFound => Error::SignatureNotFound,
                _ => err.into(),
            })?;
        Ok(transaction_info.into())
    }

    async fn get_full_transaction(
        &self,
        signature: &Signature,
    ) -> Result<Option<ConfirmedTransactionWithStatusMeta>> {
        debug!(
            "LedgerStorage::get_full_transaction request received: {:?}",
            signature
        );
        // inc_new_counter_debug!("storage-hbase-query", 1);

        let mut hbase = self.connection.client();

        let tx_cell_data = hbase
            .get_protobuf_or_bincode_cell::<StoredConfirmedTransactionWithStatusMeta, generated::ConfirmedTransactionWithStatusMeta>(
                "tx_full",
                signature.to_string(),
            )
            .await
            .map_err(|err| match err {
                hbase_error::Error::RowNotFound => Error::SignatureNotFound,
                _ => err.into(),
            })?;

        Ok(match tx_cell_data {
            hbase::CellData::Bincode(tx) => Some(tx.into()),
            hbase::CellData::Protobuf(tx) => Some(tx.try_into().map_err(|_err| {
                error!("Protobuf object is corrupted");
                hbase_error::Error::ObjectCorrupt(format!("tx_full/{}", signature.to_string()))
            })?),
        })
    }

    /// Fetch a confirmed transaction
    async fn get_confirmed_transaction(
        &self,
        signature: &Signature,
    ) -> Result<Option<ConfirmedTransactionWithStatusMeta>> {
        debug!(
            "LedgerStorage::get_confirmed_transaction request received: {:?}",
            signature
        );
        debug!("LedgerStorage::get_confirmed_transaction using address: {:?}", self.connection);

        // let mut source = "tx";
        let _tx_type;
        let _epoch: u64;

        if let Some(cache_client) = &self.cache_client {
            match get_cached_transaction::<generated::ConfirmedTransactionWithStatusMeta>(cache_client, signature).await {
                Ok(Some(tx)) => {
                    let confirmed_tx: ConfirmedTransactionWithStatusMeta = match tx.try_into() {
                        Ok(val) => val,
                        Err(_) => {
                            warn!("Cached protobuf object is corrupted for transaction {}", signature.to_string());
                            return Ok(None);
                        }
                    };

                    _epoch = calculate_epoch(confirmed_tx.slot);

                    // source = "cache";
                    _tx_type = determine_transaction_type(&confirmed_tx.tx_with_meta);
                    // TODO: Implement metrics
                    // self.metrics.record_transaction(source, _epoch, _tx_type);
                    //-------------------------

                    return Ok(Some(confirmed_tx));
                }
                Ok(None) => {
                    debug!("Transaction {} not found in cache", signature);
                }
                Err(e) => {
                    warn!("Failed to read transaction from cache for {}: {:?}",signature, e);
                }
            }
        }

        // inc_new_counter_debug!("storage-hbase-query", 1);

        if let Ok(Some(full_tx)) = self.get_full_transaction(signature).await {
            _epoch = calculate_epoch(full_tx.slot);

            // source = "tx_full";
            _tx_type = determine_transaction_type(&full_tx.tx_with_meta);
            // TODO: Implement metrics
            // self.metrics.record_transaction(source, epoch, _tx_type);
            //------------------------

            return Ok(Some(full_tx));
        } else {
            debug!("Transaction not found in the full_tx table");
        }

        debug!("disable_tx_fallback: {:?}", self.disable_tx_fallback);

        if self.disable_tx_fallback {
            debug!("Fallback to tx table is disabled");
            return Ok(None);
        }

        debug!("Looking for transaction in tx table");

        let mut hbase = self.connection.client();

        // Figure out which block the transaction is located in
        let TransactionInfo { slot, index, .. } = hbase
            .get_bincode_cell("tx", signature.to_string())
            .await
            .map_err(|err| match err {
                hbase_error::Error::RowNotFound => Error::SignatureNotFound,
                _ => Error::StorageBackendError(Box::new(err)),
            })?;

        _epoch = calculate_epoch(slot);

        // Load the block and return the transaction
        let block = self.get_confirmed_block(slot).await?;
        match block.transactions.into_iter().nth(index as usize) {
            None => {
                warn!("Transaction info for {} is corrupt", signature);
                Ok(None)
            }
            Some(tx_with_meta) => {
                if tx_with_meta.transaction_signature() != signature {
                    warn!(
                        "Transaction info or confirmed block for {} is corrupt",
                        signature
                    );
                    Ok(None)
                } else {
                    _tx_type = determine_transaction_type(&tx_with_meta); // Determine the transaction type
                    // TODO: Implement metrics
                    // self.metrics.record_transaction(source, _epoch, _tx_type);
                    //-------------------------

                    Ok(Some(ConfirmedTransactionWithStatusMeta {
                        slot,
                        tx_with_meta,
                        block_time: block.block_time,
                    }))
                }
            }
        }
    }

    async fn get_confirmed_signatures_for_address(
        &self,
        address: &Pubkey,
        before_signature: Option<&Signature>,
        until_signature: Option<&Signature>,
        limit: usize,
    ) -> Result<
        Vec<(
            ConfirmedTransactionStatusWithSignature,
            u32,
        )>,
    > {
        // info!(
        //     "LedgerStorage::get_confirmed_signatures_for_address: {:?}",
        //     address
        // );
        // info!("Using signature range [before: {:?}, until: {:?}]", before_signature.clone(), until_signature.clone());

        // inc_new_counter_debug!("storage-hbase-query", 1);
        let mut hbase = self.connection.client();
        let address_prefix = format!("{address}/");

        // Figure out where to start listing from based on `before_signature`
        let (first_slot, before_transaction_index, before_fallback) = match before_signature {
            None => (Slot::MAX, 0, false),
            Some(before_signature) => {
                // Try fetching from `tx` first
                match hbase.get_bincode_cell("tx", before_signature.to_string()).await {
                    Ok(TransactionInfo { slot, index, .. }) => (slot, index, false),
                    // Fallback to `tx_full` if `tx` is not found
                    Err(hbase_error::Error::RowNotFound) => {
                        match self.get_full_transaction(before_signature).await? {
                            Some(full_transaction) => (full_transaction.slot, 0, true),
                            None => return Ok(vec![]),
                        }
                    },
                    Err(err) => return Err(err.into()),
                }
            }
        };

        debug!("Got starting slot: {:?}, index: {:?}, using tx_full fallback: {:?}",
            first_slot.clone(),
            before_transaction_index.clone(),
            before_fallback
        );

        // Figure out where to end listing from based on `until_signature`
        let (last_slot, until_transaction_index, until_fallback) = match until_signature {
            None => (0, u32::MAX, false),
            Some(until_signature) => {
                // Try fetching from `tx` first
                match hbase.get_bincode_cell("tx", until_signature.to_string()).await {
                    Ok(TransactionInfo { slot, index, .. }) => (slot, index, false),
                    // Fallback to `tx_full` if `tx` is not found
                    Err(hbase_error::Error::RowNotFound) => {
                        match self.get_full_transaction(until_signature).await? {
                            Some(full_transaction) => (full_transaction.slot, 0, true),
                            None => return Ok(vec![]),
                        }
                    },
                    Err(err) => return Err(err.into()),
                }
            }
        };

        debug!("Got ending slot: {:?}, index: {:?}, using tx_full fallback: {:?}",
            last_slot.clone(),
            until_transaction_index.clone(),
            until_fallback
        );

        let mut infos = vec![];

        debug!("Getting the starting slot length from tx-by-addr");

        let starting_slot_tx_len = hbase
            .get_protobuf_or_bincode_cell::<Vec<LegacyTransactionByAddrInfo>, tx_by_addr::TransactionByAddr>(
                "tx-by-addr",
                format!("{}{}", address_prefix, slot_to_tx_by_addr_key(first_slot)),
            )
            .await
            .map(|cell_data| {
                match cell_data {
                    hbase::CellData::Bincode(tx_by_addr) => tx_by_addr.len(),
                    hbase::CellData::Protobuf(tx_by_addr) => tx_by_addr.tx_by_addrs.len(),
                }
            })
            .unwrap_or(0);

        debug!("Got starting slot tx len: {:?}", starting_slot_tx_len);

        // Return the next tx-by-addr data of amount `limit` plus extra to account for the largest
        // number that might be flitered out
        let tx_by_addr_data = hbase
            .get_row_data(
                "tx-by-addr",
                Some(format!(
                    "{}{}",
                    address_prefix,
                    slot_to_tx_by_addr_key(first_slot),
                )),
                Some(format!(
                    "{}{}",
                    address_prefix,
                    slot_to_tx_by_addr_key(last_slot.saturating_sub(1)),
                )),
                limit as i64 + starting_slot_tx_len as i64,
            )
            .await?;

        debug!("Loaded {:?} tx-by-addr entries", tx_by_addr_data.len());

        'outer: for (row_key, data) in tx_by_addr_data {
            let slot = !key_to_slot(&row_key[address_prefix.len()..]).ok_or_else(|| {
                hbase_error::Error::ObjectCorrupt(format!(
                    "Failed to convert key to slot: tx-by-addr/{row_key}"
                ))
            })?;

            debug!("Deserializing tx-by-addr result data");

            let deserialized_cell_data = deserialize_protobuf_or_bincode_cell_data::<
                Vec<LegacyTransactionByAddrInfo>,
                tx_by_addr::TransactionByAddr,
            >(&data, "tx-by-addr", row_key.clone())?;

            let mut cell_data: Vec<TransactionByAddrInfo> = match deserialized_cell_data {
                hbase::CellData::Bincode(tx_by_addr) => {
                    tx_by_addr.into_iter().map(|legacy| legacy.into()).collect()
                }
                hbase::CellData::Protobuf(tx_by_addr) => {
                    tx_by_addr.try_into().map_err(|error| {
                        hbase_error::Error::ObjectCorrupt(format!(
                            "Failed to deserialize: {}: tx-by-addr/{}",
                            error,
                            row_key.clone()
                        ))
                    })?
                }
            };

            cell_data.reverse();

            debug!("Filtering the result data");

            for tx_by_addr_info in cell_data.into_iter() {
                debug!("Checking result [slot: {:?}, index: {:?}], signature: {:?}", slot, tx_by_addr_info.index, tx_by_addr_info.signature);

                // Filter out records before `before_transaction_index`
                if !before_fallback && slot == first_slot && tx_by_addr_info.index >= before_transaction_index {
                    debug!("Skipping transaction before [slot: {:?}, index: {:?}], signature: {:?}", slot, tx_by_addr_info.index, tx_by_addr_info.signature);
                    continue;
                }

                // Filter out records after `until_transaction_index` unless fallback was used
                if !until_fallback && slot == last_slot && tx_by_addr_info.index <= until_transaction_index {
                    debug!("Skipping transaction until [slot: {:?}, index: {:?}], signature: {:?}", slot, tx_by_addr_info.index, tx_by_addr_info.signature);
                    continue;
                }

                infos.push((
                    ConfirmedTransactionStatusWithSignature {
                        signature: tx_by_addr_info.signature,
                        slot,
                        err: tx_by_addr_info.err,
                        memo: tx_by_addr_info.memo,
                        block_time: tx_by_addr_info.block_time,
                    },
                    tx_by_addr_info.index,
                ));
                // Respect limit
                debug!("Checking the limit: {:?}/{:?}", infos.len(), limit);
                if infos.len() >= limit {
                    debug!("Limit was reached, exiting loop");
                    break 'outer;
                }
            }
        }

        debug!("Returning {:?} result entries", infos.len());

        Ok(infos)
    }

    async fn get_latest_stored_slot(&self) -> Result<Slot> {
        // inc_new_counter_debug!("storage-hbase-query", 1);
        let mut hbase = self.connection.client();
        match hbase.get_last_row_key("blocks").await {
            Ok(last_row_key) => {
                match key_to_slot(&last_row_key) {
                    Some(slot) => Ok(slot),
                    None => Err(Error::StorageBackendError(Box::new(hbase_error::Error::ObjectCorrupt(format!(
                        "Failed to parse row key '{}' as slot number",
                        last_row_key
                    ))))),
                }
            },
            Err(hbase_error::Error::RowNotFound) => {
                // If the table is empty, return a default value (e.g., first_slot - 1)
                Ok(Slot::default())
            },
            Err(e) => Err(Error::StorageBackendError(Box::new(e))),
        }
    }

    fn clone_box(&self) -> Box<dyn LedgerStorageAdapter> {
        Box::new(self.clone())
    }
}