Skip to content

Commit 01902bb

Browse files
committed
postpone polling db-sync configuration
1 parent b0daed8 commit 01902bb

File tree

5 files changed

+105
-29
lines changed

5 files changed

+105
-29
lines changed

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

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//! Db-Sync data source used by Partner Chain committee selection
22
use crate::DataSourceError::*;
33
use crate::db_model::{
4-
self, Address, Asset, BlockNumber, EpochNumber, MainchainTxOutput, StakePoolEntry,
5-
TxInConfiguration,
4+
self, Address, Asset, BlockNumber, DbSyncConfigurationProvider, EpochNumber, MainchainTxOutput,
5+
StakePoolEntry,
66
};
77
use crate::metrics::McFollowerMetrics;
88
use crate::observed_async_trait;
@@ -50,8 +50,8 @@ pub struct CandidatesDataSourceImpl {
5050
pool: PgPool,
5151
/// Prometheus metrics client
5252
metrics_opt: Option<McFollowerMetrics>,
53-
/// Transaction input configuration used by Db-Sync
54-
tx_in_config: TxInConfiguration,
53+
/// Configuration used by Db-Sync
54+
db_sync_config: DbSyncConfigurationProvider,
5555
}
5656

5757
observed_async_trait!(
@@ -129,8 +129,11 @@ impl CandidatesDataSourceImpl {
129129
) -> Result<CandidatesDataSourceImpl, Box<dyn std::error::Error + Send + Sync>> {
130130
db_model::create_idx_ma_tx_out_ident(&pool).await?;
131131
db_model::create_idx_tx_out_address(&pool).await?;
132-
let tx_in_config = TxInConfiguration::from_connection(&pool).await?;
133-
Ok(Self { pool, metrics_opt, tx_in_config })
132+
Ok(Self {
133+
pool: pool.clone(),
134+
metrics_opt,
135+
db_sync_config: DbSyncConfigurationProvider::new(pool),
136+
})
134137
}
135138

136139
/// Creates a new caching instance of the data source
@@ -159,8 +162,13 @@ impl CandidatesDataSourceImpl {
159162
let address: Address = Address(committee_candidate_address.to_string());
160163
let active_utxos = match registrations_block_for_epoch {
161164
Some(block) => {
162-
db_model::get_utxos_for_address(&self.pool, &address, block, self.tx_in_config)
163-
.await?
165+
db_model::get_utxos_for_address(
166+
&self.pool,
167+
&address,
168+
block,
169+
self.db_sync_config.get_tx_in_config().await?,
170+
)
171+
.await?
164172
},
165173
None => vec![],
166174
};

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
use crate::candidates::CandidatesDataSourceImpl;
2-
use crate::db_model::{TxInConfiguration, index_exists_unsafe};
2+
use crate::db_model::{DbSyncConfigurationProvider, TxInConfiguration, index_exists_unsafe};
33
use crate::metrics::mock::test_metrics;
44
use authority_selection_inherents::AuthoritySelectionDataSource;
55
use hex_literal::hex;
66
use sidechain_domain::*;
77
use sqlx::PgPool;
8+
use std::cell::OnceCell;
89
use std::str::FromStr;
10+
use std::sync::Arc;
911
use tokio_test::assert_err;
1012

1113
const D_PARAM_POLICY: [u8; 28] = hex!("500000000000000000000000000000000000434845434b504f494e69");
@@ -290,7 +292,14 @@ mod candidate_caching {
290292
}
291293

292294
fn make_source(pool: PgPool, tx_in_config: TxInConfiguration) -> CandidatesDataSourceImpl {
293-
CandidatesDataSourceImpl { pool, metrics_opt: Some(test_metrics()), tx_in_config }
295+
CandidatesDataSourceImpl {
296+
pool: pool.clone(),
297+
metrics_opt: Some(test_metrics()),
298+
db_sync_config: DbSyncConfigurationProvider {
299+
pool,
300+
tx_in_config: Arc::new(tokio::sync::Mutex::new(OnceCell::from(tx_in_config))),
301+
},
302+
}
294303
}
295304

296305
fn candidates_address() -> MainchainAddress {

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

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
use crate::SqlxError;
21
use crate::db_datum::DbDatum;
2+
use crate::{DataSourceError, SqlxError};
33
use bigdecimal::ToPrimitive;
44
use cardano_serialization_lib::PlutusData;
55
use chrono::NaiveDateTime;
@@ -9,8 +9,11 @@ use sidechain_domain::{
99
MainchainBlock, McBlockHash, McBlockNumber, McEpochNumber, McSlotNumber, McTxHash, UtxoId,
1010
UtxoIndex,
1111
};
12-
use sqlx::{Decode, Pool, Postgres, database::Database, error::BoxDynError, postgres::PgTypeInfo};
13-
use std::str::FromStr;
12+
use sqlx::{
13+
Decode, PgPool, Pool, Postgres, database::Database, error::BoxDynError, postgres::PgTypeInfo,
14+
};
15+
use std::{cell::OnceCell, str::FromStr, sync::Arc};
16+
use tokio::sync::Mutex;
1417

1518
/// Db-Sync `tx_in.value` configuration field
1619
#[derive(Debug, PartialEq, Copy, Clone)]
@@ -45,6 +48,37 @@ impl TxInConfiguration {
4548
}
4649
}
4750

51+
/// Structure that queries, caches and provides Db-Sync configuration
52+
pub struct DbSyncConfigurationProvider {
53+
/// Postgres connection pool
54+
pub(crate) pool: PgPool,
55+
/// Transaction input configuration used by Db-Sync
56+
pub(crate) tx_in_config: Arc<Mutex<OnceCell<TxInConfiguration>>>,
57+
}
58+
59+
impl DbSyncConfigurationProvider {
60+
pub(crate) fn new(pool: PgPool) -> Self {
61+
Self { tx_in_config: Arc::new(Mutex::new(OnceCell::new())), pool }
62+
}
63+
64+
pub(crate) async fn get_tx_in_config(
65+
&self,
66+
) -> std::result::Result<TxInConfiguration, DataSourceError> {
67+
let lock = self.tx_in_config.lock().await;
68+
if let Some(tx_in_config) = lock.get() {
69+
return Ok(*tx_in_config);
70+
} else {
71+
let tx_in_config = TxInConfiguration::from_connection(&self.pool).await?;
72+
lock.set(tx_in_config).map_err(|_| {
73+
DataSourceError::InternalDataSourceError(
74+
"Failed to set tx_in_config in GovernedMapDataSourceImpl".into(),
75+
)
76+
})?;
77+
return Ok(tx_in_config);
78+
}
79+
}
80+
}
81+
4882
#[derive(Debug, Clone, sqlx::FromRow, PartialEq)]
4983
pub(crate) struct Block {
5084
pub block_no: BlockNumber,

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

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
use crate::DataSourceError::ExpectedDataNotFound;
33
use crate::Result;
44
use crate::block::BlockDataSourceImpl;
5-
use crate::db_model::{GovernedMapAction, TxInConfiguration};
5+
use crate::db_model::{DbSyncConfigurationProvider, GovernedMapAction, TxInConfiguration};
66
use crate::{metrics::McFollowerMetrics, observed_async_trait};
77
use db_sync_sqlx::{Asset, BlockNumber};
88
use itertools::Itertools;
@@ -26,8 +26,8 @@ pub struct GovernedMapDataSourceImpl {
2626
pub pool: PgPool,
2727
/// Prometheus metrics client
2828
pub metrics_opt: Option<McFollowerMetrics>,
29-
/// Transaction input configuration used by Db-Sync
30-
tx_in_config: TxInConfiguration,
29+
/// Configuration used by Db-Sync
30+
db_sync_config: DbSyncConfigurationProvider,
3131
}
3232

3333
impl GovernedMapDataSourceImpl {
@@ -37,8 +37,11 @@ impl GovernedMapDataSourceImpl {
3737
metrics_opt: Option<McFollowerMetrics>,
3838
) -> std::result::Result<Self, Box<dyn std::error::Error + Send + Sync>> {
3939
crate::db_model::create_idx_tx_out_address(&pool).await?;
40-
let tx_in_config = TxInConfiguration::from_connection(&pool).await?;
41-
Ok(Self { pool, metrics_opt, tx_in_config })
40+
Ok(Self {
41+
pool: pool.clone(),
42+
metrics_opt,
43+
db_sync_config: DbSyncConfigurationProvider::new(pool),
44+
})
4245
}
4346
}
4447

@@ -50,7 +53,12 @@ impl GovernedMapDataSource for GovernedMapDataSourceImpl {
5053
scripts: MainChainScriptsV1,
5154
) -> std::result::Result<BTreeMap<String, ByteString>, Box<dyn std::error::Error + Send + Sync>>
5255
{
53-
Ok(get_mappings_entries(&self.pool, mc_block, scripts, self.tx_in_config).await?.into())
56+
Ok(get_mappings_entries(
57+
&self.pool,
58+
mc_block,
59+
scripts,
60+
self.db_sync_config.get_tx_in_config().await?
61+
).await?.into())
5462
}
5563

5664
async fn get_mapping_changes(
@@ -131,8 +139,8 @@ pub struct GovernedMapDataSourceCachedImpl {
131139
cache: Arc<Mutex<Cache>>,
132140
/// [BlockDataSourceImpl] instance shared with other data sources for cache reuse.
133141
blocks: Arc<BlockDataSourceImpl>,
134-
/// Transaction input configuration used by Db-Sync
135-
tx_in_config: TxInConfiguration,
142+
/// Configuration used by Db-Sync
143+
db_sync_config: DbSyncConfigurationProvider,
136144
}
137145

138146
impl GovernedMapDataSourceCachedImpl {
@@ -145,8 +153,14 @@ impl GovernedMapDataSourceCachedImpl {
145153
) -> std::result::Result<Self, Box<dyn std::error::Error + Send + Sync>> {
146154
crate::db_model::create_idx_tx_out_address(&pool).await?;
147155
let cache = Default::default();
148-
let tx_in_config = TxInConfiguration::from_connection(&pool).await?;
149-
Ok(Self { pool, metrics_opt, cache_size, cache, blocks, tx_in_config })
156+
Ok(Self {
157+
pool: pool.clone(),
158+
metrics_opt,
159+
cache_size,
160+
cache,
161+
blocks,
162+
db_sync_config: DbSyncConfigurationProvider::new(pool),
163+
})
150164
}
151165
}
152166

@@ -158,7 +172,7 @@ impl GovernedMapDataSource for GovernedMapDataSourceCachedImpl {
158172
scripts: MainChainScriptsV1,
159173
) -> std::result::Result<BTreeMap<String, ByteString>, Box<dyn std::error::Error + Send + Sync>>
160174
{
161-
Ok(get_mappings_entries(&self.pool, mc_block, scripts, self.tx_in_config).await?.into())
175+
Ok(get_mappings_entries(&self.pool, mc_block, scripts, self.db_sync_config.get_tx_in_config().await?).await?.into())
162176
}
163177

164178
async fn get_mapping_changes(
@@ -244,7 +258,7 @@ impl GovernedMapDataSourceCachedImpl {
244258
since_block,
245259
up_to_block,
246260
Asset::new(scripts.asset_policy_id),
247-
self.tx_in_config,
261+
self.db_sync_config.get_tx_in_config().await?,
248262
)
249263
.await?;
250264

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use super::{Cache, GovernedMapDataSourceCachedImpl, GovernedMapDataSourceImpl};
22
use crate::block::{BlockDataSourceImpl, DbSyncBlockDataSourceConfig};
3-
use crate::db_model::TxInConfiguration;
3+
use crate::db_model::{DbSyncConfigurationProvider, TxInConfiguration};
44
use crate::metrics::mock::test_metrics;
55
use hex_literal::hex;
66
use pretty_assertions::assert_eq;
@@ -9,6 +9,7 @@ use sidechain_domain::mainchain_epoch::{Duration, MainchainEpochConfig, Timestam
99
use sidechain_domain::*;
1010
use sp_governed_map::{GovernedMapDataSource, MainChainScriptsV1};
1111
use sqlx::PgPool;
12+
use std::cell::OnceCell;
1213
use std::str::FromStr;
1314
use std::sync::{Arc, Mutex};
1415
use tokio_test::assert_err;
@@ -150,7 +151,14 @@ fn scripts() -> MainChainScriptsV1 {
150151
}
151152

152153
fn make_source(pool: PgPool, tx_in_config: TxInConfiguration) -> GovernedMapDataSourceImpl {
153-
GovernedMapDataSourceImpl { pool, metrics_opt: Some(test_metrics()), tx_in_config }
154+
GovernedMapDataSourceImpl {
155+
pool: pool.clone(),
156+
metrics_opt: Some(test_metrics()),
157+
db_sync_config: DbSyncConfigurationProvider {
158+
pool,
159+
tx_in_config: Arc::new(tokio::sync::Mutex::new(OnceCell::from(tx_in_config))),
160+
},
161+
}
154162
}
155163

156164
async fn make_cached_source(
@@ -163,15 +171,18 @@ async fn make_cached_source(
163171
cache_size: 10u16,
164172
cache: Arc::new(Mutex::new(Cache::default())),
165173
blocks: Arc::new(BlockDataSourceImpl::from_config(
166-
pool,
174+
pool.clone(),
167175
DbSyncBlockDataSourceConfig {
168176
cardano_security_parameter: 432,
169177
cardano_active_slots_coeff: 0.05,
170178
block_stability_margin: 0,
171179
},
172180
&mainchain_epoch_config(),
173181
)),
174-
tx_in_config,
182+
db_sync_config: DbSyncConfigurationProvider {
183+
pool,
184+
tx_in_config: Arc::new(tokio::sync::Mutex::new(OnceCell::from(tx_in_config))),
185+
},
175186
}
176187
}
177188

0 commit comments

Comments
 (0)