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 simple_certificate::CertificatePair,
36 traits::{
37 block_contents::BlockHeader,
38 metrics::{Counter, Gauge, Histogram, Metrics},
39 node_implementation::NodeType,
40 EncodeBytes,
41 },
42};
43use itertools::Itertools;
44use jf_merkle_tree_compat::prelude::{MerkleNode, MerkleProof};
45pub use sqlx::Executor;
46use sqlx::{
47 pool::Pool, query_builder::Separated, types::BitVec, Encode, Execute, FromRow, QueryBuilder,
48 Type,
49};
50use tokio::time::sleep;
51
52use super::{
53 queries::{
54 self,
55 state::{build_hash_batch_insert, Node},
56 DecodeError,
57 },
58 Database, Db,
59};
60use crate::{
61 availability::{
62 BlockQueryData, LeafQueryData, QueryableHeader, QueryablePayload, VidCommonQueryData,
63 },
64 data_source::{
65 storage::{pruning::PrunedHeightStorage, NodeStorage, 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> + Clone,
378 {
379 let set_columns = columns
380 .iter()
381 .map(|col| format!("{col} = excluded.{col}"))
382 .join(",");
383
384 let columns_str = columns.iter().map(|col| format!("\"{col}\"")).join(",");
385
386 let pk = pk.into_iter().join(",");
387
388 let rows: Vec<_> = rows.into_iter().collect();
389 let num_rows = rows.len();
390
391 if num_rows == 0 {
392 tracing::warn!("trying to upsert 0 rows into {table}, this has no effect");
393 return Ok(());
394 }
395
396 let interval = Duration::from_secs(1);
397 let mut retries = 5;
398
399 let mut query_builder =
400 QueryBuilder::new(format!("INSERT INTO \"{table}\" ({columns_str}) "));
401
402 loop {
403 let query_builder = query_builder.reset();
408
409 query_builder.push_values(rows.clone(), |mut b, row| {
410 row.bind(&mut b);
411 });
412
413 query_builder.push(format!(" ON CONFLICT ({pk}) DO UPDATE SET {set_columns}"));
414
415 let query = query_builder.build();
416 let statement = query.sql();
417
418 match self.execute(query).await {
419 Ok(res) => {
420 let rows_modified = res.rows_affected() as usize;
421 if rows_modified != num_rows {
422 let error = format!(
423 "unexpected number of rows modified: expected {num_rows}, got \
424 {rows_modified}. query: {statement}"
425 );
426 tracing::error!(error);
427 bail!(error);
428 }
429 return Ok(());
430 },
431 Err(err) => {
432 tracing::error!(
433 statement,
434 "error in statement execution ({} tries remaining): {err}",
435 retries
436 );
437 if retries == 0 {
438 bail!(err);
439 }
440 retries -= 1;
441 sleep(interval).await;
442 },
443 }
444 }
445 }
446}
447
448impl Transaction<Write> {
450 pub(super) async fn delete_batch(
452 &mut self,
453 state_tables: Vec<String>,
454 height: u64,
455 ) -> anyhow::Result<()> {
456 self.execute(query("DELETE FROM header WHERE height <= $1").bind(height as i64))
457 .await?;
458
459 for state_table in state_tables {
463 self.execute(
464 query(&format!(
465 "
466 DELETE FROM {state_table} WHERE (path, created) IN
467 (SELECT path, created FROM
468 (SELECT path, created,
469 ROW_NUMBER() OVER (PARTITION BY path ORDER BY created DESC) as rank
470 FROM {state_table} WHERE created <= $1) ranked_nodes WHERE rank != 1)"
471 ))
472 .bind(height as i64),
473 )
474 .await?;
475 }
476
477 self.save_pruned_height(height).await?;
478 Ok(())
479 }
480
481 pub(super) async fn save_pruned_height(&mut self, height: u64) -> anyhow::Result<()> {
483 self.upsert(
486 "pruned_height",
487 ["id", "last_height"],
488 ["id"],
489 [(1i32, height as i64)],
490 )
491 .await
492 }
493}
494
495impl<Types> UpdateAvailabilityStorage<Types> for Transaction<Write>
496where
497 Types: NodeType,
498 Payload<Types>: QueryablePayload<Types>,
499 Header<Types>: QueryableHeader<Types>,
500{
501 async fn insert_leaf_with_qc_chain(
502 &mut self,
503 leaf: LeafQueryData<Types>,
504 qc_chain: Option<[CertificatePair<Types>; 2]>,
505 ) -> anyhow::Result<()> {
506 let height = leaf.height();
507
508 if let Some(pruned_height) = self.load_pruned_height().await? {
511 if height <= pruned_height {
512 tracing::info!(
513 height,
514 pruned_height,
515 "ignoring leaf which is already pruned"
516 );
517 return Ok(());
518 }
519 }
520
521 let header_json = serde_json::to_value(leaf.leaf().block_header())
524 .context("failed to serialize header")?;
525 self.upsert(
526 "header",
527 ["height", "hash", "payload_hash", "data", "timestamp"],
528 ["height"],
529 [(
530 height as i64,
531 leaf.block_hash().to_string(),
532 leaf.leaf().block_header().payload_commitment().to_string(),
533 header_json,
534 leaf.leaf().block_header().timestamp() as i64,
535 )],
536 )
537 .await?;
538
539 let query = query("INSERT INTO payload (height) VALUES ($1) ON CONFLICT DO NOTHING")
547 .bind(height as i64);
548 query.execute(self.as_mut()).await?;
549
550 let leaf_json = serde_json::to_value(leaf.leaf()).context("failed to serialize leaf")?;
553 let qc_json = serde_json::to_value(leaf.qc()).context("failed to serialize QC")?;
554 self.upsert(
555 "leaf2",
556 ["height", "hash", "block_hash", "leaf", "qc"],
557 ["height"],
558 [(
559 height as i64,
560 leaf.hash().to_string(),
561 leaf.block_hash().to_string(),
562 leaf_json,
563 qc_json,
564 )],
565 )
566 .await?;
567
568 let block_height = NodeStorage::<Types>::block_height(self).await? as u64;
569 if height + 1 >= block_height {
570 let qcs = serde_json::to_value(&qc_chain)?;
575 self.upsert("latest_qc_chain", ["id", "qcs"], ["id"], [(1i32, qcs)])
576 .await?;
577 }
578
579 Ok(())
580 }
581
582 async fn insert_block(&mut self, block: BlockQueryData<Types>) -> anyhow::Result<()> {
583 let height = block.height();
584
585 if let Some(pruned_height) = self.load_pruned_height().await? {
588 if height <= pruned_height {
589 tracing::info!(
590 height,
591 pruned_height,
592 "ignoring block which is already pruned"
593 );
594 return Ok(());
595 }
596 }
597
598 let payload = block.payload.encode();
601
602 self.upsert(
603 "payload",
604 ["height", "data", "size", "num_transactions"],
605 ["height"],
606 [(
607 height as i64,
608 payload.as_ref().to_vec(),
609 block.size() as i32,
610 block.num_transactions() as i32,
611 )],
612 )
613 .await?;
614
615 let mut rows = vec![];
617 for (txn_ix, txn) in block.enumerate() {
618 let ns_id = block.header().namespace_id(&txn_ix.ns_index).unwrap();
619 rows.push((
620 txn.commit().to_string(),
621 height as i64,
622 txn_ix.ns_index.into(),
623 ns_id.into(),
624 txn_ix.position as i64,
625 ));
626 }
627 if !rows.is_empty() {
628 self.upsert(
629 "transactions",
630 ["hash", "block_height", "ns_index", "ns_id", "position"],
631 ["block_height", "ns_id", "position"],
632 rows,
633 )
634 .await?;
635 }
636
637 Ok(())
638 }
639
640 async fn insert_vid(
641 &mut self,
642 common: VidCommonQueryData<Types>,
643 share: Option<VidShare>,
644 ) -> anyhow::Result<()> {
645 let height = common.height();
646
647 if let Some(pruned_height) = self.load_pruned_height().await? {
650 if height <= pruned_height {
651 tracing::info!(
652 height,
653 pruned_height,
654 "ignoring VID common which is already pruned"
655 );
656 return Ok(());
657 }
658 }
659
660 let common_data =
661 bincode::serialize(common.common()).context("failed to serialize VID common data")?;
662 if let Some(share) = share {
663 let share_data = bincode::serialize(&share).context("failed to serialize VID share")?;
664 self.upsert(
665 "vid2",
666 ["height", "common", "share"],
667 ["height"],
668 [(height as i64, common_data, share_data)],
669 )
670 .await
671 } else {
672 self.upsert(
676 "vid2",
677 ["height", "common"],
678 ["height"],
679 [(height as i64, common_data)],
680 )
681 .await
682 }
683 }
684}
685
686#[async_trait]
687impl<Types: NodeType, State: MerklizedState<Types, ARITY>, const ARITY: usize>
688 UpdateStateData<Types, State, ARITY> for Transaction<Write>
689{
690 async fn set_last_state_height(&mut self, height: usize) -> anyhow::Result<()> {
691 self.upsert(
692 "last_merklized_state_height",
693 ["id", "height"],
694 ["id"],
695 [(1i32, height as i64)],
696 )
697 .await?;
698
699 Ok(())
700 }
701
702 async fn insert_merkle_nodes(
703 &mut self,
704 proof: MerkleProof<State::Entry, State::Key, State::T, ARITY>,
705 traversal_path: Vec<usize>,
706 block_number: u64,
707 ) -> anyhow::Result<()> {
708 let pos = proof.pos;
709 let path = proof.proof;
710
711 let name = State::state_type();
712 let block_number = block_number as i64;
713
714 let mut traversal_path = traversal_path.iter().map(|n| *n as i32);
715
716 let mut nodes = Vec::new();
719 let mut hashset = HashSet::new();
720
721 for node in path.iter() {
722 match node {
723 MerkleNode::Empty => {
724 let index = serde_json::to_value(pos.clone())
725 .decode_error("malformed merkle position")?;
726 let node_path = traversal_path.clone().rev().collect();
730 nodes.push((
731 Node {
732 path: node_path,
733 idx: Some(index),
734 ..Default::default()
735 },
736 None,
737 [0_u8; 32].to_vec(),
738 ));
739 hashset.insert([0_u8; 32].to_vec());
740 },
741 MerkleNode::ForgettenSubtree { .. } => {
742 bail!("Node in the Merkle path contains a forgetten subtree");
743 },
744 MerkleNode::Leaf { value, pos, elem } => {
745 let mut leaf_commit = Vec::new();
746 value
748 .serialize_compressed(&mut leaf_commit)
749 .decode_error("malformed merkle leaf commitment")?;
750
751 let path = traversal_path.clone().rev().collect();
752
753 let index = serde_json::to_value(pos.clone())
754 .decode_error("malformed merkle position")?;
755 let entry =
756 serde_json::to_value(elem).decode_error("malformed merkle element")?;
757
758 nodes.push((
759 Node {
760 path,
761 idx: Some(index),
762 entry: Some(entry),
763 ..Default::default()
764 },
765 None,
766 leaf_commit.clone(),
767 ));
768
769 hashset.insert(leaf_commit);
770 },
771 MerkleNode::Branch { value, children } => {
772 let mut branch_hash = Vec::new();
774 value
775 .serialize_compressed(&mut branch_hash)
776 .decode_error("malformed merkle branch hash")?;
777
778 let mut children_bitvec = BitVec::new();
781 let mut children_values = Vec::new();
782 for child in children {
783 let child = child.as_ref();
784 match child {
785 MerkleNode::Empty => {
786 children_bitvec.push(false);
787 },
788 MerkleNode::Branch { value, .. }
789 | MerkleNode::Leaf { value, .. }
790 | MerkleNode::ForgettenSubtree { value } => {
791 let mut hash = Vec::new();
792 value
793 .serialize_compressed(&mut hash)
794 .decode_error("malformed merkle node hash")?;
795
796 children_values.push(hash);
797 children_bitvec.push(true);
799 },
800 }
801 }
802
803 let path = traversal_path.clone().rev().collect();
805 nodes.push((
806 Node {
807 path,
808 children: None,
809 children_bitvec: Some(children_bitvec),
810 ..Default::default()
811 },
812 Some(children_values.clone()),
813 branch_hash.clone(),
814 ));
815 hashset.insert(branch_hash);
816 hashset.extend(children_values);
817 },
818 }
819
820 traversal_path.next();
823 }
824 let hashes = hashset.into_iter().collect::<Vec<Vec<u8>>>();
826
827 let (query, sql) = build_hash_batch_insert(&hashes)?;
831 let nodes_hash_ids: HashMap<Vec<u8>, i32> = query
832 .query_as(&sql)
833 .fetch(self.as_mut())
834 .try_collect()
835 .await?;
836
837 for (node, children, hash) in &mut nodes {
839 node.created = block_number;
840 node.hash_id = *nodes_hash_ids.get(&*hash).ok_or(QueryError::Error {
841 message: "Missing node hash".to_string(),
842 })?;
843
844 if let Some(children) = children {
845 let children_hashes = children
846 .iter()
847 .map(|c| nodes_hash_ids.get(c).copied())
848 .collect::<Option<Vec<i32>>>()
849 .ok_or(QueryError::Error {
850 message: "Missing child hash".to_string(),
851 })?;
852
853 node.children = Some(children_hashes.into());
854 }
855 }
856
857 Node::upsert(name, nodes.into_iter().map(|(n, ..)| n), self).await?;
858
859 Ok(())
860 }
861}
862
863#[async_trait]
864impl<Mode: TransactionMode> PrunedHeightStorage for Transaction<Mode> {
865 async fn load_pruned_height(&mut self) -> anyhow::Result<Option<u64>> {
866 let Some((height,)) =
867 query_as::<(i64,)>("SELECT last_height FROM pruned_height ORDER BY id DESC LIMIT 1")
868 .fetch_optional(self.as_mut())
869 .await?
870 else {
871 return Ok(None);
872 };
873 Ok(Some(height as u64))
874 }
875}
876
877#[derive(Clone, Debug)]
878pub(super) struct PoolMetrics {
879 open_transactions: Box<dyn Gauge>,
880 transaction_durations: Box<dyn Histogram>,
881 commits: Box<dyn Counter>,
882 reverts: Box<dyn Counter>,
883 drops: Box<dyn Counter>,
884}
885
886impl PoolMetrics {
887 pub(super) fn new(metrics: &(impl Metrics + ?Sized)) -> Self {
888 Self {
889 open_transactions: metrics.create_gauge("open_transactions".into(), None),
890 transaction_durations: metrics
891 .create_histogram("transaction_duration".into(), Some("s".into())),
892 commits: metrics.create_counter("committed_transactions".into(), None),
893 reverts: metrics.create_counter("reverted_transactions".into(), None),
894 drops: metrics.create_counter("dropped_transactions".into(), None),
895 }
896 }
897}