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

feat(superposition): Introduce type state pattern for superposition configs framework (#10902)

chikke srujan5c07f70c1202
diff --git a/Cargo.lock b/Cargo.lock
index 248352424c..67cdcf605d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4984,7 +4984,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
dependencies = [
"cfg-if 1.0.0",
- "windows-targets 0.52.6",
+ "windows-targets 0.53.5",
]
[[package]]
@@ -6086,6 +6086,12 @@ dependencies = [
"subtle",
]
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
[[package]]
name = "pathdiff"
version = "0.2.1"
@@ -7345,8 +7351,10 @@ dependencies = [
"num-traits",
"num_cpus",
"once_cell",
+ "open-feature",
"openidconnect",
"openssl",
+ "paste",
"payment_link",
"payment_methods",
"pm_auth",
diff --git a/crates/external_services/src/lib.rs b/crates/external_services/src/lib.rs
index 6fd57efe37..6d64794ab4 100644
--- a/crates/external_services/src/lib.rs
+++ b/crates/external_services/src/lib.rs
@@ -118,3 +118,13 @@ pub mod metrics {
#[cfg(feature = "aws_kms")]
histogram_metric_f64!(AWS_KMS_ENCRYPT_TIME, GLOBAL_METER); // Histogram for AWS KMS encryption time (in sec)
}
+
+/// Metrics for config-related operations
+#[cfg(feature = "superposition")]
+pub mod config_metrics {
+ use router_env::{counter_metric, global_meter};
+
+ global_meter!(GLOBAL_METER, "EXTERNAL_SERVICES");
+
+ counter_metric!(CONFIG_SUPERPOSITION_FETCH, GLOBAL_METER); // No. of configs fetched from Superposition
+}
diff --git a/crates/external_services/src/superposition.rs b/crates/external_services/src/superposition.rs
index 06b18142eb..9b6b2f3c09 100644
--- a/crates/external_services/src/superposition.rs
+++ b/crates/external_services/src/superposition.rs
@@ -10,6 +10,7 @@ use error_stack::report;
use masking::ExposeInterface;
pub use self::types::{ConfigContext, SuperpositionClientConfig, SuperpositionError};
+use crate::config_metrics;
fn convert_open_feature_value(value: open_feature::Value) -> Result<serde_json::Value, String> {
match value {
@@ -29,6 +30,69 @@ fn convert_open_feature_value(value: open_feature::Value) -> Result<serde_json::
}
}
+/// Trait abstracting the different type-specific client methods
+pub trait GetValue<T> {
+ /// Get a typed value from the OpenFeature client
+ fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> impl std::future::Future<Output = Result<T, open_feature::EvaluationError>> + Send;
+}
+
+impl GetValue<bool> for open_feature::Client {
+ async fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> Result<bool, open_feature::EvaluationError> {
+ self.get_bool_value(key, Some(context), None).await
+ }
+}
+
+impl GetValue<String> for open_feature::Client {
+ async fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> Result<String, open_feature::EvaluationError> {
+ self.get_string_value(key, Some(context), None).await
+ }
+}
+
+impl GetValue<i64> for open_feature::Client {
+ async fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> Result<i64, open_feature::EvaluationError> {
+ self.get_int_value(key, Some(context), None).await
+ }
+}
+
+impl GetValue<f64> for open_feature::Client {
+ async fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> Result<f64, open_feature::EvaluationError> {
+ self.get_float_value(key, Some(context), None).await
+ }
+}
+
+impl GetValue<serde_json::Value> for open_feature::Client {
+ async fn get_value(
+ &self,
+ key: &str,
+ context: &open_feature::EvaluationContext,
+ ) -> Result<serde_json::Value, open_feature::EvaluationError> {
+ let json_result = self
+ .get_struct_value::<types::JsonValue>(key, Some(context), None)
+ .await?;
+ Ok(json_result.into_inner())
+ }
+}
+
/// Superposition client wrapper
// Debug trait cannot be derived because open_feature::Client doesn't implement Debug
#[allow(missing_debug_implementations)]
@@ -91,96 +155,86 @@ impl SuperpositionClient {
}
}
- /// Get a boolean configuration value from Superposition
- pub async fn get_bool_value(
- &self,
- key: &str,
- context: Option<&ConfigContext>,
- ) -> CustomResult<bool, SuperpositionError> {
- let evaluation_context = self.build_evaluation_context(context);
-
- self.client
- .get_bool_value(key, Some(&evaluation_context), None)
- .await
- .map_err(|e| {
- report!(SuperpositionError::ClientError(format!(
- "Failed to get bool value for key '{key}': {e:?}"
- )))
- })
- }
-
- /// Get a string configuration value from Superposition
- pub async fn get_string_value(
- &self,
- key: &str,
- context: Option<&ConfigContext>,
- ) -> CustomResult<String, SuperpositionError> {
- let evaluation_context = self.build_evaluation_context(context);
-
- self.client
- .get_string_value(key, Some(&evaluation_context), None)
- .await
- .map_err(|e| {
- report!(SuperpositionError::ClientError(format!(
- "Failed to get string value for key '{key}': {e:?}"
- )))
- })
- }
-
- /// Get an integer configuration value from Superposition
- pub async fn get_int_value(
- &self,
- key: &str,
- context: Option<&ConfigContext>,
- ) -> CustomResult<i64, SuperpositionError> {
- let evaluation_context = self.build_evaluation_context(context);
-
- self.client
- .get_int_value(key, Some(&evaluation_context), None)
- .await
- .map_err(|e| {
- report!(SuperpositionError::ClientError(format!(
- "Failed to get int value for key '{key}': {e:?}"
- )))
- })
- }
-
- /// Get a float configuration value from Superposition
- pub async fn get_float_value(
+ /// Generic method to get a typed configuration value from Superposition
+ ///
+ /// # Type Parameters
+ /// * `T` - The type of value to retrieve. Supported types: `bool`, `String`, `i64`, `f64`, `serde_json::Value`
+ ///
+ /// # Arguments
+ /// * `key` - The configuration key
+ /// * `context` - Optional evaluation context
+ ///
+ /// # Returns
+ /// * `CustomResult<T, SuperpositionError>` - The configuration value or error
+ pub async fn get_config_value<T>(
&self,
key: &str,
context: Option<&ConfigContext>,
- ) -> CustomResult<f64, SuperpositionError> {
+ ) -> CustomResult<T, SuperpositionError>
+ where
+ open_feature::Client: GetValue<T>,
+ {
let evaluation_context = self.build_evaluation_context(context);
+ let type_name = std::any::type_name::<T>();
self.client
- .get_float_value(key, Some(&evaluation_context), None)
+ .get_value(key, &evaluation_context)
.await
.map_err(|e| {
report!(SuperpositionError::ClientError(format!(
- "Failed to get float value for key '{key}': {e:?}"
+ "Failed to get {type_name} value for key '{key}': {e:?}"
)))
})
}
+}
- /// Get an object configuration value from Superposition
- pub async fn get_object_value(
- &self,
- key: &str,
- context: Option<&ConfigContext>,
- ) -> CustomResult<serde_json::Value, SuperpositionError> {
- let evaluation_context = self.build_evaluation_context(context);
-
- let json_result = self
- .client
- .get_struct_value::<types::JsonValue>(key, Some(&evaluation_context), None)
- .await
- .map_err(|e| {
- report!(SuperpositionError::ClientError(format!(
- "Failed to get object value for key '{key}': {e:?}"
- )))
- })?;
-
- Ok(json_result.into_inner())
+/// Each config type implements this trait to define how its value should be
+/// retrieved from Superposition.
+pub trait Config {
+ /// The output type of this configuration
+ type Output: Default + Clone;
+
+ /// Get the Superposition key for this config
+ const SUPERPOSITION_KEY: &'static str;
+
+ /// Get the default value for this config
+ const DEFAULT_VALUE: Self::Output;
+
+ /// Fetch config value from Superposition.
+ fn fetch(
+ superposition_client: &SuperpositionClient,
+ context: Option<ConfigContext>,
+ ) -> impl std::future::Future<Output = CustomResult<Self::Output, SuperpositionError>> + Send
+ where
+ open_feature::Client: GetValue<Self::Output>,
+ {
+ async move {
+ match superposition_client
+ .get_config_value::<Self::Output>(Self::SUPERPOSITION_KEY, context.as_ref())
+ .await
+ {
+ Ok(value) => {
+ router_env::logger::info!(
+ "Superposition config hit: key='{}', type='{}'",
+ Self::SUPERPOSITION_KEY,
+ std::any::type_name::<Self::Output>()
+ );
+ config_metrics::CONFIG_SUPERPOSITION_FETCH.add(
+ 1,
+ router_env::metric_attributes!(("config_type", Self::SUPERPOSITION_KEY)),
+ );
+ Ok(value)
+ }
+ Err(e) => {
+ router_env::logger::warn!(
+ "Superposition config miss: key='{}', type='{}', error='{:?}'",
+ Self::SUPERPOSITION_KEY,
+ std::any::type_name::<Self::Output>(),
+ e
+ );
+ Err(e)
+ }
+ }
+ }
}
}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index df49487fad..5f0ff361fd 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -54,6 +54,7 @@ async-bb8-diesel = "0.2.1"
async-trait = "0.1.88"
base64 = "0.22.1"
bb8 = "0.8"
+open-feature = { version = "0.2.5"}
blake3 = "1.8.2"
bytes = "1.10.1"
clap = { version = "4.5.38", default-features = false, features = ["std", "derive", "help", "usage"] }
@@ -73,6 +74,7 @@ josekit = "0.8.7"
jsonwebtoken = "9.3.1"
maud = { version = "0.26.0", features = ["actix-web"] }
mimalloc = { version = "0.1", optional = true }
+paste = "1.0.15"
mime = "0.3.17"
nanoid = "0.4.0"
num_cpus = "1.16.0"
diff --git a/crates/router/src/core/configs.rs b/crates/router/src/core/configs.rs
index 649ab4003c..be3a0ba0cb 100644
--- a/crates/router/src/core/configs.rs
+++ b/crates/router/src/core/configs.rs
@@ -1,10 +1,14 @@
+pub mod dimension_config;
+pub mod dimension_state;
+
use common_utils::errors::CustomResult;
use error_stack::ResultExt;
-use external_services::superposition::ConfigContext;
+use external_services::superposition::{self, ConfigContext};
use crate::{
core::errors::{self, utils::StorageErrorExt, RouterResponse},
- routes::SessionState,
+ db,
+ routes::{metrics, SessionState},
services::ApplicationResponse,
types::{api, transformers::ForeignInto},
};
@@ -53,224 +57,162 @@ pub async fn config_delete(state: SessionState, key: String) -> RouterResponse<a
Ok(ApplicationResponse::Json(config.foreign_into()))
}
-/// Get a boolean configuration value with superposition and database fallback
-pub async fn get_config_bool(
- state: &SessionState,
- superposition_key: &str,
- db_key: &str,
- context: Option<ConfigContext>,
- default_value: bool,
-) -> CustomResult<bool, errors::StorageError> {
- // Try superposition first if available
- let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
- match superposition_client
- .get_bool_value(superposition_key, context.as_ref())
- .await
- {
- Ok(value) => Some(value),
- Err(err) => {
- router_env::logger::warn!(
- "Failed to retrieve config from superposition, falling back to database: {:?}",
- err
- );
- None
- }
- }
- } else {
- None
- };
+/// Trait for types that can be stored and retrieved as a configuration value
+pub trait ConfigType: Sized {
+ /// Parse the value from database string representation
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError>;
- // Use superposition result or fall back to database
- if let Some(value) = superposition_result {
- Ok(value)
- } else {
- let config = state
- .store
- .find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
- .await?;
+ /// Convert the value to a string for database storage
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError>;
+}
- config
- .config
- .parse::<bool>()
- .change_context(errors::StorageError::DeserializationFailed)
+impl ConfigType for String {
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {
+ Ok(config_str.to_string())
}
-}
-/// Get a string configuration value with superposition and database fallback
-pub async fn get_config_string(
- state: &SessionState,
- superposition_key: &str,
- db_key: &str,
- context: Option<ConfigContext>,
- default_value: String,
-) -> CustomResult<String, errors::StorageError> {
- // Try superposition first if available
- let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
- match superposition_client
- .get_string_value(superposition_key, context.as_ref())
- .await
- {
- Ok(value) => Some(value),
- Err(err) => {
- router_env::logger::warn!(
- "Failed to retrieve config from superposition, falling back to database: {:?}",
- err
- );
- None
- }
- }
- } else {
- None
- };
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {
+ Ok(self.clone())
+ }
+}
- // Use superposition result or fall back to database
- if let Some(value) = superposition_result {
- Ok(value)
- } else {
- let config = state
- .store
- .find_config_by_key_unwrap_or(db_key, Some(default_value))
- .await?;
+impl ConfigType for bool {
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {
+ config_str
+ .parse::<Self>()
+ .change_context(errors::StorageError::DeserializationFailed)
+ }
- Ok(config.config)
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {
+ Ok(self.to_string())
}
}
-/// Get an integer configuration value with superposition and database fallback
-pub async fn get_config_int(
- state: &SessionState,
- superposition_key: &str,
- db_key: &str,
- context: Option<ConfigContext>,
- default_value: i64,
-) -> CustomResult<i64, errors::StorageError> {
- // Try superposition first if available
- let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
- match superposition_client
- .get_int_value(superposition_key, context.as_ref())
- .await
- {
- Ok(value) => Some(value),
- Err(err) => {
- router_env::logger::warn!(
- "Failed to retrieve config from superposition, falling back to database: {:?}",
- err
- );
- None
- }
- }
- } else {
- None
- };
+impl ConfigType for i64 {
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {
+ config_str
+ .parse::<Self>()
+ .change_context(errors::StorageError::DeserializationFailed)
+ }
- // Use superposition result or fall back to database
- if let Some(value) = superposition_result {
- Ok(value)
- } else {
- let config = state
- .store
- .find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
- .await?;
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {
+ Ok(self.to_string())
+ }
+}
- config
- .config
- .parse::<i64>()
+impl ConfigType for f64 {
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {
+ config_str
+ .parse::<Self>()
.change_context(errors::StorageError::DeserializationFailed)
}
-}
-/// Get a float configuration value with superposition and database fallback
-pub async fn get_config_float(
- state: &SessionState,
- superposition_key: &str,
- db_key: &str,
- context: Option<ConfigContext>,
- default_value: f64,
-) -> CustomResult<f64, errors::StorageError> {
- // Try superposition first if available
- let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
- match superposition_client
- .get_float_value(superposition_key, context.as_ref())
- .await
- {
- Ok(value) => Some(value),
- Err(err) => {
- router_env::logger::warn!(
- "Failed to retrieve config from superposition, falling back to database: {:?}",
- err
- );
- None
- }
- }
- } else {
- None
- };
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {
+ Ok(self.to_string())
+ }
+}
- // Use superposition result or fall back to database
- if let Some(value) = superposition_result {
- Ok(value)
- } else {
- let config = state
- .store
- .find_config_by_key_unwrap_or(db_key, Some(default_value.to_string()))
- .await?;
+impl ConfigType for serde_json::Value {
+ fn from_config_str(config_str: &str) -> CustomResult<Self, errors::StorageError> {
+ serde_json::from_str(config_str).change_context(errors::StorageError::DeserializationFailed)
+ }
- config
- .config
- .parse::<f64>()
- .change_context(errors::StorageError::DeserializationFailed)
+ fn to_config_string(&self) -> CustomResult<String, errors::StorageError> {
+ serde_json::to_string(self).change_context(errors::StorageError::SerializationFailed)
}
}
-/// Get an object configuration value with superposition and database fallback
-pub async fn get_config_object<T>(
- state: &SessionState,
- superposition_key: &str,
+/// Fetch configuration value from Superposition with database fallback using dimension-aware key.
+/// This function is specifically for DatabaseBackedConfig types and enforces
+/// that database fallback is used when superposition fails. It uses the config's
+/// `db_key` method to construct the database key from dimensions.
+pub async fn fetch_db_with_dimensions<C, M, O, P>(
+ storage: &dyn db::StorageInterface,
+ superposition_client: Option<&superposition::SuperpositionClient>,
+ dimensions: &dimension_state::Dimensions<M, O, P>,
+) -> C::Output
+where
+ C: DatabaseBackedConfig,
+ C::Output: ConfigType,
+ M: Send + Sync,
+ O: Send + Sync,
+ P: Send + Sync,
+ open_feature::Client: superposition::GetValue<C::Output>,
+{
+ let db_key = <C as DatabaseBackedConfig>::db_key(dimensions);
+ let context = dimensions.to_superposition_context();
+
+ fetch_db_config::<C>(storage, superposition_client, &db_key, context).await
+}
+
+/// This trait extends external_services::superposition::Config with database-specific metadata
+/// and enforces that implementations must provide db_key construction.
+pub trait DatabaseBackedConfig: superposition::Config {
+ /// The database key suffix for this config
+ const KEY: &'static str;
+
+ /// Generate the database key for this config based on dimensions
+ fn db_key<M, O, P>(dimensions: &dimension_state::Dimensions<M, O, P>) -> String;
+}
+
+/// Fetch configuration value from Superposition with database fallback.
+/// This function is specifically for DatabaseBackedConfig types and enforces
+/// that database fallback is used when superposition fetch fails.
+pub async fn fetch_db_config<C>(
+ storage: &dyn db::StorageInterface,
+ superposition_client: Option<&superposition::SuperpositionClient>,
db_key: &str,
context: Option<ConfigContext>,
- default_value: T,
-) -> CustomResult<T, errors::StorageError>
+) -> C::Output
where
- T: serde::de::DeserializeOwned + serde::Serialize,
+ C: DatabaseBackedConfig,
+ C::Output: ConfigType,
+ open_feature::Client: superposition::GetValue<C::Output>,
{
- // Try superposition first if available
- let superposition_result = if let Some(ref superposition_client) = state.superposition_service {
- match superposition_client
- .get_object_value(superposition_key, context.as_ref())
- .await
- {
- Ok(json_value) => Some(
- serde_json::from_value::<T>(json_value)
- .change_context(errors::StorageError::DeserializationFailed),
- ),
- Err(err) => {
- router_env::logger::warn!(
- "Failed to retrieve config from superposition, falling back to database: {:?}",
- err
- );
- None
- }
- }
- } else {
- None
- };
-
- // Use superposition result or fall back to database
- if let Some(superposition_result) = superposition_result {
- superposition_result
- } else {
- let config = state
- .store
- .find_config_by_key_unwrap_or(
- db_key,
- Some(
- serde_json::to_string(&default_value)
- .change_context(errors::StorageError::SerializationFailed)?,
- ),
+ let default_value = C::DEFAULT_VALUE;
+ let config_type = C::KEY;
+
+ let superposition_result = match superposition_client {
+ Some(client) => C::fetch(client, context).await,
+ None => Err(error_stack::report!(
+ superposition::SuperpositionError::ClientError(
+ "No superposition client available".to_string()
)
- .await?;
+ )),
+ };
- serde_json::from_str::<T>(&config.config)
- .change_context(errors::StorageError::DeserializationFailed)
+ match superposition_result {
+ Ok(value) => value,
+ Err(_) => {
+ router_env::logger::info!("Retrieving config from database for key '{}'", db_key);
+
+ let config_result = storage
+ .find_config_by_key_unwrap_or(
+ db_key,
+ Some(default_value.to_config_string().unwrap_or_default()),
+ )
+ .await;
+
+ match config_result
+ .ok()
+ .and_then(|config| C::Output::from_config_str(&config.config).ok())
+ {
+ Some(value) => {
+ metrics::CONFIG_DATABASE_FETCH.add(
+ 1,
+ router_env::metric_attributes!(("config_type", config_type)),
+ );
+ value
+ }
+ None => {
+ router_env::logger::info!("Using default config value for key '{}'", db_key);
+ metrics::CONFIG_DEFAULT_FALLBACK.add(
+ 1,
+ router_env::metric_attributes!(("config_type", config_type)),
+ );
+ default_value
+ }
+ }
+ }
}
}
diff --git a/crates/router/src/core/configs/dimension_config.rs b/crates/router/src/core/configs/dimension_config.rs
new file mode 100644
index 0000000000..0f9f569934
--- /dev/null
+++ b/crates/router/src/core/configs/dimension_config.rs
@@ -0,0 +1,92 @@
+use external_services::superposition;
+
+use super::{
+ dimension_state::{Dimensions, HasMerchantId},
+ fetch_db_with_dimensions, DatabaseBackedConfig,
+};
+use crate::{consts::superposition as superposition_consts, db::StorageInterface};
+
+/// Macro to generate config struct and superposition::Config trait implementation
+/// Note: Manually implement `DatabaseBackedConfig` for the config struct:
+/// The `fetch_db` method is provided by the default implementation in DatabaseBackedConfig.
+#[macro_export]
+macro_rules! config {
+ (
+ superposition_key = $superposition_key:ident,
+ output = $output:ty,
+ default = $default:expr,
+ requires = $requirement:ty
+ ) => {
+ paste::paste! {
+ /// Config definition
+ pub struct [<$superposition_key:camel>];
+
+ impl superposition::Config for [<$superposition_key:camel>] {
+ type Output = $output;
+
+ const SUPERPOSITION_KEY: &'static str =
+ superposition_consts::$superposition_key;
+
+ const DEFAULT_VALUE: $output = $default;
+ }
+
+ /// Get [<$superposition_key:camel>] - ONLY available when Dimensions has required state
+ impl<O, P> Dimensions<$requirement, O, P>
+ where
+ O: Send + Sync,
+ P: Send + Sync,
+ {
+ pub async fn [<get_ $superposition_key:lower>](
+ &self,
+ storage: &dyn StorageInterface,
+ superposition_client: Option<&superposition::SuperpositionClient>,
+ ) -> $output {
+ fetch_db_with_dimensions::<[<$superposition_key:camel>], $requirement, O, P>(
+ storage,
+ superposition_client,
+ self,
+ )
+ .await
+ }
+ }
+ }
+ };
+}
+
+config! {
+ superposition_key = REQUIRES_CVV,
+ output = bool,
+ default = true,
+ requires = HasMerchantId
+}
+
+impl DatabaseBackedConfig for RequiresCvv {
+ const KEY: &'static str = "requires_cvv";
+
+ fn db_key<M, O, P>(dimensions: &Dimensions<M, O, P>) -> String {
+ let merchant_id = dimensions
+ .get_merchant_id()
+ .map(|id| id.get_string_repr())
+ .unwrap_or_default();
+ format!("{}_{}", merchant_id, Self::KEY)
+ }
+}
+
+config! {
+ superposition_key = IMPLICIT_CUSTOMER_UPDATE,
+ output = bool,
+ default = false,
+ requires = HasMerchantId
+}
+
+impl DatabaseBackedConfig for ImplicitCustomerUpdate {
+ const KEY: &'static str = "implicit_customer_update";
+
+ fn db_key<M, O, P>(dimensions: &Dimensions<M, O, P>) -> String {
+ let merchant_id = dimensions
+ .get_merchant_id()
+ .map(|id| id.get_string_repr())
+ .unwrap_or_default();
+ format!("{}_{}", merchant_id, Self::KEY)
+ }
+}
diff --git a/crates/router/src/core/configs/dimension_state.rs b/crates/router/src/core/configs/dimension_state.rs
new file mode 100644
index 0000000000..b6f681ffc3
--- /dev/null
+++ b/crates/router/src/core/configs/dimension_state.rs
@@ -0,0 +1,167 @@
+use std::marker::PhantomData;
+
+use common_utils::id_type;
+use external_services::superposition;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub enum DimensionError {
+ #[error("merchant_id not available in dimension state")]
+ MissingMerchantId,
+ #[error("organization_id not available in dimension state")]
+ MissingOrganizationId,
+ #[error("profile_id not available in dimension state")]
+ MissingProfileId,
+}
+
+/// Marker for state WITHOUT merchant_id
+pub struct NoMerchantId;
+
+/// Marker for state WITH merchant_id
+pub struct HasMerchantId;
+
+/// Marker for state WITHOUT organization_id
+pub struct NoOrgId;
+
+/// Marker for state WITH organization_id
+pub struct HasOrgId;
+
+/// Marker for state WITHOUT profile_id
+pub struct NoProfileId;
+
+/// Marker for state WITH profile_id
+pub struct HasProfileId;
+
+// Dimensional State with type parameters
+
+/// Dimensional state with type-level guarantees about which dimensions are present.
+///
+/// Uses the type-state pattern where type parameters indicate which fields are available.
+///
+/// # Type Parameters
+/// * `M` - Merchant ID type: `HasMerchantId` (present) or `NoMerchantId` (absent)
+/// * `O` - Organization ID type: `HasOrgId` (present) or `NoOrgId` (absent)
+/// * `P` - Profile ID type: `HasProfileId` (present) or `NoProfileId` (absent)
+pub struct Dimensions<M, O, P> {
+ merchant_id: Option<id_type::MerchantId>,
+ organization_id: Option<id_type::OrganizationId>,
+ profile_id: Option<id_type::ProfileId>,
+ _phantom: PhantomData<(M, O, P)>,
+}
+
+impl Dimensions<NoMerchantId, NoOrgId, NoProfileId> {
+ pub fn new() -> Self {
+ Self {
+ merchant_id: None,
+ organization_id: None,
+ profile_id: None,
+ _phantom: PhantomData,
+ }
+ }
+}
+
+/// Can only add merchant_id if not already present
+impl<O, P> Dimensions<NoMerchantId, O, P> {
+ pub fn with_merchant_id(self, id: id_type::MerchantId) -> Dimensions<HasMerchantId, O, P> {
+ Dimensions {
+ merchant_id: Some(id),
+ organization_id: self.organization_id,
+ profile_id: self.profile_id,
+ _phantom: PhantomData,
+ }
+ }
+}
+
+/// Can only add organization_id if not already present
+impl<M, P> Dimensions<M, NoOrgId, P> {
+ pub fn with_organization_id(self, id: id_type::OrganizationId) -> Dimensions<M, HasOrgId, P> {
+ Dimensions {
+ merchant_id: self.merchant_id,
+ organization_id: Some(id),
+ profile_id: self.profile_id,
+ _phantom: PhantomData,
+ }
+ }
+}
+
+/// Can only add profile_id if not already present
+impl<M, O> Dimensions<M, O, NoProfileId> {
+ pub fn with_profile_id(self, id: id_type::ProfileId) -> Dimensions<M, O, HasProfileId> {
+ Dimensions {
+ merchant_id: self.merchant_id,
+ organization_id: self.organization_id,
+ profile_id: Some(id),
+ _phantom: PhantomData,
+ }
+ }
+}
+
+/// merchant_id getter - only available if HasMerchantId
+impl<O, P> Dimensions<HasMerchantId, O, P> {
+ pub fn merchant_id(&self) -> Result<&id_type::MerchantId, DimensionError> {
+ self.merchant_id
+ .as_ref()
+ .ok_or(DimensionError::MissingMerchantId)
+ }
+}
+
+/// organization_id getter - only available if HasOrgId
+impl<M, P> Dimensions<M, HasOrgId, P> {
+ pub fn organization_id(&self) -> Result<&id_type::OrganizationId, DimensionError> {
+ self.organization_id
+ .as_ref()
+ .ok_or(DimensionError::MissingOrganizationId)
+ }
+}
+
+/// profile_id getter - only available if HasProfileId
+impl<M, O> Dimensions<M, O, HasProfileId> {
+ pub fn profile_id(&self) -> Result<&id_type::ProfileId, DimensionError> {
+ self.profile_id
+ .as_ref()
+ .ok_or(DimensionError::MissingProfileId)
+ }
+}
+
+// Optional getters (available in any state)
+impl<M, O, P> Dimensions<M, O, P> {
+ pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
+ self.merchant_id.as_ref()
+ }
+
+ pub fn get_organization_id(&self) -> Option<&id_type::OrganizationId> {
+ self.organization_id.as_ref()
+ }
+
+ pub fn get_profile_id(&self) -> Option<&id_type::ProfileId> {
+ self.profile_id.as_ref()
+ }
+}
+
+// Superposition context conversion
+impl<M, O, P> Dimensions<M, O, P> {
+ /// Converts dimension state to Superposition config context
+ pub fn to_superposition_context(&self) -> Option<superposition::ConfigContext> {
+ let mut ctx = superposition::ConfigContext::new();
+
+ if let Some(ref mid) = self.merchant_id {
+ ctx = ctx.with("merchant_id", mid.get_string_repr());
+ }
+
+ if let Some(ref oid) = self.organization_id {
+ ctx = ctx.with("organization_id", oid.get_string_repr());
+ }
+
+ if let Some(ref pid) = &self.profile_id {
+ ctx = ctx.with("profile_id", pid.get_string_repr());
+ }
+ Some(ctx)
+ }
+}
+
+impl Default for Dimensions<NoMerchantId, NoOrgId, NoProfileId> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+pub type DimensionsWithMerchantId = Dimensions<HasMerchantId, NoOrgId, NoProfileId>;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 70573c6b4c..cb8e074b18 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -78,6 +78,7 @@ use crate::{
consts as router_consts,
core::{
configs,
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, StorageErrorExt},
payment_methods::{
network_tokenization, transformers as payment_methods, utils as payment_method_utils,
@@ -4184,6 +4185,8 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
customer_id: Option<&id_type::CustomerId>,
ephemeral_api_key: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
+ let dimensions = configs::dimension_state::Dimensions::new()
+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());
let limit = req.clone().and_then(|pml_req| pml_req.limit);
let auth_cust = if let Some(key) = ephemeral_api_key {
@@ -4207,6 +4210,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
None,
customer_id,
limit,
+ dimensions,
))
.await
} else {
@@ -4226,6 +4230,7 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
payment_intent,
&customer_id,
limit,
+ dimensions,
))
.await
}
@@ -4247,6 +4252,7 @@ pub async fn list_customer_payment_method(
payment_intent: Option<storage::PaymentIntent>,
customer_id: &id_type::CustomerId,
limit: Option<i64>,
+ dimensions: DimensionsWithMerchantId,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let off_session_payment_flag = payment_intent
@@ -4269,29 +4275,10 @@ pub async fn list_customer_payment_method(
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
- let requires_cvv = configs::get_config_bool(
- state,
- router_consts::superposition::REQUIRES_CVV, // superposition key
- &platform
- .get_processor()
- .get_account()
- .get_id()
- .get_requires_cvv_key(), // database key
- Some(
- external_services::superposition::ConfigContext::new().with(
- "merchant_id",
- platform
- .get_processor()
- .get_account()
- .get_id()
- .get_string_repr(),
- ),
- ), // context
- true, // default value
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch requires_cvv config")?;
+ // Get requires_cvv using type-safe dimensions config
+ let requires_cvv = dimensions
+ .get_requires_cvv(state.store.as_ref(), state.superposition_service.as_deref())
+ .await;
let resp = db
.find_payment_method_by_customer_id_merchant_id_status(
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 10c9d25421..a0ad1c1af2 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -106,8 +106,6 @@ use super::{
},
};
#[cfg(feature = "v1")]
-use crate::core::blocklist::utils as blocklist_utils;
-#[cfg(feature = "v1")]
use crate::core::card_testing_guard::utils as card_testing_guard_utils;
#[cfg(feature = "v1")]
use crate::core::debit_routing;
@@ -121,6 +119,11 @@ use crate::core::revenue_recovery::get_workflow_entries;
use crate::core::revenue_recovery::map_to_recovery_payment_item;
#[cfg(feature = "v1")]
use crate::core::routing::helpers as routing_helpers;
+#[cfg(feature = "v1")]
+use crate::core::{
+ blocklist::utils as blocklist_utils,
+ configs::{self as configs, dimension_state::DimensionsWithMerchantId},
+};
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
use crate::types::api::convert_connector_data_to_routable_connectors;
use crate::{
@@ -607,6 +610,7 @@ pub async fn payments_operation_core<'a, F, Req, Op, FData, D>(
auth_flow: services::AuthFlow,
eligible_connectors: Option<Vec<enums::RoutableConnectors>>,
header_payload: HeaderPayload,
+ dimensions: DimensionsWithMerchantId,
) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync + Debug + 'static,
@@ -700,6 +704,7 @@ where
&mut payment_data,
customer_details, // TODO: Remove this field after implicit customer update is removed
platform.get_provider(),
+ dimensions,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
@@ -1427,6 +1432,7 @@ pub async fn proxy_for_payments_operation_core<F, Req, Op, FData, D>(
auth_flow: services::AuthFlow,
header_payload: HeaderPayload,
return_raw_connector_response: Option<bool>,
+ dimensions: DimensionsWithMerchantId,
) -> RouterResult<(D, Req, Option<u16>, Option<u128>)>
where
F: Send + Clone + Sync,
@@ -1546,6 +1552,7 @@ where
&mut payment_data,
customer_details,
platform.get_provider(),
+ dimensions,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
@@ -2389,6 +2396,8 @@ where
.flat_map(|c| c.foreign_try_into())
.collect()
});
+ let dimensions = configs::dimension_state::Dimensions::new()
+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());
let (payment_data, _req, connector_http_status_code, external_latency) =
payments_operation_core::<_, _, _, _, _>(
&state,
@@ -2402,6 +2411,7 @@ where
auth_flow,
eligible_routable_connectors,
header_payload.clone(),
+ dimensions,
)
.await?;
@@ -2450,6 +2460,8 @@ where
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
{
+ let dimensions = configs::dimension_state::Dimensions::new()
+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());
let (payment_data, _req, connector_http_status_code, external_latency) =
proxy_for_payments_operation_core::<_, _, _, _, _>(
&state,
@@ -2462,6 +2474,7 @@ where
auth_flow,
header_payload.clone(),
return_raw_connector_response,
+ dimensions,
)
.await?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 867ef3c9d7..c945c9a003 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -86,7 +86,8 @@ use crate::{
connector,
consts::{self, BASE64_ENGINE},
core::{
- authentication, configs,
+ authentication,
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers::MandateGenericData,
payment_methods::{
@@ -1865,6 +1866,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
_payment_data: &mut PaymentData<F>,
_req: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
todo!()
}
@@ -1878,6 +1880,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError> {
let merchant_id = provider.get_account().get_id();
let storage_scheme = provider.get_account().storage_scheme;
@@ -1973,21 +1976,12 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R, D>(
Some(match customer_data {
Some(c) => {
- let implicit_customer_update = configs::get_config_bool(
- state,
- consts::superposition::IMPLICIT_CUSTOMER_UPDATE,
- &provider
- .get_account()
- .get_id()
- .get_implicit_customer_update_key(), // database
- Some(external_services::superposition::ConfigContext::new().with(
- "merchant_id",
- provider.get_account().get_id().get_string_repr(),
- )), // context
- false, // Implicit Customer update is disabled by default
- )
- .await
- .attach_printable("Failed to fetch implicit_customer_update config")?;
+ let implicit_customer_update = dimensions
+ .get_implicit_customer_update(
+ state.store.as_ref(),
+ state.superposition_service.as_deref(),
+ )
+ .await;
// Update the customer data if new data is passed in the request
if implicit_customer_update
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index e5f125efbc..246deb466b 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -103,6 +103,7 @@ use crate::core::payments;
use crate::core::payments::pm_transformers::PaymentMethodWithRawData;
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult},
utils as core_utils,
},
@@ -272,6 +273,7 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {
payment_data: &mut D,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<(BoxedOperation<'a, F, R, D>, Option<domain::Customer>), errors::StorageError>;
#[cfg(feature = "v2")]
@@ -660,6 +662,7 @@ where
_payment_data: &mut D,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest, D>,
@@ -728,6 +731,7 @@ where
_payment_data: &mut D,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCaptureRequest, D>,
@@ -814,6 +818,7 @@ where
_payment_data: &mut D,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsCancelRequest, D>,
@@ -900,6 +905,7 @@ where
_payment_data: &mut D,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
BoxedOperation<'a, F, api::PaymentsRejectRequest, D>,
diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
index 5755c05183..76852f6ce4 100644
--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs
@@ -8,6 +8,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
@@ -222,6 +223,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsCancelPostCaptureRequest, Pa
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(
PaymentCancelPostCaptureOperation<'a, F>,
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index 50a5de732c..bc0b78de40 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -10,6 +10,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payments::{
@@ -408,6 +409,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index cfeb0fea34..84815ebe30 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -34,6 +34,7 @@ use crate::{
authentication,
blocklist::utils as blocklist_utils,
card_testing_guard::utils as card_testing_guard_utils,
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
metrics,
@@ -963,6 +964,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(PaymentConfirmOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
@@ -975,6 +977,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data,
request,
provider,
+ dimensions,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 7015be1d8d..66ef379e47 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -30,6 +30,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
consts,
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_link,
@@ -670,6 +671,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> CustomResult<(PaymentCreateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match provider.get_account().merchant_account_type {
@@ -680,6 +682,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data,
request,
provider,
+ dimensions,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
index 77d8f87a97..f7f9de77f4 100644
--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs
@@ -10,6 +10,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
@@ -199,6 +200,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsPostSessionTokensRequest, Pa
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(
PaymentPostSessionTokensOperation<'a, F>,
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 82bc79ffe6..7b8f092191 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -10,6 +10,7 @@ use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
@@ -327,6 +328,7 @@ where
payment_data: &mut PaymentData<F>,
request: Option<payments::CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
@@ -339,6 +341,7 @@ where
payment_data,
request,
provider,
+ dimensions,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 26c9280692..ab1738f7a9 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -9,6 +9,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
@@ -290,6 +291,7 @@ where
_payment_data: &mut PaymentData<F>,
_request: Option<CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(PaymentSessionOperation<'a, F>, Option<domain::Customer>),
errors::StorageError,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index f6e792fb4d..cfa448bacc 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -10,6 +10,7 @@ use router_env::{instrument, logger, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payments::{
helpers, operations, types as payment_types, CustomerDetails, PaymentAddress,
@@ -66,6 +67,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
PaymentStatusOperation<'a, F, api::PaymentsRequest>,
@@ -81,6 +83,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data,
request,
provider,
+ dimensions,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 2c2830881e..d01b2197a5 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -19,6 +19,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, CustomResult, RouterResult, StorageErrorExt},
mandate::helpers as m_helpers,
payment_methods::cards::create_encrypted_data,
@@ -581,6 +582,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data: &mut PaymentData<F>,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ dimensions: DimensionsWithMerchantId,
) -> CustomResult<(PaymentUpdateOperation<'a, F>, Option<domain::Customer>), errors::StorageError>
{
match provider.get_account().merchant_account_type {
@@ -591,6 +593,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for
payment_data,
request,
provider,
+ dimensions,
)
.await
}
diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rs
index 78a077c2fd..d9fb510dca 100644
--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs
+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs
@@ -11,6 +11,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
@@ -211,6 +212,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsUpdateMetadataRequest, Payme
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(
PaymentUpdateMetadataOperation<'a, F>,
diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
index ace766fc68..c9dc1f3421 100644
--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs
@@ -8,6 +8,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{self, helpers, operations, PaymentData},
},
@@ -227,6 +228,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsExtendAuthorizationRequest,
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(
PaymentExtendAuthorizationOperation<'a, F>,
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index 8b15f66ca3..b1fea0cd83 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -10,6 +10,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payments::{
self, helpers, operations, CustomerDetails, IncrementalAuthorizationDetails,
@@ -325,6 +326,7 @@ impl<F: Clone + Send + Sync>
payment_data: &mut payments::PaymentData<F>,
request: Option<CustomerDetails>,
provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> CustomResult<
(
BoxedOperation<
diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs
index f7496d3d91..4543210cf2 100644
--- a/crates/router/src/core/payments/operations/tax_calculation.rs
+++ b/crates/router/src/core/payments/operations/tax_calculation.rs
@@ -11,6 +11,7 @@ use router_env::{instrument, tracing};
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
core::{
+ configs::dimension_state::DimensionsWithMerchantId,
errors::{self, RouterResult, StorageErrorExt},
payment_methods::cards::create_encrypted_data,
payments::{self, helpers, operations, PaymentData, PaymentMethodChecker},
@@ -215,6 +216,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest
_payment_data: &mut PaymentData<F>,
_request: Option<payments::CustomerDetails>,
_provider: &domain::Provider,
+ _dimensions: DimensionsWithMerchantId,
) -> errors::CustomResult<
(
PaymentSessionUpdateOperation<'a, F>,
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index e0d389382b..c017ad5e5b 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -152,3 +152,7 @@ counter_metric!(CHAT_REQUEST_COUNT, GLOBAL_METER);
// Merchant advice code config lookup metrics
counter_metric!(MERCHANT_ADVICE_CODE_CONFIG_MISS, GLOBAL_METER);
+
+// Config Fetch Metrics
+counter_metric!(CONFIG_DATABASE_FETCH, GLOBAL_METER); // When fetched from database
+counter_metric!(CONFIG_DEFAULT_FALLBACK, GLOBAL_METER); // When defaulted to application default
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 699acb6fbb..863a0adc1c 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -14,6 +14,7 @@ use crate::workflows::revenue_recovery::update_token_expiry_based_on_schedule_ti
use crate::{
consts,
core::{
+ configs,
errors::StorageErrorExt,
payments::{self as payment_flows, operations},
},
@@ -79,6 +80,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
key_store.clone(),
None,
);
+ let dimensions = configs::dimension_state::Dimensions::new()
+ .with_merchant_id(platform.get_processor().get_account().get_id().clone());
// TODO: Add support for ReqState in PT flows
let (mut payment_data, _, _, _) = Box::pin(payment_flows::payments_operation_core::<
api::PSync,
@@ -98,6 +101,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
services::AuthFlow::Client,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
+ dimensions,
))
.await?;