Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

refactor(storage): find_config_by_key -> find_config_by_key_optional (#14131)

Hrithikesh3425dbce789b
diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rs
index eadf8e5c81..53811f6101 100644
--- a/crates/hyperswitch_domain_models/src/configs.rs
+++ b/crates/hyperswitch_domain_models/src/configs.rs
@@ -1,6 +1,10 @@
use common_utils::errors::CustomResult;
use diesel_models::configs as storage;
+/// Every method on this trait is expected to go through the caching layer:
+/// reads are served from (and populate) the config cache, and writes redact the
+/// cached entry across all instances. Direct database access is intentionally
+/// not exposed here.
#[async_trait::async_trait]
pub trait ConfigInterface {
type Error;
@@ -9,18 +13,18 @@ pub trait ConfigInterface {
config: storage::ConfigNew,
) -> CustomResult<storage::Config, Self::Error>;
- async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>;
-
- async fn find_config_by_key_unwrap_or(
+ async fn find_config_by_key_optional(
&self,
key: &str,
- // If the config is not found it will be created with the default value.
- default_config: Option<String>,
- ) -> CustomResult<storage::Config, Self::Error>;
+ ) -> CustomResult<Option<storage::Config>, Self::Error>;
- async fn find_config_by_key_from_db(
+ async fn find_config_by_key_unwrap_or(
&self,
key: &str,
+ // If the config is not found, this default value is substituted in and
+ // returned as-is. It is never written to the cache (Redis or in-memory) —
+ // only the underlying presence/absence of the key is cached.
+ default_config: String,
) -> CustomResult<storage::Config, Self::Error>;
async fn update_config_by_key(
@@ -29,11 +33,5 @@ pub trait ConfigInterface {
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error>;
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, Self::Error>;
-
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error>;
}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 74869b968c..5177b1c801 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -70,13 +70,13 @@ pub async fn toggle_blocklist_guard_for_merchant(
query: api_blocklist::ToggleBlocklistQuery,
) -> CustomResult<api_blocklist::ToggleBlocklistResponse, errors::ApiErrorResponse> {
let key = processor_merchant_id.get_blocklist_guard_key();
- let maybe_guard = state.store.find_config_by_key_from_db(&key).await;
+ let maybe_guard = state.store.find_config_by_key_optional(&key).await;
let new_config = configs::ConfigNew {
key: key.clone(),
config: query.status.to_string(),
};
match maybe_guard {
- Ok(_config) => {
+ Ok(Some(_config)) => {
let updated_config = configs::ConfigUpdate::Update {
config: Some(query.status.to_string()),
};
@@ -87,7 +87,7 @@ pub async fn toggle_blocklist_guard_for_merchant(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error enabling the blocklist guard")?;
}
- Err(e) if e.current_context().is_db_not_found() => {
+ Ok(None) => {
state
.store
.insert_config(new_config)
@@ -627,7 +627,7 @@ pub async fn is_blocklist_guard_enabled(
let blocklist_enabled_key = processor_merchant_id.get_blocklist_guard_key();
match state
.store
- .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
+ .find_config_by_key_unwrap_or(&blocklist_enabled_key, "false".to_string())
.await
{
Ok(config) => serde_json::from_str(&config.config).unwrap_or(false),
diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs
index 15c13efbea..1482ce7ec1 100644
--- a/crates/router/src/core/conditional_config.rs
+++ b/crates/router/src/core/conditional_config.rs
@@ -116,7 +116,7 @@ pub async fn upsert_conditional_config(
.get_account()
.get_id()
.get_payment_config_routing_id();
- let read_config_key = db.find_config_by_key(&key).await;
+ let read_config_key = db.find_config_by_key_optional(&key).await;
euclid::frontend::ast::lowering::lower_program(prog.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
@@ -125,7 +125,7 @@ pub async fn upsert_conditional_config(
.attach_printable("The Request has an Invalid Comparison")?;
match read_config_key {
- Ok(config) => {
+ Ok(Some(config)) => {
let previous_record: DecisionManagerRecord = config
.config
.parse_struct("DecisionManagerRecord")
@@ -167,7 +167,7 @@ pub async fn upsert_conditional_config(
Ok(service_api::ApplicationResponse::Json(new_algo))
}
- Err(e) if e.current_context().is_db_not_found() => {
+ Ok(None) => {
let new_rec = DecisionManagerRecord {
name: name
.get_required_value("name")
@@ -271,9 +271,11 @@ pub async fn retrieve_conditional_config(
.get_id()
.get_payment_config_routing_id();
let algo_config = db
- .find_config_by_key(&algorithm_id)
+ .find_config_by_key_optional(&algorithm_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)
+ .attach_printable("Error fetching the conditional config from the DB")?
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("The conditional config was not found in the DB")?;
let record: DecisionManagerRecord = algo_config
.config
diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs
index e612cb5f89..ebff7cac48 100644
--- a/crates/router/src/core/configs.rs
+++ b/crates/router/src/core/configs.rs
@@ -35,9 +35,10 @@ pub async fn set_config(state: SessionState, config: api::Config) -> RouterRespo
pub async fn read_config(state: SessionState, key: &str) -> RouterResponse<api::Config> {
let store = state.store.as_ref();
let config = store
- .find_config_by_key(key)
+ .find_config_by_key_optional(key)
.await
- .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?;
+ .to_not_found_response(errors::ApiErrorResponse::ConfigNotFound)?
+ .ok_or(errors::ApiErrorResponse::ConfigNotFound)?;
Ok(ApplicationResponse::Json(config.foreign_into()))
}
@@ -232,10 +233,11 @@ where
for db_key in db_keys.into_iter().flatten() {
attempted = true;
if resolved_value.is_none() {
- let config_result = storage.find_config_by_key(db_key).await;
+ let config_result = storage.find_config_by_key_optional(db_key).await;
if let Some(value) = config_result
.ok()
+ .flatten()
.and_then(|config| C::parse_db_config(&config.config, context.as_ref()))
{
router_env::logger::info!(
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index 6c448dfa62..661be4a4cf 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -495,7 +495,12 @@ pub async fn ensure_algorithm_cached(
let key = merchant_id.get_surcharge_dsk_key();
let value_to_cache = || async {
- let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
+ let config: diesel_models::Config = store
+ .find_config_by_key_optional(algorithm_id)
+ .await?
+ .ok_or(errors::StorageError::ValueNotFound(
+ algorithm_id.to_string(),
+ ))?;
let record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("Program")
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 861a98a788..278f734f81 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -8054,7 +8054,7 @@ where
let blocklist_enabled_key = processor_merchant_id.get_blocklist_guard_key();
let blocklist_guard_enabled = state
.store
- .find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
+ .find_config_by_key_unwrap_or(&blocklist_enabled_key, "false".to_string())
.await;
let blocklist_guard_enabled: bool = match blocklist_guard_enabled {
diff --git a/crates/router/src/core/payments/conditional_configs.rs b/crates/router/src/core/payments/conditional_configs.rs
index 55e5c657b1..cbec1635de 100644
--- a/crates/router/src/core/payments/conditional_configs.rs
+++ b/crates/router/src/core/payments/conditional_configs.rs
@@ -32,7 +32,10 @@ pub async fn perform_decision_management(
let key = merchant_id.get_dsl_config();
let find_key_from_db = || async {
- let config = db.find_config_by_key(&algorithm_id).await?;
+ let config = db
+ .find_config_by_key_optional(&algorithm_id)
+ .await?
+ .ok_or(errors::StorageError::ValueNotFound(algorithm_id.clone()))?;
let rec: DecisionManagerRecord = config
.config
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c82578a974..e60174929a 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -2510,7 +2510,7 @@ pub fn decide_payment_method_retrieval_action(
pub async fn is_config_flag_enabled(state: &SessionState, config_key: &str) -> bool {
let db = state.store.as_ref();
- db.find_config_by_key_unwrap_or(config_key, Some("false".to_string()))
+ db.find_config_by_key_unwrap_or(config_key, "false".to_string())
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to fetch `{config_key}` config from DB");
@@ -2718,8 +2718,8 @@ where
{
let db = state.store.as_ref();
- match db.find_config_by_key(config_key).await {
- Ok(rollout_config) => {
+ match db.find_config_by_key_optional(config_key).await {
+ Ok(Some(rollout_config)) => {
// Parse as JSON - log error if it fails but don't propagate
let parsed_rollout_config: Result<C, _> =
rollout_config.config.parse_struct("RolloutConfig");
@@ -2734,23 +2734,19 @@ where
})
.unwrap_or_default())
}
+ // ValueNotFound may be an expected outcome when a rollout configuration has not
+ // been provisioned. Treat it as a warning to avoid generating misleading errors.
+ Ok(None) => {
+ logger::warn!(
+ "Failed to fetch rollout config from DB. Defaulting to not execute and setting should_execute to false."
+ );
+ Ok(R::default())
+ }
Err(err) => {
- // ValueNotFound may be an expected outcome when a rollout configuration has not
- // been provisioned. Treat it as a warning to avoid generating misleading errors.
- match err.current_context() {
- errors::StorageError::ValueNotFound(_) => {
- logger::warn!(
- error = ?err,
- "Failed to fetch rollout config from DB. Defaulting to not execute and setting should_execute to false."
- );
- }
- _ => {
- logger::error!(
- error = ?err,
- "Failed to fetch rollout config from DB. Defaulting to not execute and setting should_execute to false."
- );
- }
- }
+ logger::error!(
+ error = ?err,
+ "Failed to fetch rollout config from DB. Defaulting to not execute and setting should_execute to false."
+ );
Ok(R::default())
}
}
@@ -2765,8 +2761,9 @@ where
/// 3. `ucs_rollout_config_<org_id>_<merchant_id>` — org + merchant
/// 4. `ucs_rollout_config_<org_id>` — org level
///
-/// Uses `find_config_by_key_unwrap_or` with a sentinel so absent keys are cached after
-/// the first DB miss — subsequent requests hit in-memory cache instead of the DB.
+/// Uses `find_config_by_key_unwrap_or` with a sentinel default; the key's absence
+/// (not the sentinel itself) is cached after the first DB miss, so subsequent
+/// requests still hit in-memory cache instead of the DB.
/// The future is boxed (`Box::pin`) to keep stack frames small under high concurrency.
pub async fn should_execute_based_on_rollout_with_precedence(
state: &SessionState,
@@ -2778,7 +2775,7 @@ pub async fn should_execute_based_on_rollout_with_precedence(
// Box the future to avoid large stack frames from nested async in debug builds
let result = Box::pin(state.store.find_config_by_key_unwrap_or(
key,
- Some(consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string()),
+ consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string(),
))
.await
.ok();
@@ -5281,13 +5278,21 @@ pub async fn get_merchant_connector_account(
};
let db_fetch = || async {
- db.find_config_by_key(cloned_key.as_str())
+ let config_optional = db
+ .find_config_by_key_optional(cloned_key.as_str())
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: cloned_key.to_owned(),
},
+ )?;
+ config_optional.ok_or_else(|| {
+ error_stack::Report::from(
+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: cloned_key.to_owned(),
+ },
)
+ })
};
let mca_config: String = redis_fetch()
@@ -9320,7 +9325,7 @@ pub async fn config_skip_saving_wallet_at_connector(
let config = db
.find_config_by_key_unwrap_or(
&merchant_id.get_skip_saving_wallet_at_connector_key(),
- Some("[]".to_string()),
+ "[]".to_string(),
)
.await;
Ok(match config {
@@ -9805,7 +9810,14 @@ async fn get_payment_update_enabled_for_client_auth(
) -> bool {
let key = merchant_id.get_payment_update_enabled_for_client_auth_key();
let db = &*state.store;
- let update_enabled = db.find_config_by_key(key.as_str()).await;
+ let update_enabled =
+ db.find_config_by_key_optional(key.as_str())
+ .await
+ .and_then(|config_optional| {
+ config_optional.ok_or_else(|| {
+ error_stack::Report::new(errors::StorageError::ValueNotFound(key.clone()))
+ })
+ });
match update_enabled {
Ok(conf) => conf.config.to_lowercase() == "true",
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index de3eec0006..7dec040a94 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -249,7 +249,7 @@ pub async fn is_step_up_enabled_for_merchant_connector(
) -> bool {
let key = merchant_id.get_step_up_enabled_key();
let db = &*state.store;
- db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
+ db.find_config_by_key_unwrap_or(key.as_str(), "[]".to_string())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|step_up_config| {
@@ -272,8 +272,13 @@ pub async fn get_merchant_max_auto_retries_enabled(
) -> Option<i32> {
let key = merchant_id.get_max_auto_retries_enabled();
- db.find_config_by_key(key.as_str())
+ db.find_config_by_key_optional(key.as_str())
.await
+ .and_then(|config_optional| {
+ config_optional.ok_or_else(|| {
+ error_stack::Report::new(errors::StorageError::ValueNotFound(key.clone()))
+ })
+ })
.change_context(errors::ApiErrorResponse::InternalServerError)
.and_then(|retries_config| {
retries_config
diff --git a/crates/router/src/core/payments/routing/utils.rs b/crates/router/src/core/payments/routing/utils.rs
index c4582bb776..a26a9c3312 100644
--- a/crates/router/src/core/payments/routing/utils.rs
+++ b/crates/router/src/core/payments/routing/utils.rs
@@ -3456,9 +3456,10 @@ pub async fn load_skip_pre_routing_config(
) -> HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>> {
let merchant_cfg = state
.store
- .find_config_by_key_from_db(&pre_routing_disabled_pm_pmt_key)
+ .find_config_by_key_optional(&pre_routing_disabled_pm_pmt_key)
.await
.ok()
+ .flatten()
.and_then(|cfg| serde_json::from_str::<MerchantPreRoutingConfig>(&cfg.config).ok())
.unwrap_or_default();
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 2f6d25f672..2f740125e0 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -2056,10 +2056,11 @@ where
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_id}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_id}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -2387,10 +2388,11 @@ pub async fn construct_payment_router_data_for_update_metadata<'a>(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_id}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_id}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
diff --git a/crates/router/src/core/relay/utils.rs b/crates/router/src/core/relay/utils.rs
index ac8a307a3c..32f8361453 100644
--- a/crates/router/src/core/relay/utils.rs
+++ b/crates/router/src/core/relay/utils.rs
@@ -51,10 +51,11 @@ pub async fn construct_relay_refund_router_data<F>(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_name}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_name}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -194,10 +195,11 @@ pub async fn construct_relay_capture_router_data(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_name}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_name}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -330,10 +332,11 @@ pub async fn construct_relay_incremental_authorization_router_data(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_name}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_name}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -462,10 +465,11 @@ pub async fn construct_relay_void_router_data(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_name}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_name}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -592,10 +596,11 @@ pub async fn construct_relay_payments_retrieve_router_data(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_name}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_name}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index decebde208..2120b1e112 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -84,16 +84,16 @@ pub async fn get_merchant_default_config(
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let key = get_default_config_key(merchant_id, transaction_type);
- let maybe_config = db.find_config_by_key(&key).await;
+ let config_optional = db.find_config_by_key_optional(&key).await;
- match maybe_config {
- Ok(config) => config
+ match config_optional {
+ Ok(Some(config)) => config
.config
.parse_struct("Vec<RoutableConnectors>")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant default config has invalid structure"),
- Err(e) if e.current_context().is_db_not_found() => {
+ Ok(None) => {
let new_config_conns = Vec::<routing_types::RoutableConnectorChoice>::new();
let serialized = new_config_conns
.encode_to_string_of_json()
diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs
index 10377fa303..3aa8e0919f 100644
--- a/crates/router/src/core/surcharge_decision_config.rs
+++ b/crates/router/src/core/surcharge_decision_config.rs
@@ -50,7 +50,7 @@ pub async fn upsert_surcharge_decision_config(
.get_account()
.get_id()
.get_payment_method_surcharge_routing_id();
- let read_config_key = db.find_config_by_key(&key).await;
+ let read_config_key = db.find_config_by_key_optional(&key).await;
euclid::frontend::ast::lowering::lower_program(program.clone())
.change_context(errors::ApiErrorResponse::InvalidRequestData {
@@ -59,7 +59,7 @@ pub async fn upsert_surcharge_decision_config(
.attach_printable("The Request has an Invalid Comparison")?;
let surcharge_cache_key = processor.get_account().get_id().get_surcharge_dsk_key();
match read_config_key {
- Ok(config) => {
+ Ok(Some(config)) => {
let previous_record: SurchargeDecisionManagerRecord = config
.config
.parse_struct("SurchargeDecisionManagerRecord")
@@ -102,7 +102,7 @@ pub async fn upsert_surcharge_decision_config(
Ok(service_api::ApplicationResponse::Json(new_algo))
}
- Err(e) if e.current_context().is_db_not_found() => {
+ Ok(None) => {
let new_rec = SurchargeDecisionManagerRecord {
name: name
.get_required_value("name")
@@ -216,9 +216,11 @@ pub async fn retrieve_surcharge_decision_config(
.get_id()
.get_payment_method_surcharge_routing_id();
let algo_config = db
- .find_config_by_key(&algorithm_id)
+ .find_config_by_key_optional(&algorithm_id)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)
+ .attach_printable("Error fetching the surcharge conditional config from the DB")?
+ .ok_or(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("The surcharge conditional config was not found in the DB")?;
let record: SurchargeDecisionManagerRecord = algo_config
.config
diff --git a/crates/router/src/core/unified_connector_service/kill_switch.rs b/crates/router/src/core/unified_connector_service/kill_switch.rs
index 649cb16693..abcd220c2b 100644
--- a/crates/router/src/core/unified_connector_service/kill_switch.rs
+++ b/crates/router/src/core/unified_connector_service/kill_switch.rs
@@ -362,7 +362,7 @@ pub async fn trip_status(
.store
.find_config_by_key_unwrap_or(
&config_key,
- Some(consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string()),
+ consts::UCS_ROLLOUT_CONFIG_NOT_CONFIGURED.to_string(),
)
.await
.ok()
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 9e118d81d3..f22da7db62 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -417,10 +417,11 @@ pub async fn construct_refund_router_data<'a, F>(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_enum}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_enum}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
@@ -613,10 +614,11 @@ pub async fn construct_refund_router_data<'a, F>(
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
- .find_config_by_key(&format!("connector_api_version_{connector_id}"))
+ .find_config_by_key_optional(&format!("connector_api_version_{connector_id}"))
.await
- .map(|value| value.config)
.ok()
+ .flatten()
+ .map(|value| value.config)
} else {
None
};
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index d7e55ab2ea..bc7b3779f1 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -310,28 +310,11 @@ impl ConfigInterface for KafkaStore {
self.diesel_store.insert_config(config).await
}
- async fn find_config_by_key(
+ async fn find_config_by_key_optional(
&self,
key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.diesel_store.find_config_by_key(key).await
- }
-
- async fn find_config_by_key_from_db(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.diesel_store.find_config_by_key_from_db(key).await
- }
-
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, errors::StorageError> {
- self.diesel_store
- .update_config_in_database(key, config_update)
- .await
+ ) -> CustomResult<Option<storage::Config>, errors::StorageError> {
+ self.diesel_store.find_config_by_key_optional(key).await
}
async fn update_config_by_key(
@@ -354,7 +337,7 @@ impl ConfigInterface for KafkaStore {
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
- default_config: Option<String>,
+ default_config: String,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.find_config_by_key_unwrap_or(key, default_config)
diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs
index 5f07571c11..baf13f7b41 100644
--- a/crates/router/src/utils/connector_onboarding.rs
+++ b/crates/router/src/utils/connector_onboarding.rs
@@ -84,10 +84,12 @@ pub async fn set_tracking_id_in_configs(
let timestamp = common_utils::date_time::now_unix_timestamp().to_string();
let find_config = state
.store
- .find_config_by_key(&build_key(connector_id, connector))
- .await;
+ .find_config_by_key_optional(&build_key(connector_id, connector))
+ .await
+ .change_context(ApiErrorResponse::InternalServerError)
+ .attach_printable("Error fetching data from configs table")?;
- if find_config.is_ok() {
+ if find_config.is_some() {
state
.store
.update_config_by_key(
@@ -99,12 +101,7 @@ pub async fn set_tracking_id_in_configs(
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error updating data in configs table")?;
- } else if find_config
- .as_ref()
- .map_err(|e| e.current_context().is_db_not_found())
- .err()
- .unwrap_or(false)
- {
+ } else {
state
.store
.insert_config(ConfigNew {
@@ -114,8 +111,6 @@ pub async fn set_tracking_id_in_configs(
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error inserting data in configs table")?;
- } else {
- find_config.change_context(ApiErrorResponse::InternalServerError)?;
}
Ok(())
@@ -130,7 +125,7 @@ pub async fn get_tracking_id_from_configs(
.store
.find_config_by_key_unwrap_or(
&build_key(connector_id, connector),
- Some(common_utils::date_time::now_unix_timestamp().to_string()),
+ common_utils::date_time::now_unix_timestamp().to_string(),
)
.await
.change_context(ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/workflows/post_capture_void_sync.rs b/crates/router/src/workflows/post_capture_void_sync.rs
index de77bcef2f..fc0f90b31e 100644
--- a/crates/router/src/workflows/post_capture_void_sync.rs
+++ b/crates/router/src/workflows/post_capture_void_sync.rs
@@ -144,12 +144,18 @@ pub async fn get_post_capture_void_sync_process_schedule_time(
_merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
+ let config_key = format!("pt_mapping_post_capture_void_sync_{connector}");
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
- .find_config_by_key(&format!("pt_mapping_post_capture_void_sync_{connector}"))
+ .find_config_by_key_optional(&config_key)
.await
+ .and_then(|config_optional| {
+ config_optional.ok_or_else(|| {
+ error_stack::Report::new(errors::StorageError::ValueNotFound(config_key.clone()))
+ })
+ })
.map(|value| value.config)
.and_then(|config| {
config
diff --git a/crates/storage_impl/src/configs.rs b/crates/storage_impl/src/configs.rs
index e1073df87a..6759d22df2 100644
--- a/crates/storage_impl/src/configs.rs
+++ b/crates/storage_impl/src/configs.rs
@@ -26,17 +26,6 @@ impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> {
self.router_store.insert_config(config).await
}
- #[instrument(skip_all)]
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, StorageError> {
- self.router_store
- .update_config_in_database(key, config_update)
- .await
- }
-
//update in DB and remove in redis and cache
#[instrument(skip_all)]
async fn update_config_by_key(
@@ -49,26 +38,22 @@ impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> {
.await
}
+ //check in cache, then redis then finally DB, and on the way back populate redis and cache
#[instrument(skip_all)]
- async fn find_config_by_key_from_db(
+ async fn find_config_by_key_optional(
&self,
key: &str,
- ) -> CustomResult<storage::Config, StorageError> {
- self.router_store.find_config_by_key_from_db(key).await
- }
-
- //check in cache, then redis then finally DB, and on the way back populate redis and cache
- #[instrument(skip_all)]
- async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
- self.router_store.find_config_by_key(key).await
+ ) -> CustomResult<Option<storage::Config>, StorageError> {
+ self.router_store.find_config_by_key_optional(key).await
}
#[instrument(skip_all)]
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
- // If the config is not found it will be cached with the default value.
- default_config: Option<String>,
+ // If the config is not found, this default value is substituted in and
+ // returned as-is; it is never written to the cache.
+ default_config: String,
) -> CustomResult<storage::Config, StorageError> {
self.router_store
.find_config_by_key_unwrap_or(key, default_config)
@@ -101,18 +86,6 @@ impl<T: DatabaseStore> ConfigInterface for RouterStore<T> {
Ok(inserted)
}
- #[instrument(skip_all)]
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Config::update_by_key(&conn, key, config_update)
- .await
- .map_err(|error| report!(StorageError::from(error)))
- }
-
//update in DB and remove in redis and cache
#[instrument(skip_all)]
async fn update_config_by_key(
@@ -120,68 +93,56 @@ impl<T: DatabaseStore> ConfigInterface for RouterStore<T> {
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, StorageError> {
- cache::publish_and_redact(self, CacheKind::Config(key.into()), || {
- self.update_config_in_database(key, config_update)
- })
- .await
- }
-
- #[instrument(skip_all)]
- async fn find_config_by_key_from_db(
- &self,
- key: &str,
- ) -> CustomResult<storage::Config, StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::Config::find_by_key(&conn, key)
- .await
- .map_err(|error| report!(StorageError::from(error)))
- }
-
- //check in cache, then redis then finally DB, and on the way back populate redis and cache
- #[instrument(skip_all)]
- async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
- let find_config_by_key_from_db = || async {
+ cache::publish_and_redact(self, CacheKind::Config(key.into()), || async {
let conn = connection::pg_connection_write(self).await?;
- storage::Config::find_by_key(&conn, key)
+ storage::Config::update_by_key(&conn, key, config_update)
.await
.map_err(|error| report!(StorageError::from(error)))
- };
- cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await
+ })
+ .await
}
+ //check in cache, then redis then finally DB, and on the way back populate redis and cache
#[instrument(skip_all)]
- async fn find_config_by_key_unwrap_or(
+ async fn find_config_by_key_optional(
&self,
key: &str,
- // If the config is not found it will be cached with the default value.
- default_config: Option<String>,
- ) -> CustomResult<storage::Config, StorageError> {
- let find_else_unwrap_or = || async {
+ ) -> CustomResult<Option<storage::Config>, StorageError> {
+ let find_config_by_key_from_db = || async {
let conn = connection::pg_connection_write(self).await?;
match storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(StorageError::from(error)))
{
- Ok(a) => Ok(a),
+ Ok(config) => Ok(Some(config)),
Err(err) => {
if err.current_context().is_db_not_found() {
- default_config
- .map(|c| {
- storage::ConfigNew {
- key: key.to_string(),
- config: c,
- }
- .into()
- })
- .ok_or(err)
+ Ok(None)
} else {
Err(err)
}
}
}
};
+ cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await
+ }
- cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
+ #[instrument(skip_all)]
+ async fn find_config_by_key_unwrap_or(
+ &self,
+ key: &str,
+ // Not found is not persisted anywhere (not in redis, not in the in-memory
+ // cache) — only the real DB presence/absence goes through the cache, via
+ // `find_config_by_key_optional`. This value is substituted in afterwards.
+ default_config: String,
+ ) -> CustomResult<storage::Config, StorageError> {
+ Ok(self
+ .find_config_by_key_optional(key)
+ .await?
+ .unwrap_or_else(|| storage::Config {
+ key: key.to_string(),
+ config: default_config,
+ }))
}
#[instrument(skip_all)]
@@ -216,14 +177,6 @@ impl ConfigInterface for MockDb {
Ok(config_new)
}
- async fn update_config_in_database(
- &self,
- key: &str,
- config_update: storage::ConfigUpdate,
- ) -> CustomResult<storage::Config, Self::Error> {
- self.update_config_by_key(key, config_update).await
- }
-
async fn update_config_by_key(
&self,
key: &str,
@@ -261,25 +214,25 @@ impl ConfigInterface for MockDb {
result
}
- async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
- let configs = self.configs.lock().await;
- let config = configs.iter().find(|c| c.key == key).cloned();
-
- config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into())
- }
-
- async fn find_config_by_key_unwrap_or(
+ async fn find_config_by_key_optional(
&self,
key: &str,
- _default_config: Option<String>,
- ) -> CustomResult<storage::Config, Self::Error> {
- self.find_config_by_key(key).await
+ ) -> CustomResult<Option<storage::Config>, Self::Error> {
+ let configs = self.configs.lock().await;
+ Ok(configs.iter().find(|c| c.key == key).cloned())
}
- async fn find_config_by_key_from_db(
+ async fn find_config_by_key_unwrap_or(
&self,
key: &str,
+ default_config: String,
) -> CustomResult<storage::Config, Self::Error> {
- self.find_config_by_key(key).await
+ Ok(self
+ .find_config_by_key_optional(key)
+ .await?
+ .unwrap_or_else(|| storage::Config {
+ key: key.to_string(),
+ config: default_config,
+ }))
}
}
diff --git a/crates/subscriptions/src/workflows/invoice_sync.rs b/crates/subscriptions/src/workflows/invoice_sync.rs
index 6d1b526937..3d7f2b489b 100644
--- a/crates/subscriptions/src/workflows/invoice_sync.rs
+++ b/crates/subscriptions/src/workflows/invoice_sync.rs
@@ -432,9 +432,15 @@ pub async fn get_subscription_invoice_sync_process_schedule_time(
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
+ let config_key = format!("invoice_sync_pt_mapping_{connector}");
let mapping: CustomResult<process_data::SubscriptionInvoiceSyncPTMapping, StorageError> = db
- .find_config_by_key(&format!("invoice_sync_pt_mapping_{connector}"))
+ .find_config_by_key_optional(&config_key)
.await
+ .and_then(|config_optional| {
+ config_optional.ok_or_else(|| {
+ error_stack::Report::new(StorageError::ValueNotFound(config_key.clone()))
+ })
+ })
.map(|value| value.config)
.and_then(|config| {
config