Skip to content

Commit d8e7295

Browse files
authored
change: ETCM-9687 small fixes and docs for db-sync data sources crate (#804)
1 parent fd53ad5 commit d8e7295

File tree

15 files changed

+252
-69
lines changed

15 files changed

+252
-69
lines changed

changelog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ This changelog is based on [Keep A Changelog](https://keepachangelog.com/en/1.1.
55
# Unreleased
66

77
## Changed
8+
* `partner-chains-db-sync-data-sources` crate now exports all its public members from the root
89

910
## Removed
1011

demo/node/src/data_sources.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
use authority_selection_inherents::authority_selection_inputs::AuthoritySelectionDataSource;
22
use pallet_sidechain_rpc::SidechainRpcDataSource;
33
use partner_chains_db_sync_data_sources::{
4-
block::BlockDataSourceImpl, candidates::CandidatesDataSourceImpl,
5-
governed_map::GovernedMapDataSourceCachedImpl, mc_hash::McHashDataSourceImpl,
6-
metrics::McFollowerMetrics, native_token::NativeTokenManagementDataSourceImpl,
7-
sidechain_rpc::SidechainRpcDataSourceImpl, stake_distribution::StakeDistributionDataSourceImpl,
4+
BlockDataSourceImpl, CandidatesDataSourceImpl, GovernedMapDataSourceCachedImpl,
5+
McFollowerMetrics, McHashDataSourceImpl, NativeTokenManagementDataSourceImpl,
6+
SidechainRpcDataSourceImpl, StakeDistributionDataSourceImpl,
87
};
98
use partner_chains_mock_data_sources::{
109
block::BlockDataSourceMock, candidate::AuthoritySelectionDataSourceMock,
@@ -73,7 +72,7 @@ pub const GOVERNED_MAP_CACHE_SIZE: u16 = 100;
7372
pub async fn create_cached_db_sync_data_sources(
7473
metrics_opt: Option<McFollowerMetrics>,
7574
) -> Result<DataSources, Box<dyn Error + Send + Sync + 'static>> {
76-
let pool = partner_chains_db_sync_data_sources::data_sources::get_connection_from_env().await?;
75+
let pool = partner_chains_db_sync_data_sources::get_connection_from_env().await?;
7776
// block data source is reused between mc_hash and sidechain_rpc to share cache
7877
let block = Arc::new(BlockDataSourceImpl::new_from_env(pool.clone()).await?);
7978
Ok(DataSources {

demo/node/src/service.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
use crate::data_sources::DataSources;
44
use crate::inherent_data::{CreateInherentDataConfig, ProposalCIDP, VerifierCIDP};
55
use crate::rpc::GrandpaDeps;
6-
use partner_chains_db_sync_data_sources::metrics::McFollowerMetrics;
7-
use partner_chains_db_sync_data_sources::metrics::register_metrics_warn_errors;
6+
use partner_chains_db_sync_data_sources::McFollowerMetrics;
7+
use partner_chains_db_sync_data_sources::register_metrics_warn_errors;
88
use partner_chains_demo_runtime::{self, RuntimeApi, opaque::Block};
99
use sc_client_api::BlockBackend;
1010
use sc_consensus_aura::{ImportQueueParams, SlotProportion, StartAuraParams};

toolkit/data-sources/cli/src/main.rs

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
use authority_selection_inherents::authority_selection_inputs::AuthoritySelectionDataSource;
22
use clap::Parser;
3-
use partner_chains_db_sync_data_sources::{
4-
block::{BlockDataSourceImpl, DbSyncBlockDataSourceConfig},
5-
candidates::CandidatesDataSourceImpl,
6-
data_sources::{PgPool, read_mc_epoch_config},
7-
};
3+
use partner_chains_db_sync_data_sources::{BlockDataSourceImpl, CandidatesDataSourceImpl, PgPool};
84
use sidechain_domain::*;
95
use sp_timestamp::Timestamp;
106
use std::error::Error;
@@ -86,7 +82,7 @@ mod data_source {
8682
use super::*;
8783

8884
async fn pool() -> Result<PgPool> {
89-
partner_chains_db_sync_data_sources::data_sources::get_connection_from_env().await
85+
partner_chains_db_sync_data_sources::get_connection_from_env().await
9086
}
9187

9288
pub struct BlockDataSourceWrapper {
@@ -118,11 +114,7 @@ mod data_source {
118114

119115
pub async fn block() -> Result<BlockDataSourceWrapper> {
120116
Ok(BlockDataSourceWrapper {
121-
inner: BlockDataSourceImpl::from_config(
122-
pool().await?,
123-
DbSyncBlockDataSourceConfig::from_env()?,
124-
&read_mc_epoch_config()?,
125-
),
117+
inner: BlockDataSourceImpl::new_from_env(pool().await?).await?,
126118
})
127119
}
128120

toolkit/data-sources/db-sync/src/block/mod.rs

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//! Db-Sync data source implementation that queries Cardano block information
12
use crate::{
23
DataSourceError::*,
34
data_sources::read_mc_epoch_config,
@@ -20,22 +21,41 @@ use std::{
2021
#[cfg(test)]
2122
mod tests;
2223

24+
/// Db-Sync data source that queries Cardano block information
25+
///
26+
/// This data source does not implement any data source interface used by one of the
27+
/// Partner Chain toolkit's features, but is used internally by other data sources
28+
/// that require access to Cardano block data
2329
#[allow(clippy::too_many_arguments)]
2430
#[derive(new)]
2531
pub struct BlockDataSourceImpl {
32+
/// Postgres connection pool
2633
pool: PgPool,
34+
/// Cardano security parameter
35+
///
36+
/// This parameter controls how many confirmations (blocks on top) are required by
37+
/// the Cardano node to consider a block to be stable. This is a network-wide parameter.
2738
security_parameter: u32,
28-
/// `security parameter / active slot coefficient` - minimal age of a block to be considered valid stable in relation to some given timestamp
39+
/// Minimal age of a block to be considered valid stable in relation to some given timestamp.
40+
/// Must be equal to `security parameter / active slot coefficient`.
2941
min_slot_boundary_as_seconds: TimeDelta,
3042
/// a characteristic of Ouroboros Praos and is equal to `3 * security parameter / active slot coefficient`
3143
max_slot_boundary_as_seconds: TimeDelta,
44+
/// Cardano main chain epoch configuration
3245
mainchain_epoch_config: MainchainEpochConfig,
46+
/// Additional offset applied when selecting the latest stable Cardano block
47+
///
48+
/// This parameter should be 0 by default and should only be increased to 1 in networks
49+
/// struggling with frequent block rejections due to Db-Sync or Cardano node lag.
3350
block_stability_margin: u32,
51+
/// Number of contiguous Cardano blocks to be cached by this data source
3452
cache_size: u16,
53+
/// Internal block cache
3554
stable_blocks_cache: Arc<Mutex<BlocksCache>>,
3655
}
3756

3857
impl BlockDataSourceImpl {
58+
/// Returns the latest _unstable_ Cardano block from the Db-Sync database
3959
pub async fn get_latest_block_info(
4060
&self,
4161
) -> Result<MainchainBlock, Box<dyn std::error::Error + Send + Sync>> {
@@ -45,6 +65,9 @@ impl BlockDataSourceImpl {
4565
.ok_or(ExpectedDataNotFound("No latest block on chain.".to_string()).into())
4666
}
4767

68+
/// Returns the latest _stable_ Cardano block from the Db-Sync database that is within
69+
/// acceptable bounds from `reference_timestamp`, accounting for the additional stability
70+
/// offset configured by [block_stability_margin][Self::block_stability_margin].
4871
pub async fn get_latest_stable_block_for(
4972
&self,
5073
reference_timestamp: Timestamp,
@@ -57,6 +80,8 @@ impl BlockDataSourceImpl {
5780
Ok(block.map(From::from))
5881
}
5982

83+
/// Finds a block by its `hash` and verifies that it is stable in reference to `reference_timestamp`
84+
/// and returns its info
6085
pub async fn get_stable_block_for(
6186
&self,
6287
hash: McBlockHash,
@@ -66,6 +91,7 @@ impl BlockDataSourceImpl {
6691
self.get_stable_block_by_hash(hash, reference_timestamp).await
6792
}
6893

94+
/// Finds a block by its `hash` and returns its info
6995
pub async fn get_block_by_hash(
7096
&self,
7197
hash: McBlockHash,
@@ -83,15 +109,25 @@ impl BlockDataSourceImpl {
83109
}
84110
}
85111

112+
/// Configuration for [BlockDataSourceImpl]
86113
#[derive(Debug, Clone, Deserialize)]
87114
pub struct DbSyncBlockDataSourceConfig {
115+
/// Cardano security parameter, ie. the number of confirmations needed to stabilize a block
88116
pub cardano_security_parameter: u32,
89-
//From shelley-genesis.json, example: "activeSlotsCoeff": 0.05,
117+
/// Expected fraction of Cardano slots that will have a block produced
118+
///
119+
/// This value can be found in `shelley-genesis.json` file used by the Cardano node,
120+
/// example: `"activeSlotsCoeff": 0.05`.
90121
pub cardano_active_slots_coeff: f64,
122+
/// Additional offset applied when selecting the latest stable Cardano block
123+
///
124+
/// This parameter should be 0 by default and should only be increased to 1 in networks
125+
/// struggling with frequent block rejections due to Db-Sync or Cardano node lag.
91126
pub block_stability_margin: u32,
92127
}
93128

94129
impl DbSyncBlockDataSourceConfig {
130+
/// Reads the config from environment
95131
pub fn from_env() -> std::result::Result<Self, Box<dyn Error + Send + Sync + 'static>> {
96132
let config: Self = Figment::new()
97133
.merge(Env::raw())
@@ -103,6 +139,7 @@ impl DbSyncBlockDataSourceConfig {
103139
}
104140

105141
impl BlockDataSourceImpl {
142+
/// Creates a new instance of [BlockDataSourceImpl], reading configuration from the environment.
106143
pub async fn new_from_env(
107144
pool: PgPool,
108145
) -> std::result::Result<Self, Box<dyn Error + Send + Sync + 'static>> {
@@ -113,6 +150,7 @@ impl BlockDataSourceImpl {
113150
))
114151
}
115152

153+
/// Creates a new instance of [BlockDataSourceImpl], using passed configuration.
116154
pub fn from_config(
117155
pool: PgPool,
118156
DbSyncBlockDataSourceConfig {

toolkit/data-sources/db-sync/src/candidates/datum.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@ use partner_chains_plutus_data::permissioned_candidates::PermissionedCandidateDa
33
use partner_chains_plutus_data::permissioned_candidates::PermissionedCandidateDatums;
44
use sidechain_domain::*;
55

6-
pub fn raw_permissioned_candidate_data_from(
6+
pub(crate) fn raw_permissioned_candidate_data_from(
77
datum: PermissionedCandidateDatumV0,
88
) -> RawPermissionedCandidateData {
99
let PermissionedCandidateDatumV0 { sidechain_public_key, aura_public_key, grandpa_public_key } =
1010
datum;
1111
RawPermissionedCandidateData { sidechain_public_key, aura_public_key, grandpa_public_key }
1212
}
1313

14-
pub fn raw_permissioned_candidate_data_vec_from(
14+
pub(crate) fn raw_permissioned_candidate_data_vec_from(
1515
datums: PermissionedCandidateDatums,
1616
) -> Vec<RawPermissionedCandidateData> {
1717
match datums {

toolkit/data-sources/db-sync/src/candidates/mod.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//! Db-Sync data source used by Partner Chain committee selection
12
use crate::DataSourceError::*;
23
use crate::db_model::{
34
self, Address, Asset, BlockNumber, EpochNumber, MainchainTxOutput, StakePoolEntry,
@@ -17,11 +18,11 @@ use sqlx::PgPool;
1718
use std::collections::HashMap;
1819
use std::error::Error;
1920

20-
pub mod cached;
21-
pub mod datum;
21+
mod cached;
22+
mod datum;
2223

2324
#[cfg(test)]
24-
pub mod tests;
25+
mod tests;
2526

2627
#[derive(Clone, Debug)]
2728
struct ParsedCandidate {
@@ -45,8 +46,11 @@ struct RegisteredCandidate {
4546
utxo_info: UtxoInfo,
4647
}
4748

49+
/// Db-Sync data source serving data for Partner Chain committee selection
4850
pub struct CandidatesDataSourceImpl {
51+
/// Postgres connection pool
4952
pool: PgPool,
53+
/// Prometheus metrics client
5054
metrics_opt: Option<McFollowerMetrics>,
5155
}
5256

@@ -121,6 +125,7 @@ impl AuthoritySelectionDataSource for CandidatesDataSourceImpl {
121125
});
122126

123127
impl CandidatesDataSourceImpl {
128+
/// Creates new instance of the data source
124129
pub async fn new(
125130
pool: PgPool,
126131
metrics_opt: Option<McFollowerMetrics>,
@@ -130,6 +135,7 @@ impl CandidatesDataSourceImpl {
130135
Ok(Self { pool, metrics_opt })
131136
}
132137

138+
/// Creates a new caching instance of the data source
133139
pub fn cached(
134140
self,
135141
candidates_for_epoch_cache_size: usize,

toolkit/data-sources/db-sync/src/data_sources.rs

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
//! Data sources implementations that read from db-sync postgres.
2-
1+
//! Helpers for configuring and creating a Postgres database connection
32
use figment::Figment;
43
use figment::providers::Env;
54
use serde::Deserialize;
@@ -12,18 +11,24 @@ use std::fmt::Debug;
1211
use std::fmt::Formatter;
1312
use std::str::FromStr;
1413

14+
/// Reads Cardano main chain epoch configuration from the environment.
15+
///
16+
/// See documentation of [MainchainEpochConfig::read_from_env] for the list of environment variables read.
1517
#[cfg(feature = "block-source")]
1618
pub fn read_mc_epoch_config() -> Result<MainchainEpochConfig, Box<dyn Error + Send + Sync>> {
1719
Ok(MainchainEpochConfig::read_from_env()
1820
.map_err(|e| format!("Failed to read main chain config: {}", e))?)
1921
}
2022

23+
/// Postgres connection config used when creating a [PgPool].
2124
#[derive(Debug, Clone, Deserialize)]
2225
pub struct ConnectionConfig {
26+
/// Postgres connection pool, eg. `postgres://postgres-user:postgres-password@db-sync-postgres-host:5432/db-sync-db`
2327
pub(crate) db_sync_postgres_connection_string: SecretString,
2428
}
2529

2630
impl ConnectionConfig {
31+
/// Reads Postgres connection config from the environment
2732
pub fn from_env() -> Result<Self, Box<dyn Error + Send + Sync + 'static>> {
2833
let config: Self = Figment::new()
2934
.merge(Env::raw())
@@ -42,7 +47,7 @@ impl Debug for SecretString {
4247
}
4348
}
4449

45-
pub async fn get_connection(
50+
async fn get_connection(
4651
connection_string: &str,
4752
acquire_timeout: std::time::Duration,
4853
) -> Result<PgPool, Box<dyn Error + Send + Sync + 'static>> {
@@ -68,6 +73,11 @@ pub async fn get_connection(
6873
#[error("Could not connect to database: postgres://***:***@{0}:{1}/{2}; error: {3}")]
6974
struct PostgresConnectionError(String, u16, String, String);
7075

76+
/// Returns a Postgres connection pool constructed using configuration read from environment
77+
///
78+
/// # Environment variables read:
79+
/// - `DB_SYNC_POSTGRES_CONNECTION_STRING`: Postgres connection pool, eg.
80+
/// `postgres://postgres-user:postgres-password@db-sync-postgres-host:5432/db-sync-db`
7181
pub async fn get_connection_from_env() -> Result<PgPool, Box<dyn Error + Send + Sync + 'static>> {
7282
let config = ConnectionConfig::from_env()?;
7383
get_connection(

toolkit/data-sources/db-sync/src/governed_map/mod.rs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//! Db-Sync data source used by Partner Chain Governed Map feature
12
use crate::DataSourceError::ExpectedDataNotFound;
23
use crate::Result;
34
use crate::block::BlockDataSourceImpl;
@@ -15,14 +16,20 @@ use std::cmp::{max, min};
1516
use std::sync::{Arc, Mutex};
1617

1718
#[cfg(test)]
18-
pub mod tests;
19+
mod tests;
1920

21+
/// Data source for the Governed Map feature of Partner Chains toolkit
22+
///
23+
/// See documentation of [sp_governed_map] for a description of the feature
2024
pub struct GovernedMapDataSourceImpl {
25+
/// Postgres connection pool
2126
pub pool: PgPool,
27+
/// Prometheus metrics client
2228
pub metrics_opt: Option<McFollowerMetrics>,
2329
}
2430

2531
impl GovernedMapDataSourceImpl {
32+
/// Creates a new instance of the data source
2633
pub async fn new(
2734
pool: PgPool,
2835
metrics_opt: Option<McFollowerMetrics>,
@@ -105,15 +112,24 @@ async fn get_mappings_entries(
105112
Ok(mappings)
106113
}
107114

115+
/// Cached data source serving the Governed Map feature of Partner Chains toolkit
116+
///
117+
/// See documentation of [sp_governed_map] for a description of the feature
108118
pub struct GovernedMapDataSourceCachedImpl {
119+
/// Postgres connection pool
109120
pub pool: PgPool,
121+
/// Prometheus metrics client
110122
pub metrics_opt: Option<McFollowerMetrics>,
123+
/// Internal data cache size
111124
cache_size: u16,
125+
/// Internal cache
112126
cache: Arc<Mutex<Cache>>,
127+
/// [BlockDataSourceImpl] instance shared with other data sources for cache reuse.
113128
blocks: Arc<BlockDataSourceImpl>,
114129
}
115130

116131
impl GovernedMapDataSourceCachedImpl {
132+
/// Constructs a new Governed Map data source
117133
pub async fn new(
118134
pool: PgPool,
119135
metrics_opt: Option<McFollowerMetrics>,

0 commit comments

Comments
 (0)