1use std::{
22 collections::{HashMap, HashSet},
23 marker::PhantomData,
24 time::{Duration, Instant},
25};
26
27use anyhow::{bail, Context};
28use ark_serialize::CanonicalSerialize;
29use async_trait::async_trait;
30use committable::Committable;
31use derive_more::{Deref, DerefMut};
32use futures::{future::Future, stream::TryStreamExt};
33use hotshot_types::{
34 data::VidShare,
35 traits::{
36 block_contents::BlockHeader,
37 metrics::{Counter, Gauge, Histogram, Metrics},
38 node_implementation::{ConsensusTime, NodeType},
39 EncodeBytes,
40 },
41};
42use itertools::Itertools;
43use jf_merkle_tree::prelude::{MerkleNode, MerkleProof};
44pub use sqlx::Executor;
45use sqlx::{
46 pool::Pool, query_builder::Separated, types::BitVec, Encode, Execute, FromRow, QueryBuilder,
47 Type,
48};
49use tokio::time::sleep;
50
51use super::{
52 queries::{
53 self,
54 state::{build_hash_batch_insert, Node},
55 DecodeError,
56 },
57 Database, Db,
58};
59use crate::{
60 availability::{
61 BlockQueryData, LeafQueryData, QueryableHeader, QueryablePayload, StateCertQueryDataV2,
62 VidCommonQueryData,
63 },
64 data_source::{
65 storage::{pruning::PrunedHeightStorage, UpdateAvailabilityStorage},
66 update,
67 },
68 merklized_state::{MerklizedState, UpdateStateData},
69 types::HeightIndexed,
70 Header, Payload, QueryError, QueryResult,
71};
72
73pub type Query<'q> = sqlx::query::Query<'q, Db, <Db as Database>::Arguments<'q>>;
74pub type QueryAs<'q, T> = sqlx::query::QueryAs<'q, Db, T, <Db as Database>::Arguments<'q>>;
75
76pub fn query(sql: &str) -> Query<'_> {
77 sqlx::query(sql)
78}
79
80pub fn query_as<'q, T>(sql: &'q str) -> QueryAs<'q, T>
81where
82 T: for<'r> FromRow<'r, <Db as Database>::Row>,
83{
84 sqlx::query_as(sql)
85}
86
87#[derive(Clone, Copy, Debug, Default)]
89pub struct Write;
90
91#[derive(Clone, Copy, Debug, Default)]
93pub struct Read;
94
95pub trait TransactionMode: Send + Sync {
97 fn begin(
98 conn: &mut <Db as Database>::Connection,
99 ) -> impl Future<Output = anyhow::Result<()>> + Send;
100
101 fn display() -> &'static str;
102}
103
104impl TransactionMode for Write {
105 #[allow(unused_variables)]
106 async fn begin(conn: &mut <Db as Database>::Connection) -> anyhow::Result<()> {
107 #[cfg(feature = "embedded-db")]
136 conn.execute("UPDATE pruned_height SET id = id WHERE false")
137 .await?;
138
139 #[cfg(not(feature = "embedded-db"))]
142 conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE")
143 .await?;
144
145 Ok(())
146 }
147
148 fn display() -> &'static str {
149 "write"
150 }
151}
152
153impl TransactionMode for Read {
154 #[allow(unused_variables)]
155 async fn begin(conn: &mut <Db as Database>::Connection) -> anyhow::Result<()> {
156 #[cfg(not(feature = "embedded-db"))]
165 conn.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE")
166 .await?;
167
168 Ok(())
169 }
170
171 fn display() -> &'static str {
172 "read-only"
173 }
174}
175
176#[derive(Clone, Copy, Debug)]
177enum CloseType {
178 Commit,
179 Revert,
180 Drop,
181}
182
183#[derive(Debug)]
184struct TransactionMetricsGuard<Mode> {
185 started_at: Instant,
186 metrics: PoolMetrics,
187 close_type: CloseType,
188 _mode: PhantomData<Mode>,
189}
190
191impl<Mode: TransactionMode> TransactionMetricsGuard<Mode> {
192 fn begin(metrics: PoolMetrics) -> Self {
193 let started_at = Instant::now();
194 tracing::trace!(mode = Mode::display(), ?started_at, "begin");
195 metrics.open_transactions.update(1);
196
197 Self {
198 started_at,
199 metrics,
200 close_type: CloseType::Drop,
201 _mode: Default::default(),
202 }
203 }
204
205 fn set_closed(&mut self, t: CloseType) {
206 self.close_type = t;
207 }
208}
209
210impl<Mode> Drop for TransactionMetricsGuard<Mode> {
211 fn drop(&mut self) {
212 self.metrics
213 .transaction_durations
214 .add_point((self.started_at.elapsed().as_millis() as f64) / 1000.);
215 self.metrics.open_transactions.update(-1);
216 match self.close_type {
217 CloseType::Commit => self.metrics.commits.add(1),
218 CloseType::Revert => self.metrics.reverts.add(1),
219 CloseType::Drop => self.metrics.drops.add(1),
220 }
221 tracing::trace!(started_at = ?self.started_at, reason = ?self.close_type, "close");
222 }
223}
224
225#[derive(Debug, Deref, DerefMut)]
227pub struct Transaction<Mode> {
228 #[deref]
229 #[deref_mut]
230 inner: sqlx::Transaction<'static, Db>,
231 metrics: TransactionMetricsGuard<Mode>,
232}
233
234impl<Mode: TransactionMode> Transaction<Mode> {
235 pub(super) async fn new(pool: &Pool<Db>, metrics: PoolMetrics) -> anyhow::Result<Self> {
236 let mut inner = pool.begin().await?;
237 let metrics = TransactionMetricsGuard::begin(metrics);
238 Mode::begin(inner.as_mut()).await?;
239 Ok(Self { inner, metrics })
240 }
241}
242
243impl<Mode: TransactionMode> update::Transaction for Transaction<Mode> {
244 async fn commit(mut self) -> anyhow::Result<()> {
245 self.inner.commit().await?;
246 self.metrics.set_closed(CloseType::Commit);
247 Ok(())
248 }
249 fn revert(mut self) -> impl Future + Send {
250 async move {
251 self.inner.rollback().await.unwrap();
252 self.metrics.set_closed(CloseType::Revert);
253 }
254 }
255}
256
257pub trait Params<'p> {
287 fn bind<'q, 'r>(
288 self,
289 q: &'q mut Separated<'r, 'p, Db, &'static str>,
290 ) -> &'q mut Separated<'r, 'p, Db, &'static str>
291 where
292 'p: 'r;
293}
294
295pub trait FixedLengthParams<'p, const N: usize>: Params<'p> {}
301
302macro_rules! impl_tuple_params {
303 ($n:literal, ($($t:ident,)+)) => {
304 impl<'p, $($t),+> Params<'p> for ($($t,)+)
305 where $(
306 $t: 'p + Encode<'p, Db> + Type<Db>
307 ),+{
308 fn bind<'q, 'r>(self, q: &'q mut Separated<'r, 'p, Db, &'static str>) -> &'q mut Separated<'r, 'p, Db, &'static str>
309 where 'p: 'r,
310 {
311 #[allow(non_snake_case)]
312 let ($($t,)+) = self;
313 q $(
314 .push_bind($t)
315 )+
316
317 }
318 }
319
320 impl<'p, $($t),+> FixedLengthParams<'p, $n> for ($($t,)+)
321 where $(
322 $t: 'p + for<'q> Encode<'q, Db> + Type<Db>
323 ),+ {
324 }
325 };
326}
327
328impl_tuple_params!(1, (T,));
329impl_tuple_params!(2, (T1, T2,));
330impl_tuple_params!(3, (T1, T2, T3,));
331impl_tuple_params!(4, (T1, T2, T3, T4,));
332impl_tuple_params!(5, (T1, T2, T3, T4, T5,));
333impl_tuple_params!(6, (T1, T2, T3, T4, T5, T6,));
334impl_tuple_params!(7, (T1, T2, T3, T4, T5, T6, T7,));
335impl_tuple_params!(8, (T1, T2, T3, T4, T5, T6, T7, T8,));
336
337pub fn build_where_in<'a, I>(
338 query: &'a str,
339 column: &'a str,
340 values: I,
341) -> QueryResult<(queries::QueryBuilder<'a>, String)>
342where
343 I: IntoIterator,
344 I::Item: 'a + Encode<'a, Db> + Type<Db>,
345{
346 let mut builder = queries::QueryBuilder::default();
347 let params = values
348 .into_iter()
349 .map(|v| Ok(format!("{} ", builder.bind(v)?)))
350 .collect::<QueryResult<Vec<String>>>()?;
351
352 if params.is_empty() {
353 return Err(QueryError::Error {
354 message: "failed to build WHERE IN query. No parameter found ".to_string(),
355 });
356 }
357
358 let sql = format!(
359 "{query} where {column} IN ({}) ",
360 params.into_iter().join(",")
361 );
362
363 Ok((builder, sql))
364}
365
366impl Transaction<Write> {
368 pub async fn upsert<'p, const N: usize, R>(
369 &mut self,
370 table: &str,
371 columns: [&str; N],
372 pk: impl IntoIterator<Item = &str>,
373 rows: R,
374 ) -> anyhow::Result<()>
375 where
376 R: IntoIterator,
377 R::Item: 'p + FixedLengthParams<'p, N>,
378 {
379 let set_columns = columns
380 .iter()
381 .map(|col| format!("{col} = excluded.{col}"))
382 .join(",");
383 let columns_str = columns
384 .into_iter()
385 .map(|col| format!("\"{col}\""))
386 .join(",");
387 let pk = pk.into_iter().join(",");
388
389 let mut query_builder =
390 QueryBuilder::new(format!("INSERT INTO \"{table}\" ({columns_str}) "));
391 let mut num_rows = 0;
392
393 query_builder.push_values(rows, |mut b, row| {
394 num_rows += 1;
395 row.bind(&mut b);
396 });
397
398 if num_rows == 0 {
399 tracing::warn!("trying to upsert 0 rows, this has no effect");
400 return Ok(());
401 }
402 query_builder.push(format!(" ON CONFLICT ({pk}) DO UPDATE SET {set_columns}"));
403
404 let interval = Duration::from_secs(1);
405 let mut retries = 5;
406
407 loop {
408 let query = query_builder.build();
409 let statement = query.sql();
410 match self.execute(query).await {
411 Ok(res) => {
412 let rows_modified = res.rows_affected() as usize;
413 if rows_modified != num_rows {
414 let error = format!(
415 "unexpected number of rows modified: expected {num_rows}, got \
416 {rows_modified}. query: {statement}"
417 );
418 tracing::error!(error);
419 bail!(error);
420 }
421 return Ok(());
422 },
423 Err(err) => {
424 tracing::error!(
425 statement,
426 "error in statement execution ({} tries remaining): {err}",
427 retries
428 );
429 if retries == 0 {
430 bail!(err);
431 }
432 retries -= 1;
433 sleep(interval).await;
434 },
435 }
436 }
437 }
438}
439
440impl Transaction<Write> {
442 pub(super) async fn delete_batch(
444 &mut self,
445 state_tables: Vec<String>,
446 height: u64,
447 ) -> anyhow::Result<()> {
448 self.execute(query("DELETE FROM header WHERE height <= $1").bind(height as i64))
449 .await?;
450
451 for state_table in state_tables {
455 self.execute(
456 query(&format!(
457 "
458 DELETE FROM {state_table} WHERE (path, created) IN
459 (SELECT path, created FROM
460 (SELECT path, created,
461 ROW_NUMBER() OVER (PARTITION BY path ORDER BY created DESC) as rank
462 FROM {state_table} WHERE created <= $1) ranked_nodes WHERE rank != 1)"
463 ))
464 .bind(height as i64),
465 )
466 .await?;
467 }
468
469 self.save_pruned_height(height).await?;
470 Ok(())
471 }
472
473 pub(super) async fn save_pruned_height(&mut self, height: u64) -> anyhow::Result<()> {
475 self.upsert(
478 "pruned_height",
479 ["id", "last_height"],
480 ["id"],
481 [(1i32, height as i64)],
482 )
483 .await
484 }
485}
486
487impl<Types> UpdateAvailabilityStorage<Types> for Transaction<Write>
488where
489 Types: NodeType,
490 Payload<Types>: QueryablePayload<Types>,
491 Header<Types>: QueryableHeader<Types>,
492{
493 async fn insert_leaf(&mut self, leaf: LeafQueryData<Types>) -> anyhow::Result<()> {
494 let height = leaf.height();
495
496 if let Some(pruned_height) = self.load_pruned_height().await? {
499 if height <= pruned_height {
500 tracing::info!(
501 height,
502 pruned_height,
503 "ignoring leaf which is already pruned"
504 );
505 return Ok(());
506 }
507 }
508
509 let header_json = serde_json::to_value(leaf.leaf().block_header())
512 .context("failed to serialize header")?;
513 self.upsert(
514 "header",
515 ["height", "hash", "payload_hash", "data", "timestamp"],
516 ["height"],
517 [(
518 height as i64,
519 leaf.block_hash().to_string(),
520 leaf.leaf().block_header().payload_commitment().to_string(),
521 header_json,
522 leaf.leaf().block_header().timestamp() as i64,
523 )],
524 )
525 .await?;
526
527 let query = query("INSERT INTO payload (height) VALUES ($1) ON CONFLICT DO NOTHING")
535 .bind(height as i64);
536 query.execute(self.as_mut()).await?;
537
538 let leaf_json = serde_json::to_value(leaf.leaf()).context("failed to serialize leaf")?;
541 let qc_json = serde_json::to_value(leaf.qc()).context("failed to serialize QC")?;
542 self.upsert(
543 "leaf2",
544 ["height", "hash", "block_hash", "leaf", "qc"],
545 ["height"],
546 [(
547 height as i64,
548 leaf.hash().to_string(),
549 leaf.block_hash().to_string(),
550 leaf_json,
551 qc_json,
552 )],
553 )
554 .await?;
555
556 Ok(())
557 }
558
559 async fn insert_block(&mut self, block: BlockQueryData<Types>) -> anyhow::Result<()> {
560 let height = block.height();
561
562 if let Some(pruned_height) = self.load_pruned_height().await? {
565 if height <= pruned_height {
566 tracing::info!(
567 height,
568 pruned_height,
569 "ignoring block which is already pruned"
570 );
571 return Ok(());
572 }
573 }
574
575 let payload = block.payload.encode();
578
579 self.upsert(
580 "payload",
581 ["height", "data", "size", "num_transactions"],
582 ["height"],
583 [(
584 height as i64,
585 payload.as_ref().to_vec(),
586 block.size() as i32,
587 block.num_transactions() as i32,
588 )],
589 )
590 .await?;
591
592 let mut rows = vec![];
594 for (txn_ix, txn) in block.enumerate() {
595 let ns_id = block.header().namespace_id(&txn_ix.ns_index).unwrap();
596 rows.push((
597 txn.commit().to_string(),
598 height as i64,
599 txn_ix.ns_index.into(),
600 ns_id.into(),
601 txn_ix.position as i64,
602 ));
603 }
604 if !rows.is_empty() {
605 self.upsert(
606 "transactions",
607 ["hash", "block_height", "ns_index", "ns_id", "position"],
608 ["block_height", "ns_id", "position"],
609 rows,
610 )
611 .await?;
612 }
613
614 Ok(())
615 }
616
617 async fn insert_vid(
618 &mut self,
619 common: VidCommonQueryData<Types>,
620 share: Option<VidShare>,
621 ) -> anyhow::Result<()> {
622 let height = common.height();
623
624 if let Some(pruned_height) = self.load_pruned_height().await? {
627 if height <= pruned_height {
628 tracing::info!(
629 height,
630 pruned_height,
631 "ignoring VID common which is already pruned"
632 );
633 return Ok(());
634 }
635 }
636
637 let common_data =
638 bincode::serialize(common.common()).context("failed to serialize VID common data")?;
639 if let Some(share) = share {
640 let share_data = bincode::serialize(&share).context("failed to serialize VID share")?;
641 self.upsert(
642 "vid2",
643 ["height", "common", "share"],
644 ["height"],
645 [(height as i64, common_data, share_data)],
646 )
647 .await
648 } else {
649 self.upsert(
653 "vid2",
654 ["height", "common"],
655 ["height"],
656 [(height as i64, common_data)],
657 )
658 .await
659 }
660 }
661
662 async fn insert_state_cert(
663 &mut self,
664 state_cert: StateCertQueryDataV2<Types>,
665 ) -> anyhow::Result<()> {
666 let height = state_cert.height();
667
668 if let Some(pruned_height) = self.load_pruned_height().await? {
671 if height <= pruned_height {
672 tracing::info!(
673 height,
674 pruned_height,
675 "ignoring state cert which is already pruned"
676 );
677 return Ok(());
678 }
679 }
680 let epoch = state_cert.0.epoch.u64();
681 let bytes = bincode::serialize(&state_cert.0).context("failed to serialize state cert")?;
682 self.upsert(
685 "finalized_state_cert",
686 ["epoch", "state_cert"],
687 ["epoch"],
688 [(epoch as i64, bytes)],
689 )
690 .await?;
691 Ok(())
692 }
693}
694
695#[async_trait]
696impl<Types: NodeType, State: MerklizedState<Types, ARITY>, const ARITY: usize>
697 UpdateStateData<Types, State, ARITY> for Transaction<Write>
698{
699 async fn set_last_state_height(&mut self, height: usize) -> anyhow::Result<()> {
700 self.upsert(
701 "last_merklized_state_height",
702 ["id", "height"],
703 ["id"],
704 [(1i32, height as i64)],
705 )
706 .await?;
707
708 Ok(())
709 }
710
711 async fn insert_merkle_nodes(
712 &mut self,
713 proof: MerkleProof<State::Entry, State::Key, State::T, ARITY>,
714 traversal_path: Vec<usize>,
715 block_number: u64,
716 ) -> anyhow::Result<()> {
717 let pos = proof.pos;
718 let path = proof.proof;
719
720 let name = State::state_type();
721 let block_number = block_number as i64;
722
723 let mut traversal_path = traversal_path.iter().map(|n| *n as i32);
724
725 let mut nodes = Vec::new();
728 let mut hashset = HashSet::new();
729
730 for node in path.iter() {
731 match node {
732 MerkleNode::Empty => {
733 let index = serde_json::to_value(pos.clone())
734 .decode_error("malformed merkle position")?;
735 let node_path = traversal_path.clone().rev().collect();
739 nodes.push((
740 Node {
741 path: node_path,
742 idx: Some(index),
743 ..Default::default()
744 },
745 None,
746 [0_u8; 32].to_vec(),
747 ));
748 hashset.insert([0_u8; 32].to_vec());
749 },
750 MerkleNode::ForgettenSubtree { .. } => {
751 bail!("Node in the Merkle path contains a forgetten subtree");
752 },
753 MerkleNode::Leaf { value, pos, elem } => {
754 let mut leaf_commit = Vec::new();
755 value
757 .serialize_compressed(&mut leaf_commit)
758 .decode_error("malformed merkle leaf commitment")?;
759
760 let path = traversal_path.clone().rev().collect();
761
762 let index = serde_json::to_value(pos.clone())
763 .decode_error("malformed merkle position")?;
764 let entry =
765 serde_json::to_value(elem).decode_error("malformed merkle element")?;
766
767 nodes.push((
768 Node {
769 path,
770 idx: Some(index),
771 entry: Some(entry),
772 ..Default::default()
773 },
774 None,
775 leaf_commit.clone(),
776 ));
777
778 hashset.insert(leaf_commit);
779 },
780 MerkleNode::Branch { value, children } => {
781 let mut branch_hash = Vec::new();
783 value
784 .serialize_compressed(&mut branch_hash)
785 .decode_error("malformed merkle branch hash")?;
786
787 let mut children_bitvec = BitVec::new();
790 let mut children_values = Vec::new();
791 for child in children {
792 let child = child.as_ref();
793 match child {
794 MerkleNode::Empty => {
795 children_bitvec.push(false);
796 },
797 MerkleNode::Branch { value, .. }
798 | MerkleNode::Leaf { value, .. }
799 | MerkleNode::ForgettenSubtree { value } => {
800 let mut hash = Vec::new();
801 value
802 .serialize_compressed(&mut hash)
803 .decode_error("malformed merkle node hash")?;
804
805 children_values.push(hash);
806 children_bitvec.push(true);
808 },
809 }
810 }
811
812 let path = traversal_path.clone().rev().collect();
814 nodes.push((
815 Node {
816 path,
817 children: None,
818 children_bitvec: Some(children_bitvec),
819 ..Default::default()
820 },
821 Some(children_values.clone()),
822 branch_hash.clone(),
823 ));
824 hashset.insert(branch_hash);
825 hashset.extend(children_values);
826 },
827 }
828
829 traversal_path.next();
832 }
833 let hashes = hashset.into_iter().collect::<Vec<Vec<u8>>>();
835
836 let (query, sql) = build_hash_batch_insert(&hashes)?;
840 let nodes_hash_ids: HashMap<Vec<u8>, i32> = query
841 .query_as(&sql)
842 .fetch(self.as_mut())
843 .try_collect()
844 .await?;
845
846 for (node, children, hash) in &mut nodes {
848 node.created = block_number;
849 node.hash_id = *nodes_hash_ids.get(&*hash).ok_or(QueryError::Error {
850 message: "Missing node hash".to_string(),
851 })?;
852
853 if let Some(children) = children {
854 let children_hashes = children
855 .iter()
856 .map(|c| nodes_hash_ids.get(c).copied())
857 .collect::<Option<Vec<i32>>>()
858 .ok_or(QueryError::Error {
859 message: "Missing child hash".to_string(),
860 })?;
861
862 node.children = Some(children_hashes.into());
863 }
864 }
865
866 Node::upsert(name, nodes.into_iter().map(|(n, ..)| n), self).await?;
867
868 Ok(())
869 }
870}
871
872#[async_trait]
873impl<Mode: TransactionMode> PrunedHeightStorage for Transaction<Mode> {
874 async fn load_pruned_height(&mut self) -> anyhow::Result<Option<u64>> {
875 let Some((height,)) =
876 query_as::<(i64,)>("SELECT last_height FROM pruned_height ORDER BY id DESC LIMIT 1")
877 .fetch_optional(self.as_mut())
878 .await?
879 else {
880 return Ok(None);
881 };
882 Ok(Some(height as u64))
883 }
884}
885
886#[derive(Clone, Debug)]
887pub(super) struct PoolMetrics {
888 open_transactions: Box<dyn Gauge>,
889 transaction_durations: Box<dyn Histogram>,
890 commits: Box<dyn Counter>,
891 reverts: Box<dyn Counter>,
892 drops: Box<dyn Counter>,
893}
894
895impl PoolMetrics {
896 pub(super) fn new(metrics: &(impl Metrics + ?Sized)) -> Self {
897 Self {
898 open_transactions: metrics.create_gauge("open_transactions".into(), None),
899 transaction_durations: metrics
900 .create_histogram("transaction_duration".into(), Some("s".into())),
901 commits: metrics.create_counter("committed_transactions".into(), None),
902 reverts: metrics.create_counter("reverted_transactions".into(), None),
903 drops: metrics.create_counter("dropped_transactions".into(), None),
904 }
905 }
906}