partner_chains_db_sync_data_sources/lib.rs
1//! Crate providing implementations of Partner Chain Data Sources that read from Db-Sync Postgres.
2//!
3//! # Usage
4//!
5//! ## Adding to the node
6//!
7//! All data sources defined in this crate require a Postgres connection pool [PgPool] to run
8//! queries, which should be shared between all data sources. For convenience, this crate provides
9//! a helper function [get_connection_from_env] that will create a connection pool based on
10//! configuration read from node environment.
11//!
12//! Each data source also accepts an optional Prometheus metrics client [McFollowerMetrics] for
13//! reporting metrics to the Substrate's Prometheus metrics service. This client can be obtained
14//! using the [register_metrics_warn_errors] function.
15//!
16//! In addition to these two common arguments, some data sources depend on [BlockDataSourceImpl]
17//! which provides basic queries about blocks, and additional configuration for their data cache
18//! size.
19//!
20//! An example node code that creates the data sources can look like the following:
21//!
22//! ```rust
23//! # use std::error::Error;
24//! # use std::sync::Arc;
25//! use partner_chains_db_sync_data_sources::*;
26//!
27//! pub const CANDIDATES_FOR_EPOCH_CACHE_SIZE: usize = 64;
28//! pub const STAKE_CACHE_SIZE: usize = 100;
29//! pub const GOVERNED_MAP_CACHE_SIZE: u16 = 100;
30//!
31//! async fn create_data_sources(
32//! metrics_registry_opt: Option<&substrate_prometheus_endpoint::Registry>
33//! ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
34//! let metrics = register_metrics_warn_errors(metrics_registry_opt);
35//! let pool = get_connection_from_env().await?;
36//!
37//! // Block data source is shared by others for cache reuse
38//! let block = Arc::new(BlockDataSourceImpl::new_from_env(pool.clone()).await?);
39//!
40//! let sidechain_rpc = SidechainRpcDataSourceImpl::new(block.clone(), metrics.clone());
41//!
42//! let mc_hash = Arc::new(McHashDataSourceImpl::new(block.clone(), metrics.clone()));
43//!
44//! let authority_selection =
45//! CandidatesDataSourceImpl::new(pool.clone(), metrics.clone())
46//! .await?
47//! .cached(CANDIDATES_FOR_EPOCH_CACHE_SIZE)?;
48//!
49//! let native_token =
50//! NativeTokenManagementDataSourceImpl::new_from_env(pool.clone(), metrics.clone()).await?;
51//!
52//! let block_participation =
53//! StakeDistributionDataSourceImpl::new(pool.clone(), metrics.clone(), STAKE_CACHE_SIZE);
54//!
55//! let governed_map =
56//! GovernedMapDataSourceCachedImpl::new(pool, metrics.clone(), GOVERNED_MAP_CACHE_SIZE, block).await?;
57//! Ok(())
58//! }
59//! ```
60//!
61//! ## Cardano DB Sync configuration
62//!
63//! Partner Chains data sources require specific Db-Sync configuration to be set for them to
64//! operate correctly:
65//! - `insert_options.tx_out.value`: must be either `"enable"` (default) or `"consumed"`.
66//! When `"consumed"` is used then `tx_out.force_tx_in` has to be `true`.
67//! Code in this crate depends on `tx_in` table being present.
68//! - `insert_options.tx_out.use_address_table`: must be `false` (default).
69//! - `insert_options.ledger`: must be `"enable"` (default).
70//! - `insert_options.multi_asset`: must be `true` (default).
71//! - `insert_options.governance`: must `"enable"` (default).
72//! - `insert_options.remove_jsonb_from_schema`: must be `"disable"` (default).
73//! - `insert_options.plutus`: must be `"enable"` (default).
74//!
75//! The default Cardano DB Sync configuration meets these requirements, so Partner Chain node
76//! operators that do not wish to use any custom configuration can use the defaults, otherwise
77//! they must preserve the values described above. See [Db-Sync configuration docs] for more
78//! information.
79//!
80//! ## Custom Indexes
81//!
82//! In addition to indexes automatically created by Db-Sync itself, data sources in this crate
83//! require additional ones to be created for some of the queries to execute efficiently. These
84//! indexes are:
85//! - `idx_ma_tx_out_ident ON ma_tx_out(ident)`
86//! - `idx_tx_out_address ON tx_out USING hash (address)`
87//!
88//! The data sources in this crate automatically create these indexes when needed at node startup.
89//!
90//! [PgPool]: sqlx::PgPool
91//! [BlockDataSourceImpl]: crate::block::BlockDataSourceImpl
92//! [McFollowerMetrics]: crate::metrics::McFollowerMetrics
93//! [get_connection_from_env]: crate::data_sources::get_connection_from_env
94//! [register_metrics_warn_errors]: crate::metrics::register_metrics_warn_errors
95//! [Db-Sync configuration docs]: https://github.com/IntersectMBO/cardano-db-sync/blob/master/doc/configuration.md
96#![deny(missing_docs)]
97#![allow(rustdoc::private_intra_doc_links)]
98
99pub use crate::{
100 data_sources::{ConnectionConfig, PgPool, get_connection_from_env, read_mc_epoch_config},
101 metrics::{McFollowerMetrics, register_metrics_warn_errors},
102};
103
104#[cfg(feature = "block-source")]
105pub use crate::block::{BlockDataSourceImpl, DbSyncBlockDataSourceConfig};
106#[cfg(feature = "candidate-source")]
107pub use crate::candidates::CandidatesDataSourceImpl;
108#[cfg(feature = "governed-map")]
109pub use crate::governed_map::{GovernedMapDataSourceCachedImpl, GovernedMapDataSourceImpl};
110#[cfg(feature = "mc-hash")]
111pub use crate::mc_hash::McHashDataSourceImpl;
112#[cfg(feature = "native-token")]
113pub use crate::native_token::NativeTokenManagementDataSourceImpl;
114#[cfg(feature = "sidechain-rpc")]
115pub use crate::sidechain_rpc::SidechainRpcDataSourceImpl;
116#[cfg(feature = "block-participation")]
117pub use crate::stake_distribution::StakeDistributionDataSourceImpl;
118
119mod data_sources;
120mod db_datum;
121mod db_model;
122mod metrics;
123
124#[cfg(feature = "block-source")]
125mod block;
126#[cfg(feature = "candidate-source")]
127mod candidates;
128#[cfg(feature = "governed-map")]
129mod governed_map;
130#[cfg(feature = "mc-hash")]
131mod mc_hash;
132#[cfg(feature = "native-token")]
133mod native_token;
134#[cfg(feature = "sidechain-rpc")]
135mod sidechain_rpc;
136#[cfg(feature = "block-participation")]
137mod stake_distribution;
138
139/// Wrapper error type for [sqlx::Error]
140pub struct SqlxError(sqlx::Error);
141
142impl From<sqlx::Error> for SqlxError {
143 fn from(value: sqlx::Error) -> Self {
144 SqlxError(value)
145 }
146}
147
148impl From<SqlxError> for DataSourceError {
149 fn from(e: SqlxError) -> Self {
150 DataSourceError::InternalDataSourceError(e.0.to_string())
151 }
152}
153
154impl From<SqlxError> for Box<dyn std::error::Error + Send + Sync> {
155 fn from(e: SqlxError) -> Self {
156 e.0.into()
157 }
158}
159
160/// Error type returned by Db-Sync based data sources
161#[derive(Debug, PartialEq, thiserror::Error)]
162pub enum DataSourceError {
163 /// Indicates that the Db-Sync database rejected a request as invalid
164 #[error("Bad request: `{0}`.")]
165 BadRequest(String),
166 /// Indicates that an internal error occured when querying the Db-Sync database
167 #[error("Internal error of data source: `{0}`.")]
168 InternalDataSourceError(String),
169 /// Indicates that expected data was not found when querying the Db-Sync database
170 #[error(
171 "'{0}' not found. Possible causes: data source configuration error, db-sync not synced fully, or data not set on the main chain."
172 )]
173 ExpectedDataNotFound(String),
174 /// Indicates that data returned by the Db-Sync database is invalid
175 #[error(
176 "Invalid data. {0} Possible cause is an error in Plutus scripts or data source is outdated."
177 )]
178 InvalidData(String),
179}
180
181/// Result type used by Db-Sync data sources
182pub(crate) type Result<T> = std::result::Result<T, DataSourceError>;
183
184#[cfg(test)]
185mod tests {
186 use ctor::{ctor, dtor};
187 use std::sync::OnceLock;
188 use testcontainers_modules::testcontainers::Container;
189 use testcontainers_modules::{postgres::Postgres as PostgresImg, testcontainers::clients::Cli};
190
191 static POSTGRES: OnceLock<Container<PostgresImg>> = OnceLock::new();
192 static CLI: OnceLock<Cli> = OnceLock::new();
193
194 fn init_postgres() -> Container<'static, PostgresImg> {
195 let docker = CLI.get_or_init(Cli::default);
196 docker.run(PostgresImg::default())
197 }
198
199 #[ctor]
200 fn on_startup() {
201 let postgres = POSTGRES.get_or_init(init_postgres);
202 let database_url = &format!(
203 "postgres://postgres:postgres@127.0.0.1:{}/postgres",
204 postgres.get_host_port_ipv4(5432)
205 );
206 // Needed for sqlx::test macro annotation
207 unsafe {
208 std::env::set_var("DATABASE_URL", database_url);
209 }
210 }
211
212 #[dtor]
213 fn on_shutdown() {
214 POSTGRES.get().iter().for_each(|postgres| postgres.rm());
215 }
216}